问:
SharePoint cascading dropdown to multi-select field, retaining selections when filter changes
I followed the cascading dropdown with jquery that is listed here: https://www.c-sharpcorner.com/blogs/cascading-dropdownlist-in-sharepoint and it works fine. The child entry is a multi-select field. When you change the parent field, it resets the child list to the applicable children.

Parent: Manufacturer that has Brand in Title

Child: list of products for each brand. Product is listed as Title with a field for BrandLookUp.

UPDATE: Some Child feeds are listed multiple times because they are associated with multiple years. Even though the ID for each child is different, I just need to retain the child title field (item) for this part of the list. I.e.

-ID - Brand - Item - Year

-1 - XYZ - A - 21

-2 - XYZ - A - 22

-3 - ABC - B

-4 - WXY - C

I am trying to figure out how to modify the code to only display unique item names when the child list is populated.

UPDATE 2: I realized while there is a code solution, I could also fix it by restructuring the data. I changed the year field to a multi-value and added the multiple years, then removed the duplicate entries. The filter fields works and pulls the item for the correct year.

答:
Checked the linked code. I do not have the environment to test, but here is my suggestion.

Only append new products to the child. Never call $(child).empty();. Add  option to the child selector to select the options in it and call $(childOptions).hide(); to hide them all.

```<code>   var childOptions = $("................. option");
   childOptions.hide();
</code>```

When brand is changed, first check if its products are already in the list. Better, keep an array of brands products of which are already added to the child, visible or not. If they are on the list, do not add them again. When you are going to add new products to the select, add a data-brand attribute to the options so you can filter them later.

```<code>  for (index in data.d.results) {
      options += "<option value='" + data.d.results[index].Id + "' data-brand='" + brandName + "'>" +
          data.d.results[index][params.childLookupField] + "</option>";
  }
  $(child).append(options);
</code>```

Select the product options of the current brand and show them, something like $("option[data-brand='ACME']").show();

Body:
Checked the linked code. I do not have the environment to test, but here is my suggestion.

Only append new products to the child. Never call $(child).empty();. Add  option to the child selector to select the options in it and call $(childOptions).hide(); to hide them all.

   var childOptions = $("................. option");
   childOptions.hide();

When brand is changed, first check if its products are already in the list. Better, keep an array of brands products of which are already added to the child, visible or not. If they are on the list, do not add them again. When you are going to add new products to the select, add a data-brand attribute to the options so you can filter them later.

  for (index in data.d.results) {
      options += "<option value='" + data.d.results[index].Id + "' data-brand='" + brandName + "'>" +
          data.d.results[index][params.childLookupField] + "</option>";
  }
  $(child).append(options);

Select the product options of the current brand and show them, something like $("option[data-brand='ACME']").show();


来源: stackexchange

问:
GGplot | Barchart for counting characters as fill
Need some help getting this bar chart to form. I get errors about not being able to count characters.
Trying to get it to look like this:

```<code>ggplot(Interview_State_Data,aes(x = Interview_Stage,
                          y = as.factor(Level_Simplified),
                          fill = Level_Simplified)) +

  geom_bar(stat="identity", position="dodge")

structure(list(Interview_Stage = c("Third Onsite", "Recruiter Phone Screen",
"Second Onsite", "Third Onsite", "Recruiter Phone Screen", "Second Onsite"
), Level_Simplified = c("MR", "IC", "MR", "MR", "MR", "MR")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
```<code>ggplot(Interview_Stage_Data,aes(x = Interview_Stage,
                      #   y = Level_Simplified, #
                          fill = Level_Simplified)) +

  geom_bar(stat="count", position="dodge")
</code>```

Changed geom_bar(stat="identity"  to geom_bar(stat="count" and removed  y = Level_Simplified from the code and it ran perfect.

Thanks to @markus

ContentLicense: CC BY-SA 4.0

Body:
Need some help getting this bar chart to form. I get errors about not being able to count characters.
Trying to get it to look like this:

ggplot(Interview_State_Data,aes(x = Interview_Stage,
                          y = as.factor(Level_Simplified),
                          fill = Level_Simplified)) +

  geom_bar(stat="identity", position="dodge")

structure(list(Interview_Stage = c("Third Onsite", "Recruiter Phone Screen",
"Second Onsite", "Third Onsite", "Recruiter Phone Screen", "Second Onsite"
), Level_Simplified = c("MR", "IC", "MR", "MR", "MR", "MR")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

Body:
ggplot(Interview_Stage_Data,aes(x = Interview_Stage,
                      #   y = Level_Simplified, #
                          fill = Level_Simplified)) +

  geom_bar(stat="count", position="dodge")

Changed geom_bar(stat="identity"  to geom_bar(stat="count" and removed  y = Level_Simplified from the code and it ran perfect.

Thanks to @markus


问:
Can SUMIFS calculate data from current month with 2 or more criteria?
I have a spreadsheet that uses a few SUMIFS formulas to calculate data based on 2 criteria and a normal range. Currently I'm having to change this manually every month to capture metrics of tickets reported that meet some of those criteria. Ideally i'd like to implement some logic to only calculate data that has dates from the current month.

Here's my original sumifs:

```<code>=SUMIFS($G$2:$G$100,$A$2:$A$100,"primary",B2:B100,"little")
=SUMIFS($G$2:$G$100,$A$2:$A$100,"primary",B2:B100,"panic")
</code>```

etc..

I was told something to the extent of this would get me where I needed to be, but it doesn't seem to be actually calculating only data with dates within this month.

```<code>=SUMIFS($G$2:$G$100,$A$2:$A$100,"primary*",$B$2:$B$101,"little")+SUMIFS($G$2:$G$100,$F$2:$F$100,">="&DATE(YEAR(TODAY()),MONTH(TODAY()),1))
</code>```

Any help would be greatly appreciated!!

Spreadsheet_data

答:
Why not try using the Incredibly Versatile SUMPRODUCT Function here,

Formula used in cell I2

```<code>    =SUMPRODUCT(($G$2:$G$9)*($A$2:$A$9=$J2)*($B$2:$B$9=$K2)*
     (TEXT($F$2:$F$9,"mmmmyyyy")=$I$1&YEAR(TODAY())))
</code>```

The SUMPRODUCT function simply multiplies arrays together and returns the sum of products. If only one array is supplied, SUMPRODUCT will simply sum the items in the array. Up to 30 ranges or arrays can be supplied.

It may seem boring, complex, and even pointless. But SUMPRODUCT is an amazingly versatile function with many uses. Because it will handle arrays gracefully, you can use it to process ranges of cells in clever, elegant ways. It can be used to count and sum like COUNTIFS or SUMIFS, but with more flexibility.

So, let me go through you a bit what the formula does,

Array 1

```<code>($A$2:$A$9=$J2) {TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;TRUE;TRUE}
</code>```

Array 2

```<code>($B$2:$B$9=$K2) {TRUE;FALSE;FALSE;FALSE;FALSE;FALSE;TRUE;FALSE}
</code>```

Array 3

```<code>(TEXT($F$2:$F$9,"mmmmyyyy")=$I$1&YEAR(TODAY()))

{FALSE;TRUE;FALSE;FALSE;FALSE;TRUE;TRUE;TRUE}
</code>```

And this is the whole part which is wrapped within SUMPRODUCT

```<code>($G$2:$G$9)*($A$2:$A$9=$J2)*($B$2:$B$9=$K2)*(TEXT($F$2:$F$9,"mmmmyyyy")=$I$1&YEAR(TODAY()))
</code>```

When you select this part and press F9, it evaluates and shows you an array of numbers

```<code>{0;0;0;0;0;0;12;0}
</code>```

Basically its creates an array of TRUE's & FALSE's and then multiplies with the corresponding values to give you the exact output which you need!

Also why you need to use SUMPRODUCT Function ---> Let me tell about it more

It never gives an error for text values unless you are not using a double negative or double minus, I always say SUMPRODUCT is much versatile function than other, it can be clubbed with many other excel functions without any issue.

The double negative (--) is one of several ways to coerce TRUE and FALSE values into their numeric equivalents, 1 and 0. One we have 1s and 0s, we can perform various operations on the arrays with Boolean logic. The table below shows the result in array1,array2, array3 based on the formula above, after the double negative (--) has changed the TRUE and FALSE values to 1s and 0s.

Body:
I have a spreadsheet that uses a few SUMIFS formulas to calculate data based on 2 criteria and a normal range. Currently I'm having to change this manually every month to capture metrics of tickets reported that meet some of those criteria. Ideally i'd like to implement some logic to only calculate data that has dates from the current month.

Here's my original sumifs:

=SUMIFS($G$2:$G$100,$A$2:$A$100,"primary",B2:B100,"little")
=SUMIFS($G$2:$G$100,$A$2:$A$100,"primary",B2:B100,"panic")

etc..

I was told something to the extent of this would get me where I needed to be, but it doesn't seem to be actually calculating only data with dates within this month.

=SUMIFS($G$2:$G$100,$A$2:$A$100,"primary*",$B$2:$B$101,"little")+SUMIFS($G$2:$G$100,$F$2:$F$100,">="&DATE(YEAR(TODAY()),MONTH(TODAY()),1))

Any help would be greatly appreciated!!

Spreadsheet_data

Body:
Why not try using the Incredibly Versatile SUMPRODUCT Function here,

Formula used in cell I2

    =SUMPRODUCT(($G$2:$G$9)*($A$2:$A$9=$J2)*($B$2:$B$9=$K2)*
     (TEXT($F$2:$F$9,"mmmmyyyy")=$I$1&YEAR(TODAY())))

The SUMPRODUCT function simply multiplies arrays together and returns the sum of products. If only one array is supplied, SUMPRODUCT will simply sum the items in the array. Up to 30 ranges or arrays can be supplied.

It may seem boring, complex, and even pointless. But SUMPRODUCT is an amazingly versatile function with many uses. Because it will handle arrays gracefully, you can use it to process ranges of cells in clever, elegant ways. It can be used to count and sum like COUNTIFS or SUMIFS, but with more flexibility.

So, let me go through you a bit what the formula does,

Array 1

($A$2:$A$9=$J2) {TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;TRUE;TRUE}

Array 2

($B$2:$B$9=$K2) {TRUE;FALSE;FALSE;FALSE;FALSE;FALSE;TRUE;FALSE}

Array 3

(TEXT($F$2:$F$9,"mmmmyyyy")=$I$1&YEAR(TODAY()))

{FALSE;TRUE;FALSE;FALSE;FALSE;TRUE;TRUE;TRUE}

And this is the whole part which is wrapped within SUMPRODUCT

($G$2:$G$9)*($A$2:$A$9=$J2)*($B$2:$B$9=$K2)*(TEXT($F$2:$F$9,"mmmmyyyy")=$I$1&YEAR(TODAY()))

When you select this part and press F9, it evaluates and shows you an array of numbers

{0;0;0;0;0;0;12;0}

Basically its creates an array of TRUE's & FALSE's and then multiplies with the corresponding values to give you the exact output which you need!

Also why you need to use SUMPRODUCT Function ---> Let me tell about it more

It never gives an error for text values unless you are not using a double negative or double minus, I always say SUMPRODUCT is much versatile function than other, it can be clubbed with many other excel functions without any issue.

The double negative (--) is one of several ways to coerce TRUE and FALSE values into their numeric equivalents, 1 and 0. One we have 1s and 0s, we can perform various operations on the arrays with Boolean logic. The table below shows the result in array1,array2, array3 based on the formula above, after the double negative (--) has changed the TRUE and FALSE values to 1s and 0s.


问:
@StateObject vs @ObservedObject when passed externally but owned by the view
Based on this answer: What is the difference between ObservedObject and StateObject in SwiftUI

And the Apple documentation code here: https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

In SwiftUI app, a @StateObject property wrapper should be used when a View instantiates the object itself, so that the object won't be recreated during a view update.

If the object is instantiated somewhere else, an @ObservedObject wrapper should be used instead.

However, there is a fine line which makes it a bit unclear: what if the object is instantiated somewhere else, but "injected" to the View and then the view is the sole owner / holder of that object? Should it be @StateObject or @ObservedObject?

Sample code to get the point illustrated:

```<code>import SwiftUI
import Combine
import Foundation

struct ViewFactory {
    func makeView() -> some View {
        let viewModel = ViewModel()
        return NameView(viewModel)
    }
}

final class ViewModel: ObservableObject {
    @Published var name = ""
    init() {}
}

struct NameView: View {

    // Should this be an `@ObservedObject` or `@StateObject`?
    @ObservedObject var viewModel: ViewModel

    init(_ viewModel: ViewModel) {
        self.viewModel = viewModel
    }

    var body: some View {
        Text(viewModel.name)
    }
}
</code>```

Based on this article: https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject

There is one important difference between @StateObject and @ObservedObject, which is ownership – which view created the object, and which view is just watching it.

The rule is this: whichever view is the first to create your object must use @StateObject, to tell SwiftUI it is the owner of the data and is responsible for keeping it alive. All other views must use @ObservedObject, to tell SwiftUI they want to watch the object for changes but don’t own it directly.

it appears that if the View to instantiate the ViewModel, it has to be declared with @StateObject. My code is very similar, the only difference is that the ViewModel is created elsewhere, but the View "owns" it after the initialization.

答:
This is a really interesting question. There's some subtle behavior going on here.

First, notice that you can't just change @ObservedObject to @StateObject in NameView. It won't compile:

struct NameView: View {
    @StateObject var viewModel: ViewModel

    init(_ viewModel: ViewModel) {
        self.viewModel = viewModel
        //   ^  Cannot assign to property: 'viewModel' is a get-only property
    }
    ...
}
```
<p>To make it compile, you have to initialize the underlying <code>_viewModel</code> stored property of type <code>StateObject<ViewModel></code>:</p>
<pre class="lang-swift prettyprint-override"><code>struct NameView: View {
    @StateObject var viewModel: ViewModel

    init(_ viewModel: ViewModel) {
        _viewModel = .init(wrappedValue: viewModel)
    }
    ...
}
</code>```

But there's something hidden there. StateObject.init(wrappedValue:) is declared like this:

public init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType)
```
<p>So the expression given as an argument (just <code>viewModel</code> above) is wrapped up in a closure, and is <strong>not</strong> evaluated right away. That closure is stored for later use, which is why it is <code>@escaping</code>.</p>
<p>As you might guess from the hoops we have to jump through to make it compile, this is a weird way to use <code>StateObject</code>. The normal use looks like this:</p>
<pre class="lang-swift prettyprint-override"><code>struct NormalView: View {
    @StateObject var viewModel = ViewModel()

  var body: some View {
        Text(viewModel.name)
    }
}
</code>```

And doing it the weird way has some drawbacks. To understand the drawbacks, we need to look at the context in which  makeView() or NormalView() is evaluated. Let's say it looks like this:

struct ContentView: View {
    @Binding var count: Int

    var body: some View {
        VStack {
            Text("count: \(count)")
            NormalView()
            ViewFactory().makeView()
        }
    }
}
```

When count's value changes, SwiftUI will ask ContentView for its body again, which will evaluate both NormalView() and makeView() again.

So body calls NormalView() during this second evaluation, which creates another instance of NormalView. NormalView.init creates a closure which calls ViewModel(), and passes the closure to  StateObject.init(wrappedValue:). But StateObject.init does not evaluate this closure immediately. It stores it away for later use.

Then body calls makeView(), which does call ViewModel() immediately. It passes the new ViewModel to NameView.init, which wraps the new ViewModel in a closure and passes the closure to StateObject.init(wrappedValue:). This StateObject also doesn't evaluate the closure immediately, but the new ViewModel has been created regardless.

Some time after ContentView.body returns, SwiftUI wants to call NormalView.body. But before doing so, it has to make sure the StateObject in this NormalView has a ViewModel. It notices that this NormalView is replacing a prior NormalView at the same position in the view hierarchy, so it retrieves the ViewModel used by that prior NormalView and puts it in the StateObject of the new NormalView. It does not execute the closure given to  StateObject.init, so it does not create a new ViewModel.

Even later, SwiftUI wants to call NameView.body. But before doing so, it has to make sure the StateObject in this NameView has a ViewModel. It notices that this NameView is replacing a prior NameView at the same position in the view hierarchy, so it retrieves the ViewModel used by that prior NameView and puts it in the StateObject of the new NameView. It does not execute the closure given to StateObject.init, and so it does not use the ViewModel referenced by that closure. But the ViewModel was created anyway.

So there are two drawbacks to the weird way in which you're using @StateObject:

You're creating a new ViewModel each time you call makeView, even though that ViewModel may never be used. This may be expensive, depending on your ViewModel.

You're creating the ViewModel while the ContentView.body getter is running. If creating the ViewModel has side effects, this may confuse SwiftUI. SwiftUI expects the body getter to be a pure function. In the NormalView case, SwiftUI is calling the StateObject's closure at a known time when it may be better prepared to handle side effects.

So, back to your original question:

Should it be @StateObject or @ObservedObject?

Well, ha ha, that's difficult to answer without seeing an example that's less of a toy. But if you do need to use @StateObject, you should probably try to initialize it in the ‘normal’ way.

Body:
Based on this answer: What is the difference between ObservedObject and StateObject in SwiftUI

And the Apple documentation code here: https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

In SwiftUI app, a @StateObject property wrapper should be used when a View instantiates the object itself, so that the object won't be recreated during a view update.

If the object is instantiated somewhere else, an @ObservedObject wrapper should be used instead.

However, there is a fine line which makes it a bit unclear: what if the object is instantiated somewhere else, but "injected" to the View and then the view is the sole owner / holder of that object? Should it be @StateObject or @ObservedObject?

Sample code to get the point illustrated:

import SwiftUI
import Combine
import Foundation

struct ViewFactory {
    func makeView() -> some View {
        let viewModel = ViewModel()
        return NameView(viewModel)
    }
}

final class ViewModel: ObservableObject {
    @Published var name = ""
    init() {}
}

struct NameView: View {

    // Should this be an `@ObservedObject` or `@StateObject`?
    @ObservedObject var viewModel: ViewModel

    init(_ viewModel: ViewModel) {
        self.viewModel = viewModel
    }

    var body: some View {
        Text(viewModel.name)
    }
}

Based on this article: https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject

There is one important difference between @StateObject and @ObservedObject, which is ownership – which view created the object, and which view is just watching it.

The rule is this: whichever view is the first to create your object must use @StateObject, to tell SwiftUI it is the owner of the data and is responsible for keeping it alive. All other views must use @ObservedObject, to tell SwiftUI they want to watch the object for changes but don’t own it directly.

it appears that if the View to instantiate the ViewModel, it has to be declared with @StateObject. My code is very similar, the only difference is that the ViewModel is created elsewhere, but the View "owns" it after the initialization.

Body:
This is a really interesting question. There's some subtle behavior going on here.

First, notice that you can't just change @ObservedObject to @StateObject in NameView. It won't compile:

struct NameView: View {
    @StateObject var viewModel: ViewModel

    init(_ viewModel: ViewModel) {
        self.viewModel = viewModel
        //   ^  Cannot assign to property: 'viewModel' is a get-only property
    }
    ...
}

To make it compile, you have to initialize the underlying _viewModel stored property of type StateObject<ViewModel>:

struct NameView: View {
    @StateObject var viewModel: ViewModel

    init(_ viewModel: ViewModel) {
        _viewModel = .init(wrappedValue: viewModel)
    }
    ...
}

But there's something hidden there. StateObject.init(wrappedValue:) is declared like this:

public init(wrappedValue thunk: @autoclosure @escaping () -> ObjectType)

So the expression given as an argument (just viewModel above) is wrapped up in a closure, and is not evaluated right away. That closure is stored for later use, which is why it is @escaping.

As you might guess from the hoops we have to jump through to make it compile, this is a weird way to use StateObject. The normal use looks like this:

struct NormalView: View {
    @StateObject var viewModel = ViewModel()

  var body: some View {
        Text(viewModel.name)
    }
}

And doing it the weird way has some drawbacks. To understand the drawbacks, we need to look at the context in which  makeView() or NormalView() is evaluated. Let's say it looks like this:

struct ContentView: View {
    @Binding var count: Int

    var body: some View {
        VStack {
            Text("count: \(count)")
            NormalView()
            ViewFactory().makeView()
        }
    }
}

When count's value changes, SwiftUI will ask ContentView for its body again, which will evaluate both NormalView() and makeView() again.

So body calls NormalView() during this second evaluation, which creates another instance of NormalView. NormalView.init creates a closure which calls ViewModel(), and passes the closure to  StateObject.init(wrappedValue:). But StateObject.init does not evaluate this closure immediately. It stores it away for later use.

Then body calls makeView(), which does call ViewModel() immediately. It passes the new ViewModel to NameView.init, which wraps the new ViewModel in a closure and passes the closure to StateObject.init(wrappedValue:). This StateObject also doesn't evaluate the closure immediately, but the new ViewModel has been created regardless.

Some time after ContentView.body returns, SwiftUI wants to call NormalView.body. But before doing so, it has to make sure the StateObject in this NormalView has a ViewModel. It notices that this NormalView is replacing a prior NormalView at the same position in the view hierarchy, so it retrieves the ViewModel used by that prior NormalView and puts it in the StateObject of the new NormalView. It does not execute the closure given to  StateObject.init, so it does not create a new ViewModel.

Even later, SwiftUI wants to call NameView.body. But before doing so, it has to make sure the StateObject in this NameView has a ViewModel. It notices that this NameView is replacing a prior NameView at the same position in the view hierarchy, so it retrieves the ViewModel used by that prior NameView and puts it in the StateObject of the new NameView. It does not execute the closure given to StateObject.init, and so it does not use the ViewModel referenced by that closure. But the ViewModel was created anyway.

So there are two drawbacks to the weird way in which you're using @StateObject:

You're creating a new ViewModel each time you call makeView, even though that ViewModel may never be used. This may be expensive, depending on your ViewModel.

You're creating the ViewModel while the ContentView.body getter is running. If creating the ViewModel has side effects, this may confuse SwiftUI. SwiftUI expects the body getter to be a pure function. In the NormalView case, SwiftUI is calling the StateObject's closure at a known time when it may be better prepared to handle side effects.

So, back to your original question:

Should it be @StateObject or @ObservedObject?

Well, ha ha, that's difficult to answer without seeing an example that's less of a toy. But if you do need to use @StateObject, you should probably try to initialize it in the ‘normal’ way.


问:
can't install rails 4.2.10 with source "http://rubygems.org" getting forbidden error
While installing

```<code>gem install rails -v 4.2.10 --source https://rubygems.org
</code>```

on mac monterey getting error:

```<code>ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
bad response Forbidden 403 (http://api.rubygems.org/quick/Marshal.4.8/nokogiri-1.13.1-x64-unknown.gemspec.rz)
</code>```

答:
I had the same issue. M1 Mac, while setting up to run Ruby 2.5.1 and an older Rails app.

I followed these steps from a Github comment:

```<code>gem update --system
xcode-select --install (didn't need to do this, though it was a listed step)
gem install nokogiri
bundle install
</code>```

Body:
While installing

gem install rails -v 4.2.10 --source https://rubygems.org

on mac monterey getting error:

ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
bad response Forbidden 403 (http://api.rubygems.org/quick/Marshal.4.8/nokogiri-1.13.1-x64-unknown.gemspec.rz)

Body:
I had the same issue. M1 Mac, while setting up to run Ruby 2.5.1 and an older Rails app.

I followed these steps from a Github comment:

gem update --system
xcode-select --install (didn't need to do this, though it was a listed step)
gem install nokogiri
bundle install


问:
How is cout << <variable> different from cout << <mathematical-expression>?
I'm trying to solve this problem: https://www.codechef.com/FEB222C/problems/WCC

I've solved this problem and have successfully submitted the solution, but I'm getting 'WRONG ANSWER' error in an alternate approach in one test case:

My successful submission approach is:

```<code>#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int X;
        cin >> X;
        int prize = 100 * X;
        string str;
        cin >> str;
        int carlsenPoints = 0;
        int chefPoints = 0;
        for (int i = 0; i < str.length(); i++)
        {
            if(str[i] == 'C'){
                carlsenPoints += 2;
            }
            else if(str[i] == 'N'){
                chefPoints += 2;
            }
            else if(str[i] == 'D'){
                carlsenPoints++;
                chefPoints++;
            }
        }
        int sum;
        if(carlsenPoints > chefPoints){
            sum = 0.6 * prize;
        }
        else if(carlsenPoints == chefPoints){
            sum = 0.55 * prize;
        }
        else if(carlsenPoints < chefPoints){
            sum = 0.4 * prize;
        }
        cout << sum << endl;
    }
}
</code>```

The above solution works well. I'm having problems with the below solution, which gives 'WRONG ANSWER' in one test case.

```<code>#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int X;
        cin >> X;
        string str;
        cin >> str;
        int carlsenPoints = 0;
        int chefPoints = 0;
        for (int i = 0; i < str.length(); i++)
        {
            if(str[i] == 'C'){
                carlsenPoints += 2;
            }
            else if(str[i] == 'N'){
                chefPoints += 2;
            }
            else if(str[i] == 'D'){
                carlsenPoints++;
                chefPoints++;
            }
        }
        if(carlsenPoints > chefPoints){
            cout << 0.6 * 100 * X << endl;
        }
        else if(carlsenPoints == chefPoints){
            cout << 0.55 * 100 * X << endl;
        }
        else if(carlsenPoints < chefPoints){
            cout << 0.4 * 100 * X << endl;
        }
    }
}
</code>```

Why is the second solution resulting in an error?
To me, they're both pretty much same.

TL;DR :

How is:

```<code>int sum;
        int prize = 100*X;
        if(carlsenPoints > chefPoints){
            sum = 0.6 * prize;
        }
        else if(carlsenPoints == chefPoints){
            sum = 0.55 * prize;
        }
        else if(carlsenPoints < chefPoints){
            sum = 0.4 * prize;
        }
        cout << sum << endl;
</code>```

different from :

```<code>        if(carlsenPoints > chefPoints){
            cout << 0.6 * 100 * X << endl;
        }
        else if(carlsenPoints == chefPoints){
            cout << 0.55 * 100 * X << endl;
        }
        else if(carlsenPoints < chefPoints){
            cout << 0.4 * 100 * X << endl;
        }
</code>```

?

答:
In the first program the variable sum is declared as having the type int.

```<code>int sum;
</code>```

So this statement

```<code>cout << sum << endl;
</code>```

outputs an integer.

In the second program expressions like this

```<code>0.6 * 100 * X
</code>```

have the type double.

So this statement

```<code>cout << 0.6 * 100 * X << endl;
</code>```

outputs a floating point value.

Body:
I'm trying to solve this problem: https://www.codechef.com/FEB222C/problems/WCC

I've solved this problem and have successfully submitted the solution, but I'm getting 'WRONG ANSWER' error in an alternate approach in one test case:

My successful submission approach is:

#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int X;
        cin >> X;
        int prize = 100 * X;
        string str;
        cin >> str;
        int carlsenPoints = 0;
        int chefPoints = 0;
        for (int i = 0; i < str.length(); i++)
        {
            if(str[i] == 'C'){
                carlsenPoints += 2;
            }
            else if(str[i] == 'N'){
                chefPoints += 2;
            }
            else if(str[i] == 'D'){
                carlsenPoints++;
                chefPoints++;
            }
        }
        int sum;
        if(carlsenPoints > chefPoints){
            sum = 0.6 * prize;
        }
        else if(carlsenPoints == chefPoints){
            sum = 0.55 * prize;
        }
        else if(carlsenPoints < chefPoints){
            sum = 0.4 * prize;
        }
        cout << sum << endl;
    }
}

The above solution works well. I'm having problems with the below solution, which gives 'WRONG ANSWER' in one test case.

#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int X;
        cin >> X;
        string str;
        cin >> str;
        int carlsenPoints = 0;
        int chefPoints = 0;
        for (int i = 0; i < str.length(); i++)
        {
            if(str[i] == 'C'){
                carlsenPoints += 2;
            }
            else if(str[i] == 'N'){
                chefPoints += 2;
            }
            else if(str[i] == 'D'){
                carlsenPoints++;
                chefPoints++;
            }
        }
        if(carlsenPoints > chefPoints){
            cout << 0.6 * 100 * X << endl;
        }
        else if(carlsenPoints == chefPoints){
            cout << 0.55 * 100 * X << endl;
        }
        else if(carlsenPoints < chefPoints){
            cout << 0.4 * 100 * X << endl;
        }
    }
}

Why is the second solution resulting in an error?
To me, they're both pretty much same.

TL;DR :

How is:

int sum;
        int prize = 100*X;
        if(carlsenPoints > chefPoints){
            sum = 0.6 * prize;
        }
        else if(carlsenPoints == chefPoints){
            sum = 0.55 * prize;
        }
        else if(carlsenPoints < chefPoints){
            sum = 0.4 * prize;
        }
        cout << sum << endl;

different from :

        if(carlsenPoints > chefPoints){
            cout << 0.6 * 100 * X << endl;
        }
        else if(carlsenPoints == chefPoints){
            cout << 0.55 * 100 * X << endl;
        }
        else if(carlsenPoints < chefPoints){
            cout << 0.4 * 100 * X << endl;
        }

?

Body:
In the first program the variable sum is declared as having the type int.

int sum;

So this statement

cout << sum << endl;

outputs an integer.

In the second program expressions like this

0.6 * 100 * X

have the type double.

So this statement

cout << 0.6 * 100 * X << endl;

outputs a floating point value.


问:
How to retrieve the Request data from Post request that is triggered by Javascript
I am new to test Javascript. and the test is like this,

Load a page, then the Javascript is triggered, it fills the request payload data and then trigger the POST request with the generated payload data.  My test need to validate the payload data are right.
My problem is in the Chrome developer tool, I can see the POST request with Request Payload data. But I don't know how to get the Request payload data with any automation test tool or any other way.

答:
It's pretty simple with something like Cypress.

You can view the docs how to setup Cypress:
https://docs.cypress.io/guides/getting-started/installing-cypress

The test itself can be something like:

it('Should log the request body', () => {

  // start by intercepting the request
  cy.intercept('POST', '**/endpoint').as('interceptedRequest')

  // visit your url, and do some actions to trigger the request
  cy.visit('http://yoururl.com')

  // wait for your request to trigger
  cy.wait('@interceptedRequest')
    .its('request.body')
    .then((body) => {
      console.log(body)
    })
})
```


问:
Can't implement pagination in firebase website
Intenteded Functionality

I would like to be able to have pagination on my website. The way it'd work is that users would view the first 10 questions on the main page, then they could click a button to flip to the next page to see the next 10 questions. They should also be able to go in the reverse direction as well.

Method

Presumably, it'd be best to have two parameters in my listenForQuestions function called pageNumber and pageLength. pageLnegth would be the number of questions to display on a given page and pageNumber would be the actual page number to go to.
I tried using startAt, but this doesn't takes an actual value to limit by rather than just by limiting to the first n results of the query as I would want.

```<code>import { getAuth } from '@firebase/auth';
import {
  collection,
  doc,
  getDoc,
  getFirestore, limit, onSnapshot,
  orderBy,
  query,
  where,
  startAt,
  endAt
} from '@firebase/firestore';

export function listenForQuestions(options, callback) {
  let filters = [
        where('answerAccepted', '==', false),
        orderBy('bounty', 'desc'),
        orderBy('postedTimestamp', 'desc'),
    ];

  // filters.push(startAt(0), endAt(10)) // This doesn't seem to work???
  onSnapshot(
    query(collection(getFirestore(), 'questions'), ...filters),
    (snapshot) => {
      callback(snapshot.docs.map((doc) => doc.data()));
    }
  );
}
</code>```

答: Firestore pagination isn't based on offsets, but rather on a cursor - typically last item of the previous page. I recommend checking out the Firestore documentation on pagination with cursors or some of the previous questions on the pagination with firestore.</p>

Body:
Intenteded Functionality

I would like to be able to have pagination on my website. The way it'd work is that users would view the first 10 questions on the main page, then they could click a button to flip to the next page to see the next 10 questions. They should also be able to go in the reverse direction as well.

Method

Presumably, it'd be best to have two parameters in my listenForQuestions function called pageNumber and pageLength. pageLnegth would be the number of questions to display on a given page and pageNumber would be the actual page number to go to.
I tried using startAt, but this doesn't takes an actual value to limit by rather than just by limiting to the first n results of the query as I would want.

import { getAuth } from '@firebase/auth';
import {
  collection,
  doc,
  getDoc,
  getFirestore, limit, onSnapshot,
  orderBy,
  query,
  where,
  startAt,
  endAt
} from '@firebase/firestore';

export function listenForQuestions(options, callback) {
  let filters = [
        where('answerAccepted', '==', false),
        orderBy('bounty', 'desc'),
        orderBy('postedTimestamp', 'desc'),
    ];

  // filters.push(startAt(0), endAt(10)) // This doesn't seem to work???
  onSnapshot(
    query(collection(getFirestore(), 'questions'), ...filters),
    (snapshot) => {
      callback(snapshot.docs.map((doc) => doc.data()));
    }
  );
}


问:
How to display success message in Struts?
we could display errors in Struts by doing actionErrors.add(key, new Actionmessage("string")), addErrors(request, actionErrors); and then outputting it into a JSP page via

I'm wondering, how do I output success messages in Struts? How do you normally/conventionally do it?

答:
If you're using Struts2, you should be able to use addActionMessage instead of addActionError.

http://struts.apache.org/2.0.14/struts2-core/apidocs/com/opensymphony/xwork2/ValidationAwareSupport.html

Your post is missing what you were putting in your JSP, but if you add an action message, you can use the <s:actionmessage/> tag to display what you added.

http://struts.apache.org/2.0.14/docs/actionmessage.html

OwnerDisplayName: mamamambo

ContentLicense: CC BY-SA 2.5


问:
Need to link a website to the "OK" button
I'm not really well-versed with codes and I just wanted to try this out for my team.  What I have is just a simple code that pops up an alert message (with OK button) everytime we open our Google Spreadsheet.  What I wanted to happen is when we click "OK", it will open a link in a new tab.  Here's my "script editor" code:

```<code>function onOpen() {
 var ss= SpreadsheetApp.getActiveSpreadsheet();
 var ui = SpreadsheetApp.getUi().alert('Welcome to HAVENLY Offshore Team Workspace! Check out our CONFLUENCE updates today!');
}
</code>```

Please help me achieve my ultimate goal here, I've been trying to find a solution for hours already.  Thanks in advance!

答:
```<code>function onOpen(){
  confluencePopup()
}

function confluencePopup(){
  // will display the dialog box with html text
  var text = "Welcome to HAVENLY Offshore Team Workspace! Check out our CONFLUENCE updates today!'"
  var url = "https://stackoverflow.com/questions/40888267/need-to-link-a-website-to-the-ok-button"
  var rawHTML = '<a onclick="google.script.host.close()" target="_blank" href="' + String(url) + '">' + text + '</a>'
  var htmlSerivce = HtmlService.createHtmlOutput(rawHTML)
  SpreadsheetApp.getUi()
      .showModelessDialog(htmlSerivce, "Welcome")
}
</code>```

Change the url to your link, and text to the anchor text you would like. You can then just call this function in your onOpen() function. When run it will display a popup with your anchor text, and link to your page.

You may need to configure permissions to run the pop-up. See Google's documentation for that information. Simply you need to add oauthScopes to your appsscript.json file.

Edit: this can be altered to change the link dynamically with a variable, and does not require an additional file to run.

ContentLicense: CC BY-SA 3.0

Body:
I'm not really well-versed with codes and I just wanted to try this out for my team.  What I have is just a simple code that pops up an alert message (with OK button) everytime we open our Google Spreadsheet.  What I wanted to happen is when we click "OK", it will open a link in a new tab.  Here's my "script editor" code:

function onOpen() {
 var ss= SpreadsheetApp.getActiveSpreadsheet();
 var ui = SpreadsheetApp.getUi().alert('Welcome to HAVENLY Offshore Team Workspace! Check out our CONFLUENCE updates today!');
}

Please help me achieve my ultimate goal here, I've been trying to find a solution for hours already.  Thanks in advance!

Body:
function onOpen(){
  confluencePopup()
}

function confluencePopup(){
  // will display the dialog box with html text
  var text = "Welcome to HAVENLY Offshore Team Workspace! Check out our CONFLUENCE updates today!'"
  var url = "https://stackoverflow.com/questions/40888267/need-to-link-a-website-to-the-ok-button"
  var rawHTML = '<a onclick="google.script.host.close()" target="_blank" href="' + String(url) + '">' + text + '</a>'
  var htmlSerivce = HtmlService.createHtmlOutput(rawHTML)
  SpreadsheetApp.getUi()
      .showModelessDialog(htmlSerivce, "Welcome")
}

Change the url to your link, and text to the anchor text you would like. You can then just call this function in your onOpen() function. When run it will display a popup with your anchor text, and link to your page.

You may need to configure permissions to run the pop-up. See Google's documentation for that information. Simply you need to add oauthScopes to your appsscript.json file.

Edit: this can be altered to change the link dynamically with a variable, and does not require an additional file to run.


问:
How to move multiple buttons to the top right
I have 10 buttons and I would like to place the buttons on the top right, but I don't know how to do it? Currently my buttons are at the bottom, I don't know how to move my buttons?

I would like to get this result, (see below)

example

I think I need to use a display:flex ?

Do you have any idea, please?

Here is my code below

Thank you in advance for your help et your time.

<!DOCTYPE html>

      <title>HTML CSS JS</title>

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Signalétique

                           Ticker
                           SOLB

                           Code SVM
                           347075

                           Code ISIN
                           BE00003470755

                           Genre
                           Actions

                           Pays d'origine
                           Belgique

                           Secteur économique
                           Matériaux

                           Devise de cotation
                           EUR

                           Groupe de cotation
                           (AO)

                           Unité de cotation
                           1,0000000

                           Site Internet
                           www.solvay.com

                     <button type="button" class="btn btn-primary mb-2 ">Best Execution</button>
                     <button type="button" class="btn btn-primary mb-2">Etat du marché</button>
                     <button type="button" class="btn btn-primary mb-2">Graphiques Historiques</button>
                     <button type="button" class="btn btn-primary mb-2">Historique des cours</button>
                     <button type="button" class="btn btn-primary mb-2">Ordre</button>

                     <button type="button" class="btn btn-primary mb-2 ms-2">Best Execution</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Etat du marché</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Graphiques Historiques</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Historique des cours</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Ordre</button>

```

答:
Minor adjustments will need to be made to the columns, but here's a solution:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />

Signalétique

                    Ticker
                    SOLB

                    Code SVM
                    347075

                    Code ISIN
                    BE00003470755

                    Genre
                    Actions

                    Pays d'origine
                    Belgique

                    Secteur économique
                    Matériaux

                    Devise de cotation
                    EUR

                    Groupe de cotation
                    (AO)

                    Unité de cotation
                    1,0000000

                    Site Internet
                    www.solvay.com

                <button type="button" class="btn btn-primary mb-2">
                    Best Execution
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Etat du marché
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Graphiques Historiques
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Historique des cours
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Ordre
                  </button>

                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Best Execution
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Etat du marché
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Graphiques Historiques
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Historique des cours
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Ordre
                  </button>

```

Body:
Minor adjustments will need to be made to the columns, but here's a solution:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />

<body>
  <div class="home-content container">
    <h1 class="text-center pt-5 pb-3">Signalétique</h1>
    <div class="row pt-3 container">
      <div class="card" style="width: 100%;">
        <div class="card-body">
          <div class="row">
            <div class="col">
              <table class="table table-hover table-striped" style="width: 60%;">
                <tbody>
                  <tr>
                    <th>Ticker</th>
                    <td>SOLB</td>
                  </tr>
                  <tr>
                    <th>Code SVM</th>
                    <td>347075</td>
                  </tr>
                  <tr>
                    <th>Code ISIN</th>
                    <td>BE00003470755</td>
                  </tr>
                  <tr>
                    <th>Genre</th>
                    <td>Actions</td>
                  </tr>
                  <tr>
                    <th>Pays d'origine</th>
                    <td>Belgique</td>
                  </tr>
                  <tr>
                    <th>Secteur économique</th>
                    <td>Matériaux</td>
                  </tr>
                  <tr>
                    <th>Devise de cotation</th>
                    <td>EUR</td>
                  </tr>
                  <tr>
                    <th>Groupe de cotation</th>
                    <td>(AO)</td>
                  </tr>
                  <tr>
                    <th>Unité de cotation</th>
                    <td>1,0000000</td>
                  </tr>
                  <tr>
                    <th>Site Internet</th>
                    <td>www.solvay.com</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="col">
              <div class="btn-group-vertical">
                <button type="button" class="btn btn-primary mb-2">
                    Best Execution
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Etat du marché
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Graphiques Historiques
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Historique des cours
                  </button>
                <button type="button" class="btn btn-primary mb-2">
                    Ordre
                  </button>
              </div>
              <div class="btn-group-vertical">
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Best Execution
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Etat du marché
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Graphiques Historiques
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Historique des cours
                  </button>
                <button type="button" class="btn btn-primary mb-2 ms-2">
                    Ordre
                  </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>


问:
What is the billing for an aws s3 sync operation which makes no changes?
I have an aws s3 bucket with 10,000 files totally around 1GB in size.

I call:

```<code>aws s3 sync <remote bucket> <local folder> --exact-timestamps
</code>```

And no files are found to be changed, so no actual file downloads take place.

However, there must be data exchange for the sync - does anyone know how much?

答:
The ListObjects() API call returns a maximum of 1000 objects.

Therefore, the AWS CLI would require at least 10 API calls to retrieve information about 10,000 objects to determine whether files need to by sync'd.

However, since the cost of requests is only $0.005 per 1,000 requests, the cost would be quite small.

Body:
I have an aws s3 bucket with 10,000 files totally around 1GB in size.

I call:

aws s3 sync <remote bucket> <local folder> --exact-timestamps

And no files are found to be changed, so no actual file downloads take place.

However, there must be data exchange for the sync - does anyone know how much?


问:
BigQuery dynamic declare variable to the table name?
trying to figure out if I can declare a variable to then insert into part of the table name.

```<code>declare SiteLoc string default "04";

Select *
from FROM `gdw-prod-data.factory_04_data.YieldData`
</code>```

How can I swap out the '04' in the from table to another location, like 07, 15, etc?

答:
You can use EXECUTE_IMMEDIATE for this.

```<code>declare SiteLoc string default "04";

EXECUTE_IMMEDIATE (
  'Select * from FROM `gdw-prod-data.factory_' || SiteLoc || '_data.YieldData`'
);
</code>```

Body:
trying to figure out if I can declare a variable to then insert into part of the table name.

declare SiteLoc string default "04";

Select *
from FROM `gdw-prod-data.factory_04_data.YieldData`

How can I swap out the '04' in the from table to another location, like 07, 15, etc?

Body:
You can use EXECUTE_IMMEDIATE for this.

declare SiteLoc string default "04";

EXECUTE_IMMEDIATE (
  'Select * from FROM `gdw-prod-data.factory_' || SiteLoc || '_data.YieldData`'
);


问:
How to show number counts on terminal in linux
Please how can I count the list of numbers in a file

```<code>awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}'
</code>```

Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them.  Please how can I show the count of the numbers on the terminal for example

```<code>1-20,
2-22,
3-23,
4-24,
etc
</code>```

I know I can use wc but I don't know how to infuse it into the command above

答:
While I'm personally an awk fan, you might be glad to learn about grep -o functionality.  I'm using grep -o to match all numbers in the file, and then awk can be used to pick all the numbers between 0 and 25 (inclusive).  Last, we can use sort and uniq to count the results.

```<code>grep -o  "[0-9][0-9]*" file  |  awk ' $1 >= 0 && $1 <= 25 ' |  sort -n  | uniq -c
</code>```

Of course, you could do the counting in awk with an associative array as Ed Morton suggests:

```<code>egrep -o  "\d+" file |  awk ' $1 >= 0 && $1 <= 25 ' |  awk '{cnt[$1]++} END { for (i in cnt) printf("%s-%s\n",  i,cnt[i] ) } '
</code>```

I modified Ed's code (typically not a good idea - I've been reading his code for years now) to show a modular approach - an awk script for filtering numbers in the range of 0 and 25 and another awk script for counting a list (of anything).

I also provided another subtle difference from my first script with egrep instead of grep.

To be honest, the second awk script generates some unexpected output, but I wanted to share an example of a more general approach.  EDIT:  I applied Ed's suggestion to correct the unexpected output - it's fine now.

Body:
Please how can I count the list of numbers in a file

awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}'

Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them.  Please how can I show the count of the numbers on the terminal for example

1-20,
2-22,
3-23,
4-24,
etc

I know I can use wc but I don't know how to infuse it into the command above

Body:
While I'm personally an awk fan, you might be glad to learn about grep -o functionality.  I'm using grep -o to match all numbers in the file, and then awk can be used to pick all the numbers between 0 and 25 (inclusive).  Last, we can use sort and uniq to count the results.

grep -o  "[0-9][0-9]*" file  |  awk ' $1 >= 0 && $1 <= 25 ' |  sort -n  | uniq -c

Of course, you could do the counting in awk with an associative array as Ed Morton suggests:

egrep -o  "\d+" file |  awk ' $1 >= 0 && $1 <= 25 ' |  awk '{cnt[$1]++} END { for (i in cnt) printf("%s-%s\n",  i,cnt[i] ) } '

I modified Ed's code (typically not a good idea - I've been reading his code for years now) to show a modular approach - an awk script for filtering numbers in the range of 0 and 25 and another awk script for counting a list (of anything).

I also provided another subtle difference from my first script with egrep instead of grep.

To be honest, the second awk script generates some unexpected output, but I wanted to share an example of a more general approach.  EDIT:  I applied Ed's suggestion to correct the unexpected output - it's fine now.


问:
Why simple mysql++ code compiles standalone, but not in project?
At first, small program:

```<code>#include <mysql++.h>
using namespace mysqlpp;

void mainuu ()
{ Connection conn("mysql", "localhost", "root", "pwd");}
</code>```

If I compile it as one file in CodeLite or in such way:

```<code>g++ -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -o Test mysql_api.cpp
</code>```

it's ok
but, when I try to build whole project with this file I get this:

```<code>g++ -o ./Debug/server ./Debug/main.o ./Debug/log.o ./Debug/packet.o ./Debug/mysql_api.o  -L.
./Debug/mysql_api.o: In function `mainuu()':
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::Connection(char const*, char const*, char const*, char const*, unsigned int)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:12: undefined reference to `mysqlpp::Connection::query(char const*)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(char const*, bool)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::operator<<(mysqlpp::quote_type1, mysqlpp::SQLTypeAdapter const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:19: undefined reference to `mysqlpp::operator<<(std::basic_ostream<char, std::char_traits<char> >&, mysqlpp::String const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
./Debug/mysql_api.o: In function `mysqlpp::Row::operator[](int) const':
/usr/include/mysql++/row.h:328: undefined reference to `mysqlpp::Row::at(unsigned int) const'
./Debug/mysql_api.o: In function `mysqlpp::Query::store()':
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::str(mysqlpp::SQLQueryParms&)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::store(mysqlpp::SQLTypeAdapter const&)'
collect2: ld returned 1 exit status
make[1]: *** [Debug/server] Error 1
make[1]: Leaving directory `/home/asyler/.codelite/workspace/test/server'
make: *** [All] Error 2
</code>```

Here is CodeLite g++ compiler settings:

```<code>-g -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -L/usr/lib/mysql -L/usr/lib/mysql++ -lmysql++
</code>```

答:
Those are linker errors.

When you create your final executable, you still must provide references to all library functions, just as you did when you compiled the single translation unit.

So, pass -lmysqlclient -lmysqlpp to g++ this time, too.

If you are using an Integrated Development Environment, configure your project's build settings accordingly. In particular, I see that CodeLite has both "Compiler" and "Linker" build settings. It's "Linker" settings that you're after.

For more information on the build process (i.e. compiling, linking and the difference), read a good C++ book.

Body:
At first, small program:

#include <mysql++.h>
using namespace mysqlpp;

void mainuu ()
{ Connection conn("mysql", "localhost", "root", "pwd");}

If I compile it as one file in CodeLite or in such way:

g++ -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -o Test mysql_api.cpp

it's ok
but, when I try to build whole project with this file I get this:

g++ -o ./Debug/server ./Debug/main.o ./Debug/log.o ./Debug/packet.o ./Debug/mysql_api.o  -L.
./Debug/mysql_api.o: In function `mainuu()':
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::Connection(char const*, char const*, char const*, char const*, unsigned int)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:12: undefined reference to `mysqlpp::Connection::query(char const*)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(char const*, bool)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::operator<<(mysqlpp::quote_type1, mysqlpp::SQLTypeAdapter const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:19: undefined reference to `mysqlpp::operator<<(std::basic_ostream<char, std::char_traits<char> >&, mysqlpp::String const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
./Debug/mysql_api.o: In function `mysqlpp::Row::operator[](int) const':
/usr/include/mysql++/row.h:328: undefined reference to `mysqlpp::Row::at(unsigned int) const'
./Debug/mysql_api.o: In function `mysqlpp::Query::store()':
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::str(mysqlpp::SQLQueryParms&)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::store(mysqlpp::SQLTypeAdapter const&)'
collect2: ld returned 1 exit status
make[1]: *** [Debug/server] Error 1
make[1]: Leaving directory `/home/asyler/.codelite/workspace/test/server'
make: *** [All] Error 2

Here is CodeLite g++ compiler settings:

-g -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -L/usr/lib/mysql -L/usr/lib/mysql++ -lmysql++


答:
Try using a flexbox
First use main container then display it as flex and with some container and items properties you will get what you want
Display : flex
And proceed ....</p>

Title: How to move multiple buttons to the top right

Body:
I have 10 buttons and I would like to place the buttons on the top right, but I don't know how to do it? Currently my buttons are at the bottom, I don't know how to move my buttons?

I would like to get this result, (see below)

example

I think I need to use a display:flex ?

Do you have any idea, please?

Here is my code below

Thank you in advance for your help et your time.

<!DOCTYPE html>

      <title>HTML CSS JS</title>

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Signalétique

                           Ticker
                           SOLB

                           Code SVM
                           347075

                           Code ISIN
                           BE00003470755

                           Genre
                           Actions

                           Pays d'origine
                           Belgique

                           Secteur économique
                           Matériaux

                           Devise de cotation
                           EUR

                           Groupe de cotation
                           (AO)

                           Unité de cotation
                           1,0000000

                           Site Internet
                           www.solvay.com

                     <button type="button" class="btn btn-primary mb-2 ">Best Execution</button>
                     <button type="button" class="btn btn-primary mb-2">Etat du marché</button>
                     <button type="button" class="btn btn-primary mb-2">Graphiques Historiques</button>
                     <button type="button" class="btn btn-primary mb-2">Historique des cours</button>
                     <button type="button" class="btn btn-primary mb-2">Ordre</button>

                     <button type="button" class="btn btn-primary mb-2 ms-2">Best Execution</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Etat du marché</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Graphiques Historiques</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Historique des cours</button>
                     <button type="button" class="btn btn-primary mb-2 ms-2">Ordre</button>


问:
How to make the if else statement that will display the last satisfied statement
I am new to flutter and i want to display the last satisfied statement on this code.

```<code>   if (led.last.contains('SEAT: on'))...
     [const Icon(
      Icons.fingerprint,
      color: Colors.teal,
      size: 50,
   )]
   else if (led.last.contains('SEAT: off')) ...
    [const Icon(
      Icons.fingerprint,
      color: Colors.grey,
      size: 50,
   )
</code>```

My goal is that the icon will not disappear when the conditional statements are not satisfied.

答:
if you want just to change the color of the Icon according to a condition, you can do this :</p>
```<code>Icon(
  Icons.fingerprint,
  color: led.last.contains('SEAT: on') ? Colors.teal: Colors.grey ,
  size: 50,
)
</code>```

Body:
I am new to flutter and i want to display the last satisfied statement on this code.

   if (led.last.contains('SEAT: on'))...
     [const Icon(
      Icons.fingerprint,
      color: Colors.teal,
      size: 50,
   )]
   else if (led.last.contains('SEAT: off')) ...
    [const Icon(
      Icons.fingerprint,
      color: Colors.grey,
      size: 50,
   )

My goal is that the icon will not disappear when the conditional statements are not satisfied.

Body:
if you want just to change the color of the Icon according to a condition, you can do this :

Icon(
  Icons.fingerprint,
  color: led.last.contains('SEAT: on') ? Colors.teal: Colors.grey ,
  size: 50,
)


问:
Perform match if parameter is present in MongoAggregation
I have a aggregation pipeline where i'd like to perform a match only if the intended params is present. For example;

params = { fruit: 'apple', other_params.. }

In my aggregation pipeline:

Some.collection.aggregate([ { "$match": { fruit: params[:friut] } } ...other stages ])

So I'd like to run match stage only if i have fruit in params. can it be done?

Note that params is not a collection but some external request parameters.

答:
You can realize this via simple $or logic in the match stage:

```<code>db.collection.aggregate([
 {
  $match: {
   $or: [
    {
      fruit: {
        $exists: true,
        $eq: "apple"
      }
    },
    {
      fruit: {
        $exists: false
      }
    }
  ]
 }
}
])
</code>```

explained:

If the key fruit exist it will check if is equal to "apple"

If the key do not exist it will not do anything

playground

Body:
You can realize this via simple $or logic in the match stage:

db.collection.aggregate([
 {
  $match: {
   $or: [
    {
      fruit: {
        $exists: true,
        $eq: "apple"
      }
    },
    {
      fruit: {
        $exists: false
      }
    }
  ]
 }
}
])

explained:

If the key fruit exist it will check if is equal to "apple"

If the key do not exist it will not do anything

playground


问:
Set a fixed numerical ration between alternative sorted numbers
So I am working on a large text file made up of rows and rows of numbers,
below is just an short excerpt to help with the question, but it could even be a series of random incrementing numbers with all sorts of numerical gaps between each row.

```<code>267
368
758
936
1248
1415
1739
1917
</code>```

I am looking for a way to set a fixed numerical gap between every second pair of numbers starting on the 2nd and 3rd number. such as 100 whist maintaining the numerical difference within each pair but this difference could be any number.

Such that if the numerical gap was set to 100 the above example would become:

```<code>267
368
#      gap of 100
468
646
#      gap of 100
746
913
#      gap of 100
1013
1191
</code>```

would anybody know of a possible one liner to do this in terminal of a shell script. Thanks

答:
A little bit clumsy, but for starters this would do, I guess. It reads the list of numbers from stdin (i.e. start with cat numbers.txt or the like), then pipe it into the rest.

paste - - | {
        read -r x m;    echo $x;          echo $m
  while read -r x y; do echo $((m+=100)); echo $((m+=y-x)); done
}
```
```267
368
468
646
746
913
1013
1191
```
<p>Explanation: <code>paste - -</code> lets us read two numbers at once, so we can read line by line (two numbers). The first pair is printed out unchanged, but the subsequent pairs only serve as the base for calculating the diffrence, which is added onto a running variable, which also increments by <code>100</code> on each iteration.</p>
<hr />
<p>Here's a rewrite as parametrized function, and without the use of <code>paste</code>:</p>
<pre class="lang-sh prettyprint-override"><code>addgaps() {
  read -r m; echo $m; read -r m; echo $m
  while read -r x; read -r y; do echo $((m+=$1)); echo $((m+=y-x)); done;
}
</code>```

cat numbers.txt | addgaps 100
```

Body:
So I am working on a large text file made up of rows and rows of numbers,
below is just an short excerpt to help with the question, but it could even be a series of random incrementing numbers with all sorts of numerical gaps between each row.

267
368
758
936
1248
1415
1739
1917

I am looking for a way to set a fixed numerical gap between every second pair of numbers starting on the 2nd and 3rd number. such as 100 whist maintaining the numerical difference within each pair but this difference could be any number.

Such that if the numerical gap was set to 100 the above example would become:

267
368
#      gap of 100
468
646
#      gap of 100
746
913
#      gap of 100
1013
1191

would anybody know of a possible one liner to do this in terminal of a shell script. Thanks

Body:
A little bit clumsy, but for starters this would do, I guess. It reads the list of numbers from stdin (i.e. start with cat numbers.txt or the like), then pipe it into the rest.

paste - - | {
        read -r x m;    echo $x;          echo $m
  while read -r x y; do echo $((m+=100)); echo $((m+=y-x)); done
}

267
368
468
646
746
913
1013
1191

Explanation: paste - - lets us read two numbers at once, so we can read line by line (two numbers). The first pair is printed out unchanged, but the subsequent pairs only serve as the base for calculating the diffrence, which is added onto a running variable, which also increments by 100 on each iteration.

Here's a rewrite as parametrized function, and without the use of paste:

addgaps() {
  read -r m; echo $m; read -r m; echo $m
  while read -r x; read -r y; do echo $((m+=$1)); echo $((m+=y-x)); done;
}

cat numbers.txt | addgaps 100


问:
How to pipe a here-document through a command and capture the result into a variable?
Right now this outputs the value I need on stdout. How can I capture it into a variable so I can use it in the rest of the script?

Requirements:

The script needs to be all in one file.

I'd prefer not to write any temp files, if possible.

.

```<code>#!/bin/bash

cat << EOF | xsltproc - ../pom.xml | tail -1
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/"><xsl:value-of select="/project/version"/></xsl:template>
</xsl:stylesheet>
EOF
</code>```

答:
You don't need the tail -1 by adding omit-xml-declaration="yes":

VERSION=$(xsltproc - pom.xml << EOF
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mvn="http://maven.apache.org/POM/4.0.0">
<xsl:output method="text" omit-xml-declaration="yes"/>
<xsl:template match="/"><xsl:value-of select="mvn:project/mvn:version"/></xsl:template>
</xsl:stylesheet>
EOF
)
```

Body:
Right now this outputs the value I need on stdout. How can I capture it into a variable so I can use it in the rest of the script?

Requirements:

The script needs to be all in one file.

I'd prefer not to write any temp files, if possible.

.

#!/bin/bash

cat << EOF | xsltproc - ../pom.xml | tail -1
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/"><xsl:value-of select="/project/version"/></xsl:template>
</xsl:stylesheet>
EOF


问:
chrome extension manifest 3 https://apis.google.com
This line in manifest 3

```<code> "content_security_policy": {
    "extension_pages": "script-src 'self'; script-src-elem 'self' https://apis.google.com; object-src 'self';"
  },
</code>```

Gives me error

Refused to load the script 'https://apis.google.com/js/api.js?onload=__iframefcb41660' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I'm using google api for authentication with firebase. In manifest v2 all was fine.

答:
You cannot use external scripts in manifest V3, everything should be inside the extension.

Try using a fetch() if it's an API endpoint.

Body:
This line in manifest 3

 "content_security_policy": {
    "extension_pages": "script-src 'self'; script-src-elem 'self' https://apis.google.com; object-src 'self';"
  },

Gives me error

Refused to load the script 'https://apis.google.com/js/api.js?onload=__iframefcb41660' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I'm using google api for authentication with firebase. In manifest v2 all was fine.


问:
A task failed to un-serialize
I'm trying to evaluate an ANN. I get the accuracies if I use n_jobs = 1, however, when I use n_jobs = - 1 I get the following error.
    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

I have tried using other numbers but it only works if I use n_jobs = 1

This is the code I am running:
    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

This is the error I am getting:

```<code> Traceback (most recent call last):
 File "<ipython-input-12-cc51c2d2980a>", line 1, in <module>
 accuracies = cross_val_score(estimator = classifier, X = X_train,
 y = y_train, cv = 10, n_jobs = -1)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 402, in
 cross_val_score
 error_score=error_score)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 240, in
 cross_validate
 for train, test in cv.split(X, y, groups))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
 self.retrieve()

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
 self._output.extend(job.get(timeout=self.timeout))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in
 wrap_future_result
 return future.result(timeout=timeout)

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 432, in result
 return self.__get_result()

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 384, in __get_result
 raise self._exception

 BrokenProcessPool: A task has failed to un-serialize. Please ensure that
 the arguments of the function are all picklable.`
</code>```

Spyder should have analyzed each batch in parallel, but even when I use n_jobs = 1 it only analyzes 10 epochs.

答:
Got a similar error when I was using RandomizedSearchCV with all possible cores and threads. Realized that I am getting this error only when the number of combinations I was sampling from the parameter space is a less number like 5. When I selected a higher n_iter value, the issue was fixed. I believe it has something to with the fact that the number fits happening should be at least greater than the number cores and parallel compute units on your system
Hope this might help someone later.

Title: A task failed to un-serialize

Body:
I'm trying to evaluate an ANN. I get the accuracies if I use n_jobs = 1, however, when I use n_jobs = - 1 I get the following error.
    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

I have tried using other numbers but it only works if I use n_jobs = 1

This is the code I am running:
    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

This is the error I am getting:

 Traceback (most recent call last):
 File "<ipython-input-12-cc51c2d2980a>", line 1, in <module>
 accuracies = cross_val_score(estimator = classifier, X = X_train,
 y = y_train, cv = 10, n_jobs = -1)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 402, in
 cross_val_score
 error_score=error_score)

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\model_selection\_validation.py", line 240, in
 cross_validate
 for train, test in cv.split(X, y, groups))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
 self.retrieve()

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
 self._output.extend(job.get(timeout=self.timeout))

 File "C:\Users\javie\Anaconda3\lib\site-
 packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in
 wrap_future_result
 return future.result(timeout=timeout)

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 432, in result
 return self.__get_result()

 File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line
 384, in __get_result
 raise self._exception

 BrokenProcessPool: A task has failed to un-serialize. Please ensure that
 the arguments of the function are all picklable.`

Spyder should have analyzed each batch in parallel, but even when I use n_jobs = 1 it only analyzes 10 epochs.


问:
For the same set of values, how do I pull just one value from a different column in Excel?
For each set of PPIDs that has a “Delete” value and no “Reassign”, how would I populate the Intended Result column. In this example, I only need to populate “Delete” for PPIDS 123 and 789 because there is no “Reassign” value

答:
Assuming to start at A1 for PPID:
B1 cell should contain: if(and(a1=a2,b2=""),"Delete", "")
Copy that formula into all B cells.  The formulas will adjust the references.</p>


Title: For the same set of values, how do I pull just one value from a different column in Excel?

Body: For each set of PPIDs that has a “Delete” value and no “Reassign”, how would I populate the Intended Result column. In this example, I only need to populate “Delete” for PPIDS 123 and 789 because there is no “Reassign” value

Body:
In cell C2 try:

=IF($B2="Delete",IF(SUMPRODUCT(($A$2:$A$8=$A2)*($B$2:$B$8="Reassign"))=0,"Delete",""),"")


问:
VSCode/TextMate syntax highlighting grammar -- matching code until end of line
I am writing a TextMate grammar to implement syntax highlighting in VSCode for a custom flavor of Markdown. I would like everything on the same line after @@$  to be highlighted as Javascript.

This is what I came up with:

"majsdown_execute_statement": {
    "begin": "(.*?)(@@\\$)",
    "name": "test",
    "end": "(\\r\\n|\\r|\\n)",
    "beginCaptures": {
        "2": {
            "name": "keyword.control.majsdown"
        }
    },
    "patterns": [
        {
            "include": "source.js"
        }
    ]
},
```
<p>That <em>almost</em> works:</p>
<p><img src="https://i.stack.imgur.com/41lsU.png" alt="what happens" /></p>
<p>But I would like the <code>@@$</code> part to always be highlighted as a keyword. Here's a mockup (edited image) of my desired result:</p>
<p><img src="https://i.stack.imgur.com/NWrZM.png" alt="what I would like" /></p>
<p>I've tried a lot of different combinations of <code>"begin"</code> and <code>"end"</code>, and I've also tried many nested patterns like the following one:</p>
<pre class="lang-json prettyprint-override"><code>"patterns": [
    {
        "begin": "\\s",
        "while": "^(\\r\\n|\\r|\\n)",
        "patterns": [
            {
                "include": "source.js"
            }
        ]
    }
]
</code>```

Unfortunately, nothing provides the result I desire. How can I achieve my desired result?

答:
try using match instead...

"patterns": [
        {
          "name": "keyword.control.factory",
          "match": "(\\w|-)[^(]*"
        }
      ]
```
<p>this code matches everything up to a "(" character</p>
<p>so your code look something like this:</p>
<pre class="lang-json prettyprint-override"><code>"majsdown_execute_statement": {
    "patterns": [
        {
          "name": "keyword.control.majsdown",
          "match": "(?<=@@\$)\\w*"
        }
      ]
    }
</code>```

you can also try [^@@$]*(\\w)

try it out here

Body:
I am writing a TextMate grammar to implement syntax highlighting in VSCode for a custom flavor of Markdown. I would like everything on the same line after @@$  to be highlighted as Javascript.

This is what I came up with:

"majsdown_execute_statement": {
    "begin": "(.*?)(@@\\$)",
    "name": "test",
    "end": "(\\r\\n|\\r|\\n)",
    "beginCaptures": {
        "2": {
            "name": "keyword.control.majsdown"
        }
    },
    "patterns": [
        {
            "include": "source.js"
        }
    ]
},

That almost works:

But I would like the @@$ part to always be highlighted as a keyword. Here's a mockup (edited image) of my desired result:

I've tried a lot of different combinations of "begin" and "end", and I've also tried many nested patterns like the following one:

"patterns": [
    {
        "begin": "\\s",
        "while": "^(\\r\\n|\\r|\\n)",
        "patterns": [
            {
                "include": "source.js"
            }
        ]
    }
]

Unfortunately, nothing provides the result I desire. How can I achieve my desired result?

Body:
try using match instead...

"patterns": [
        {
          "name": "keyword.control.factory",
          "match": "(\\w|-)[^(]*"
        }
      ]

this code matches everything up to a "(" character

so your code look something like this:

"majsdown_execute_statement": {
    "patterns": [
        {
          "name": "keyword.control.majsdown",
          "match": "(?<=@@\$)\\w*"
        }
      ]
    }

you can also try [^@@$]*(\\w)

try it out here


问:
Convincing R that the .dbf file associated with a .shp file is not an executable during command checks
I am working on submitting an R package to CRAN. Right now I am trying to reduce the memory footprint of the package. Because this package deals with spatial data that has a very particular format, I want to include a properly formatted shapefile as an example. If I include the full-size original shapefile, there are no warnings (other than file size) in the R CMD checks. However, if I crop the file and include the cropped version in the package (in "inst/extdata") I get this warning:

```<code>W  checking for executable files (389ms)
   Found the following executable file:
     inst/extdata/temp/temp.dbf
   Source packages should not contain undeclared executable files.
   See section ‘Package structure’ in the ‘Writing R Extensions’ manual.
</code>```

This file is the database file associated with the shapefile. I have tried cropping the file and saving it using rgdal functions, sf functions, and using QGIS. I have also verified that the modes of the cropped files match the original file using chmod. I even tried changing .dbf to .DBF. Does anyone have any additional suggestions, other than listing it in BinaryFiles, which CRAN will not accept in a submission?

I'm running R version 4.0.2 via RStudio 2021.09.1 on Mac OSX 10.15.7. rgdal and sf are fully updated, as are all of their dependencies.

答:
This is a known issue[1] where file will mis-identify DBF files with last-update date in the year 2022. Easiest fix is to not use a 2022 update date when saving the file. Alternatively you can simply change the second byte of the file after the fact, e.g.:

fn = "myfile.dbf"
sz = file.info(fn)$size
r = readBin(fn, raw(), sz)
r[2] = as.raw(121) ## make it 2021 instead of 2022
writeBin(r, fn)
```

(See also corresponding discussion on R-package-devel)

Body:
I am working on submitting an R package to CRAN. Right now I am trying to reduce the memory footprint of the package. Because this package deals with spatial data that has a very particular format, I want to include a properly formatted shapefile as an example. If I include the full-size original shapefile, there are no warnings (other than file size) in the R CMD checks. However, if I crop the file and include the cropped version in the package (in "inst/extdata") I get this warning:

W  checking for executable files (389ms)
   Found the following executable file:
     inst/extdata/temp/temp.dbf
   Source packages should not contain undeclared executable files.
   See section ‘Package structure’ in the ‘Writing R Extensions’ manual.

This file is the database file associated with the shapefile. I have tried cropping the file and saving it using rgdal functions, sf functions, and using QGIS. I have also verified that the modes of the cropped files match the original file using chmod. I even tried changing .dbf to .DBF. Does anyone have any additional suggestions, other than listing it in BinaryFiles, which CRAN will not accept in a submission?

I'm running R version 4.0.2 via RStudio 2021.09.1 on Mac OSX 10.15.7. rgdal and sf are fully updated, as are all of their dependencies.

Body:
This is a known issue[1] where file will mis-identify DBF files with last-update date in the year 2022. Easiest fix is to not use a 2022 update date when saving the file. Alternatively you can simply change the second byte of the file after the fact, e.g.:

fn = "myfile.dbf"
sz = file.info(fn)$size
r = readBin(fn, raw(), sz)
r[2] = as.raw(121) ## make it 2021 instead of 2022
writeBin(r, fn)

(See also corresponding discussion on R-package-devel)


问:
Rails click on div to upload image
```<code>    <div id="photo_attachment_container">
        <%= f.file_field :photo %>
    </div>
</code>```

Currently this is how my standard image upload button looks in rails. I would like to improve it aesthetically by having a div on the page with a background image as placeholder, and people can click on that div to upload an image (the function currently provided by the button) and when the image is uploaded it becomes the background of the div.

Also paperclip handles the upload and can resize to the size of the div.

How can I do something like this in rails? Thanks

答:
If you want to show a browse file prompt you have to use a form file input.

What you can do is position the file input absolutely within the div and track the mouse around the div when it moves. That way, wherever the mouse clicks on the div, the file input will be under the mouse and show the browser prompt.

You can then hide the file input using opacity 0.

Obviously this method requires javascript.

You can then apply an onchange listener to the file input so that on selection of a file it submits the form to a hidden iframe. The server uploads the image in the iframe and then prints something like

```<code>window.top.returnFileUrl('new-file-name.jpg');
</code>```

If this function is defined in the parent window....

```<code>function returnFileUrl(url)
{
    document.getElementById('image-div').style.background = 'url('+url+')';
}
</code>```

That is untested code to point you in the right direction.

Title: Rails click on div to upload image

Body:
        <%= f.file_field :photo %>

Currently this is how my standard image upload button looks in rails. I would like to improve it aesthetically by having a div on the page with a background image as placeholder, and people can click on that div to upload an image (the function currently provided by the button) and when the image is uploaded it becomes the background of the div.

Also paperclip handles the upload and can resize to the size of the div.

How can I do something like this in rails? Thanks

Body:
If you want to show a browse file prompt you have to use a form file input.

What you can do is position the file input absolutely within the div and track the mouse around the div when it moves. That way, wherever the mouse clicks on the div, the file input will be under the mouse and show the browser prompt.

You can then hide the file input using opacity 0.

Obviously this method requires javascript.

You can then apply an onchange listener to the file input so that on selection of a file it submits the form to a hidden iframe. The server uploads the image in the iframe and then prints something like

window.top.returnFileUrl('new-file-name.jpg');

If this function is defined in the parent window....

function returnFileUrl(url)
{
    document.getElementById('image-div').style.background = 'url('+url+')';
}

That is untested code to point you in the right direction.


问:
Using conda environments after copying entire home dir
I had miniconda3 installed in ~/miniconda. I had to reinstall my OS, so I had the entire home directory backed up. After that, I copied (most) dirs back into the newly created home dir. As well as .bashrc (which contains a few lines that make sure conda ends up on the $PATH). Pretty much everything else is the same (same distro, python still installed, the same username).

When trying to run any conda command, I get the error bash: /home/andrei/miniconda3/bin/conda: Permission denied. I tried running sudo chown -R andrei:andrei miniconda3 in ~, but I still get the same error when trying to run any conda command.

How would I fix this?

I would prefer to just access the environments I have, as some of the packages were actually compiled/took a very long time to download.

答: Turns out the solution was sudo chmod -R 777 miniconda3. Not sure why no other answer on SO mentioned it.


问:
Regex to get 00 if the string has less digits
I have a column that is giving me output like 'ABC2001' , 'ABC100145', 'ABC009282' ,' ABC1901'

I want to change this column value to have '00' in between literals and numbers if number is less than 6 digits. Something like -

```<code>COL_A
------------
ABC2001
ABC100145
ABC009282
ABC1901
</code>```

Expected output

```<code>COL_B
------------
ABC002001
ABC100145
ABC009282
ABC001901
</code>```

How to use regex for this ? Currently I am using

```<code>SELECT SUBSTR(COL_A,1,3)||LPAD(REGEXP_REPLACE(COL_A,'\D+'),6,'0') FROM TAB
</code>```

and it is giving me output like -

```<code>ABC210073
ABC210073
</code>```

答:
Just for fun, for different prefixes:

usual string functions: trim/lpad/substr:

with table_name (col_a) AS (
SELECT 'ABC2001'   FROM DUAL UNION ALL
SELECT 'ABC100145' FROM DUAL UNION ALL
SELECT 'ABC009282' FROM DUAL UNION ALL
SELECT 'ABC1901'   FROM DUAL UNION ALL
-- other different prefixes:
select 'ABC2001'     from dual union all
select 'AB100145'    from dual union all
select 'A-BC9282'    from dual union all
select 'A8C2374'     from dual union all
select '7x-ABC32129' from dual union all
select '123ABC8942'  from dual
)
select v.*, prefix||num as col_b
from (
    select
      col_a,
      rtrim(col_a,'0123456789') as prefix,
      lpad(substr(col_a,1+length(rtrim(col_a,'0123456789'))),6,'0') as num
    from table_name
) v
;
```
<p>DBFiddle</p>
<ol start="2">
<li>using regex functions:</li>
</ol>
<pre class="lang-sql prettyprint-override"><code>with table_name (col_a) AS (
SELECT 'ABC2001'   FROM DUAL UNION ALL
SELECT 'ABC100145' FROM DUAL UNION ALL
SELECT 'ABC009282' FROM DUAL UNION ALL
SELECT 'ABC1901'   FROM DUAL UNION ALL
-- other different prefixes:
select 'ABC2001'     from dual union all
select 'AB100145'    from dual union all
select 'A-BC9282'    from dual union all
select 'A8C2374'     from dual union all
select '7x-ABC32129' from dual union all
select '123ABC8942'  from dual
)
select
    col_a,
    regexp_replace(
       regexp_replace(col_a,'(\d+)$','00000\1')
      ,'0*(\d{6})$'
      ,'\1'
    ) as col_b
from table_name
;
</code>```

DBFiddle

regex solution for padding numbers to the maximum their length, ie not knowing max numbers length(if it's not hard-coded 6):

```<code>select
    v.*,
    regexp_replace(
       regexp_replace(col_a,'(\d+)$',rpad('0',max_num_length,'0')||'\1')
      ,'0*(\d{'||max_num_length||'})$'
      ,'\1'
    ) as col_b
from (
    select t.*, max(length(regexp_substr(col_a,'\d+$')))over() as max_num_length
    from table_name t
) v
;
</code>```

DBFiddle

Body:
I have a column that is giving me output like 'ABC2001' , 'ABC100145', 'ABC009282' ,' ABC1901'

I want to change this column value to have '00' in between literals and numbers if number is less than 6 digits. Something like -

COL_A
------------
ABC2001
ABC100145
ABC009282
ABC1901

Expected output

COL_B
------------
ABC002001
ABC100145
ABC009282
ABC001901

How to use regex for this ? Currently I am using

SELECT SUBSTR(COL_A,1,3)||LPAD(REGEXP_REPLACE(COL_A,'\D+'),6,'0') FROM TAB

and it is giving me output like -

ABC210073
ABC210073

Body:
Just for fun, for different prefixes:

usual string functions: trim/lpad/substr:

with table_name (col_a) AS (
SELECT 'ABC2001'   FROM DUAL UNION ALL
SELECT 'ABC100145' FROM DUAL UNION ALL
SELECT 'ABC009282' FROM DUAL UNION ALL
SELECT 'ABC1901'   FROM DUAL UNION ALL
-- other different prefixes:
select 'ABC2001'     from dual union all
select 'AB100145'    from dual union all
select 'A-BC9282'    from dual union all
select 'A8C2374'     from dual union all
select '7x-ABC32129' from dual union all
select '123ABC8942'  from dual
)
select v.*, prefix||num as col_b
from (
    select
      col_a,
      rtrim(col_a,'0123456789') as prefix,
      lpad(substr(col_a,1+length(rtrim(col_a,'0123456789'))),6,'0') as num
    from table_name
) v
;

DBFiddle

using regex functions:

with table_name (col_a) AS (
SELECT 'ABC2001'   FROM DUAL UNION ALL
SELECT 'ABC100145' FROM DUAL UNION ALL
SELECT 'ABC009282' FROM DUAL UNION ALL
SELECT 'ABC1901'   FROM DUAL UNION ALL
-- other different prefixes:
select 'ABC2001'     from dual union all
select 'AB100145'    from dual union all
select 'A-BC9282'    from dual union all
select 'A8C2374'     from dual union all
select '7x-ABC32129' from dual union all
select '123ABC8942'  from dual
)
select
    col_a,
    regexp_replace(
       regexp_replace(col_a,'(\d+)$','00000\1')
      ,'0*(\d{6})$'
      ,'\1'
    ) as col_b
from table_name
;

DBFiddle

regex solution for padding numbers to the maximum their length, ie not knowing max numbers length(if it's not hard-coded 6):

select
    v.*,
    regexp_replace(
       regexp_replace(col_a,'(\d+)$',rpad('0',max_num_length,'0')||'\1')
      ,'0*(\d{'||max_num_length||'})$'
      ,'\1'
    ) as col_b
from (
    select t.*, max(length(regexp_substr(col_a,'\d+$')))over() as max_num_length
    from table_name t
) v
;

DBFiddle


问:
Solve for q: (log(n))^q = log(log(n))
I'm proving the big O runtime of an algorithm for an assignment but am unfortunately quite rusty when it comes to logs. Currently, I have:

(log(n))^q <= log(log(n))

I am trying to isolate q in terms of n (where I'm hoping n will cancel out). Can someone please explain to me how to do this (and not just provide an answer)? Thanks!

答:
This would've been prettier on math stackexchange (because we can use latex), but you can just log both sides to bring the q exponent down (since log(x^n) = nlog(x) is a property of logs over the reals):

q log(log(n)) <= log(log(log(n)))

Now you can divide both sides to isolate q:

q <= log(log(log(n)))/log(log(n))

Title: Solve for q: (log(n))^q = log(log(n))


问:
How can I automatically change directory on ssh.exe login?
I'm trying to get ssh.exe to open an ssh session in the specific direrecory on the remote server.

my command: ssh.exe root@1.1.1.1 -p 22 "cd /home && bash"
it works, but I didnt got login message and the root@1.1.1.1:~# prefix

how it looks

答:
solved with replace && to \;
my final batch (maybe)

```<code>@echo off
%USERPROFILE%\AppData\Local\Microsoft\WindowsApps\wt.exe --title %6 ssh %3 -p %4 -t "cd %5 \; bash --login"
</code>```

Body:
solved with replace && to \;
my final batch (maybe)

@echo off
%USERPROFILE%\AppData\Local\Microsoft\WindowsApps\wt.exe --title %6 ssh %3 -p %4 -t "cd %5 \; bash --login"


答:
Mongodb queries are javascript objects, so you can construct them easy and dynamically, with code, based on the params you got.

If you want all params to be part of the match you can do something like.

Some.collection.aggregate([ { "$match": params } ...other stages ])

//params is variable that ou already have
//params = { fruit: 'apple', other_params.. }
```
<p>If you want some params to be part of the match you can do something like</p>
<pre class="lang-js prettyprint-override"><code>var matchQuery={};
if(params has "fruit") matchQuery["fruit"]=params["fruit"];
//.....you can do this for all the parameters.....

Some.collection.aggregate([ { "$match": matchQuery } ...other stages ])
</code>```

Alternative instead of starting with {} you can remove from params the pairs that shouldnt be part of the matchQuery.

Title: Perform match if parameter is present in MongoAggregation

Body:
I have a aggregation pipeline where i'd like to perform a match only if the intended params is present. For example;

params = { fruit: 'apple', other_params.. }

In my aggregation pipeline:

Some.collection.aggregate([ { "$match": { fruit: params[:friut] } } ...other stages ])

So I'd like to run match stage only if i have fruit in params. can it be done?

Note that params is not a collection but some external request parameters.

Body:
Mongodb queries are javascript objects, so you can construct them easy and dynamically, with code, based on the params you got.

If you want all params to be part of the match you can do something like.

Some.collection.aggregate([ { "$match": params } ...other stages ])

//params is variable that ou already have
//params = { fruit: 'apple', other_params.. }

If you want some params to be part of the match you can do something like

var matchQuery={};
if(params has "fruit") matchQuery["fruit"]=params["fruit"];
//.....you can do this for all the parameters.....

Some.collection.aggregate([ { "$match": matchQuery } ...other stages ])

Alternative instead of starting with {} you can remove from params the pairs that shouldnt be part of the matchQuery.