问:
flutter unable to run project in ios simulator
Error output from Xcode build:
↳
** BUILD FAILED **

Xcode's output:
↳
Writing result bundle at path:
/var/folders/s5/4_qqjtfs4xb49hsqkc0zxbp80000gn/T/flutter_tools.WfBuSW/flutt
er_ios_build_temp_dirLqqAmi/temporary_xcresult_bundle

```<code>Failed to package /Users/striky/Desktop/PROJECTS/todolist.
Command PhaseScriptExecution failed with a nonzero exit code
note: Building targets in dependency order
note: Removed stale file
'/Users/striky/Library/Developer/Xcode/DerivedData/Runner-hdulzpfkpeuryafona
wcbytfruum/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Ru
nner.build/DerivedSources/Pods-Runner-checkManifestLockResult.txt'

note: Removed stale file
'/Users/striky/Library/Developer/Xcode/DerivedData/Runner-hdulzpfkpeuryafona
wcbytfruum/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Ru
nner.build/Script-1539170295D304EE9D220D88.sh'

warning: Run script build phase 'Run Script' will be run during every build
because it does not specify any outputs. To address this warning, either add
output dependencies to the script phase, or configure it to run in every
build by unchecking "Based on dependency analysis" in the script phase. (in
target 'Runner' from project 'Runner')
warning: Run script build phase 'Thin Binary' will be run during every build
because it does not specify any outputs. To address this warning, either add
output dependencies to the script phase, or configure it to run in every
build by unchecking "Based on dependency analysis" in the script phase. (in
target 'Runner' from project 'Runner')

Result bundle written to path:
    /var/folders/s5/4_qqjtfs4xb49hsqkc0zxbp80000gn/T/flutter_tools.WfBuSW/flutt
    er_ios_build_temp_dirLqqAmi/temporary_xcresult_bundle
</code>```

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.

my flutter doctor -v

[✓] Flutter (Channel stable, 3.3.10, on macOS 13.1 22C65 darwin-arm (Rosetta),
locale en-MY)
• Flutter version 3.3.10 on channel stable at /Users/striky/flutter 2
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 135454af32 (4 weeks ago), 2022-12-15 07:36:55 -0800
• Engine revision 3316dd8728
• Dart version 2.18.6
• DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
• Android SDK at /Users/striky/Library/Android/sdk
• Platform android-33, build-tools 33.0.1
• Java binary at: /Applications/Android
Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 14C18
• CocoaPods version 1.11.3

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.74.2)
• VS Code at /Users/striky/Desktop/Visual Studio Code.app/Contents
• Flutter extension version 3.56.0

[✓] Connected device (3 available)
• iPhone 14 Pro Max (mobile) • 39508EF8-CD30-49F2-8FF2-F124A0F25CE5 • ios
• com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
• macOS (desktop)            • macos                                •
darwin-arm64   • macOS 13.1 22C65 darwin-arm (Rosetta)
• Chrome (web)               • chrome                               •
web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
• All required HTTP hosts are available

• No issues found!

Body:
Error output from Xcode build:
↳
** BUILD FAILED **

Xcode's output:
↳
Writing result bundle at path:
/var/folders/s5/4_qqjtfs4xb49hsqkc0zxbp80000gn/T/flutter_tools.WfBuSW/flutt
er_ios_build_temp_dirLqqAmi/temporary_xcresult_bundle

Failed to package /Users/striky/Desktop/PROJECTS/todolist.
Command PhaseScriptExecution failed with a nonzero exit code
note: Building targets in dependency order
note: Removed stale file
'/Users/striky/Library/Developer/Xcode/DerivedData/Runner-hdulzpfkpeuryafona
wcbytfruum/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Ru
nner.build/DerivedSources/Pods-Runner-checkManifestLockResult.txt'

note: Removed stale file
'/Users/striky/Library/Developer/Xcode/DerivedData/Runner-hdulzpfkpeuryafona
wcbytfruum/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Ru
nner.build/Script-1539170295D304EE9D220D88.sh'

warning: Run script build phase 'Run Script' will be run during every build
because it does not specify any outputs. To address this warning, either add
output dependencies to the script phase, or configure it to run in every
build by unchecking "Based on dependency analysis" in the script phase. (in
target 'Runner' from project 'Runner')
warning: Run script build phase 'Thin Binary' will be run during every build
because it does not specify any outputs. To address this warning, either add
output dependencies to the script phase, or configure it to run in every
build by unchecking "Based on dependency analysis" in the script phase. (in
target 'Runner' from project 'Runner')

Result bundle written to path:
    /var/folders/s5/4_qqjtfs4xb49hsqkc0zxbp80000gn/T/flutter_tools.WfBuSW/flutt
    er_ios_build_temp_dirLqqAmi/temporary_xcresult_bundle

Could not build the application for the simulator.
Error launching application on iPhone 14 Pro Max.

my flutter doctor -v

[✓] Flutter (Channel stable, 3.3.10, on macOS 13.1 22C65 darwin-arm (Rosetta),
locale en-MY)
• Flutter version 3.3.10 on channel stable at /Users/striky/flutter 2
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 135454af32 (4 weeks ago), 2022-12-15 07:36:55 -0800
• Engine revision 3316dd8728
• Dart version 2.18.6
• DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
• Android SDK at /Users/striky/Library/Android/sdk
• Platform android-33, build-tools 33.0.1
• Java binary at: /Applications/Android
Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 14C18
• CocoaPods version 1.11.3

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.74.2)
• VS Code at /Users/striky/Desktop/Visual Studio Code.app/Contents
• Flutter extension version 3.56.0

[✓] Connected device (3 available)
• iPhone 14 Pro Max (mobile) • 39508EF8-CD30-49F2-8FF2-F124A0F25CE5 • ios
• com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
• macOS (desktop)            • macos                                •
darwin-arm64   • macOS 13.1 22C65 darwin-arm (Rosetta)
• Chrome (web)               • chrome                               •
web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
• All required HTTP hosts are available

• No issues found!


来源: stackexchange

问:
Power BI slicer based on date
I am struggling to manage to set up a slicer in Power BI on date column.

The problem I have is that I have a table with SalesDate so I created a table with client name and date of last sale.

Then I added a slicer on date column and here I am stuck.

I would like to be able to mark date into a slicer so the table returned me all the customers who DID NOT buy anything from a specific amount of time: last three months for example.
By default slicer shows me those transactions who did happen in the period I provide to a slicer.

Can I do it in anyway?

ContentLicense: CC BY-SA 4.0

Title: Power BI slicer based on date


问:
Angular getting TypeError: You provided an invalid object where a stream was expected
I am using Angular 11 and having a get method in a service as below.

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

```<code>get<T>(url: string, params: HttpParams = null): Observable<T> {
    const httpOptions: any = {
        headers: this.getHeaders(),
        params: params
    };
    return this.httpClient.get(this.apiPath + url, httpOptions)
        .pipe(
            catchError((httpResponse: HttpResponse<T>) => {
                return this.getError(httpResponse);
            }));
}

private getError(res: HttpResponse<any>): Observable<any> {
    return throwError(() => new Error(`Server error: ${res.statusText} (${res.status})`));
}
</code>```

The above code keep throwing eerror inside getError method saying

```<code>TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable
</code>```

Can anyone please let me know what am i doing wrong?

Thanks

Body:
I am using Angular 11 and having a get method in a service as below.

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

get<T>(url: string, params: HttpParams = null): Observable<T> {
    const httpOptions: any = {
        headers: this.getHeaders(),
        params: params
    };
    return this.httpClient.get(this.apiPath + url, httpOptions)
        .pipe(
            catchError((httpResponse: HttpResponse<T>) => {
                return this.getError(httpResponse);
            }));
}

private getError(res: HttpResponse<any>): Observable<any> {
    return throwError(() => new Error(`Server error: ${res.statusText} (${res.status})`));
}

The above code keep throwing eerror inside getError method saying

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

Can anyone please let me know what am i doing wrong?

Thanks


问:
accessibilityIdentifier not working the same starting with iOS 15
The app on which I am working has it's ui tested using Appium. Because of this, I set accessibility identifiers on views.

```<code>struct RootView: View {
    var body: some View {
        VStack {
            Text("some text")
            Text("more text")
        }
        // wrapper 1
        .accessibilityElement(children: .contain)
        .accessibilityIdentifier("ID 1111111111111")
        // wrapper 2
        .accessibilityElement(children: .contain)
        .accessibilityIdentifier("ID 2222222222222")
    }
}
</code>```

(the code is oversimplified to ease the understanding of the problem)

Running the code above on iOS 14 would output this on Appium Inspector when inspecting the views:

```<code> <XCUIElementTypeOther type="XCUIElementTypeOther" name="ID 2222222222222" enabled="true" visible="true" accessible="false" x="157" y="408" width="76" height="41" index="0">
              <XCUIElementTypeOther type="XCUIElementTypeOther" name="ID 1111111111111" enabled="true" visible="true" accessible="false" x="157" y="408" width="76" height="41" index="0">
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="some text" name="some text" label="some text" enabled="true" visible="true" accessible="true" x="157" y="408" width="76" height="21" index="0"/>
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="more text" name="more text" label="more text" enabled="true" visible="true" accessible="true" x="159" y="428" width="73" height="21" index="1"/>
              </XCUIElementTypeOther>
            </XCUIElementTypeOther>
</code>```

So each group of accessibilityElement and accessibilityIdentifier would create a XCUIElementTypeOther with the same name property as the id set by accessibilityIdentifier.

With iOS 15/16 these are not working anymore, here is the output on Appium Inspector when inspecting the views:

```<code><XCUIElementTypeOther type="XCUIElementTypeOther" name="ID 2222222222222" enabled="true" visible="true" accessible="false" x="157" y="408" width="76" height="41" index="0">
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="some text" name="some text" label="some text" enabled="true" visible="true" accessible="true" x="157" y="408" width="76" height="21" index="0"/>
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="more text" name="more text" label="more text" enabled="true" visible="true" accessible="true" x="158" y="428" width="74" height="21" index="1"/>
              </XCUIElementTypeOther>
</code>```

It looks like the first group of accessibilityElement and accessibilityIdentifier is no longer generating an XCUIElementTypeOther.

Is there a way to have the same output of iOS 14 on iOS 15/16?

Body:
The app on which I am working has it's ui tested using Appium. Because of this, I set accessibility identifiers on views.

struct RootView: View {
    var body: some View {
        VStack {
            Text("some text")
            Text("more text")
        }
        // wrapper 1
        .accessibilityElement(children: .contain)
        .accessibilityIdentifier("ID 1111111111111")
        // wrapper 2
        .accessibilityElement(children: .contain)
        .accessibilityIdentifier("ID 2222222222222")
    }
}

(the code is oversimplified to ease the understanding of the problem)

Running the code above on iOS 14 would output this on Appium Inspector when inspecting the views:

 <XCUIElementTypeOther type="XCUIElementTypeOther" name="ID 2222222222222" enabled="true" visible="true" accessible="false" x="157" y="408" width="76" height="41" index="0">
              <XCUIElementTypeOther type="XCUIElementTypeOther" name="ID 1111111111111" enabled="true" visible="true" accessible="false" x="157" y="408" width="76" height="41" index="0">
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="some text" name="some text" label="some text" enabled="true" visible="true" accessible="true" x="157" y="408" width="76" height="21" index="0"/>
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="more text" name="more text" label="more text" enabled="true" visible="true" accessible="true" x="159" y="428" width="73" height="21" index="1"/>
              </XCUIElementTypeOther>
            </XCUIElementTypeOther>

So each group of accessibilityElement and accessibilityIdentifier would create a XCUIElementTypeOther with the same name property as the id set by accessibilityIdentifier.

With iOS 15/16 these are not working anymore, here is the output on Appium Inspector when inspecting the views:

<XCUIElementTypeOther type="XCUIElementTypeOther" name="ID 2222222222222" enabled="true" visible="true" accessible="false" x="157" y="408" width="76" height="41" index="0">
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="some text" name="some text" label="some text" enabled="true" visible="true" accessible="true" x="157" y="408" width="76" height="21" index="0"/>
                <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="more text" name="more text" label="more text" enabled="true" visible="true" accessible="true" x="158" y="428" width="74" height="21" index="1"/>
              </XCUIElementTypeOther>

It looks like the first group of accessibilityElement and accessibilityIdentifier is no longer generating an XCUIElementTypeOther.

Is there a way to have the same output of iOS 14 on iOS 15/16?


问:
how to color mat-header-cell dynamically according to values previously obtained from a service
I have this in my template

And this is my class component

```<code> ngOnInit(): void {
  this.route.queryParamMap
  .pipe(
    concatMap(
      params => {
        this.añoUrl = Number(params.get('year'));
        this.mesUrl = Number(params.get('mes'));

        return this.generalService.getFestivosMes('leioa', this.añoUrl, this.mesUrl)
      }
    )
  )
  .subscribe(festivos => {
    this.festivos = festivos;
  }
  )
}

colorColumna(columna: string): string {
 var dia = new Date(this.añoUrl, this.mesUrl - 1, +columna.slice(1));

 if (columna.slice(0, 1) == 'S' || columna.slice(0, 1) == 'D') {
  return 'red'
 }

 if (this.festivos.find(f => new Date(f.fecha) == dia)) {
  return 'red';
 }

 return 'green';
}
</code>```

The problem is that when the function colorColumn() is executed this.festivos is empty.

But when the component is finished loading I have this.festivos

I don't know at what point in the component's life cycle I can access the service in order to have the return values available when the angular material table is rendered.

Any idea, please?

Thanks

Body:
I have this in my template

And this is my class component

 ngOnInit(): void {
  this.route.queryParamMap
  .pipe(
    concatMap(
      params => {
        this.añoUrl = Number(params.get('year'));
        this.mesUrl = Number(params.get('mes'));

        return this.generalService.getFestivosMes('leioa', this.añoUrl, this.mesUrl)
      }
    )
  )
  .subscribe(festivos => {
    this.festivos = festivos;
  }
  )
}

colorColumna(columna: string): string {
 var dia = new Date(this.añoUrl, this.mesUrl - 1, +columna.slice(1));

 if (columna.slice(0, 1) == 'S' || columna.slice(0, 1) == 'D') {
  return 'red'
 }

 if (this.festivos.find(f => new Date(f.fecha) == dia)) {
  return 'red';
 }

 return 'green';
}

The problem is that when the function colorColumn() is executed this.festivos is empty.

But when the component is finished loading I have this.festivos

I don't know at what point in the component's life cycle I can access the service in order to have the return values available when the angular material table is rendered.

Any idea, please?

Thanks


问:
Stacked Funnel Plot from certain stage on
I want to plot a stacked funnel but it should be stacked form a certain stage on and for the following stages.

id
stage
date_time
event_name
event_value

1
AA
05.1.2023 23:59:12
None
None

1
BB
05.1.2023 23:59:17
None
None

1
CC
05.1.2023 23:57:40
event
1

1
DD
05.1.2023 23:57:50
None
None

2
AA
05.1.2023 21:37:30
None
None

2
BB
05.1.2023 21:37:32
None
None

2
CC
05.1.2023 21:37:34
event
2

2
DD
05.1.2023 21:37:40
None
None

3
AA
05.1.2023 19:27:11
None
None

3
BB
05.1.2023 19:27:13
None
None

3
CC
05.1.2023 19:27:19
event
1

3
DD
05.1.2023 19:27:30
None
None

None = Field is empty

I have the dataframe (see above), which contains webtracking data. Every stage has a timestamp and for some stages (in this case CC) it is possible, that the customer can decide between two options by clicking a button, and the column "event_name" is filled with the name of the event and additionally the column "event_value" describes the option that the customer choose. (1 = Option A, 2 = Option B).

So what I want is, a funnel plot which is stacked from the stage CC on and for all the following stages, which the customers take and I want to see how many customers choose option A and option B at the stage CC and all the following stages should be stacked as well, based on the decisions at stage CC.

I already wrote a function to calculate the funnel and to plot this (both worked very well) but I have no idea how to calculate the stacked part and plot this. Currently I do not use the fields "event_name" and "event_value" in my function.

Thanks for your help!

list_steps = [AA, BB, CC, DD]

def create_funnel(df,list_steps):
    """
    function to create a dataframe that can be passed to functions for generating funnel plots
    """
    # filter df for only events in the steps list
    df = df[df['stage'].isin(list_steps)] # in my example case not neccessary but for the real webtracking  data, where i have a lot URL calls, which are not relevant for the funnel

    values = []
    dfs = {}
    # for the rest steps, create a df
    for i, step in enumerate(list_steps):
        if i == 0:

            dfs[step] = df[df['stage'] == step]\
            .sort_values(['id','date_time'],ascending = True)\
            .drop_duplicates(subset=['id','stage'], keep ='first') # in my example case not neccessary but for the real webtracking  data

        else:
            dfs[step] = df[df['stage'] == step]
            # outer join with previous step
            merged = pd.merge(dfs[list_steps[i - 1]], dfs[step], on='id', how='left')
            # keep only events that happened after previous step and sort by time
            merged = merged[merged['date_time_y'] >=(merged['date_time_x'])].sort_values('date_time_y', ascending=True)
            merged = merged.drop_duplicates(subset=['id', 'stage_x', 'stage_y'], keep='first')
            merged = merged[['id', 'stage_y', 'date_time_y']].rename({'stage_y': 'stage','date_time_y': 'date_time'}, axis=1)
            dfs[step]= merged

        # append number of step-visitors to the values list
        values.append(len(dfs[step]))

    #create a dataframe
    funnel_df = pd.DataFrame({'Funnel_Stage': list_steps,'Count':values})
    return  funnel_df

def plot_funnel(df,name):
    """
    Function to generate a Singel-Funnel Plot
    """

    fig=go.Figure(go.Funnel(
        name = f"{name}-Besuche",
        y = df['Funnel_Stage'],
        x = df['Count'],
        textinfo = "value+percent initial",
        marker = {"color":["#03add8"]},
        connector_fillcolor = "lightgrey"
    ))

    fig.update_layout(
         autosize=False, width=1000,height=1000,
        title={'text': f"{name} Conversion Funnel"})

    fig.show()
```


问:
how do i use the id in mongodb document
I am creating an add to cart functionality using redux toolkit. I fetched my data using rtk query and it works fine but my problem is how do I read the mongodb id in my projects. please help.

```<code>const initialState = {

    cart: []
}
</code>```

const carttSlice = createSlice({
name: 'cart',
initialState,

```<code>reducers: {
 addToCart: (state, action)=>{
  //check if the item exist in cart
const ItemInCart = state.cart.find((item) => item.id === action.payload.id);
 // please note the id cant read

//if item in cart increment the quantity, if not, we push item to cart.
    if(ItemInCart){
       ItemInCart.quantity++
    }else{
    //pushing item to cart
      state.cart.push({...action.payload, quantity: 1})
    }

   }
 },
</code>```

I tied not loading the data from nmongodb and it worked

Title: how do i use the id in mongodb document

Body:
I am creating an add to cart functionality using redux toolkit. I fetched my data using rtk query and it works fine but my problem is how do I read the mongodb id in my projects. please help.

const initialState = {

    cart: []
}

const carttSlice = createSlice({
name: 'cart',
initialState,

reducers: {
 addToCart: (state, action)=>{
  //check if the item exist in cart
const ItemInCart = state.cart.find((item) => item.id === action.payload.id);
 // please note the id cant read

//if item in cart increment the quantity, if not, we push item to cart.
    if(ItemInCart){
       ItemInCart.quantity++
    }else{
    //pushing item to cart
      state.cart.push({...action.payload, quantity: 1})
    }

   }
 },

I tied not loading the data from nmongodb and it worked


问:
Set a Kubernetes Secret with data from an external Key Vault
I'm using ArgoCD (a GitOps tool) to deploy my Helm project in a Kubernetes cluster.  My cluster is configured to connect to my external key vault, so once my application is deployed to my cluster, it can fetch an access token and grab any secret it needs in the vault.  My project also has a use case in which is spins up a new pod within my cluster to run some batch process, and this pod uses a imagePullSecret to connect to my private registry that contains an image for this pod.

If this imagePullSecret is present in my cluster and in the same namespace as my project, this process works.  However, I'm trying to keep my project IaC as cluster agnostic as possible.  Basically, should I spin up a new Kubernetes cluster, I can deploy my project to this cluster without any manual changes needed, and the project has everything it needs to run.

What I want to do is add a yaml file in my template folder that defines a secret in the cluster (which will be my imagePullSecret) so that I know that secret will always be there.  Since this secret is project dependent, assume that the IaC code to deploy the cluster will not do this task.  Of course, to be secure, I don't want to have the actual secret data in the file itself.

As my cluster is already seamlessly connected to an external Key Vault, I'm wondering if there's a way to fetch this information from the vault at the time of deployment.  So the secret yaml would look like:

```<code>kind: Secret
apiVersion: v1
metadata:
  name: superSecretData
  namespace: projectNameSpace
  # Maybe some connection annotation needed here?
type: dockerconfigjson
data:
  secretData: <Data from Key Vault>
</code>```

I saw there was some small project for this, but I wanted to know if there is a more...standard way to do it.  When searching online for a solution, there are many to set secrets in a Pod, but I want to actually create a Kubernetes secret in my namespace.  My GitOps tool may be able to do this, and may be a solution to this problem, but if I can avoid this middleman situation (KV -> ArgoCD -> k8s secret -> project instead of just KV -> k8s secret -> project) I would like to go that route

Body:
I'm using ArgoCD (a GitOps tool) to deploy my Helm project in a Kubernetes cluster.  My cluster is configured to connect to my external key vault, so once my application is deployed to my cluster, it can fetch an access token and grab any secret it needs in the vault.  My project also has a use case in which is spins up a new pod within my cluster to run some batch process, and this pod uses a imagePullSecret to connect to my private registry that contains an image for this pod.

If this imagePullSecret is present in my cluster and in the same namespace as my project, this process works.  However, I'm trying to keep my project IaC as cluster agnostic as possible.  Basically, should I spin up a new Kubernetes cluster, I can deploy my project to this cluster without any manual changes needed, and the project has everything it needs to run.

What I want to do is add a yaml file in my template folder that defines a secret in the cluster (which will be my imagePullSecret) so that I know that secret will always be there.  Since this secret is project dependent, assume that the IaC code to deploy the cluster will not do this task.  Of course, to be secure, I don't want to have the actual secret data in the file itself.

As my cluster is already seamlessly connected to an external Key Vault, I'm wondering if there's a way to fetch this information from the vault at the time of deployment.  So the secret yaml would look like:

kind: Secret
apiVersion: v1
metadata:
  name: superSecretData
  namespace: projectNameSpace
  # Maybe some connection annotation needed here?
type: dockerconfigjson
data:
  secretData: <Data from Key Vault>

I saw there was some small project for this, but I wanted to know if there is a more...standard way to do it.  When searching online for a solution, there are many to set secrets in a Pod, but I want to actually create a Kubernetes secret in my namespace.  My GitOps tool may be able to do this, and may be a solution to this problem, but if I can avoid this middleman situation (KV -> ArgoCD -> k8s secret -> project instead of just KV -> k8s secret -> project) I would like to go that route


问:
How to switch with git subtree to a different branch for one of the subtree projects
When I have a container project with bunch of git subtree directories, each tracking their respective main, how can I switch (and even create) a branch in one of the subtrees?

The setup being:

```<code>.\container-proj       # branch main
   .\sub-proj-1            # branch main
   .\sub-proj-2            # branch main
   .\sub-proj-3            # branch main
</code>```

Now I want to ake changes and when I do

(.\container-proj) $ git checkout -b new-branch

I get

```<code>.\container-proj       # branch new-branch
   .\sub-proj-1            # branch main
   .\sub-proj-2            # branch main
   .\sub-proj-3            # branch main
</code>```

Now I make changes

```<code>(.\container-proj) $ touch README.md
(.\container-proj) $ cd sub-proj-1
(.\container-proj\sub-proj-1) $ touch README.md
</code>```

I can commit and push these changes with

```<code>(.\container-proj) $ git commit -m MyChange -a ; git push
</code>```

but of course they ony get into my container-projs branch new-branch.

I can publish the changes upstream into the sub-proj-1 with

```<code>(.\container-proj) $ git subtree push --prefix sub-proj-1 sub-proj-1 main
</code>```

but that will only push it into the main branch of the project.

I would like to have those changes in a branch sub-new-branch in that project.

Basically, that I have the setup

```<code>.\container-proj       # branch new-branch
   .\sub-proj-1            # branch sub-new-branch
   .\sub-proj-2            # branch main
   .\sub-proj-3            # branch main
</code>```

for a while, but can easily switch back to main for sub-proj-1.

Body:
When I have a container project with bunch of git subtree directories, each tracking their respective main, how can I switch (and even create) a branch in one of the subtrees?

The setup being:

.\container-proj       # branch main
   .\sub-proj-1            # branch main
   .\sub-proj-2            # branch main
   .\sub-proj-3            # branch main

Now I want to ake changes and when I do

(.\container-proj) $ git checkout -b new-branch

I get

.\container-proj       # branch new-branch
   .\sub-proj-1            # branch main
   .\sub-proj-2            # branch main
   .\sub-proj-3            # branch main

Now I make changes

(.\container-proj) $ touch README.md
(.\container-proj) $ cd sub-proj-1
(.\container-proj\sub-proj-1) $ touch README.md

I can commit and push these changes with

(.\container-proj) $ git commit -m MyChange -a ; git push

but of course they ony get into my container-projs branch new-branch.

I can publish the changes upstream into the sub-proj-1 with

(.\container-proj) $ git subtree push --prefix sub-proj-1 sub-proj-1 main

but that will only push it into the main branch of the project.

I would like to have those changes in a branch sub-new-branch in that project.

Basically, that I have the setup

.\container-proj       # branch new-branch
   .\sub-proj-1            # branch sub-new-branch
   .\sub-proj-2            # branch main
   .\sub-proj-3            # branch main

for a while, but can easily switch back to main for sub-proj-1.


问:
Ctrl Down recorded macro is not working as expected
The macro I have recorded is not acting as expected.

I  am selecting cell H1 and then Ctrl+ down to the next cell with data but it just doesn't seem to move from H1

```<code>function UntitledMacro1() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Auto Print'), true);
  spreadsheet.getActiveSheet().setFrozenRows(0);
  spreadsheet.getRange('H:H').activate();
  spreadsheet.getActiveRangeList().setFontColor('#ffffff');
  spreadsheet.getRange('H1').activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Lables'), true);
  spreadsheet.getRange('T7').activate();
var selection = SpreadsheetApp.getActiveSpreadsheet().getSelection();
var currentCell = selection.getCurrentCell();
};

</code>```

Body:
The macro I have recorded is not acting as expected.

I  am selecting cell H1 and then Ctrl+ down to the next cell with data but it just doesn't seem to move from H1

function UntitledMacro1() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Auto Print'), true);
  spreadsheet.getActiveSheet().setFrozenRows(0);
  spreadsheet.getRange('H:H').activate();
  spreadsheet.getActiveRangeList().setFontColor('#ffffff');
  spreadsheet.getRange('H1').activate();
  spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Lables'), true);
  spreadsheet.getRange('T7').activate();
var selection = SpreadsheetApp.getActiveSpreadsheet().getSelection();
var currentCell = selection.getCurrentCell();
};


问:
Flask Plot with matplotlib
I saw quite a few different approaches to plot in flask app with matplotlib.

My question is now, why does my plot not appear.

```<code>@blueprint.route('/plot')
def plot():
    left = [1, 2, 3, 4, 5]
    # heights of bars
    height = [10, 24, 36, 40, 5]
    # labels for bars
    tick_label = ['one', 'two', 'three', 'four', 'five']
    # plotting a bar chart
    plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green'])
    # naming the y-axis
    plt.ylabel('y - axis')
    # naming the x-axis
    plt.xlabel('x - axis')
    # plot title
    plt.title('My bar chart!')

    plt.savefig('apps/static/images/assets/plot.png')

    return render_template('tables.html', url='apps/static/images/assets/plot.png')
</code>```
```<code><body>
<div>
<img src={{url}} alt="Chart" height="auto" width="100%">
    </div>
</body>

</code>```

Thank you in Advance

Title: Flask Plot with matplotlib

Body:
I saw quite a few different approaches to plot in flask app with matplotlib.

My question is now, why does my plot not appear.

@blueprint.route('/plot')
def plot():
    left = [1, 2, 3, 4, 5]
    # heights of bars
    height = [10, 24, 36, 40, 5]
    # labels for bars
    tick_label = ['one', 'two', 'three', 'four', 'five']
    # plotting a bar chart
    plt.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green'])
    # naming the y-axis
    plt.ylabel('y - axis')
    # naming the x-axis
    plt.xlabel('x - axis')
    # plot title
    plt.title('My bar chart!')

    plt.savefig('apps/static/images/assets/plot.png')

    return render_template('tables.html', url='apps/static/images/assets/plot.png')

Thank you in Advance


问:
How can I use GitHub Nightly Merge action in Gitlab
I am trying to auto merge from master to develop if a commit is made to master. GitHub has the action : "Nightly Merge" for it , how can I achieve the same in my Gitlab repo.</p>


问:
Angular local SSL with universal does not work
I created an angular universal app and followed the following tutorial to use SSL for local development with SSR:
https://medium.com/@dnlcyan/local-angular-ssr-with-https-b9d305dc620d

The certificate is trusted in the browser and also the requests work on browser level. But for request coming from the node server the API throws the following exception:

Microsoft.AspNetCore.Server.Kestrel.Https.Internal.HttpsConnectionMiddleware
Failed to authenticate HTTPS connection. System.IO.IOException:
Received an unexpected EOF or 0 bytes from the transport stream.    at
System.Net.Security.SslStream.g__InternalFillHandshakeBufferAsync|189_0[TIOAdapter](TIOAdapter
adap, ValueTask`1 task, Int32 minSize)    at
System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter
adapter)    at
System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter
adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean
isApm)    at
Microsoft.AspNetCore.Server.Kestrel.Https.Internal.HttpsConnectionMiddleware.OnConnectionAsync(ConnectionContext
context)

I read something about that the certificate might not be trusted, but I added it to windows and also the browser indicates that it's correct. I tried to create a new certificate according to this tutorial but it doesn't work as well: https://fmoralesdev.com/2020/01/03/serve-angular-app-over-https-using-angular-cli/

Does anyone know what the issue might be here?


问:
How to Draw a Normal Line Plot in a Quiver PLot
I have a quiver plot that plots (1, f(x)) for each (x,y) whereas f(x) = exp(-(x-4)^2)

```<code>import numpy as np
import matplotlib.pyplot as plt

# Define domain
x = np.linspace(0, 8, 40)
y = np.linspace(0, 2, 40)
x, y = np.meshgrid(x, y)

# Compute direction using the derivative
def dv(x):
    y = np.exp(-2*(x-4)**2)
    n = -2*(x-4)*np.exp(-2*(x-4)**2)

    return y*n

# Define functions
u = 1
v = dv(x)

# Plot
fig = plt.figure()  # a new figure window
ax = fig.add_subplot(1, 1, 1)  # specify (nrows, ncols, axnum)
ax.quiver(x, y, u, v, fn(x))
#ax.plot(x, fn(x))
fig.show()
</code>```

It looks like this

Now I want to also plot a line that starts at e.g. (x=0, y=2) and follows the vector field/flow i.e. basically plot f(x) for a fixed y. I tried to do so by sharing the axes with ax.plot(), but that didn't work for a reason unknown to me.

The ultimate goal is to show how a particle would move if we dropped it somewhere at the start. I know there is streamplot() but I really want a vector field like this because I wanna relate the Eulerian and the Lagragian point of view.

Body:
I have a quiver plot that plots (1, f(x)) for each (x,y) whereas f(x) = exp(-(x-4)^2)

import numpy as np
import matplotlib.pyplot as plt

# Define domain
x = np.linspace(0, 8, 40)
y = np.linspace(0, 2, 40)
x, y = np.meshgrid(x, y)

# Compute direction using the derivative
def dv(x):
    y = np.exp(-2*(x-4)**2)
    n = -2*(x-4)*np.exp(-2*(x-4)**2)

    return y*n

# Define functions
u = 1
v = dv(x)

# Plot
fig = plt.figure()  # a new figure window
ax = fig.add_subplot(1, 1, 1)  # specify (nrows, ncols, axnum)
ax.quiver(x, y, u, v, fn(x))
#ax.plot(x, fn(x))
fig.show()

It looks like this

Now I want to also plot a line that starts at e.g. (x=0, y=2) and follows the vector field/flow i.e. basically plot f(x) for a fixed y. I tried to do so by sharing the axes with ax.plot(), but that didn't work for a reason unknown to me.

The ultimate goal is to show how a particle would move if we dropped it somewhere at the start. I know there is streamplot() but I really want a vector field like this because I wanna relate the Eulerian and the Lagragian point of view.


问:
Block update while setting multiple widgets
Is it possible using Panel to temporarily disable the automatic linking of widgets while setting the values of multiple widgets?

The code below shows a simplified example of my situation, in reality I have much more widgets. The key issue is that I have a Select widget, that links to some pre-configured values in a dictionary, and on-change I want it to update all other widgets.

All of this works fine, except that when the first widget gets a new value using this, it instantly triggers a redraw of the entire plot before all other widgets are also updated. Not only gives this a unnecessary flickering effect (updating the plot n_widgets times instead of once), some intermediate values also cause the plot to show some "wild" results because the intermediate values cause unrealistic combinations.

dropdown_box = pn.widgets.Select(options=selection_options, name="selection")
slider1 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider1")
slider2 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider2")
slider3 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider3")
slider4 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider4")

@pn.depends(dropdown_box.param.value, watch=True)
def update_cfg(selection):

    val1, val2, val3, val4 = lookup_cfg[selection] # lookup_cfg

    # < some intermediate stuff >

    slider1.value = val1
    slider2.value = val2
    slider3.value = val3
    slider4.value = val4

my_plot = hv.DynamicMap(pn.bind(
    create_plot,
    param1=slider1,
    param2=slider2,
    param3=slider3,
    param4=slider4,
    **plot_kwargs,
))
```
<p>Even assigning all <code>slider.value</code>'s on the same line still causes the widgets to be updated one-by-one, so that's not a workaround. I'm wondering if there's something along the lines of the progress spinner that actually blocks any updates/triggering until "released" so I can change many widgets while only updating the plot once?</p>
<p>Something along the lines of:</p>
<pre class="lang-py prettyprint-override"><code>with pn.block_updates():
    slider1.value = val1
    slider2.value = val2
    slider3.value = val3
    slider4.value = val4
</code>```

I also tried disabling the widgets up front (slider.disabled = True), but that only prevent the user from interacting with them.

I could make a fully working example with some toy data if the code above is unclear.

Body:
Is it possible using Panel to temporarily disable the automatic linking of widgets while setting the values of multiple widgets?

The code below shows a simplified example of my situation, in reality I have much more widgets. The key issue is that I have a Select widget, that links to some pre-configured values in a dictionary, and on-change I want it to update all other widgets.

All of this works fine, except that when the first widget gets a new value using this, it instantly triggers a redraw of the entire plot before all other widgets are also updated. Not only gives this a unnecessary flickering effect (updating the plot n_widgets times instead of once), some intermediate values also cause the plot to show some "wild" results because the intermediate values cause unrealistic combinations.

dropdown_box = pn.widgets.Select(options=selection_options, name="selection")
slider1 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider1")
slider2 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider2")
slider3 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider3")
slider4 = pn.widgets.FloatSlider(start=0, end=1, step=0.01, value=0.5, name="slider4")

@pn.depends(dropdown_box.param.value, watch=True)
def update_cfg(selection):

    val1, val2, val3, val4 = lookup_cfg[selection] # lookup_cfg

    # < some intermediate stuff >

    slider1.value = val1
    slider2.value = val2
    slider3.value = val3
    slider4.value = val4

my_plot = hv.DynamicMap(pn.bind(
    create_plot,
    param1=slider1,
    param2=slider2,
    param3=slider3,
    param4=slider4,
    **plot_kwargs,
))

Even assigning all slider.value's on the same line still causes the widgets to be updated one-by-one, so that's not a workaround. I'm wondering if there's something along the lines of the progress spinner that actually blocks any updates/triggering until "released" so I can change many widgets while only updating the plot once?

Something along the lines of:

with pn.block_updates():
    slider1.value = val1
    slider2.value = val2
    slider3.value = val3
    slider4.value = val4

I also tried disabling the widgets up front (slider.disabled = True), but that only prevent the user from interacting with them.

I could make a fully working example with some toy data if the code above is unclear.


问:
Spark Multi-threading, Could not serialize object exception

_pickle.PicklingError: Could not serialize object: Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.

I'm working in implementing a page rank algorithm in spark with a large data frame.

I'm using a udf in order to calculate the algorithm:

```<code>new_pagerank_udf = udf(lambda x,y: new_pagerank(x,pageRankDF,y), FloatType())

</code>```

The function:

```<code>def new_pagerank(links, current_pr, counters):
  n_pr = 0;
  #for each incoming link to the page calculate the pagerank
  #zip the links and counters to get them both in the loop
  for l, c in zip(links, counters):

    #get current_pr of the link l
    try:
      current_link_pr=current_pr[current_pr['id']==l].PR.item()

    except:
      current_link_pr=0.85/N

    n_pr += current_link_pr/c
  new_pr = 0.85/N+0.15*n_pr
  return new_pr

</code>```

pageRankDF:

```<code> #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   id      77 non-null     int64
 1   PR      77 non-null     float64

</code>```

Where the udf is called:

```<code>count=0;
display(pageRankPDF)
previous_pr_sum=0
while ((converged(previous_pr_sum,pageRankPDF["PR"].sum())==False) & (count<7)):
    previous_pr_sum=pageRankPDF["PR"].sum()
    NewPageRankDF=ReverseDF.select(
        ReverseDF["id"],
        new_pagerank_udf(ReverseDF["links"],ReverseDF["counters"]).alias("PR"))
    pageRankDF=NewPageRankDF
    display(pageRankDF)
    count=count+1

</code>```

ReverseDF:

```<code>root
 |-- id: long (nullable = false)
 |-- Links: array (nullable = false)
 |    |-- element: integer (containsNull = false)
 |-- counters: array (nullable = false)
 |    |-- element: integer (containsNull = false)

</code>```

The only way that i have found working is to convert the spark data frame to a pandas data frame using .toPandas(), but is too slow for a large data frame.

Can i fix it without use a pandas df?

Body:
_pickle.PicklingError: Could not serialize object: Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.

I'm working in implementing a page rank algorithm in spark with a large data frame.

I'm using a udf in order to calculate the algorithm:

new_pagerank_udf = udf(lambda x,y: new_pagerank(x,pageRankDF,y), FloatType())

The function:

def new_pagerank(links, current_pr, counters):
  n_pr = 0;
  #for each incoming link to the page calculate the pagerank
  #zip the links and counters to get them both in the loop
  for l, c in zip(links, counters):

    #get current_pr of the link l
    try:
      current_link_pr=current_pr[current_pr['id']==l].PR.item()

    except:
      current_link_pr=0.85/N

    n_pr += current_link_pr/c
  new_pr = 0.85/N+0.15*n_pr
  return new_pr

pageRankDF:

 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   id      77 non-null     int64
 1   PR      77 non-null     float64

Where the udf is called:

count=0;
display(pageRankPDF)
previous_pr_sum=0
while ((converged(previous_pr_sum,pageRankPDF["PR"].sum())==False) & (count<7)):
    previous_pr_sum=pageRankPDF["PR"].sum()
    NewPageRankDF=ReverseDF.select(
        ReverseDF["id"],
        new_pagerank_udf(ReverseDF["links"],ReverseDF["counters"]).alias("PR"))
    pageRankDF=NewPageRankDF
    display(pageRankDF)
    count=count+1

ReverseDF:

root
 |-- id: long (nullable = false)
 |-- Links: array (nullable = false)
 |    |-- element: integer (containsNull = false)
 |-- counters: array (nullable = false)
 |    |-- element: integer (containsNull = false)

The only way that i have found working is to convert the spark data frame to a pandas data frame using .toPandas(), but is too slow for a large data frame.

Can i fix it without use a pandas df?


问:
Setting an hourly, daily, weekly or monthly email with mailgun, nodejs and nodecron
I have 3 main files of my project which link together - index.html, server.js and mail.js

A portion of mail.js is below

```<code>const sendMail = (message, cb) => {
    var dict = {
        'hourly': '* * 0-23 * * ',
        'daily': ' * * 1-31 * ',
        'weekly': ' * * * * ',
        'monthly': ' * * * 1-12 *'
};
const mailOptions = {
    from: 'blah',
    to: 'blah',
    subject: 'Emails',
    text: message
};

transporter.sendMail(mailOptions, function(err, data){
    if (err){
        cb(err, null);
    } else {
        cb(null, data);
    }
});
</code>```

Portion of server.js below

app.post('/email', (req, res) => {     const {message} = req.body;     console.log('Data: ', req.body);     sendMail(message, function(err, data) {         if (err) {             res.status(500).json({say: 'Internal Error' });         } else {             res.json({say: 'Email sent'});         }     });     res.json({message: 'Message received'}); });

portion of index.html below

```<code><body>

<form>

    <input type = "text" id = "message" placeholder = "Message"> <br>
    <select id = "frequency" placeholder = "frequency">
        <option value="hourly">Hourly</option>
        <option value="daily">Daily</option>
        <option value="weekly">Weekly</option>
        <option value="monthly">Monthly</option>
      </select> <br>
    <input type = "submit" value ="Submit"> <br>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
    $('form').on('submit', (e) => {
        e.preventDefault();

        const frequency = $('#frequency').val().trim();
        const message = $('#message').val().trim();

        const data = {
            frequency,
            message

        };
        $.post('/email', data, function(){
            console.log('Data is received by server')
        });
    })
</script>
</code>```

What the project is supposed to do is to select a frequency option from the form in index js, write a message and from that it send an email to a certain email address (which will be in mail.js) with the frequency of the option until the program is terminated. I'm having issues with the frequency bit using nodecron in mail.js. How do I include the frequency with this? I have currently held the values in a dictionary in mail.js but I want to know how to use this to my advantage. Please help.

I had tried to use them in a dictionary with nodecron methods but it only sent 1 email.

Body:
I have 3 main files of my project which link together - index.html, server.js and mail.js

A portion of mail.js is below

const sendMail = (message, cb) => {
    var dict = {
        'hourly': '* * 0-23 * * ',
        'daily': ' * * 1-31 * ',
        'weekly': ' * * * * ',
        'monthly': ' * * * 1-12 *'
};
const mailOptions = {
    from: 'blah',
    to: 'blah',
    subject: 'Emails',
    text: message
};

transporter.sendMail(mailOptions, function(err, data){
    if (err){
        cb(err, null);
    } else {
        cb(null, data);
    }
});

Portion of server.js below

app.post('/email', (req, res) => {     const {message} = req.body;     console.log('Data: ', req.body);     sendMail(message, function(err, data) {         if (err) {             res.status(500).json({say: 'Internal Error' });         } else {             res.json({say: 'Email sent'});         }     });     res.json({message: 'Message received'}); });

portion of index.html below

<form>

    <input type = "text" id = "message" placeholder = "Message">

    <select id = "frequency" placeholder = "frequency">
        <option value="hourly">Hourly</option>
        <option value="daily">Daily</option>
        <option value="weekly">Weekly</option>
        <option value="monthly">Monthly</option>
      </select>

    <input type = "submit" value ="Submit">

</form>

What the project is supposed to do is to select a frequency option from the form in index js, write a message and from that it send an email to a certain email address (which will be in mail.js) with the frequency of the option until the program is terminated. I'm having issues with the frequency bit using nodecron in mail.js. How do I include the frequency with this? I have currently held the values in a dictionary in mail.js but I want to know how to use this to my advantage. Please help.

I had tried to use them in a dictionary with nodecron methods but it only sent 1 email.


问:
Need to understand the use of Generics in the code below
```<code>public class MyData
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string UserId { get; set; }
}

public class MyWorkflow : IWorkflow
{
    public void Build(IWorkflowBuilder<MyData> builder)
    {
        builder
            .StartWith<CreateUser>()
                .Input(step => step.Email, data => data.Email)
                .Input(step => step.Password, data => data.Password)
                .Output(data => data.UserId, step => step.UserId)
           .Then<SendConfirmationEmail>()
               .WaitFor("confirmation", data => data.UserId)
           .Then<UpdateUser>()
               .Input(step => step.UserId, data => data.UserId);
    }
}
https://github.com/danielgerlag/workflow-core
</code>```

Trying to understand this piece of code above.

Line 13 has StartWith<CreateUser>() but I don't see anywhere CreateUser type being used at all so whats the use of CreateUser?

and also how do i know what is the object step and data in line 14?

Body:
public class MyData
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string UserId { get; set; }
}

public class MyWorkflow : IWorkflow
{
    public void Build(IWorkflowBuilder<MyData> builder)
    {
        builder
            .StartWith<CreateUser>()
                .Input(step => step.Email, data => data.Email)
                .Input(step => step.Password, data => data.Password)
                .Output(data => data.UserId, step => step.UserId)
           .Then<SendConfirmationEmail>()
               .WaitFor("confirmation", data => data.UserId)
           .Then<UpdateUser>()
               .Input(step => step.UserId, data => data.UserId);
    }
}
https://github.com/danielgerlag/workflow-core

Trying to understand this piece of code above.

Line 13 has StartWith<CreateUser>() but I don't see anywhere CreateUser type being used at all so whats the use of CreateUser?

and also how do i know what is the object step and data in line 14?


问:
select2 showing 2 options highlighted with grey color i.e. aria-selected='true'. Can anyone help to fix it?
My templateSelection function is

```<code>function formatDesAccItem (item) {
  if (item.loading) {
    return item.text;
  }
  if(item.number)
  {  var $container = $(
    `<div class='select2-result-repository clearfix'>
      <div class='select2-result-repository__meta'>
        <div class='select2-result-repository__name'>${item.name}</div>
        <div class='select2-result-repository__account_number'>${item.number}</div>
        <div class='select2-result-repository__bank'>${item.bank}</div>
        <div class='select2-result-repository__account_type'>({{__('Bank Account')}})</div>
      </div>
    </div>`
  );}
  else
  {  var $container = $(
    `<div class='select2-result-repository clearfix'>
      <div class='select2-result-repository__meta'>
        <div class='select2-result-repository__name'>${item.name}</div>
        <div class='select2-result-repository__account_type'>({{__('Cash on hand Account')}})</div>
      </div>
    </div>`
  );}

  return $container;
}
</code>```

it happens when item.name starts with same name.

I tried to use let instead of var.

Body:
My templateSelection function is

function formatDesAccItem (item) {
  if (item.loading) {
    return item.text;
  }
  if(item.number)
  {  var $container = $(
    `

${item.name}

${item.number}

${item.bank}

({{__('Bank Account')}})

`
  );}
  else
  {  var $container = $(
    `

${item.name}

({{__('Cash on hand Account')}})

`
  );}

  return $container;
}

it happens when item.name starts with same name.

I tried to use let instead of var.


问:
I'm getting a unauthorised message when i try to login at the client side
I'm working on a Auth with MERN , at the client side i'm using contextAPI ,useReducerhook to manage the user.
I have also  created a custom hook ( useLogin )  for handling the login criteria as shown  below .It takes the userCredentials whoch is a object of (email password) from the login form .I have also incorporated the reacy-hook form to handle validation of the input fields

```<code>import axios from "axios";
import { BASE_API_URL } from "../utils/BaseUrl";
import { useAuthContext } from "./useAuthContext";
export const useLogin = () => {
    const [isError, setIsError] = useState(null)
    const [isLoading, setIsLoading] = useState(false)
    const [IsSuccess, setIsSucces] = useState(false)
    const { dispatch } = useAuthContext()

    const loginUser = async (userDetails) => {
        setIsError(null)
        setIsLoading(true)
        try {
            const response = await axios.post(`${BASE_API_URL}/api/auth/login`, {
                userDetails: userDetails
            })
            //get json data

            const jsonData = await response.json()

            //if there is a error in the  response

            if (!response.ok) {
                setIsLoading(false)
                setIsError(jsonData.error)
            }
            //if it works correctly

            if (response.ok) {

                //save user to local storage
                localStorage.setItem("userData", JSON.stringify(jsonData));
                localStorage.setItem("accessToken", jsonData.data?.accessToken)

                //update the auth context
                dispatch({ type: "LOGIN", paylaod: jsonData })
                setIsLoading(false)
                setIsSucces(true)
            }

        } catch (err) {
            setIsError(err.message)
            setIsLoading(false)
        }
    }
    return { isError, isLoading, IsSuccess, loginUser }

}
</code>```

Then i re use it at my login page as shown here

```<code>import ScaleLoader from "react-spinners/ScaleLoader";
import Logo from "../../assets/images/Logo.png";
import Footer from "../Footer/index";
import { Link } from "react-router-dom";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import Input from "@material-ui/core/Input";
import Swal from "sweetalert2";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import { useLogin } from "../../hooks/useLogin";

const Login = () => {
  const [userDetails, setUserDetails] = useState("");
  const [passwordShown, setPasswordShown] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const navigate = useNavigate();
  const { loginUser } = useLogin()

  // Password toggle handler

  const togglePassword = () => {
    setPasswordShown(!passwordShown);
  };

  //handleSubmit

  const onSubmit = async () => {
    await loginUser(userDetails)
    navigate("/user/dashboard");
    setUserDetails('')
  };

  return (
    <>

      {/* <div className="d-flex justify-content-center loader">
        <ScaleLoader
          className="d-flex justify-content-center"
          color="#FFC247"
          speedMultiplier={4}
        />
      </div> */}

      <div className="login-page">
        <div className="container">
          <div className="row">
            <div className="col-lg-6 offset-lg-3 col-md-12 offset-md-1 col-sm-12 offset-sm-1 col-xs-6 offset-xs-3">
              <div className="login-form">
                <div className="login-form-header d-flex flex-column justify-content-center flex-column align-items-center">
                  <img src={Logo} alt="" />
                  <h4>We missed you , glad to see you back</h4>
                </div>
                <form onSubmit={handleSubmit(onSubmit)}>
                  <div className="form-group">
                    <label htmlFor="email1">Email address</label>
                    <input
                      type="email"
                      className={`form-control py-2 my-2 ${errors.email ? "input-error" : ""
                        }`}
                      id="email"
                      name="email"
                      placeholder="Enter email"
                      {...register("email", {
                        required: "Email is required",
                        pattern: {
                          value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                          message: "Invalid email address",
                        },
                      })}
                    />
                    {errors.email && (
                      <span className="errorMsg">{errors.email.message}</span>
                    )}
                  </div>
                  <div className="form-group">
                    <label htmlFor="password">Password</label>
                    <div className="input-group">
                      <Input
                        type={passwordShown ? "text" : "password"}
                        className="form-control py-2 my-2"
                        id="password"
                        name="password"
                        placeholder="Enter password"
                        {...register("password", {
                          required: "Password is required",
                          minLength: {
                            value: 8,
                            message: "Password must be at least 8 characters",
                          },
                          pattern: {
                            value:
                              /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])/,
                            message:
                              "Password must contain at least one lowercase letter, one uppercase letter, one number and one special character",
                          },
                        })}
                      />

                      <span
                        style={{ height: "50px", marginTop: "8px" }}
                        className="input-group-text"
                        onClick={togglePassword}
                      >
                        {passwordShown ? (
                          <FontAwesomeIcon icon={faEyeSlash} />
                        ) : (
                          <FontAwesomeIcon icon={faEye} />
                        )}
                      </span>
                    </div>

                    {errors.password && (
                      <span className="errorMsg">
                        {errors.password.message}
                      </span>
                    )}
                  </div>
                  <div className="submit-button d-flex align-items-center justify-content-between mt-5">
                    <button className="btn-home px-5 rounded">Login</button>
                    <div className="forget-password">
                      <Link
                        to="/user/forgetpassword"
                        className="text-decoration-none text-link"
                      >
                        Forget my password
                      </Link>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        <div className="footer-home">
          <Footer />
        </div>
      </div>
    </>
  );
};

export default Login;
</code>```

Body:
I'm working on a Auth with MERN , at the client side i'm using contextAPI ,useReducerhook to manage the user.
I have also  created a custom hook ( useLogin )  for handling the login criteria as shown  below .It takes the userCredentials whoch is a object of (email password) from the login form .I have also incorporated the reacy-hook form to handle validation of the input fields

import axios from "axios";
import { BASE_API_URL } from "../utils/BaseUrl";
import { useAuthContext } from "./useAuthContext";
export const useLogin = () => {
    const [isError, setIsError] = useState(null)
    const [isLoading, setIsLoading] = useState(false)
    const [IsSuccess, setIsSucces] = useState(false)
    const { dispatch } = useAuthContext()

    const loginUser = async (userDetails) => {
        setIsError(null)
        setIsLoading(true)
        try {
            const response = await axios.post(`${BASE_API_URL}/api/auth/login`, {
                userDetails: userDetails
            })
            //get json data

            const jsonData = await response.json()

            //if there is a error in the  response

            if (!response.ok) {
                setIsLoading(false)
                setIsError(jsonData.error)
            }
            //if it works correctly

            if (response.ok) {

                //save user to local storage
                localStorage.setItem("userData", JSON.stringify(jsonData));
                localStorage.setItem("accessToken", jsonData.data?.accessToken)

                //update the auth context
                dispatch({ type: "LOGIN", paylaod: jsonData })
                setIsLoading(false)
                setIsSucces(true)
            }

        } catch (err) {
            setIsError(err.message)
            setIsLoading(false)
        }
    }
    return { isError, isLoading, IsSuccess, loginUser }

}

Then i re use it at my login page as shown here

import ScaleLoader from "react-spinners/ScaleLoader";
import Logo from "../../assets/images/Logo.png";
import Footer from "../Footer/index";
import { Link } from "react-router-dom";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import Input from "@material-ui/core/Input";
import Swal from "sweetalert2";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import { useLogin } from "../../hooks/useLogin";

const Login = () => {
  const [userDetails, setUserDetails] = useState("");
  const [passwordShown, setPasswordShown] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const navigate = useNavigate();
  const { loginUser } = useLogin()

  // Password toggle handler

  const togglePassword = () => {
    setPasswordShown(!passwordShown);
  };

  //handleSubmit

  const onSubmit = async () => {
    await loginUser(userDetails)
    navigate("/user/dashboard");
    setUserDetails('')
  };

  return (
    <>

      {/*

        <ScaleLoader
          className="d-flex justify-content-center"
          color="#FFC247"
          speedMultiplier={4}
        />

 */}

We missed you , glad to see you back

                <form onSubmit={handleSubmit(onSubmit)}>

                    Email address
                    <input
                      type="email"
                      className={`form-control py-2 my-2 ${errors.email ? "input-error" : ""
                        }`}
                      id="email"
                      name="email"
                      placeholder="Enter email"
                      {...register("email", {
                        required: "Email is required",
                        pattern: {
                          value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                          message: "Invalid email address",
                        },
                      })}
                    />
                    {errors.email && (
                      {errors.email.message}
                    )}

                    Password

                      <Input
                        type={passwordShown ? "text" : "password"}
                        className="form-control py-2 my-2"
                        id="password"
                        name="password"
                        placeholder="Enter password"
                        {...register("password", {
                          required: "Password is required",
                          minLength: {
                            value: 8,
                            message: "Password must be at least 8 characters",
                          },
                          pattern: {
                            value:
                              /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])/,
                            message:
                              "Password must contain at least one lowercase letter, one uppercase letter, one number and one special character",
                          },
                        })}
                      />

                        {passwordShown ? (
                          <FontAwesomeIcon icon={faEyeSlash} />
                        ) : (
                          <FontAwesomeIcon icon={faEye} />
                        )}

                    {errors.password && (

                        {errors.password.message}

                    )}

                    <button className="btn-home px-5 rounded">Login</button>

                      <Link
                        to="/user/forgetpassword"
                        className="text-decoration-none text-link"
                      >
                        Forget my password
                      </Link>

                </form>

    </>
  );
};

export default Login;


问:
Get values of dynamically add select dropdown multiple values in Laravel 9
I have 2 Select options which are as follow:

```<code><select name="attribute[]" id="attribute" data-id="1" >
    <option value="1">Size</option>
    <option value="2">Color</option>
</select>

</code>```
```<code><select name="attribute_value[]" id="attribute_value1"  multiple>
    <option value="0">Please Select</option>
<select>

</code>```

and attribute value popup with ajax when change option on attribute

```<code>
$(document).on('change','.attribute', function() {
    let attr_id = $(this).val();
    let rowId = $(this).data('id');

    $.ajax({
        url:"{{ route('admin.getAttributeValue')}}",
        type:"post",
        data:{
            _token:'{{ csrf_token() }}',
            id:attr_id,
        },
        success:function(response){

            if(response)
            {
                var data = JSON.parse(response);
                $('#attribute_value'+rowId).empty().append('<option value="0">Please Select value</option>');

                for (var key in data) {

                     $('#attribute_value'+rowId).append('<option value="'+key+'" >'+data[key]+'</option>');
                }

            }else{
                $('#attribute_value'+rowId).empty().append('<option value="0">Please Select value</option>');
            }

        }
    });

});

</code>```

and in controller

```<code>public function getAttributeValue(Request $request)
{

    $values = AttributeValue::where('attribute_id',$request->id)->get();
    if(count($values))
    {
        $v=[];
        foreach($values as $val)
        {
            $v[$val->id]=$val->value;
        }
       return  json_encode($v);
    }
}
</code>```

and on button click  its add Row

```<code><a href='#' onclick="add_more()">Add Row<a/>
x=1;
function add_more()
{
    var wrapper = $('#product_attribute');

    var html = '<div class="card " id="c'+x+'"><div class="card-body"><div class="row">';

    var attribute = $('#attribute').html();
    attribute = attribute.replace("selected","");
    var attr = '<div class="col-2"><select name="attribute[]" id="attribute" data-id="'+x+'" class="attribute form-control">'+attribute+'</select></div>';
    html += attr;

    var val = '<div class="col-3"><select multiple name="attribute_value[]" id="attribute_value'+x+'" class="form-control"><option value="0">Please Select</option></select></div>';
    html += val;
    html += '</div></div></div>';
    wrapper.append(html);
    x++;
}
</code>```

My problem is that

when the form submit the data shows me in this format

Attribute Array

```<code>$request->attribute = Array
(
    [0] => 1
    [1] => 2
)
</code>```

Attribute value Array

```<code>$request->attribute_value = Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
    [4] => 6
)
</code>```

In above example I select 2 Values for Size and 3 values for Color

I want to data like in this format

like for each attribute has a array of attribute values

```<code>
$arr = [];

arr[1] = [1,2],
arr[2] = [4,5,6]
</code>```

Can any body help me in this matter. Thanx

Body:
I have 2 Select options which are as follow:

<select name="attribute[]" id="attribute" data-id="1" >
    <option value="1">Size</option>
    <option value="2">Color</option>
</select>

<select name="attribute_value[]" id="attribute_value1"  multiple>
    <option value="0">Please Select</option>
<select>

and attribute value popup with ajax when change option on attribute

$(document).on('change','.attribute', function() {
    let attr_id = $(this).val();
    let rowId = $(this).data('id');

    $.ajax({
        url:"{{ route('admin.getAttributeValue')}}",
        type:"post",
        data:{
            _token:'{{ csrf_token() }}',
            id:attr_id,
        },
        success:function(response){

            if(response)
            {
                var data = JSON.parse(response);
                $('#attribute_value'+rowId).empty().append('<option value="0">Please Select value</option>');

                for (var key in data) {

                     $('#attribute_value'+rowId).append('<option value="'+key+'" >'+data[key]+'</option>');
                }

            }else{
                $('#attribute_value'+rowId).empty().append('<option value="0">Please Select value</option>');
            }

        }
    });

});

and in controller

public function getAttributeValue(Request $request)
{

    $values = AttributeValue::where('attribute_id',$request->id)->get();
    if(count($values))
    {
        $v=[];
        foreach($values as $val)
        {
            $v[$val->id]=$val->value;
        }
       return  json_encode($v);
    }
}

and on button click  its add Row

Add Row
x=1;
function add_more()
{
    var wrapper = $('#product_attribute');

    var html = '

';

    var attribute = $('#attribute').html();
    attribute = attribute.replace("selected","");
    var attr = '
<select name="attribute[]" id="attribute" data-id="'+x+'" class="attribute form-control">'+attribute+'</select>
';
    html += attr;

    var val = '
<select multiple name="attribute_value[]" id="attribute_value'+x+'" class="form-control"><option value="0">Please Select</option></select>
';
    html += val;
    html += '

';
    wrapper.append(html);
    x++;
}

My problem is that

when the form submit the data shows me in this format

Attribute Array

$request->attribute = Array
(
    [0] => 1
    [1] => 2
)

Attribute value Array

$request->attribute_value = Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
    [4] => 6
)

In above example I select 2 Values for Size and 3 values for Color

I want to data like in this format

like for each attribute has a array of attribute values

$arr = [];

arr[1] = [1,2],
arr[2] = [4,5,6]

Can any body help me in this matter. Thanx


问:
C++ Socket application closes for no reason
Basically I am creating a socket server in C++ which accepts connections, and then creates threads to send data to those connections.
For this I've used a while loop which basically is:

```<code>while (TRUE){
    listen_sock = listen(sock, SOMAXCONN);
    if (listen_sock == 0){
        accept_sock = accept(sock, NULL, NULL);
        if(accept_sock == INVALID_SOCKET){
            cout << "part 5\n";
            printf("accepting connection failed with error: %d\n", WSAGetLastError());
        }
        thread thrd(send_dat, accept_sock);
        thrd.detach();
    }
    else if (listen_sock == SOCKET_ERROR){
        cout << "part 4\n";
        printf("\n\nlistening on socket failed with error: %d\n", WSAGetLastError());
    }
}
</code>```

Basically send_dat(SOCKET accept_sock) is a function that just sends data to accept_sock socket:

```<code>void send_dat(SOCKET accept_sock){
/*variable declarations here*/
data = recv(accept_sock, recvbuf, recvbuflen, 0);
if (data == SOCKET_ERROR){
    cout << "part -1\n";
    throw runtime_error("Failed to receive data");
    WSAGetLastError();
}
data_res = response(data);
send_sock = send(accept_sock, data_res_len, data_res, 0);
if (send_sock == SOCKET_ERROR){
    cout << "part -2\n";
    throw runtime_error("Failed to send data");
    WSAGetLastError();
}
}
</code>```

The problem is that whenever I run it, it just closes after sending data to one user once, without any error or messages.
Why is this happening? Please help.

Body:
Basically I am creating a socket server in C++ which accepts connections, and then creates threads to send data to those connections.
For this I've used a while loop which basically is:

while (TRUE){
    listen_sock = listen(sock, SOMAXCONN);
    if (listen_sock == 0){
        accept_sock = accept(sock, NULL, NULL);
        if(accept_sock == INVALID_SOCKET){
            cout << "part 5\n";
            printf("accepting connection failed with error: %d\n", WSAGetLastError());
        }
        thread thrd(send_dat, accept_sock);
        thrd.detach();
    }
    else if (listen_sock == SOCKET_ERROR){
        cout << "part 4\n";
        printf("\n\nlistening on socket failed with error: %d\n", WSAGetLastError());
    }
}

Basically send_dat(SOCKET accept_sock) is a function that just sends data to accept_sock socket:

void send_dat(SOCKET accept_sock){
/*variable declarations here*/
data = recv(accept_sock, recvbuf, recvbuflen, 0);
if (data == SOCKET_ERROR){
    cout << "part -1\n";
    throw runtime_error("Failed to receive data");
    WSAGetLastError();
}
data_res = response(data);
send_sock = send(accept_sock, data_res_len, data_res, 0);
if (send_sock == SOCKET_ERROR){
    cout << "part -2\n";
    throw runtime_error("Failed to send data");
    WSAGetLastError();
}
}

The problem is that whenever I run it, it just closes after sending data to one user once, without any error or messages.
Why is this happening? Please help.


问:
covering edge cases of dates in Ruby
I have one usecase, where I am doing manipulation based on dates. However there are some edgecases which is causing trouble in my logic and I am not able to figure out a way to cover those edge-cases.

Problem statement:
I want to get all the records which comes under the current month cycle.

Ex: Plan starts at: 5 Oct 2022, then Whenever I query data based on the date of querying, it should return the records count for the current month cycle. Let say, today is 3rd Nov which means current cycle is 5th Oct to 4th Nov. then query should return records from this period.

Based on the below logic, I am able to get the date which I am using in my query to fetch records which are created from date till now.

```<code>  def get_current_month_contract_start_date(email)
    contract_date = User.find_by(email: email).cycle_start_date
    contract_day = contract_date.day if contract_date.present?
    today = DateTime.now
    if DateTime.now.day < contract_day
      prev = today - 1.month
      upper_bound_date = DateTime.new(prev.year, prev.month, contract_day, 0, 0, 0)
    else
      upper_bound_date = DateTime.new(today.year, today.month, contract_day, 0, 0, 0)
    end
    upper_bound_date
  end
</code>```

I am using below query to fetch the data from database:

```<code>User.find_by(email: email).where(:created_at.gte => get_current_month_contract_start_date(email)).count
</code>```

But the problem is edge cases.

Let say contract start date is-> 31 Jan, it should end 27 Feb, next start date should be 28 Feb, but #actual is: 31-01-23 expected: 28-02-2023 when today is #28 Feb

Let say contract start date is -> 28 Feb, it should end 30 March and next start date should be 31 march. Assume, If today's date is 28 March then result is #actual: 28-03-23 expected: 28-02-23, because cycle will end on 30 March(Month end to next month end).

Same if today's date is 30th March then result is #actual: 28-03-23 expected: 28-02-23

If today date is 31th March then result is #actual: 28-03-23 expected: 31-03-23

Can someone please suggest me how to cover these edge cases as well in the current code with necessary modifications. Since I am new to ruby I am not able to figure out the exact solution.

Title: covering edge cases of dates in Ruby

Body:
I have one usecase, where I am doing manipulation based on dates. However there are some edgecases which is causing trouble in my logic and I am not able to figure out a way to cover those edge-cases.

Problem statement:
I want to get all the records which comes under the current month cycle.

Ex: Plan starts at: 5 Oct 2022, then Whenever I query data based on the date of querying, it should return the records count for the current month cycle. Let say, today is 3rd Nov which means current cycle is 5th Oct to 4th Nov. then query should return records from this period.

Based on the below logic, I am able to get the date which I am using in my query to fetch records which are created from date till now.

  def get_current_month_contract_start_date(email)
    contract_date = User.find_by(email: email).cycle_start_date
    contract_day = contract_date.day if contract_date.present?
    today = DateTime.now
    if DateTime.now.day < contract_day
      prev = today - 1.month
      upper_bound_date = DateTime.new(prev.year, prev.month, contract_day, 0, 0, 0)
    else
      upper_bound_date = DateTime.new(today.year, today.month, contract_day, 0, 0, 0)
    end
    upper_bound_date
  end

I am using below query to fetch the data from database:

User.find_by(email: email).where(:created_at.gte => get_current_month_contract_start_date(email)).count

But the problem is edge cases.

Let say contract start date is-> 31 Jan, it should end 27 Feb, next start date should be 28 Feb, but #actual is: 31-01-23 expected: 28-02-2023 when today is #28 Feb

Let say contract start date is -> 28 Feb, it should end 30 March and next start date should be 31 march. Assume, If today's date is 28 March then result is #actual: 28-03-23 expected: 28-02-23, because cycle will end on 30 March(Month end to next month end).

Same if today's date is 30th March then result is #actual: 28-03-23 expected: 28-02-23

If today date is 31th March then result is #actual: 28-03-23 expected: 31-03-23

Can someone please suggest me how to cover these edge cases as well in the current code with necessary modifications. Since I am new to ruby I am not able to figure out the exact solution.


问:
Build Error Installing Macaulay2 on Arch Linux
When running makepkg for Macaulay2, I get the following error:

```<code>+ rm -f '/home/user-name/macaulay2/src/M2/M2/usr-host/lib/*.la'
/usr/bin/install -c -d /home/user-name/macaulay2/src/M2/M2/usr-host/bin
/usr/bin/install: cannot create directory ‘/home/user-name/macaulay2/src/M2/M2/usr-host/bin’: File exists
make[2]: *** [../Makefile.library:135: .installed-6.2.0] Error 1
make[2]: Leaving directory '/home/user-name/macaulay2/src/M2/M2/libraries/csdp'
make[1]: *** [Makefile:7: all-in-csdp] Error 2
make[1]: Leaving directory '/home/user-name/macaulay2/src/M2/M2/libraries'
make: *** [GNUmakefile:251: all-in-libraries] Error 2
==> ERROR: A failure occurred in build().
Aborting...
</code>```

What can I do to resolve this?

Body:
When running makepkg for Macaulay2, I get the following error:

+ rm -f '/home/user-name/macaulay2/src/M2/M2/usr-host/lib/*.la'
/usr/bin/install -c -d /home/user-name/macaulay2/src/M2/M2/usr-host/bin
/usr/bin/install: cannot create directory ‘/home/user-name/macaulay2/src/M2/M2/usr-host/bin’: File exists
make[2]: *** [../Makefile.library:135: .installed-6.2.0] Error 1
make[2]: Leaving directory '/home/user-name/macaulay2/src/M2/M2/libraries/csdp'
make[1]: *** [Makefile:7: all-in-csdp] Error 2
make[1]: Leaving directory '/home/user-name/macaulay2/src/M2/M2/libraries'
make: *** [GNUmakefile:251: all-in-libraries] Error 2
==> ERROR: A failure occurred in build().
Aborting...

What can I do to resolve this?


问:
React router doesn't route properly with firebase authentication
first of all I'm not an expert in react so this question may seem silly.

I have a react page that has a loginAdmin and an AdminDashboard, when an admin is logged in it redirect him to the admin dashboard! for now this is ok.

EDIT

What's coming is correct and both are solutions, but the problem is they both don't work until I update something in my code, it's probably getting the auth information from firebase delay is causing the problem!

The problem happens when the admin goes back to the login page, I want to prevent the page from showing if he's already logged in!

For this problem I've tried two ways for solving it, but both doesn't work until I update something.
Here's what I've tried!

First attempt: LOGIN

```<code>const [isLoggedIn, setLogin] = React.useState(false);
React.useEffect(()=>{
  checkIfLogged();
},[]);
const checkIfLogged=()=>{
  const auth= getAuth();
  const user = auth.currentUser; //Using firebase auth
  if (user){
   setLogin(true);
   console.log(user); // This is null until updating something then it prints the user informations
  else setLogin(false);
}
</code>```

And then in the rendering I've put the conditionnal rendering :

```<code>{isLoggedIn? <AdminDashboard />: <LoginAdmin />}
</code>```

If an admin is Logged and go to the login page, the login page shows until if and only if I update something in the code then it redirects to the adminDashboard.

My second attempt was with the routing, as mentioned in React router V6

I've tried adding the RequireAuth in my App.js :

```<code><Router>

<Routes>
<Route path='/admindashboard' element={<AdminDashboard} />
<Route path='/loginadmin' element={
      <RequireAuth redirectTo='/admindashboard'>
        <LoginAdmin />
      </RequireAuth>
      } />
</Routes>

</Router>
</code>```
```<code>function RequireAuth({ children, redirectTo }) {
  let isAuthenticated = getAuth().currentUser;
  console.log(isAuthenticated); //Null until some update!
  return isAuthenticated ? <Navigate to ={redirectTo} /> : children;
}
</code>```

And also doesn't work until I make some update, it's like the page is Loading before getting the auth informations ready!
Any help?

Body:
first of all I'm not an expert in react so this question may seem silly.

I have a react page that has a loginAdmin and an AdminDashboard, when an admin is logged in it redirect him to the admin dashboard! for now this is ok.

EDIT

What's coming is correct and both are solutions, but the problem is they both don't work until I update something in my code, it's probably getting the auth information from firebase delay is causing the problem!

The problem happens when the admin goes back to the login page, I want to prevent the page from showing if he's already logged in!

For this problem I've tried two ways for solving it, but both doesn't work until I update something.
Here's what I've tried!

First attempt: LOGIN

const [isLoggedIn, setLogin] = React.useState(false);
React.useEffect(()=>{
  checkIfLogged();
},[]);
const checkIfLogged=()=>{
  const auth= getAuth();
  const user = auth.currentUser; //Using firebase auth
  if (user){
   setLogin(true);
   console.log(user); // This is null until updating something then it prints the user informations
  else setLogin(false);
}

And then in the rendering I've put the conditionnal rendering :

{isLoggedIn? <AdminDashboard />: <LoginAdmin />}

If an admin is Logged and go to the login page, the login page shows until if and only if I update something in the code then it redirects to the adminDashboard.

My second attempt was with the routing, as mentioned in React router V6

I've tried adding the RequireAuth in my App.js :

<Router>

<Routes>
<Route path='/admindashboard' element={<AdminDashboard} />
<Route path='/loginadmin' element={
      <RequireAuth redirectTo='/admindashboard'>
        <LoginAdmin />
      </RequireAuth>
      } />
</Routes>

</Router>

function RequireAuth({ children, redirectTo }) {
  let isAuthenticated = getAuth().currentUser;
  console.log(isAuthenticated); //Null until some update!
  return isAuthenticated ? <Navigate to ={redirectTo} /> : children;
}

And also doesn't work until I make some update, it's like the page is Loading before getting the auth informations ready!
Any help?


问:
Error Building Android Kernel with Proton Clang
Currently I am trying to build the Google Pixel 7 Pro Kernel with Proton-Clang but i got this Error which i can not fix.

https://hastebin.com/miyocakiyu.yaml

I used older Version of the Clang but the Error is the Same.


问:
Apache POI convert HTML/XHTML to DOC/DOCX
I need to transform HTML to a doc file, the HTML is filled with custom information and the images and CSS change depending on what is request.

I'm trying to use Apache POI for this, but I'm having an error

```<code>`
org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0

    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
    at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
</code>```

My code is this:

```<code>  // Load the HTML file
            //Doc file
            String htmlFile = "pathToHtml/file.html";
            //String htmlFile = parseHTMLTemplate(disputeLetterDetails, template, fileExtension);

            //new File(htmlFile);
            //File file = new FileReader(htmlFile);

            Path path = Path.of(htmlFile);

            OutputStream in = new FileOutputStream(htmlFile, true);

            // Create a new XWPFDocument
            XWPFDocument document = new XWPFDocument();
            // Set up the XHTML options
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(new File("./images/")));
            options.setExtractor(new FileImageExtractor(new File("./images/")));
            // Convert the HTML to XWPFDocument
            XHTMLConverter.getInstance().convert(document, in, options);
            // Save the document to a .doc file
            FileOutputStream out = new FileOutputStream("pathToHtml/OUT_from_XHTML_TEST.docx");
            document.write(out);
            out.close();

    `
</code>```

I want to get a docx file from an HTML file with the same styles but I'm getting this error `

```<code>org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0

    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
    at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
`
</code>```

Body:
I need to transform HTML to a doc file, the HTML is filled with custom information and the images and CSS change depending on what is request.

I'm trying to use Apache POI for this, but I'm having an error

`
org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0

    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
    at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)

My code is this:

  // Load the HTML file
            //Doc file
            String htmlFile = "pathToHtml/file.html";
            //String htmlFile = parseHTMLTemplate(disputeLetterDetails, template, fileExtension);

            //new File(htmlFile);
            //File file = new FileReader(htmlFile);

            Path path = Path.of(htmlFile);

            OutputStream in = new FileOutputStream(htmlFile, true);

            // Create a new XWPFDocument
            XWPFDocument document = new XWPFDocument();
            // Set up the XHTML options
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(new File("./images/")));
            options.setExtractor(new FileImageExtractor(new File("./images/")));
            // Convert the HTML to XWPFDocument
            XHTMLConverter.getInstance().convert(document, in, options);
            // Save the document to a .doc file
            FileOutputStream out = new FileOutputStream("pathToHtml/OUT_from_XHTML_TEST.docx");
            document.write(out);
            out.close();

    `

I want to get a docx file from an HTML file with the same styles but I'm getting this error `

org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0

    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
    at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
    at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
`


问:
How do you configure docker to prevent it from updating itself
We ship our app as a docker image.

The database is PostgreSQL's official image.

It runs on a Kubuntu host v 18.4 LTS unfortunately these machines mostly operate offline and have little connectivity throughout the month. I have come to realize that docker has auto-updated at some point and has caused an issue that stops the docker daemon from starting.


问:
How to send form inputs to email using html and javascript
on submit, i would like for the contents of this form to be sent to an email address, I am unsure of what to add to the function below for it to work effectively.

HTML

```<code>          <div class="form-container" id="form-container">
                        <h2>Get a quote</h2>
                        <form id="contact" autocomplete="off" action="#">
                            <div class="form-field name-field">
                                <input type="text" id="name" placeholder="Full Name">
                                <div class="error"></div>
                            </div>
                            <div class="form-field">
                                <input type="text" id="email" placeholder="Email Address">
                                <div class="error"></div>
                            </div>
                            <div class="form-field">
                                <textarea rows="4" cols="50" id="comment" placeholder="Your Message" form="usrform"></textarea>
                                <div class="error text"></div>
                            </div>
                            <button type="submit" id="submit">Send Message</button>
                        </form>
                    </div>
                    <div class="form-container2 hide" id="form-container2">
                        <img src="assets/success.svg" alt="">
                        <h3>Message Sent</h3>
                        <p>Thanks for reaching out, our team will get back to you in the next 48 hours</p>
                        <button id="back" onclick="refreshPage()">Go Back</button>
                    </div>

</code>```

JAVASCRIPT

```<code>form.addEventListener("submit", (e) => {
        e.preventDefault();

        field(user, 0, "Name cannot be blank");
        field(msg, 2, "Message cannot be blank");

        if (
            !user.classList.contains("invalid") &&
            !email.classList.contains("invalid") &&
            !msg.classList.contains("invalid")
        ) {
            location.href = form.getAttribute("action");
            container1.classList.add("hide");
            container2.classList.remove("hide");
        }

});
</code>```

Body:
on submit, i would like for the contents of this form to be sent to an email address, I am unsure of what to add to the function below for it to work effectively.

HTML

Get a quote

                        <form id="contact" autocomplete="off" action="#">

                                <input type="text" id="name" placeholder="Full Name">

                                <input type="text" id="email" placeholder="Email Address">

                                <textarea rows="4" cols="50" id="comment" placeholder="Your Message" form="usrform"></textarea>

                            <button type="submit" id="submit">Send Message</button>
                        </form>

Message Sent

Thanks for reaching out, our team will get back to you in the next 48 hours

                        <button id="back" onclick="refreshPage()">Go Back</button>

JAVASCRIPT

form.addEventListener("submit", (e) => {
        e.preventDefault();

        field(user, 0, "Name cannot be blank");
        field(msg, 2, "Message cannot be blank");

        if (
            !user.classList.contains("invalid") &&
            !email.classList.contains("invalid") &&
            !msg.classList.contains("invalid")
        ) {
            location.href = form.getAttribute("action");
            container1.classList.add("hide");
            container2.classList.remove("hide");
        }

});


问:
CORS and server related problem on azure virtual machine
I have a nextjs app hosted on vercel and a file upload server running 0n a docker container on azure virtual machine behind ngnix.

But when I try to call the api from frontend it gives Mixed Content Error and tells me to use https://121.112.20.7/api instead of http://121.112.20.7/api. It doesn’t happen when my frontend is on local machine. It only happens on the vercel’s one. I tried to fix this using self-signed ssl in nginx server and also allowed azure network rules to give permission Port 443. It works on only those browser where I access my api url manually and ignore security cautions.

I enabled cors in my express file upload api server and also set the response headers -

```<code>"Access-Control-Allow-Origin", "*”
</code>```

If anyone can help how can I access my api server from frontend

I enabled cors in my express file upload api server and also set the response headers -

```<code>"Access-Control-Allow-Origin", "*”
</code>```

I tried to fix this using self-signed ssl in nginx server and also allowed azure network rules to give permission Port 443.

Body:
I have a nextjs app hosted on vercel and a file upload server running 0n a docker container on azure virtual machine behind ngnix.

But when I try to call the api from frontend it gives Mixed Content Error and tells me to use https://121.112.20.7/api instead of http://121.112.20.7/api. It doesn’t happen when my frontend is on local machine. It only happens on the vercel’s one. I tried to fix this using self-signed ssl in nginx server and also allowed azure network rules to give permission Port 443. It works on only those browser where I access my api url manually and ignore security cautions.

I enabled cors in my express file upload api server and also set the response headers -

"Access-Control-Allow-Origin", "*”

If anyone can help how can I access my api server from frontend

I enabled cors in my express file upload api server and also set the response headers -

"Access-Control-Allow-Origin", "*”

I tried to fix this using self-signed ssl in nginx server and also allowed azure network rules to give permission Port 443.