问:
In a pinescript loop supertrend function always return sames values
excuse me for my poor english.

I'm trying develop a profitable supertrend indicator. The idea it's to get the best combination of factor and period values to get the maximum winrate and profit possible.
To get this I save all supertrend results, the success and fails trades in a matrix.

But all this fails why seems supertrend function always return the same value, even though the params I pass be differents.

```<code>    //@version=5
indicator("POC Profitable supertrend", overlay=false)

inputStartDateEvaluation = input.time(timestamp("1 Jan 2023"), title="Start Date Evaluation")

type stInfo

    float atrFactor
    int atrPeriod

    int numberOfTrades = 0
    int successfullTrades = 0

    float initialClose = 0.0

    bool isUpTrend = na

type supertrendResult

    float trend
    float trendDirection
    float atrFactor
    int atrPeriod

stInfo bestCandidate = na

var infoData = matrix.new<stInfo>(81, 46)
var supertrendData = matrix.new<supertrendResult>(81, 46)

var table summaryTable = table.new(position.top_right, 2, 10)
var table outputTable = table.new(position.middle_left, 46, 81)

Trend(trendDirection) =>
    trendDirection < 0

success(stInfo info) =>
    na(info) ? 0.0 : info.successfullTrades / info.numberOfTrades * 100

if time >= inputStartDateEvaluation

    int factor = 1

    while factor <= 80

        float atrFactor = factor / 10

        int atrPeriod = 3

        while atrPeriod <= 45

            info = matrix.get(infoData, factor, atrPeriod)

            if na(info)
                info := stInfo.new(atrFactor, atrPeriod, 0, 0, 0.0)
                matrix.set(infoData, factor, atrPeriod, info)

            [trend, trendDirection] = ta.supertrend(atrFactor, atrPeriod)

            matrix.set(supertrendData, factor, atrPeriod, supertrendResult.new(trend, trendDirection, factor, atrPeriod))

            isUpTrend = isUpTrend(trendDirection)

            if na(info.isUpTrend) or info.isUpTrend != isUpTrend

                if not na(info.isUpTrend)

                    info.numberOfTrades := info.numberOfTrades + 1

                    if (info.isUpTrend and info.initialClose < close) or (not info.isUpTrend and info.initialClose > close)
                        info.successfullTrades := info.successfullTrades + 1

                info.isUpTrend := isUpTrend
                info.initialClose := close

            matrix.set(infoData, factor, atrPeriod, info)

            atrPeriod := atrPeriod + 1

        factor := factor + 1

if barstate.islast

    for atrPeriod = 3 to 45
        for factor = 1 to 80

            supertrendResult result = matrix.get(supertrendData, factor, atrPeriod)

            table.cell(outputTable, atrPeriod, factor, str.tostring(math.round(result.trend, 2)) + "/" + str.tostring(result.trendDirection), text_color = color.white )
</code>```

For a test purpose I show the matrix test in a table and I can see how the returned values always it's same. I don't understand what I'm doing wrong here. I know could be a problem call a function in a loop context, but I don't think be a problem in this case.

Anyone knows what is happening here, or a possible alternative approach to get the result than I wait?

Body:
excuse me for my poor english.

I'm trying develop a profitable supertrend indicator. The idea it's to get the best combination of factor and period values to get the maximum winrate and profit possible.
To get this I save all supertrend results, the success and fails trades in a matrix.

But all this fails why seems supertrend function always return the same value, even though the params I pass be differents.

    //@version=5
indicator("POC Profitable supertrend", overlay=false)

inputStartDateEvaluation = input.time(timestamp("1 Jan 2023"), title="Start Date Evaluation")

type stInfo

    float atrFactor
    int atrPeriod

    int numberOfTrades = 0
    int successfullTrades = 0

    float initialClose = 0.0

    bool isUpTrend = na

type supertrendResult

    float trend
    float trendDirection
    float atrFactor
    int atrPeriod

stInfo bestCandidate = na

var infoData = matrix.new<stInfo>(81, 46)
var supertrendData = matrix.new<supertrendResult>(81, 46)

var table summaryTable = table.new(position.top_right, 2, 10)
var table outputTable = table.new(position.middle_left, 46, 81)

Trend(trendDirection) =>
    trendDirection < 0

success(stInfo info) =>
    na(info) ? 0.0 : info.successfullTrades / info.numberOfTrades * 100

if time >= inputStartDateEvaluation

    int factor = 1

    while factor <= 80

        float atrFactor = factor / 10

        int atrPeriod = 3

        while atrPeriod <= 45

            info = matrix.get(infoData, factor, atrPeriod)

            if na(info)
                info := stInfo.new(atrFactor, atrPeriod, 0, 0, 0.0)
                matrix.set(infoData, factor, atrPeriod, info)

            [trend, trendDirection] = ta.supertrend(atrFactor, atrPeriod)

            matrix.set(supertrendData, factor, atrPeriod, supertrendResult.new(trend, trendDirection, factor, atrPeriod))

            isUpTrend = isUpTrend(trendDirection)

            if na(info.isUpTrend) or info.isUpTrend != isUpTrend

                if not na(info.isUpTrend)

                    info.numberOfTrades := info.numberOfTrades + 1

                    if (info.isUpTrend and info.initialClose < close) or (not info.isUpTrend and info.initialClose > close)
                        info.successfullTrades := info.successfullTrades + 1

                info.isUpTrend := isUpTrend
                info.initialClose := close

            matrix.set(infoData, factor, atrPeriod, info)

            atrPeriod := atrPeriod + 1

        factor := factor + 1

if barstate.islast

    for atrPeriod = 3 to 45
        for factor = 1 to 80

            supertrendResult result = matrix.get(supertrendData, factor, atrPeriod)

            table.cell(outputTable, atrPeriod, factor, str.tostring(math.round(result.trend, 2)) + "/" + str.tostring(result.trendDirection), text_color = color.white )

For a test purpose I show the matrix test in a table and I can see how the returned values always it's same. I don't understand what I'm doing wrong here. I know could be a problem call a function in a loop context, but I don't think be a problem in this case.

Anyone knows what is happening here, or a possible alternative approach to get the result than I wait?


来源: stackexchange

问:
How can I write query using groupby .net core 5.0
I get this error:

Expression of type 'System.Collections.Generic.List1[berberApp.Models.ViewModel.AdminReservationviewModel]' cannot be used for parameter of type 'System.Linq.IQueryable1[berberApp.Models.ViewModel.AdminReservationviewModel]' of method 'System.Linq.IQueryable1[System.Linq.IGrouping2[System.Int32,berberApp.Models.ViewModel.AdminReservationviewModel]] GroupBy[AdminReservationviewModel,Int32](System.Linq.IQueryable1[berberApp.Models.ViewModel.AdminReservationviewModel], System.Linq.Expressions.Expression1[System.Func`2[berberApp.Models.ViewModel.AdminReservationviewModel,System.Int32]])' (Parameter 'arg0')

controller.cs

```<code>t = (from reservation in c_.Reservations
     join times in c_.Times
          on reservation.TimeId equals times.TimeId
     join users in c_.Users
          on reservation.EmployerId equals users.UserId
     orderby reservation.Date
     select new ReservationViewModel
                {
                    MeetingId = reservation.MeetingId,
                    UserName = users.UserName,
                    Date = reservation.Date,
                    Time = times.TimeName,
                    ToplamSure = reservation.ToplamSure,
                    ToplamTutar = reservation.ToplamTutar,
                    Service = (from m in c_.MultiReservations
                               join s in c_.Services on m.ServiceId equals s.ServiceId
                               where reservation.MeetingId == m.MeetingId
                               select new AdminReservationviewModel
                                    {
                                        ServiceId = m.ServiceId,
                                        Operations = s.Operation,
                                    }).ToList()
                                  .GroupBy(s => s.ServiceId).ToList()
                     }).ToList();
</code>```

ReservationViewModel.cs

```<code>    public int MeetingId { get; set; }
    public int MultiReservationId { get; set; }
    public int ServiceId { get; set; }
    public string Operations { get; set; }
    public string UserName { get; set; }
    public TimeSpan Time { get; set; }
    public int TimeId { get; set; }
    public DateTime? Date { get; set; }
    public List<IGrouping<int,AdminReservationviewModel>> Service { get; set; }
</code>```

AdminReservationviewModel.cs

```<code> public int ServiceId { get; set; }
 public string Operations { get; set; }
</code>```

I want to list user's services in user's reservation's list with using groupby expression in a Linq query.

ContentLicense: CC BY-SA 4.0

Body:
I get this error:

Expression of type 'System.Collections.Generic.List1[berberApp.Models.ViewModel.AdminReservationviewModel]' cannot be used for parameter of type 'System.Linq.IQueryable1[berberApp.Models.ViewModel.AdminReservationviewModel]' of method 'System.Linq.IQueryable1[System.Linq.IGrouping2[System.Int32,berberApp.Models.ViewModel.AdminReservationviewModel]] GroupBy[AdminReservationviewModel,Int32](System.Linq.IQueryable1[berberApp.Models.ViewModel.AdminReservationviewModel], System.Linq.Expressions.Expression1[System.Func`2[berberApp.Models.ViewModel.AdminReservationviewModel,System.Int32]])' (Parameter 'arg0')

controller.cs

t = (from reservation in c_.Reservations
     join times in c_.Times
          on reservation.TimeId equals times.TimeId
     join users in c_.Users
          on reservation.EmployerId equals users.UserId
     orderby reservation.Date
     select new ReservationViewModel
                {
                    MeetingId = reservation.MeetingId,
                    UserName = users.UserName,
                    Date = reservation.Date,
                    Time = times.TimeName,
                    ToplamSure = reservation.ToplamSure,
                    ToplamTutar = reservation.ToplamTutar,
                    Service = (from m in c_.MultiReservations
                               join s in c_.Services on m.ServiceId equals s.ServiceId
                               where reservation.MeetingId == m.MeetingId
                               select new AdminReservationviewModel
                                    {
                                        ServiceId = m.ServiceId,
                                        Operations = s.Operation,
                                    }).ToList()
                                  .GroupBy(s => s.ServiceId).ToList()
                     }).ToList();

ReservationViewModel.cs

    public int MeetingId { get; set; }
    public int MultiReservationId { get; set; }
    public int ServiceId { get; set; }
    public string Operations { get; set; }
    public string UserName { get; set; }
    public TimeSpan Time { get; set; }
    public int TimeId { get; set; }
    public DateTime? Date { get; set; }
    public List<IGrouping<int,AdminReservationviewModel>> Service { get; set; }

AdminReservationviewModel.cs

 public int ServiceId { get; set; }
 public string Operations { get; set; }

I want to list user's services in user's reservation's list with using groupby expression in a Linq query.


问:
Code optimization for Google Sheets with date autofill
Help please complete the code. The idea is that the date is automatically filled in the cell when the amount reaches zero. But the problem is that when the amount is calculated by the formula and reaches zero, the date does not appear, and if I manually put zero in this cell, everything works.

My code

```<code>// The column to check if something is entered.
const COLUMNTOCHECK = 20;
// Where the date timestamp offset from the input location. [row, column]
const DATETIMELOCATION = [0,-16];
// Sheet working on
const SHEETNAME = 'Sheet 1'

function onEdit(e) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  //checks that we're on the correct sheet.
  if( sheet.getSheetName() == SHEETNAME) {
    const selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK && e.value <= 0) {
      const dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
      dateTimeCell.setValue(new Date());
      }
  }
}
</code>```

Body:
Help please complete the code. The idea is that the date is automatically filled in the cell when the amount reaches zero. But the problem is that when the amount is calculated by the formula and reaches zero, the date does not appear, and if I manually put zero in this cell, everything works.

My code

// The column to check if something is entered.
const COLUMNTOCHECK = 20;
// Where the date timestamp offset from the input location. [row, column]
const DATETIMELOCATION = [0,-16];
// Sheet working on
const SHEETNAME = 'Sheet 1'

function onEdit(e) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  //checks that we're on the correct sheet.
  if( sheet.getSheetName() == SHEETNAME) {
    const selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK && e.value <= 0) {
      const dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
      dateTimeCell.setValue(new Date());
      }
  }
}


问:
Matplotlib add labels to individual stacks in a stacked chart for imbalanced dataset
I am trying to plot a graph based on a huge imbalanced dataset using matplotlib and it looks something like

I want to represent % values on each bar, but they all seem cluttered/messy when the stacks get really small. The dataset is dynamic, and I cannot modify it.

I tried playing around with matplotlib.text, but couldn't figure out a way to get past this.

```<code>def plot_stack_bar(plot_df, xlabel, ylabel, title):

    plot_df_percent=pd.DataFrame()
    cols = list(plot_df)
    plot_df_percent[cols] = plot_df[cols].div( plot_df[cols].sum(axis=1), axis=0 )

    plot_df.plot(kind='bar', stacked=True, figsize=(20, 17))
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)

    for n, x in enumerate([*plot_df.index.values]):
        i=0
        for (proportion, y_loc) in zip(plot_df_percent.loc[x],
                                       plot_df_percent.loc[x].cumsum()):

            y_loc = plot_df.iloc[n,I] / 2 + plot_df.iloc[n,:i].sum()
            plt.text(x=n-0.17,
                     y=y_loc,
                     s=f'{np.round(proportion * 100, 1)}%',
                     color="black",
                     fontsize=12,
                     fontweight="bold")
            i=i+1
    plt.savefig(f'draft/{title}.png')
    plt.show()
</code>```

Appreciate any help.

Body:
I am trying to plot a graph based on a huge imbalanced dataset using matplotlib and it looks something like

I want to represent % values on each bar, but they all seem cluttered/messy when the stacks get really small. The dataset is dynamic, and I cannot modify it.

I tried playing around with matplotlib.text, but couldn't figure out a way to get past this.

def plot_stack_bar(plot_df, xlabel, ylabel, title):

    plot_df_percent=pd.DataFrame()
    cols = list(plot_df)
    plot_df_percent[cols] = plot_df[cols].div( plot_df[cols].sum(axis=1), axis=0 )

    plot_df.plot(kind='bar', stacked=True, figsize=(20, 17))
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)

    for n, x in enumerate([*plot_df.index.values]):
        i=0
        for (proportion, y_loc) in zip(plot_df_percent.loc[x],
                                       plot_df_percent.loc[x].cumsum()):

            y_loc = plot_df.iloc[n,I] / 2 + plot_df.iloc[n,:i].sum()
            plt.text(x=n-0.17,
                     y=y_loc,
                     s=f'{np.round(proportion * 100, 1)}%',
                     color="black",
                     fontsize=12,
                     fontweight="bold")
            i=i+1
    plt.savefig(f'draft/{title}.png')
    plt.show()

Appreciate any help.


问:
Is there a way to implement a common go back function for both ios and android in react native webview?
My code currently utilizes BackHandler which is Android exclusive.
I want a common solution for going back in the webview on both android and ios.

The code for go back functionality is from: React-Native: Go back on android hardware back button pressed

current code:

```<code>const App = () => {
  const webView = useRef();

  const [canGoBack, setCanGoBack] = useState(false);

  const handleBack = useCallback(() => {
    if (canGoBack && webView.current) {
      webView.current.goBack();
      return true;
    }
    return false;
  }, [canGoBack]);

  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handleBack);
    return () => {
      BackHandler.removeEventListener("hardwareBackPress", handleBack);
    };
  }, [handleBack]);

  return (
    <SafeAreaView style={{flex:1}} >
      <KeyboardAvoidingView style={{flex:1}}>
        <WebView
          source={{
            uri: "<UriHere>"
          }}
          style={{flex:1}}
          ref={webView}
          onLoadProgress={(event) => setCanGoBack(event.nativeEvent.canGoBack)}
        />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};
</code>```

Body:
My code currently utilizes BackHandler which is Android exclusive.
I want a common solution for going back in the webview on both android and ios.

The code for go back functionality is from: React-Native: Go back on android hardware back button pressed

current code:

const App = () => {
  const webView = useRef();

  const [canGoBack, setCanGoBack] = useState(false);

  const handleBack = useCallback(() => {
    if (canGoBack && webView.current) {
      webView.current.goBack();
      return true;
    }
    return false;
  }, [canGoBack]);

  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handleBack);
    return () => {
      BackHandler.removeEventListener("hardwareBackPress", handleBack);
    };
  }, [handleBack]);

  return (
    <SafeAreaView style={{flex:1}} >
      <KeyboardAvoidingView style={{flex:1}}>
        <WebView
          source={{
            uri: "<UriHere>"
          }}
          style={{flex:1}}
          ref={webView}
          onLoadProgress={(event) => setCanGoBack(event.nativeEvent.canGoBack)}
        />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};


问:
How to fix/avoid header duplication in the Reportlab table?
After writing the following code, I have generated a pdf invoice (picture attached). As you can see there are header duplicaiton in the invoice table. How can I fix this? Please see the generateInvoice()function.

My code:

```<code>import tkinter as tk
from tkinter import ttk
import pandas as pd
from tkinter import filedialog
import mysql.connector
import os
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

def browse_file():
    # Open the file browser dialog
    file_path = filedialog.askopenfilename()

    # Read the Excel file into a DataFrame
    df = pd.read_excel("mpo.xlsx", sheet_name='OrderDetails')
    df = df.fillna('NULL')

    # Connect to the MySQL database
    conn = mysql.connector.connect(user='root', password='', host='localhost', database='magnetico')
    cursor = conn.cursor()

    # Insert each row into the MySQL database
    for index, row in df.iterrows():

      cursor.execute("INSERT INTO perorder (mp_task_nr, batch_id, dropoff_sequence, id_user_payout_type, task_status, city, fleet, id_user, Name, Vendor, order_date, UID, KM, total_amount, Remarks) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )", (row["mp_task_nr"], row["batch_id"], row["dropoff_sequence"], row["id_user_payout_type"], row["task_status"], row["city"], row["fleet"], row["id_user"], row["Name"], row["Vendor"], row["order_date"], row["UID"], row["KM"], row["total_amount"], row["Remarks"]))

    # Commit the changes and close the cursor and connection
    conn.commit()
    cursor.close()
    conn.close()

def populate_treeview():
    # Connect to the MySQL database
    conn = mysql.connector.connect(user='root', password='', host='localhost', database='magnetico')
    cursor = conn.cursor()

    # Execute a SELECT statement
    cursor.execute("SELECT id_user, Vendor, KM FROM perorder")

    # Fetch the results
    results = cursor.fetchall()

    # Add the results to the Treeview widget
    for result in results:
        treeview.insert("", tk.END, values=result)

    # Close the cursor and connection
    cursor.close()
    conn.close()

def generateInvoice():

  # Connect to the MySQL database
  conn = mysql.connector.connect(user='root', password='', host='localhost', database='magnetico')
  cursor = conn.cursor()

  tables = []

  # Execute the first SELECT statement
  cursor.execute("SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 1 and 3 GROUP BY CITY")

  # Process the results of the first SELECT statement
  results = cursor.fetchall()
  table_data1 = []
  table_data1.append(['City', 'Qantity', 'Rate', 'Amount', 'Taxable Value','Amount + 5% VAT', 'Grand Total'])
  for result in results:
    table_data1.append([result[0], result[1], result[2], result[3], result[4], result[5], result[6]])

  # Create the table
  table1 = Table(table_data1)

  # Set the table style
  table1.setStyle(TableStyle([
      ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
      ('BOX', (0,0), (-1,-1), 0.25, colors.black)
  ]))

  # Add the table to the list
  tables.append(table1)

  # Execute the second SELECT statement
  cursor.execute("SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 4 and 5 GROUP BY CITY")

  # Process the results of the second SELECT statement
  results = cursor.fetchall()
  table_data2 = []

  table_data2.append(['City', 'Qantity', 'Rate', 'Amount', 'Taxable Value','Amount + 5% VAT', 'Grand Total'])
  for result in results:
    table_data2.append([result[0], result[1], result[2], result[3], result[4], result[5], result[6]])

  # Create the table
  table2 = Table(table_data2)

  # Set the table style
  table2.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # Add the table to the list
  tables.append(table2)

  # Execute the third SELECT STATEMENT
  cursor.execute("SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 6 and 7 GROUP BY CITY")

  # Process the results of the second SELECT statement
  results = cursor.fetchall()
  table_data3 = []
  table_data3.append(['City', 'Qantity', 'Rate', 'Amount', 'Taxable Value','Amount + 5% VAT', 'Grand Total'])
  for result in results:
    table_data3.append([result[0], result[1], result[2], result[3], result[4], result[5], result[6]])

  # Create the table
  table3 = Table(table_data3)

  # Set the table style
  table3.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # Add the table to the list
  tables.append(table3)

  # Create the PDF file
  pdf_file = "invoice.pdf"
  doc = SimpleDocTemplate(pdf_file, pagesize=letter)

  # Create the tables
  table1 = Table(table_data1)
  table2 = Table(table_data2)
  table3 = Table(table_data3)

  # Set the table style
  table1.setStyle(TableStyle([
      ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
      ('BOX', (0,0), (-1,-1), 0.25, colors.black)
  ]))

  # table2.setStyle(TableStyle([
  table2.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # table3.setStyle(TableStyle([
  table3.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # Build the document
  doc.build([table1, table2, table3])

# Create the root window
root = tk.Tk()
root.title("Megnatico Invoice System")
root.geometry("800x800")

# Create the treeview
treeview = ttk.Treeview(root)
treeview.pack(side="left", fill="both", expand=True)

treeview["columns"] = ("id_user", "Vendor", "KM")
treeview.column("id_user", width=150, minwidth=150, stretch=tk.NO)
treeview.column("Vendor", width=150, minwidth=150, stretch=tk.NO)
treeview.column("KM", width=150, minwidth=150, stretch=tk.NO)
treeview.heading("id_user", text="User ID")
treeview.heading("Vendor", text="Vendor")
treeview.heading("KM", text="KM")
treeview["displaycolumns"] = ("id_user", "Vendor", "KM")

# Create the buttons
read_excel_button = tk.Button(root, text="Read Excel", command=browse_file)
invoice_per_order_button = tk.Button(root, text="Invoice per Order", command=populate_treeview)
save_pdf_button = tk.Button(root, text="Generate Invoice", command=generateInvoice)
close_button = tk.Button(root, text="Close")

# Place the buttons in a frame and pack the frame to the right of the root window
button_frame = tk.Frame(root)
button_frame.pack(side="right", fill="both")
read_excel_button.pack(padx=10, pady=5)
invoice_per_order_button.pack(padx=10, pady=5)
save_pdf_button.pack(padx=10, pady=5)
close_button.pack(padx=10, pady=5)

# Run the Tkinter event loop
root.mainloop()
</code>```

Invoice with header duplication

Body:
After writing the following code, I have generated a pdf invoice (picture attached). As you can see there are header duplicaiton in the invoice table. How can I fix this? Please see the generateInvoice()function.

My code:

import tkinter as tk
from tkinter import ttk
import pandas as pd
from tkinter import filedialog
import mysql.connector
import os
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

def browse_file():
    # Open the file browser dialog
    file_path = filedialog.askopenfilename()

    # Read the Excel file into a DataFrame
    df = pd.read_excel("mpo.xlsx", sheet_name='OrderDetails')
    df = df.fillna('NULL')

    # Connect to the MySQL database
    conn = mysql.connector.connect(user='root', password='', host='localhost', database='magnetico')
    cursor = conn.cursor()

    # Insert each row into the MySQL database
    for index, row in df.iterrows():

      cursor.execute("INSERT INTO perorder (mp_task_nr, batch_id, dropoff_sequence, id_user_payout_type, task_status, city, fleet, id_user, Name, Vendor, order_date, UID, KM, total_amount, Remarks) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )", (row["mp_task_nr"], row["batch_id"], row["dropoff_sequence"], row["id_user_payout_type"], row["task_status"], row["city"], row["fleet"], row["id_user"], row["Name"], row["Vendor"], row["order_date"], row["UID"], row["KM"], row["total_amount"], row["Remarks"]))

    # Commit the changes and close the cursor and connection
    conn.commit()
    cursor.close()
    conn.close()

def populate_treeview():
    # Connect to the MySQL database
    conn = mysql.connector.connect(user='root', password='', host='localhost', database='magnetico')
    cursor = conn.cursor()

    # Execute a SELECT statement
    cursor.execute("SELECT id_user, Vendor, KM FROM perorder")

    # Fetch the results
    results = cursor.fetchall()

    # Add the results to the Treeview widget
    for result in results:
        treeview.insert("", tk.END, values=result)

    # Close the cursor and connection
    cursor.close()
    conn.close()

def generateInvoice():

  # Connect to the MySQL database
  conn = mysql.connector.connect(user='root', password='', host='localhost', database='magnetico')
  cursor = conn.cursor()

  tables = []

  # Execute the first SELECT statement
  cursor.execute("SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 1 and 3 GROUP BY CITY")

  # Process the results of the first SELECT statement
  results = cursor.fetchall()
  table_data1 = []
  table_data1.append(['City', 'Qantity', 'Rate', 'Amount', 'Taxable Value','Amount + 5% VAT', 'Grand Total'])
  for result in results:
    table_data1.append([result[0], result[1], result[2], result[3], result[4], result[5], result[6]])

  # Create the table
  table1 = Table(table_data1)

  # Set the table style
  table1.setStyle(TableStyle([
      ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
      ('BOX', (0,0), (-1,-1), 0.25, colors.black)
  ]))

  # Add the table to the list
  tables.append(table1)

  # Execute the second SELECT statement
  cursor.execute("SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 4 and 5 GROUP BY CITY")

  # Process the results of the second SELECT statement
  results = cursor.fetchall()
  table_data2 = []

  table_data2.append(['City', 'Qantity', 'Rate', 'Amount', 'Taxable Value','Amount + 5% VAT', 'Grand Total'])
  for result in results:
    table_data2.append([result[0], result[1], result[2], result[3], result[4], result[5], result[6]])

  # Create the table
  table2 = Table(table_data2)

  # Set the table style
  table2.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # Add the table to the list
  tables.append(table2)

  # Execute the third SELECT STATEMENT
  cursor.execute("SELECT city, count(KM), sum(total_amount), total_amount*count(KM), total_amount*count(KM), round(total_amount*count(KM)*0.05,2), total_amount*count(KM)*0.05+(total_amount*count(KM)) FROM perorder where city like '%XB' and KM between 6 and 7 GROUP BY CITY")

  # Process the results of the second SELECT statement
  results = cursor.fetchall()
  table_data3 = []
  table_data3.append(['City', 'Qantity', 'Rate', 'Amount', 'Taxable Value','Amount + 5% VAT', 'Grand Total'])
  for result in results:
    table_data3.append([result[0], result[1], result[2], result[3], result[4], result[5], result[6]])

  # Create the table
  table3 = Table(table_data3)

  # Set the table style
  table3.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # Add the table to the list
  tables.append(table3)

  # Create the PDF file
  pdf_file = "invoice.pdf"
  doc = SimpleDocTemplate(pdf_file, pagesize=letter)

  # Create the tables
  table1 = Table(table_data1)
  table2 = Table(table_data2)
  table3 = Table(table_data3)

  # Set the table style
  table1.setStyle(TableStyle([
      ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
      ('BOX', (0,0), (-1,-1), 0.25, colors.black)
  ]))

  # table2.setStyle(TableStyle([
  table2.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # table3.setStyle(TableStyle([
  table3.setStyle(TableStyle([
    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
    ('BOX', (0,0), (-1,-1), 0.25, colors.black),
  ]))

  # Build the document
  doc.build([table1, table2, table3])

# Create the root window
root = tk.Tk()
root.title("Megnatico Invoice System")
root.geometry("800x800")

# Create the treeview
treeview = ttk.Treeview(root)
treeview.pack(side="left", fill="both", expand=True)

treeview["columns"] = ("id_user", "Vendor", "KM")
treeview.column("id_user", width=150, minwidth=150, stretch=tk.NO)
treeview.column("Vendor", width=150, minwidth=150, stretch=tk.NO)
treeview.column("KM", width=150, minwidth=150, stretch=tk.NO)
treeview.heading("id_user", text="User ID")
treeview.heading("Vendor", text="Vendor")
treeview.heading("KM", text="KM")
treeview["displaycolumns"] = ("id_user", "Vendor", "KM")

# Create the buttons
read_excel_button = tk.Button(root, text="Read Excel", command=browse_file)
invoice_per_order_button = tk.Button(root, text="Invoice per Order", command=populate_treeview)
save_pdf_button = tk.Button(root, text="Generate Invoice", command=generateInvoice)
close_button = tk.Button(root, text="Close")

# Place the buttons in a frame and pack the frame to the right of the root window
button_frame = tk.Frame(root)
button_frame.pack(side="right", fill="both")
read_excel_button.pack(padx=10, pady=5)
invoice_per_order_button.pack(padx=10, pady=5)
save_pdf_button.pack(padx=10, pady=5)
close_button.pack(padx=10, pady=5)

# Run the Tkinter event loop
root.mainloop()

Invoice with header duplication


问:
Camera 2 API throws Access denied finding property "vendor.camera.aux.packagelist"
```<code>package com.example.camerastatuscheck;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION = 200;
    public static final String ACTION_USB_PERMISSION = "com.example.usbtestapp.USB_PERMISSION";
    static final int intentFlags = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : 0;
    static final int MY_CAMERA_PERMISSION_CODE = 100;
    private Context ContextofMainAcitivity;
    public IntentFilter USBconnectdisconnect_intentFilter;
    public Intent GetEXTRA_PERMISSION_GRANTEDIntent;
    public PendingIntent current_usbpermissionIntent;
    public UsbDevice current_usbdevice;
    public UsbManager current_usbManager;
    private static final String TAG = "usbtestapp";
    TextureView new_textureview;
    Button new_open_camera,nextactivity;
    UsbDeviceConnection usbConnection;
    PendingIntent permissionIntent;
    private static final int REQUEST_CAMERA_PERMISSION = 200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        camera_start();
    }
    private void camera_start() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(fornewpos.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
            return;
        }
        Log.d("camera start", "success");
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while(deviceIterator.hasNext()){
            UsbDevice device = deviceIterator.next();
            manager.requestPermission(device, permissionIntent);;
            //your code
        }
        Log.d("Camrea srtart","camera start");
        CameraManager manager =
                (CameraManager)getSystemService(CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics chars
                        = manager.getCameraCharacteristics(cameraId);
                // Do something with the characteristics
                int deviceLevel = chars.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
                Log.d(TAG, " **** device ["+cameraId+"] level:"+deviceLevel);
                Toast.makeText(getApplicationContext(), "cameraId", Toast.LENGTH_SHORT).show();
            }
        } catch(CameraAccessException e){
            e.printStackTrace();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(device != null){
                            Toast.makeText(context, "Permission granded", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else {
                        Toast.makeText(context, "Permission denied", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
public boolean supportsExternalCameras() {
        return this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_EXTERNAL);
    }
}
</code>```

Log

2023-01-07 15:31:55.318 23651-23651 libc                    com.example.cmaera5                  E  Access denied finding property "vendor.camera.aux.packagelist"

AndroidManifest

```<code><uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera2.full" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.usb.host" />
    <uses-feature android:name="android.hardware.usb.accessory" />
    <uses-feature android:name="android.hardware.usb" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
</code>```

Description

I have been using the above code to capture an image from an External USB Camera (Web Cam). This code is working perfectly on most devices, but on some device, it throws

2023-01-07 15:31:55.318 23651-23651 libc   com.example.cmaera5  E
Access denied finding property "vendor.camera.aux.packagelist"

In some devices it shows the above error message in logcat while trying to get the camera ID to open the camera

I gave permission to camera, external storage and USB device

The device Configuration that shows the error

Android OS version: 9.0

API Level         : 28

Please provide me with an explanation of what is happening.

Body:
package com.example.camerastatuscheck;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION = 200;
    public static final String ACTION_USB_PERMISSION = "com.example.usbtestapp.USB_PERMISSION";
    static final int intentFlags = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : 0;
    static final int MY_CAMERA_PERMISSION_CODE = 100;
    private Context ContextofMainAcitivity;
    public IntentFilter USBconnectdisconnect_intentFilter;
    public Intent GetEXTRA_PERMISSION_GRANTEDIntent;
    public PendingIntent current_usbpermissionIntent;
    public UsbDevice current_usbdevice;
    public UsbManager current_usbManager;
    private static final String TAG = "usbtestapp";
    TextureView new_textureview;
    Button new_open_camera,nextactivity;
    UsbDeviceConnection usbConnection;
    PendingIntent permissionIntent;
    private static final int REQUEST_CAMERA_PERMISSION = 200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        camera_start();
    }
    private void camera_start() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(fornewpos.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
            return;
        }
        Log.d("camera start", "success");
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while(deviceIterator.hasNext()){
            UsbDevice device = deviceIterator.next();
            manager.requestPermission(device, permissionIntent);;
            //your code
        }
        Log.d("Camrea srtart","camera start");
        CameraManager manager =
                (CameraManager)getSystemService(CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics chars
                        = manager.getCameraCharacteristics(cameraId);
                // Do something with the characteristics
                int deviceLevel = chars.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
                Log.d(TAG, " **** device ["+cameraId+"] level:"+deviceLevel);
                Toast.makeText(getApplicationContext(), "cameraId", Toast.LENGTH_SHORT).show();
            }
        } catch(CameraAccessException e){
            e.printStackTrace();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // close the app
                Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(device != null){
                            Toast.makeText(context, "Permission granded", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else {
                        Toast.makeText(context, "Permission denied", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
public boolean supportsExternalCameras() {
        return this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_EXTERNAL);
    }
}

Log

2023-01-07 15:31:55.318 23651-23651 libc                    com.example.cmaera5                  E  Access denied finding property "vendor.camera.aux.packagelist"

AndroidManifest

<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera2.full" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.usb.host" />
    <uses-feature android:name="android.hardware.usb.accessory" />
    <uses-feature android:name="android.hardware.usb" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" />

Description

I have been using the above code to capture an image from an External USB Camera (Web Cam). This code is working perfectly on most devices, but on some device, it throws

2023-01-07 15:31:55.318 23651-23651 libc   com.example.cmaera5  E
Access denied finding property "vendor.camera.aux.packagelist"

In some devices it shows the above error message in logcat while trying to get the camera ID to open the camera

I gave permission to camera, external storage and USB device

The device Configuration that shows the error

Android OS version: 9.0

API Level         : 28

Please provide me with an explanation of what is happening.


问:
Publish package to yarn, npm and github registry
I just created my first package and as I wanted to show it on my GitHub profile so I published it to the GitHub package registry.

Now I ran into a problem I can't npm install it without specifying the GitHub registry.
Alright just uploaded it to the npm registry as well...

But as I am usually using yarn as package manager I found out yarn apparently has its own registry.

I don't want to publish it on every update to all 3 registries manually... can this be automated?
Is there a way to keep the same org and package name across all registries since my npm package already has another org name...

Npm package: https://www.npmjs.com/package/@sebastian.boehler/philipshue
GitHub package: https://github.com/SebastianBoehler/philipsHue/pkgs/npm/philipshue

Tho the GitHub package page shows the npm install command without the registry specified, since its auto-generated I thought it should specify it bc otherwise installation fails bc of [package] is not in this registry. error.

Or am I missing something?


问:
How to monitor JSONP URL and response time in JS?
How to detect and capture all JSONP-type URLs and response times in the application?
I'm having an application where I can detect XHR and fetch types using window objects, but in the case of JSONP, I couldn't detect it.</p>


问:
Changing a value in 2d array but result in the unexpected changes in C
I have been trying to design a tic tac toe game but I faced some weird situation when running the programme. It's like when I choose one box, all boxes in the same column are chosen. Also after the game field is drawn, I found that the result detected once again changed and becomes different from what I expected to show and what the game field has shown. I still couldn't find the solution of it so please help me (cry

```<code>#include <stdio.h>
#include <stdbool.h>

typedef enum State {
  empty,
  cross,
  circle,
} state;

typedef enum ActivePlayer {
  One= 1,
  Two= 2,
} activePlayer;

int i=0;
int j=0;
void DrawGameField(int map[i][j]){
  printf("\n");
  printf("This is the game of Tic Tac Toe:)\n");
  printf("Player 1: 'X'  Player 2: 'O' \n\n");
  for(int i=0; i<3; i++){
    for(int j=0; j<3; j++){
      if(map[i][j] == empty){
        printf(".");
      }
      else if(map[i][j] == cross){
        printf("X");
      }
      else if(map[i][j] == circle){
        printf("O");
      }
      else{
        --j;
      }
      if(j<2){
        printf("|");
      }
      else{
        printf("\n");
      }
    }
    if(i<2){
      printf("-----");
      printf("\n");
    }
    else{
      printf("\n");
    }
  }
}
int Chosenrow;
int Chosencol;
void ChosenBox(){
  printf("Please enter the row(1-3): ");
  scanf("%d", &Chosenrow);
  printf("Please enter the column(1-3): ");
  scanf("%d", &Chosencol);
}

void ChangeBox(int map[i][j], state player){
  if(Chosenrow >0 && Chosenrow <4 && Chosencol >0 && Chosencol <4){
    --Chosenrow;
    --Chosencol;
    if(map[Chosenrow][Chosencol]== empty){
      map[Chosenrow][Chosencol]= player; //change in this line leads to change in all rows
    }
    else{
      printf("This box is occupied. \nIt will be the turn of your opponent.\n");
    }
  }
  else{
    printf("Please enter number between 1 and 3!\nIt will be the turn of your opponent.\n");
  }
}

void PlayerOne(int map[i][j]){
  activePlayer Player= One;
  state playerone= cross;
  printf("%s","Player 1's Turn\n");
  ChosenBox();
  ChangeBox(map, playerone);
  DrawGameField(map);
}

void PlayerTwo(int map[i][j]){
  activePlayer Player= Two;
  state playertwo= circle;
  printf("Player 2's Turn \n");
  ChosenBox();
  ChangeBox(map, playertwo);
  DrawGameField(map);
}

bool WinGame(int map[i][j]){
  if(map[0][0]==map[0][1] && map[0][1]==map[0][2] && map[0][0] != empty
    || map[1][0]==map[1][1] && map[1][1]==map[1][2] && map[1][0] != empty
    || map[2][0]==map[2][1] && map[2][1]==map[2][2] && map[2][0] != empty
    || map[0][0]==map[1][1] && map[1][1]==map[2][2] && map[0][0] != empty
    || map[0][2]==map[1][1] && map[1][1]==map[2][0] && map[0][2] != empty){
    return true;
  }
  else{
    return false;
  }
}

bool DrawGame(int map[i][j]){
  for(int i=0; i<3; i++){
    for(int j=0; j<3; j++){
      if(map[i][j]== empty){
        return false;
      }
      else{
        continue;
      }
    }
  }
  if(!WinGame(map)){
    return true;
  }
  else{
    return false;
  }
}

bool finishedgame(int map[i][j]){
  if(WinGame(map) || DrawGame(map)){
    return true;
  }
  else{
    return false;
  }
}

int main(){
  int map[3][3];
  for(int i=0; i<3; i++){
    for(int j=0; j<3; j++){
      map[i][j]= empty;
    }
  }
  finishedgame(map);
  WinGame(map);
  DrawGame(map);
  activePlayer Player= One;

  DrawGameField(map);

  while(!WinGame(map) && !DrawGame(map) && !finishedgame(map)){
    PlayerOne(map);
    if(!WinGame(map) && !DrawGame(map) && !finishedgame(map)){
      PlayerTwo(map);
    }
  }
  if(WinGame(map)){
    if(Player== One){
      printf("Congratulations! Player 1 wins.");
    }
    else if(Player== Two){
      printf("Congratulations! Player 2 wins.");
    }
  }

  if(DrawGame(map)){
    printf("This is a draw game.");
  }
  printf("\nThe game is ended.");
  return 0;
}

</code>```

when I enter 3 3, I expect the result will be like

```<code>.|.|.
-----
.|.|.
-----
.|.|X
</code>```

but the result shown is like below

```<code>.|.|X
-----
.|.|X
-----
.|.|X
</code>```

same situation when I enter any number, all boxes in the same column of other rows are selected
Another weird thing is that I have checked the result after running PlayerOne(map) in line 160, in the above case when I input 3 3, the result after running line 160 shows that only the right top box is selected.
Also same situation to other numbers entered, the result shown after line 160 is always having only the top box in the same column among all rows is selected while all the others are empty, even though I am not choosing that box.
How could what I expected is different from what is shown in the game field which is also different from the final result given???
Anyone could help me with that? I really need your help.

Body:
I have been trying to design a tic tac toe game but I faced some weird situation when running the programme. It's like when I choose one box, all boxes in the same column are chosen. Also after the game field is drawn, I found that the result detected once again changed and becomes different from what I expected to show and what the game field has shown. I still couldn't find the solution of it so please help me (cry

#include <stdio.h>
#include <stdbool.h>

typedef enum State {
  empty,
  cross,
  circle,
} state;

typedef enum ActivePlayer {
  One= 1,
  Two= 2,
} activePlayer;

int i=0;
int j=0;
void DrawGameField(int map[i][j]){
  printf("\n");
  printf("This is the game of Tic Tac Toe:)\n");
  printf("Player 1: 'X'  Player 2: 'O' \n\n");
  for(int i=0; i<3; i++){
    for(int j=0; j<3; j++){
      if(map[i][j] == empty){
        printf(".");
      }
      else if(map[i][j] == cross){
        printf("X");
      }
      else if(map[i][j] == circle){
        printf("O");
      }
      else{
        --j;
      }
      if(j<2){
        printf("|");
      }
      else{
        printf("\n");
      }
    }
    if(i<2){
      printf("-----");
      printf("\n");
    }
    else{
      printf("\n");
    }
  }
}
int Chosenrow;
int Chosencol;
void ChosenBox(){
  printf("Please enter the row(1-3): ");
  scanf("%d", &Chosenrow);
  printf("Please enter the column(1-3): ");
  scanf("%d", &Chosencol);
}

void ChangeBox(int map[i][j], state player){
  if(Chosenrow >0 && Chosenrow <4 && Chosencol >0 && Chosencol <4){
    --Chosenrow;
    --Chosencol;
    if(map[Chosenrow][Chosencol]== empty){
      map[Chosenrow][Chosencol]= player; //change in this line leads to change in all rows
    }
    else{
      printf("This box is occupied. \nIt will be the turn of your opponent.\n");
    }
  }
  else{
    printf("Please enter number between 1 and 3!\nIt will be the turn of your opponent.\n");
  }
}

void PlayerOne(int map[i][j]){
  activePlayer Player= One;
  state playerone= cross;
  printf("%s","Player 1's Turn\n");
  ChosenBox();
  ChangeBox(map, playerone);
  DrawGameField(map);
}

void PlayerTwo(int map[i][j]){
  activePlayer Player= Two;
  state playertwo= circle;
  printf("Player 2's Turn \n");
  ChosenBox();
  ChangeBox(map, playertwo);
  DrawGameField(map);
}

bool WinGame(int map[i][j]){
  if(map[0][0]==map[0][1] && map[0][1]==map[0][2] && map[0][0] != empty
    || map[1][0]==map[1][1] && map[1][1]==map[1][2] && map[1][0] != empty
    || map[2][0]==map[2][1] && map[2][1]==map[2][2] && map[2][0] != empty
    || map[0][0]==map[1][1] && map[1][1]==map[2][2] && map[0][0] != empty
    || map[0][2]==map[1][1] && map[1][1]==map[2][0] && map[0][2] != empty){
    return true;
  }
  else{
    return false;
  }
}

bool DrawGame(int map[i][j]){
  for(int i=0; i<3; i++){
    for(int j=0; j<3; j++){
      if(map[i][j]== empty){
        return false;
      }
      else{
        continue;
      }
    }
  }
  if(!WinGame(map)){
    return true;
  }
  else{
    return false;
  }
}

bool finishedgame(int map[i][j]){
  if(WinGame(map) || DrawGame(map)){
    return true;
  }
  else{
    return false;
  }
}

int main(){
  int map[3][3];
  for(int i=0; i<3; i++){
    for(int j=0; j<3; j++){
      map[i][j]= empty;
    }
  }
  finishedgame(map);
  WinGame(map);
  DrawGame(map);
  activePlayer Player= One;

  DrawGameField(map);

  while(!WinGame(map) && !DrawGame(map) && !finishedgame(map)){
    PlayerOne(map);
    if(!WinGame(map) && !DrawGame(map) && !finishedgame(map)){
      PlayerTwo(map);
    }
  }
  if(WinGame(map)){
    if(Player== One){
      printf("Congratulations! Player 1 wins.");
    }
    else if(Player== Two){
      printf("Congratulations! Player 2 wins.");
    }
  }

  if(DrawGame(map)){
    printf("This is a draw game.");
  }
  printf("\nThe game is ended.");
  return 0;
}

when I enter 3 3, I expect the result will be like

.|.|.
-----
.|.|.
-----
.|.|X

but the result shown is like below

.|.|X
-----
.|.|X
-----
.|.|X

same situation when I enter any number, all boxes in the same column of other rows are selected
Another weird thing is that I have checked the result after running PlayerOne(map) in line 160, in the above case when I input 3 3, the result after running line 160 shows that only the right top box is selected.
Also same situation to other numbers entered, the result shown after line 160 is always having only the top box in the same column among all rows is selected while all the others are empty, even though I am not choosing that box.
How could what I expected is different from what is shown in the game field which is also different from the final result given???
Anyone could help me with that? I really need your help.


问:
Pass authorization from Blazor Server to .NET Core via SignalR
I have an SignalR connection between Blazor Server and  .NET Core. In Blazor I have authentication on Auth0 and get token and all needed claims. My authorization with roles work on Blazor with tags but not work then I pass it to .NET Core

This code works fine in Blazor

<AuthorizeView Roles="admin, Superuser">

You can only see this if you're an Admin or Superuser.

</AuthorizeView>

<AuthorizeView Roles="participant">

You can only see this if you're an participant.

</AuthorizeView>

<AuthorizeView Roles="user">

You can only see this if you're an user.

</AuthorizeView>

```
<p>Here's part of my controller:</p>
<pre class="lang-cs prettyprint-override"><code>hubConnection = new HubConnectionBuilder()
    .WithUrl("https://localhost:7277/users", options =>
        {
            options.AccessTokenProvider = () => Task.FromResult(tokenString);
        })
    .WithHeaders()
    .WithAutomaticReconnect()
    .Build();

hubConnection.On<List<User>>("ReceiveGetAll", async (users) =>
{
    messages = users;
    isLoaded = true;
});

await hubConnection.InvokeAsync("GetAll");
</code>```

Here's part of my hub (with generics)

[HubMethodName("GetAll")]
[Authorize]
public async System.Threading.Tasks.Task GetAll()
{
    var context = _contextAccessor.HttpContext;
    context.GetTokenAsync("access_token");
    var dtoItems = await _context.Set<Tmodel>()
        .IncludeVirtualProperties(new Tmodel { })
        .Select(e => e.ConvertToDto<Tmodel, TmodelDTO>())
        .ToListAsync();

    await Clients.Caller.SendAsync("ReceiveGetAll", dtoItems);
}
```
<p>Program.cs</p>
<pre class="lang-cs prettyprint-override"><code>
using Microsoft.EntityFrameworkCore;
using MsSqlAccessor.Models;
using Microsoft.AspNet.SignalR;
using Microsoft.Extensions.Hosting;
using MsSqlAccessor.Hubs;
using MsSqlAccessor.DbControllers;
using MsSqlAccessor.Services;
using Owin;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
using System.Threading.Tasks;
namespace MsSqlAccessor
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers().AddJsonOptions(options => {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            builder.Services.AddAuthentication(options =>
            {
                // Identity made Cookie authentication the default.
                // However, we want JWT Bearer Auth to be the default.
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        /*                        if (!string.IsNullOrEmpty(accessToken) &&
                                                    (path.StartsWithSegments("/hubs/chat")))*/
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return System.Threading.Tasks.Task.CompletedTask;
                    }
                };
            });

            builder.Services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
                hubOptions.KeepAliveInterval = System.TimeSpan.FromMinutes(1);
            });
            builder.Services.AddHttpContextAccessor();

            builder.Services.AddDbContext<CompetitionBdTestContext>();

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //builder.Services.AddSwaggerGen();

            builder.Services.AddSwaggerGen(opt =>
            {
                opt.SwaggerDoc("v1", new OpenApiInfo { Title = "MyAPI", Version = "v1" });
                opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Description = "Please enter token",
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    BearerFormat = "JWT",
                    Scheme = "bearer"
                });
                opt.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type=ReferenceType.SecurityScheme,
                                    Id="Bearer"
                                }
                            },
                            new string[]{}
                        }
                });
            });

            //builder.Services.AddTransient<IUserRole, MockUserRole>();
            builder.Services.AddTransient<EventsDbController>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: default,
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                //endpoints.MapHub<UserHub>("/users");
            });

            //app.MapHub<UserHub>("/users");
            //app.MapHub<MssqlHubOld<User>>("/users");
            //app.MapHub<EventParticipantTeamHub>("/eventparticipantteams");
            app.MapHub<EventHub>("/events");
            app.MapHub<MsSQLHub<EventManager, EventManagerDTO>>("/EventManagers");
            app.MapHub<MsSQLHub<EventParticipantTeam, EventParticipantTeamDTO>>("/eventparticipantteams");
            app.MapHub<MsSQLHub<EventTask, EventTaskDTO>>("/EventTasks");
            app.MapHub<MsSQLHub<EventTaskEvaluateUser, EventTaskEvaluateUserDTO>>("/EventTaskEvaluateUsers");
            app.MapHub<MsSQLHub<Role, RoleDTO>>("/Roles");
            app.MapHub<MsSQLHub<Status, StatusDTO>>("/Statuses");
            app.MapHub<MsSQLHub<MsSqlAccessor.Models.Task, TaskDTO>>("/Tasks");
            app.MapHub<MsSQLHub<TaskCategory, TaskCategoryDTO>>("/TaskCategories");
            app.MapHub<MsSQLHub<TaskParticipant, TaskParticipantDTO>>("/TaskParticipants");
            app.MapHub<MsSQLHub<Team, TeamDTO>>("/Teams");
            app.MapHub<MsSQLHub<TeamTask, TeamTaskDTO>>("/TeamTasks");
            app.MapHub<MsSQLHub<User, UserDTO>>("/Users");

            app.MapControllers();

            app.Run();
        }
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            GlobalHost.HubPipeline.AddModule(new ErrorHandlingPipelineModule());
            app.MapSignalR();
        }
    }
}
</code>```

Im trying get token on

AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
```
<p>and in Hub like</p>
<pre class="lang-cs prettyprint-override"><code>var context = _contextAccessor.HttpContext;
context.GetTokenAsync("access_token");
</code>```

But anything was failed. Tell me please how i can receive authorization on .Net Core?

Body:
I have an SignalR connection between Blazor Server and  .NET Core. In Blazor I have authentication on Auth0 and get token and all needed claims. My authorization with roles work on Blazor with tags but not work then I pass it to .NET Core

This code works fine in Blazor

<AuthorizeView Roles="admin, Superuser">

You can only see this if you're an Admin or Superuser.

</AuthorizeView>

<AuthorizeView Roles="participant">

You can only see this if you're an participant.

</AuthorizeView>

<AuthorizeView Roles="user">

You can only see this if you're an user.

</AuthorizeView>

Here's part of my controller:

hubConnection = new HubConnectionBuilder()
    .WithUrl("https://localhost:7277/users", options =>
        {
            options.AccessTokenProvider = () => Task.FromResult(tokenString);
        })
    .WithHeaders()
    .WithAutomaticReconnect()
    .Build();

hubConnection.On<List<User>>("ReceiveGetAll", async (users) =>
{
    messages = users;
    isLoaded = true;
});

await hubConnection.InvokeAsync("GetAll");

Here's part of my hub (with generics)

[HubMethodName("GetAll")]
[Authorize]
public async System.Threading.Tasks.Task GetAll()
{
    var context = _contextAccessor.HttpContext;
    context.GetTokenAsync("access_token");
    var dtoItems = await _context.Set<Tmodel>()
        .IncludeVirtualProperties(new Tmodel { })
        .Select(e => e.ConvertToDto<Tmodel, TmodelDTO>())
        .ToListAsync();

    await Clients.Caller.SendAsync("ReceiveGetAll", dtoItems);
}

Program.cs

using Microsoft.EntityFrameworkCore;
using MsSqlAccessor.Models;
using Microsoft.AspNet.SignalR;
using Microsoft.Extensions.Hosting;
using MsSqlAccessor.Hubs;
using MsSqlAccessor.DbControllers;
using MsSqlAccessor.Services;
using Owin;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
using System.Threading.Tasks;
namespace MsSqlAccessor
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers().AddJsonOptions(options => {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
            });

            builder.Services.AddAuthentication(options =>
            {
                // Identity made Cookie authentication the default.
                // However, we want JWT Bearer Auth to be the default.
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        /*                        if (!string.IsNullOrEmpty(accessToken) &&
                                                    (path.StartsWithSegments("/hubs/chat")))*/
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return System.Threading.Tasks.Task.CompletedTask;
                    }
                };
            });

            builder.Services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
                hubOptions.KeepAliveInterval = System.TimeSpan.FromMinutes(1);
            });
            builder.Services.AddHttpContextAccessor();

            builder.Services.AddDbContext<CompetitionBdTestContext>();

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //builder.Services.AddSwaggerGen();

            builder.Services.AddSwaggerGen(opt =>
            {
                opt.SwaggerDoc("v1", new OpenApiInfo { Title = "MyAPI", Version = "v1" });
                opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Description = "Please enter token",
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    BearerFormat = "JWT",
                    Scheme = "bearer"
                });
                opt.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type=ReferenceType.SecurityScheme,
                                    Id="Bearer"
                                }
                            },
                            new string[]{}
                        }
                });
            });

            //builder.Services.AddTransient<IUserRole, MockUserRole>();
            builder.Services.AddTransient<EventsDbController>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: default,
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                //endpoints.MapHub<UserHub>("/users");
            });

            //app.MapHub<UserHub>("/users");
            //app.MapHub<MssqlHubOld<User>>("/users");
            //app.MapHub<EventParticipantTeamHub>("/eventparticipantteams");
            app.MapHub<EventHub>("/events");
            app.MapHub<MsSQLHub<EventManager, EventManagerDTO>>("/EventManagers");
            app.MapHub<MsSQLHub<EventParticipantTeam, EventParticipantTeamDTO>>("/eventparticipantteams");
            app.MapHub<MsSQLHub<EventTask, EventTaskDTO>>("/EventTasks");
            app.MapHub<MsSQLHub<EventTaskEvaluateUser, EventTaskEvaluateUserDTO>>("/EventTaskEvaluateUsers");
            app.MapHub<MsSQLHub<Role, RoleDTO>>("/Roles");
            app.MapHub<MsSQLHub<Status, StatusDTO>>("/Statuses");
            app.MapHub<MsSQLHub<MsSqlAccessor.Models.Task, TaskDTO>>("/Tasks");
            app.MapHub<MsSQLHub<TaskCategory, TaskCategoryDTO>>("/TaskCategories");
            app.MapHub<MsSQLHub<TaskParticipant, TaskParticipantDTO>>("/TaskParticipants");
            app.MapHub<MsSQLHub<Team, TeamDTO>>("/Teams");
            app.MapHub<MsSQLHub<TeamTask, TeamTaskDTO>>("/TeamTasks");
            app.MapHub<MsSQLHub<User, UserDTO>>("/Users");

            app.MapControllers();

            app.Run();
        }
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            GlobalHost.HubPipeline.AddModule(new ErrorHandlingPipelineModule());
            app.MapSignalR();
        }
    }
}

Im trying get token on

AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>

and in Hub like

var context = _contextAccessor.HttpContext;
context.GetTokenAsync("access_token");

But anything was failed. Tell me please how i can receive authorization on .Net Core?


问:
How to profile expensive useSelector functions in React Redux, in relation to the render time?
I had a component that was rendered with an overzealous selector, like so: (example is simplified)

import { useSelector } from 'react-redux';
const aLotOfData = useSelector(state => {
    return { ...state.object };
});
```
<p>This was re-rendering each time any value in the <code>state</code> changed. So I have changed it to be:</p>
<pre class="lang-js prettyprint-override"><code>import { useSelector } from 'react-redux';
import equalsES6 from 'fast-deep-equal/es6';
const aLotOfData = useSelector(state => {
    return processKeys(state.object); // returns a new object each time
}, equalsES6);
</code>```

processKeys selects a specific subset of keys that we need and transforms their values, so that the component only re-renders when the given values change. I need equalsES6 because the returned object is nested. I could also split out the hook into multiple individual selectors.

I have checked with React Devtools, and this prevents unnecessary renders. Now, I am concerned that my deep equals might be slightly expensive. Or my processKeys function might be slightly expensive.

Question: how can I profile the cost of my useSelector hooks in my component? My aim is to prove that one/multiple expensive hook functions might still be cheaper than an unnecessary re-render. I know my component takes 100ms to render, from the React DevTools. So I want to get the timing information for the expensive hooks, so I can compare between the two.

Body:
I had a component that was rendered with an overzealous selector, like so: (example is simplified)

import { useSelector } from 'react-redux';
const aLotOfData = useSelector(state => {
    return { ...state.object };
});

This was re-rendering each time any value in the state changed. So I have changed it to be:

import { useSelector } from 'react-redux';
import equalsES6 from 'fast-deep-equal/es6';
const aLotOfData = useSelector(state => {
    return processKeys(state.object); // returns a new object each time
}, equalsES6);

processKeys selects a specific subset of keys that we need and transforms their values, so that the component only re-renders when the given values change. I need equalsES6 because the returned object is nested. I could also split out the hook into multiple individual selectors.

I have checked with React Devtools, and this prevents unnecessary renders. Now, I am concerned that my deep equals might be slightly expensive. Or my processKeys function might be slightly expensive.

Question: how can I profile the cost of my useSelector hooks in my component? My aim is to prove that one/multiple expensive hook functions might still be cheaper than an unnecessary re-render. I know my component takes 100ms to render, from the React DevTools. So I want to get the timing information for the expensive hooks, so I can compare between the two.


问:
GRAPH API - Issues while accessing messages for the mail boxes; (MailboxNotEnabledForRESTAPI & ErrorInvalidUser)
I am trying to read messages from two of my mail boxes using GRAPH APIs and getting following exceptions.

ServiceException: Code: MailboxNotEnabledForRESTAPI
Message: The mailbox is either inactive, soft-deleted, or is hosted on-premise.
My mailbox is active (can access emails) and hosted on EXO only (can access emails using Microsoft GRAPH Explorer - login and providing consent explicitly).
I have validated the generated accessToken and that is as per the configuration I did so it doesn't look like any issues with app registration.

ServiceException: Code: ErrorInvalidUser
Message: The requested user 'manoj.a.patel@outlook.com' is invalid.
This exception is with my another mailbox. This one is active I am able to access it.

Both of these email accounts I have created recently and shared the Office 365 family license I have. And added these two accounts to my Azure AD as users. These two accounts have all the required access so if I login to Azure account using these two accounts then I can see the app registered as well as other details thought it's not required.

I am suspecting these mailboxes are not associated properly with my Azure app id thought I have added them as AD users?

This request works and gives me 3 users with their email addresses

```<code>var client = GetAuthenticatedGraphClient(config);
var graphRequest = client.Users.Request();
var results = graphRequest.GetAsync().Result;
</code>```

While accessing emails getting exceptions mentioned above. Below is the code

```<code>var inboxMessages = client.Users["manoj.a.patel@outlook.com"].
              MailFolders["inbox"].Messages.Request().Expand("attachments").Top(20).GetAsync();
            var response = inboxMessages.Result;
</code>```

Please can you suggest what can be an issue here?

Thanks,

Body:
I am trying to read messages from two of my mail boxes using GRAPH APIs and getting following exceptions.

ServiceException: Code: MailboxNotEnabledForRESTAPI
Message: The mailbox is either inactive, soft-deleted, or is hosted on-premise.
My mailbox is active (can access emails) and hosted on EXO only (can access emails using Microsoft GRAPH Explorer - login and providing consent explicitly).
I have validated the generated accessToken and that is as per the configuration I did so it doesn't look like any issues with app registration.

ServiceException: Code: ErrorInvalidUser
Message: The requested user 'manoj.a.patel@outlook.com' is invalid.
This exception is with my another mailbox. This one is active I am able to access it.

Both of these email accounts I have created recently and shared the Office 365 family license I have. And added these two accounts to my Azure AD as users. These two accounts have all the required access so if I login to Azure account using these two accounts then I can see the app registered as well as other details thought it's not required.

I am suspecting these mailboxes are not associated properly with my Azure app id thought I have added them as AD users?

This request works and gives me 3 users with their email addresses

var client = GetAuthenticatedGraphClient(config);
var graphRequest = client.Users.Request();
var results = graphRequest.GetAsync().Result;

While accessing emails getting exceptions mentioned above. Below is the code

var inboxMessages = client.Users["manoj.a.patel@outlook.com"].
              MailFolders["inbox"].Messages.Request().Expand("attachments").Top(20).GetAsync();
            var response = inboxMessages.Result;

Please can you suggest what can be an issue here?

Thanks,


问:
react native - firestore data able to show on console.log but not able to show on screen
i'm try to fetch data from firestore and  display data in react native screen

```<code>    onAuthStateChanged(auth, async (user) => {
    if (user) {
      setUser(user);
      const uid = user.email;
      const uemail = user.email;
      const q = query(
      collection(db, "student"), where("studentEmail", "==", uemail));
      const querySnapshot = await getDocs(q);
      querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data()); /*data showing on console */
        console.log(doc.data());
      });
      } else {
      }
      });
</code>```

Error - not showing data in react native screen

```<code>return (
<View\>
<Text style={styles.name}>{doc.Address}\</Text\>
</View\>
)
</code>```

Body:
i'm try to fetch data from firestore and  display data in react native screen

    onAuthStateChanged(auth, async (user) => {
    if (user) {
      setUser(user);
      const uid = user.email;
      const uemail = user.email;
      const q = query(
      collection(db, "student"), where("studentEmail", "==", uemail));
      const querySnapshot = await getDocs(q);
      querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data()); /*data showing on console */
        console.log(doc.data());
      });
      } else {
      }
      });

Error - not showing data in react native screen

return (
<View\>
<Text style={styles.name}>{doc.Address}\</Text\>
</View\>
)


问:
How to prevent flickering on dark mode during page load
I have a light/dark mode toggle on my webpage, the problem is the screen is giving a brief white flash when loading another page while on dark mode. I have read the other similar problems and the solution, but since i'm using an AdminLTE the way dark mode works in my webpage is to change the class of:

```<code><body class="hold-transition sidebar-mini">
...
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
...
<aside class="main-sidebar sidebar-light-primary elevation-4">
</code>```

into

```<code><body class="hold-transition sidebar-mini dark-mode">
...
<nav class="main-header navbar navbar-expand navbar-dark">
...
<aside class="main-sidebar sidebar-dark-primary elevation-4">
</code>```

My scripts are like this:

```<code><script>
  var darkSwitch = document.getElementById("darkSwitch");
  window.addEventListener("load", function () {
    if (darkSwitch) {
      initTheme();
      darkSwitch.addEventListener("change", function () {
        resetTheme();
      });
    }
  });

  function dark() {
    $('body').addClass('dark-mode');
    $('.main-header').removeClass('navbar-white navbar-light').addClass('navbar-dark');
    $('.main-sidebar').removeClass('sidebar-light-primary elevation-4').addClass('sidebar-dark-primary elevation-4');
  }

  function light() {
    $('body').removeClass('dark-mode');
    $('.main-header').removeClass('navbar-dark').addClass('navbar-white navbar-light');
    $('.main-sidebar').removeClass('sidebar-dark-primary elevation-4').addClass('sidebar-light-primary elevation-4');
  }

  function initTheme() {
    var darkThemeSelected =
      localStorage.getItem("darkSwitch") !== null &&
      localStorage.getItem("darkSwitch") === "dark";
    darkSwitch.checked = darkThemeSelected;
    darkThemeSelected
      ? dark()
      : light()
  }

  function resetTheme() {
    if (darkSwitch.checked) {
      dark()
      localStorage.setItem("darkSwitch", "dark");
    } else {
      light()
      localStorage.removeItem("darkSwitch");
    }
  }
</script>
</code>```

The toggle

```<code><div class="custom-control custom-switch">
   <input type="checkbox" class="custom-control-input" id="darkSwitch">
   <label class="custom-control-label" for="darkSwitch">Dark Mode</label>
</div>
</code>```

How to fix?

Body:
I have a light/dark mode toggle on my webpage, the problem is the screen is giving a brief white flash when loading another page while on dark mode. I have read the other similar problems and the solution, but since i'm using an AdminLTE the way dark mode works in my webpage is to change the class of:

...

...

into

...

...

My scripts are like this:

The toggle

   <input type="checkbox" class="custom-control-input" id="darkSwitch">
   Dark Mode

How to fix?


问:
How to apply Decision Tree classification to dataset in R?
I tried to apply Decision Tree classification to my dataset. I created a subset to take useful columns from the raw dataset. The columns: Basin Name, Temperature of field, pH of field. Except basin name, they are numeric. That's why I tried to change the basin name type with ifelse condition. What else can I do to get rid of this error?

```<code>library(datasets)
library(caTools)
library(party)
library(dplyr)
library(magrittr)

train <- trainData[,c(9,13,14)]

train$BASIN_NAME <- ifelse(train$BASIN_NAME == "Odra Basin", 1, 2)

colSums(is.na(train))
train <- na.omit(train)

model<- ctree(BASIN_NAME ~ ., train)
plot(model)
ctree(formula, dataset)
</code>```

However, I got this error message:

Error in valid.viewport(x, y, width, height, just, gp, clip, mask, xscale,  :
invalid 'yscale' in viewport

Body:
I tried to apply Decision Tree classification to my dataset. I created a subset to take useful columns from the raw dataset. The columns: Basin Name, Temperature of field, pH of field. Except basin name, they are numeric. That's why I tried to change the basin name type with ifelse condition. What else can I do to get rid of this error?

library(datasets)
library(caTools)
library(party)
library(dplyr)
library(magrittr)

train <- trainData[,c(9,13,14)]

train$BASIN_NAME <- ifelse(train$BASIN_NAME == "Odra Basin", 1, 2)

colSums(is.na(train))
train <- na.omit(train)

model<- ctree(BASIN_NAME ~ ., train)
plot(model)
ctree(formula, dataset)

However, I got this error message:

Error in valid.viewport(x, y, width, height, just, gp, clip, mask, xscale,  :
invalid 'yscale' in viewport


问:
How to setup a laravel site in sub folder while main site is a wordpress
I am having problem setting up a Laravel site on a WordPress site's sub folder.

My site structure is here: - Mainsite/laravelfiles/public

I also have an existing. Htaccess file in main public_html

```<code><IfModule security2_module>
    SecRuleRemoveByTag unoeuro
</IfModule>

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

In the laravelfiles/public folder, I have this. htaccess file

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

In public folder, index.php file has these lines

```<code>require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
</code>```

In the .env file, I have these lines

```<code>APP_URL='https://mainsite/laravelfiles'
FRONTEND_URL='https://mainsite/laravelfiles/public'
</code>```

After all, this page not found message appears.

I've tried almost all solutions provided online, including. htaccess, .env, index.php file changing. Clearing cache etc...

Body:
I am having problem setting up a Laravel site on a WordPress site's sub folder.

My site structure is here: - Mainsite/laravelfiles/public

I also have an existing. Htaccess file in main public_html

<IfModule security2_module>
    SecRuleRemoveByTag unoeuro
</IfModule>

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

In the laravelfiles/public folder, I have this. htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

In public folder, index.php file has these lines

require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';

In the .env file, I have these lines

APP_URL='https://mainsite/laravelfiles'
FRONTEND_URL='https://mainsite/laravelfiles/public'

After all, this page not found message appears.

I've tried almost all solutions provided online, including. htaccess, .env, index.php file changing. Clearing cache etc...


问:
Can JDT find org.eclipse.jdt.core.IMethod by java.lang.reflect.Method? Are there any related utilities?
i did this

IType class Element = .... ;
String name = ... ;
String[] parameterTypeSignatures = ... ;
classElement.getMethod(name, parameterTypeSignatures) ;
```

When I have a java.lang.reflect.Method object, I need to convert it to name and parameterTypeSignatures

I wrote the conversion rules by referring to the code of JDT

JDT Is there any practical tool that can directly use the internal reflection type of java.lang.reflect to search?

Body:
i did this

IType class Element = .... ;
String name = ... ;
String[] parameterTypeSignatures = ... ;
classElement.getMethod(name, parameterTypeSignatures) ;

When I have a java.lang.reflect.Method object, I need to convert it to name and parameterTypeSignatures

I wrote the conversion rules by referring to the code of JDT

JDT Is there any practical tool that can directly use the internal reflection type of java.lang.reflect to search?


问:
JAXB-api is converting my POJOS automatically into XML. If I want to unmarshall again I am getting XML object only. How to avoid that?
I am using maven. and this dependency group-id is javax.xml.bind artifact id is jaxb-api with version 2.3.1

As soon as I add this dependency it is automatically converting and giving XML objects how to avoid that?

I tried to get the POJO by using toString() in the console but I am getting the XML object without even marshalling.


问:
Fixed effects in probit model
I am kind of desperate at the moment. My teacher says there is a way to add equivalents of industry and year-fixed effects to a probit model. We didn't get any data from him, but we have to explain and give an R template function, how we have to imply those fixed effects in a probit model. Can somebody please help me?</p>

Title: Fixed effects in probit model


问:
How to verify TransparentUpgradeableProxy which is deployed using create2?
I have deployed an upgradable contract using a factory contract which its code is as fallows:

```<code>bytes memory bytecode = abi.encodePacked(
    type(TransparentUpgradeableProxy).creationCode,
    abi.encode(implementation, proxyAdmin, "")
);

assembly {
    contractAddress := create2(
        0,
        add(bytecode, 32),
        mload(bytecode),
        salt
    )
}
</code>```

Everything is working fine. I did verify the implementation using hardhat but I can't verify the proxy itself. Hardhat gives me the following error:

Failed to verify TransparentUpgradeableProxy contract at addr: Bytecode does not match with the current version of TransparentUpgradeableProxy in the Hardhat Upgrades plugin.

Any ideas?

I tried the hardhat CLI tool for verification

Body:
I have deployed an upgradable contract using a factory contract which its code is as fallows:

bytes memory bytecode = abi.encodePacked(
    type(TransparentUpgradeableProxy).creationCode,
    abi.encode(implementation, proxyAdmin, "")
);

assembly {
    contractAddress := create2(
        0,
        add(bytecode, 32),
        mload(bytecode),
        salt
    )
}

Everything is working fine. I did verify the implementation using hardhat but I can't verify the proxy itself. Hardhat gives me the following error:

Failed to verify TransparentUpgradeableProxy contract at addr: Bytecode does not match with the current version of TransparentUpgradeableProxy in the Hardhat Upgrades plugin.

Any ideas?

I tried the hardhat CLI tool for verification


问:
Python: Passing a function with arguments as argument of another function
In the code below, inside WKB, I'm trying to pass the function "integrand" as an argument of the function int_gauss (like this: int_gauss(integrand(E,x0,m1,x),xp,wp)) and it returns me an error.

```<code>TypeError: 'numpy.ndarray' object is not callable
</code>```

Thanks in advance for your help.

```<code>x0=1
m1=1
h=1
e=100

import numpy as np
import matplotlib.pyplot as plt
def gaussxw(N):

    a = np.linspace(3,4*N-1,N)/(4*N+2)
    x = np.cos(np.pi*a+1/(8*N*N*np.tan(a)))

    # Find roots using Newton's method
    epsilon = 1e-15
    delta = 1.0
    while delta>epsilon:
        p0 = np.ones(N,float)
        p1 = np.copy(x)
        for k in range(1,N):
            p0,p1 = p1,((2*k+1)*x*p1-k*p0)/(k+1)
        dp = (N+1)*(p0-x*p1)/(1-x*x)
        dx = p1/dp
        x -= dx
        delta = max(abs(dx))

    # Calculate the weights
    w = 2*(N+1)*(N+1)/(N*N*(1-x*x)*dp*dp)

    return x,w

def gaussxwab(N,a,b):
    x,w = gaussxw(N)
    return 0.5*(b-a)*x+0.5*(b+a),0.5*(b-a)*w

N = 50
x, w = gaussxw(N)

def integrand(E,x0,m1,x):
    return    np.sqrt((2*m1*(E-    (e*( ((x0/x)**12) -2*((x0/x)**6)   )   ))))

def WKB(E,x0,e):
    a, b = x0*(1+np.sqrt(1+(E/e)))**(-1/6), x0*(1-np.sqrt(1+(E/e)))**(-1/6)
    xp = 0.5*(b - a)*x + 0.5*(b + a)
    wp = 0.5*(b - a)*w
    return int_gauss(integrand(E,x0,m1,x),xp,wp)

def int_gauss(f,nodes, weights):
  result = 0.0
  for x, w in zip(nodes, weights):
    result += w *f(x)
  return result

plt.close()
En=np.linspace(-100,-1,496)
W=[WKB(i,x0,e) for i in En]
plt.figure()
plt.plot(En,W)
plt.grid()
plt.axis()

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

I find the desired result when I explicitly compute the desired function "integrand" inside int_gauss like this but I'd like to be able to call int_gauss with the integrand function as a parameter int_gauss(integrand(E,x0,m1,x),xp,wp) inside WKB:

```<code>def WKB(E,x0,e):
    a, b = x0*(1+np.sqrt(1+(E/e)))**(-1/6), x0*(1-np.sqrt(1+(E/e)))**(-1/6)
    xp = 0.5*(b - a)*x + 0.5*(b + a)
    wp = 0.5*(b - a)*w
    return int_gauss(E,x0,m1,xp,wp)

def int_gauss(E,x0,m1,nodes, weights):
  result = 0.0
  for x, w in zip(nodes, weights):
    result += w * np.sqrt((2*m1*(E-    (e*( ((x0/x)**12) -2*((x0/x)**6)   )   ))))
  return result
</code>```

Body:
In the code below, inside WKB, I'm trying to pass the function "integrand" as an argument of the function int_gauss (like this: int_gauss(integrand(E,x0,m1,x),xp,wp)) and it returns me an error.

TypeError: 'numpy.ndarray' object is not callable

Thanks in advance for your help.

x0=1
m1=1
h=1
e=100

import numpy as np
import matplotlib.pyplot as plt
def gaussxw(N):

    a = np.linspace(3,4*N-1,N)/(4*N+2)
    x = np.cos(np.pi*a+1/(8*N*N*np.tan(a)))

    # Find roots using Newton's method
    epsilon = 1e-15
    delta = 1.0
    while delta>epsilon:
        p0 = np.ones(N,float)
        p1 = np.copy(x)
        for k in range(1,N):
            p0,p1 = p1,((2*k+1)*x*p1-k*p0)/(k+1)
        dp = (N+1)*(p0-x*p1)/(1-x*x)
        dx = p1/dp
        x -= dx
        delta = max(abs(dx))

    # Calculate the weights
    w = 2*(N+1)*(N+1)/(N*N*(1-x*x)*dp*dp)

    return x,w

def gaussxwab(N,a,b):
    x,w = gaussxw(N)
    return 0.5*(b-a)*x+0.5*(b+a),0.5*(b-a)*w

N = 50
x, w = gaussxw(N)

def integrand(E,x0,m1,x):
    return    np.sqrt((2*m1*(E-    (e*( ((x0/x)**12) -2*((x0/x)**6)   )   ))))

def WKB(E,x0,e):
    a, b = x0*(1+np.sqrt(1+(E/e)))**(-1/6), x0*(1-np.sqrt(1+(E/e)))**(-1/6)
    xp = 0.5*(b - a)*x + 0.5*(b + a)
    wp = 0.5*(b - a)*w
    return int_gauss(integrand(E,x0,m1,x),xp,wp)

def int_gauss(f,nodes, weights):
  result = 0.0
  for x, w in zip(nodes, weights):
    result += w *f(x)
  return result

plt.close()
En=np.linspace(-100,-1,496)
W=[WKB(i,x0,e) for i in En]
plt.figure()
plt.plot(En,W)
plt.grid()
plt.axis()

plt.show()

I find the desired result when I explicitly compute the desired function "integrand" inside int_gauss like this but I'd like to be able to call int_gauss with the integrand function as a parameter int_gauss(integrand(E,x0,m1,x),xp,wp) inside WKB:

def WKB(E,x0,e):
    a, b = x0*(1+np.sqrt(1+(E/e)))**(-1/6), x0*(1-np.sqrt(1+(E/e)))**(-1/6)
    xp = 0.5*(b - a)*x + 0.5*(b + a)
    wp = 0.5*(b - a)*w
    return int_gauss(E,x0,m1,xp,wp)

def int_gauss(E,x0,m1,nodes, weights):
  result = 0.0
  for x, w in zip(nodes, weights):
    result += w * np.sqrt((2*m1*(E-    (e*( ((x0/x)**12) -2*((x0/x)**6)   )   ))))
  return result