问:
Error when disabling keys on a workbook using Application.OnKey and Workbook_Activate()
I have a specific document I am trying to prevent people from cutting, copying, or pasting to and from. I found a few different snippets of VBA online have managed to get it to work, however, when I click the button to apply the script, any other open document/workbook also becomes locked.

This VBA script is only located in the specific document I need and nowhere else, under 'ThisWorkbook' portion specifically.

```<code>Private Sub DisableXCV()
With Application
.OnKey "^x", ""
.OnKey "^c", ""
.OnKey "^v", ""
.CommandBars("Cell").Controls(1).Enabled = False
.CommandBars("Cell").Controls(2).Enabled = False
.CommandBars("Cell").Controls(3).Enabled = False
End With
End Sub
</code>```

I tried to add an if condition to check if the workbook name is 'xyz' before applying, but that did not work.

```<code>Private Sub DisableXCV()
If ActiveWorkbook.Name = "insert workbookname here" Then
With Application
.OnKey "^x", ""
.OnKey "^c", ""
.OnKey "^v", ""
.CommandBars("Cell").Controls(1).Enabled = False
.CommandBars("Cell").Controls(2).Enabled = False
.CommandBars("Cell").Controls(3).Enabled = False
End With
End If
End Sub
</code>```

Would appreciate any help or guidance I can get here.

EDIT:
I have tried implementing the solution found and posted here by Scott Craner this past friday.
(Application.OnKey for one workbook of multiple open workbooks)

I am, however, getting an error doing so:
"Compile error: Procedure declaration does not match description of event or procedure having the same name"

Within the VBA editor, the left drop down menu is selected as 'Workbook' and the right drop down menu is selected as 'Activate' and 'Deactivate' respectively.

The code being

```<code>Private Sub Workbook_Activate(ByVal sh As Object)
If sh.Name = "System Checks" Then
    Application.OnKey "^{x}", ""
    Application.OnKey "^{c}", ""
    Application.OnKey "^{v}", ""
    Application.CommandBars("Cell").Controls(1).Enabled = False
    Application.CommandBars("Cell").Controls(2).Enabled = False
    Application.CommandBars("Cell").Controls(3).Enabled = False
Else
    Application.OnKey "^{x}"
    Application.OnKey "^{c}"
    Application.OnKey "^{v}"
    Application.CommandBars("Cell").Controls(1).Enabled = True
    Application.CommandBars("Cell").Controls(2).Enabled = True
    Application.CommandBars("Cell").Controls(3).Enabled = True
End If
End Sub

Private Sub Workbook_Deactivate()
    Application.OnKey "^{x}"
    Application.OnKey "^{c}"
    Application.OnKey "^{v}"
    Application.CommandBars("Cell").Controls(1).Enabled = True
    Application.CommandBars("Cell").Controls(2).Enabled = True
    Application.CommandBars("Cell").Controls(3).Enabled = True
End Sub
</code>```

Body:
I have a specific document I am trying to prevent people from cutting, copying, or pasting to and from. I found a few different snippets of VBA online have managed to get it to work, however, when I click the button to apply the script, any other open document/workbook also becomes locked.

This VBA script is only located in the specific document I need and nowhere else, under 'ThisWorkbook' portion specifically.

Private Sub DisableXCV()
With Application
.OnKey "^x", ""
.OnKey "^c", ""
.OnKey "^v", ""
.CommandBars("Cell").Controls(1).Enabled = False
.CommandBars("Cell").Controls(2).Enabled = False
.CommandBars("Cell").Controls(3).Enabled = False
End With
End Sub

I tried to add an if condition to check if the workbook name is 'xyz' before applying, but that did not work.

Private Sub DisableXCV()
If ActiveWorkbook.Name = "insert workbookname here" Then
With Application
.OnKey "^x", ""
.OnKey "^c", ""
.OnKey "^v", ""
.CommandBars("Cell").Controls(1).Enabled = False
.CommandBars("Cell").Controls(2).Enabled = False
.CommandBars("Cell").Controls(3).Enabled = False
End With
End If
End Sub

Would appreciate any help or guidance I can get here.

EDIT:
I have tried implementing the solution found and posted here by Scott Craner this past friday.
(Application.OnKey for one workbook of multiple open workbooks)

I am, however, getting an error doing so:
"Compile error: Procedure declaration does not match description of event or procedure having the same name"

Within the VBA editor, the left drop down menu is selected as 'Workbook' and the right drop down menu is selected as 'Activate' and 'Deactivate' respectively.

The code being

Private Sub Workbook_Activate(ByVal sh As Object)
If sh.Name = "System Checks" Then
    Application.OnKey "^{x}", ""
    Application.OnKey "^{c}", ""
    Application.OnKey "^{v}", ""
    Application.CommandBars("Cell").Controls(1).Enabled = False
    Application.CommandBars("Cell").Controls(2).Enabled = False
    Application.CommandBars("Cell").Controls(3).Enabled = False
Else
    Application.OnKey "^{x}"
    Application.OnKey "^{c}"
    Application.OnKey "^{v}"
    Application.CommandBars("Cell").Controls(1).Enabled = True
    Application.CommandBars("Cell").Controls(2).Enabled = True
    Application.CommandBars("Cell").Controls(3).Enabled = True
End If
End Sub

Private Sub Workbook_Deactivate()
    Application.OnKey "^{x}"
    Application.OnKey "^{c}"
    Application.OnKey "^{v}"
    Application.CommandBars("Cell").Controls(1).Enabled = True
    Application.CommandBars("Cell").Controls(2).Enabled = True
    Application.CommandBars("Cell").Controls(3).Enabled = True
End Sub


来源: stackexchange

问:
Need to insert events with existing attendees default ACCEPTED
Our CMS handles events for DJS, mostly weddings.  The client and DJ have already created the date and obviously the client has accepted.  When inserting a new event, setting responseStatus to accepted, the attendee (client) still receives a request to accept or decline.  This is causing a lot of confusion.

We simply need to generate and insert an event with attendees, already confirmed, with no action required on the attendee.

I've gone through the API and other help tutorials and created an object that handles the calendar.  When trying to set various items such as responseStatus:"Accepted" -- each and every time all attendees require action.  I just want the event to appear, no action required on any person.

ContentLicense: CC BY-SA 4.0


问:
Material slider's setTickActiveTintList is not working
I am trying to create a ColorStateList programatically using this:

```<code>ColorStateList stateList = ColorStateList.valueOf(Color.RED);
</code>```

to pass in setTickActiveTintList method

```<code>slider.setTickInactiveTintList(stateList);
</code>```

But seems above code is not working. and I want to do it programmatically not in XML.
I am using material version : 1.0.0

Can somebody please explain me how to create this ?

Body:
I am trying to create a ColorStateList programatically using this:

ColorStateList stateList = ColorStateList.valueOf(Color.RED);

to pass in setTickActiveTintList method

slider.setTickInactiveTintList(stateList);

But seems above code is not working. and I want to do it programmatically not in XML.
I am using material version : 1.0.0

Can somebody please explain me how to create this ?


问:
Grouping & subgrouping a list of objects based on the object attributes
I'm working on an OpenCV problem that deals with many lines from a Hough Line Detector. I am attempting to reduce the number of lines by joining overlapping lines together, based on slope, y-intercept, and % overlap.

Just for some background. Here is the image with Hough lines pasted on:

```<code>hough = cv.HoughLinesP(can, h_rho, h_theta, h_threshold, minLineLength=h_min_line_length, maxLineGap=h_max_line_gap)  # Hough Line Detection
h1 = hough.squeeze() # Output "h1" is an array containing endpoints of detected line segments
</code>```

From this code, I obtain a list of lines that are each a 1x4 NumPy array containing [x1 y1 x2 y2] coordinates.

I then created a class called Line that denotes its coordinates, slope, and y-intercept

```<code>class Line:
    def __init__(self, x1, y1, x2, y2) -> None:
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2

        if ((x2-x1) != 0): # IF it is NOT vertical
            self.m = (y2-y1) / (x2-x1)
            self.b = y2 - self.m*x2
        else: # IF it is vertical
            self.m = 999
            self.b = 999 # set up as 999 as an identifier & to not have to deal with NoneType
</code>```

Iterated over the list and converted every np array to an instance of this class:

```<code>l1 = []
for i,line in enumerate(h1):
    x1,y1,x2,y2 = np.ravel(line,"C")
    l = Line(x1,y1,x2,y2)
    l1.append(l)
</code>```

So now I have a list of instances of this class 'Line' that each hold an attribute 'm' & 'b'.

So my plan now is to first sort based on the attribute 'm':

```<code># Sort a list of instances based on the property slope, 'm'
l1.sort(key=operator.attrgetter('m'))
</code>```

So now my list of instances is sorted in ascending order of the value of 'm'.

I want to now create a sub-list within this list of instances based on a threshold value for 'm'. I have a sorted list of instances [<instance.Line object ...1>, <... 2>, <... 3>, etc] with its associated slopes & intercepts where the corresponding slopes would look something like [-85, -50, -50, -1.125, -0.75, -0.679, -0.12, -0.13, -0.16, 25, 27,..., 999, 999]. With a threshold value of say 2, I would like to output a grouped list of instances [ [1], [2, 3], [4 5 6], [7 8 9], [10 11], ..., [850 851] ] which correspond to the slopes looking like [ [-85], [-50, -50], [-1.125, -0.75, -0.679], [-0.12, -0.13, -0.16], [25, 27], ..., [999, 999] ].

(Just for clarity, if the threshold was 5 and the list was [-5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 ], it should output [ [-5 -4 -3 -2 -1], [0 1 2 3 4], [5 6 7 8 9], [10 11] ] )

I saw this and adapted it to a list of instances.
Grouping a list of objects by their attribute threshold into subgroups

```<code># Sub-group the list based on similarity in slope, 'm' (the sub-grouping order can be switched to optimize speed based on the standard deviation of the 'm' & 'b')
    l2 = [list(group) for _, group in itertools.groupby(l1, lambda num: num.m//2)]
</code>```

However, it sub-groups as it crosses a 0 value. meaning that it will not sub-group correctly.

My plan for next steps would be to now sub-group within each sub-group based on the attribute 'b' using a similar method. Squeeze out the previous sub-grouping such that now it is simply a list of lines that are grouped by similarity in both 'm' & 'b'. I will then iterate over each group and define a %overlap with the other lines in the group, and then decide on how to delete the lines that are completely enveloped by another line.

Is there perhaps a simpler way to approach this problem?

Body:
I'm working on an OpenCV problem that deals with many lines from a Hough Line Detector. I am attempting to reduce the number of lines by joining overlapping lines together, based on slope, y-intercept, and % overlap.

Just for some background. Here is the image with Hough lines pasted on:

hough = cv.HoughLinesP(can, h_rho, h_theta, h_threshold, minLineLength=h_min_line_length, maxLineGap=h_max_line_gap)  # Hough Line Detection
h1 = hough.squeeze() # Output "h1" is an array containing endpoints of detected line segments

From this code, I obtain a list of lines that are each a 1x4 NumPy array containing [x1 y1 x2 y2] coordinates.

I then created a class called Line that denotes its coordinates, slope, and y-intercept

class Line:
    def __init__(self, x1, y1, x2, y2) -> None:
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2

        if ((x2-x1) != 0): # IF it is NOT vertical
            self.m = (y2-y1) / (x2-x1)
            self.b = y2 - self.m*x2
        else: # IF it is vertical
            self.m = 999
            self.b = 999 # set up as 999 as an identifier & to not have to deal with NoneType

Iterated over the list and converted every np array to an instance of this class:

l1 = []
for i,line in enumerate(h1):
    x1,y1,x2,y2 = np.ravel(line,"C")
    l = Line(x1,y1,x2,y2)
    l1.append(l)

So now I have a list of instances of this class 'Line' that each hold an attribute 'm' & 'b'.

So my plan now is to first sort based on the attribute 'm':

# Sort a list of instances based on the property slope, 'm'
l1.sort(key=operator.attrgetter('m'))

So now my list of instances is sorted in ascending order of the value of 'm'.

I want to now create a sub-list within this list of instances based on a threshold value for 'm'. I have a sorted list of instances [<instance.Line object ...1>, <... 2>, <... 3>, etc] with its associated slopes & intercepts where the corresponding slopes would look something like [-85, -50, -50, -1.125, -0.75, -0.679, -0.12, -0.13, -0.16, 25, 27,..., 999, 999]. With a threshold value of say 2, I would like to output a grouped list of instances [ [1], [2, 3], [4 5 6], [7 8 9], [10 11], ..., [850 851] ] which correspond to the slopes looking like [ [-85], [-50, -50], [-1.125, -0.75, -0.679], [-0.12, -0.13, -0.16], [25, 27], ..., [999, 999] ].

(Just for clarity, if the threshold was 5 and the list was [-5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 ], it should output [ [-5 -4 -3 -2 -1], [0 1 2 3 4], [5 6 7 8 9], [10 11] ] )

I saw this and adapted it to a list of instances.
Grouping a list of objects by their attribute threshold into subgroups

# Sub-group the list based on similarity in slope, 'm' (the sub-grouping order can be switched to optimize speed based on the standard deviation of the 'm' & 'b')
    l2 = [list(group) for _, group in itertools.groupby(l1, lambda num: num.m//2)]

However, it sub-groups as it crosses a 0 value. meaning that it will not sub-group correctly.

My plan for next steps would be to now sub-group within each sub-group based on the attribute 'b' using a similar method. Squeeze out the previous sub-grouping such that now it is simply a list of lines that are grouped by similarity in both 'm' & 'b'. I will then iterate over each group and define a %overlap with the other lines in the group, and then decide on how to delete the lines that are completely enveloped by another line.

Is there perhaps a simpler way to approach this problem?


问:
devextreme pivot grid date groups handler.apply error
Midway through this: https://js.devexpress.com/Documentation/Guide/UI_Components/PivotGrid/Fields_and_Areas/#Areas

It talks about groups.
This is my implementation for grouping daily data into months and year columns:

```<code>// Cast Created At to be date (for later formatting)
this.pivotGridSource.field("Created At", {
        dataType: "date",
        area: "column"
      });

// Get all grid fields
let dateRollupFields = this.pivotGridSource.fields()

// Get index of Created At field
const createdAtIndex = dateRollupFields.map(o => o.caption).indexOf("Created At");

// Create groups for years and months of Created At values
      let dateGroups: any[] = [{
        area: 'column',
        dataType: 'date',
        caption: 'Created At Month',
        groupName: 'created_at_date',
        groupInterval: 'month',
        sortOrder: 'desc'
      }, {
        area: 'column',
        dataType: 'date',
        caption: 'Created At Year',
        groupName: 'created_at_date',
        groupInterval: 'year',
        sortOrder: 'desc'
      }]
      dateRollupFields.splice(createdAtIndex + 1, 0, ...dateGroups);

// Apply fields
      this.pivotGridSource.fields(dateRollupFields);
</code>```

This gives me two columns but when I go to view their values, I get the error from this screenshot.

Body:
Midway through this: https://js.devexpress.com/Documentation/Guide/UI_Components/PivotGrid/Fields_and_Areas/#Areas

It talks about groups.
This is my implementation for grouping daily data into months and year columns:

// Cast Created At to be date (for later formatting)
this.pivotGridSource.field("Created At", {
        dataType: "date",
        area: "column"
      });

// Get all grid fields
let dateRollupFields = this.pivotGridSource.fields()

// Get index of Created At field
const createdAtIndex = dateRollupFields.map(o => o.caption).indexOf("Created At");

// Create groups for years and months of Created At values
      let dateGroups: any[] = [{
        area: 'column',
        dataType: 'date',
        caption: 'Created At Month',
        groupName: 'created_at_date',
        groupInterval: 'month',
        sortOrder: 'desc'
      }, {
        area: 'column',
        dataType: 'date',
        caption: 'Created At Year',
        groupName: 'created_at_date',
        groupInterval: 'year',
        sortOrder: 'desc'
      }]
      dateRollupFields.splice(createdAtIndex + 1, 0, ...dateGroups);

// Apply fields
      this.pivotGridSource.fields(dateRollupFields);

This gives me two columns but when I go to view their values, I get the error from this screenshot.


问:
Set cookies automatically csfr and session from sanctum in sveltekit
I'm doing a login with laravel/sanctum and sveltekit, when I submit the form,first inside the actions I execute first a fetch to the csfr endpoint from sanctum ('/sanctum/csrf-cookie') but in the reponse the cookies are not set automatically in the browser but cookies arrive.So how i can set automatically?

Here the code :
`export const actions: Actions = {
default: async ({ request, fetch, cookies }) => {
const formData = await request.formData();

```<code>    const user = {
        name: formData.get('name'),
        email: formData.get('email'),
        password: formData.get('password'),
        password_confirmation: formData.get('password_confirm')
    };

    await fetch('http://localhost:8000/sanctum/csrf-cookie', {
        method: 'GET',
        credentials: 'include'
    });

    const res = await fetch('http://127.0.0.1:8000/api/register', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json'
            // 'X-XSRF-TOKEN': '' || ''
        },
        body: JSON.stringify(user)
    });

    const data = await res.json();
    console.log(data);
}
</code>```

};`

Body:
I'm doing a login with laravel/sanctum and sveltekit, when I submit the form,first inside the actions I execute first a fetch to the csfr endpoint from sanctum ('/sanctum/csrf-cookie') but in the reponse the cookies are not set automatically in the browser but cookies arrive.So how i can set automatically?

Here the code :
`export const actions: Actions = {
default: async ({ request, fetch, cookies }) => {
const formData = await request.formData();

    const user = {
        name: formData.get('name'),
        email: formData.get('email'),
        password: formData.get('password'),
        password_confirmation: formData.get('password_confirm')
    };

    await fetch('http://localhost:8000/sanctum/csrf-cookie', {
        method: 'GET',
        credentials: 'include'
    });

    const res = await fetch('http://127.0.0.1:8000/api/register', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json'
            // 'X-XSRF-TOKEN': '' || ''
        },
        body: JSON.stringify(user)
    });

    const data = await res.json();
    console.log(data);
}

};`


问:
on the purchase of a product from a distributor (price entered by the customer), minimum number of pieces to be refunded (python)
I have an exercise where I need to know how much the distributor will give back to the customer who bought a product. (constraint: the refund has to be done just with 50 cents, 1€(100 cents) and 2€(200 cents) coins

I can do the calculation to find out how much the distributor should refund.
But the problem I encounter is to try to display the number of coins that make up the total refunded to the customer

Here is what I have done so far :

```<code>coins = {200: 5, 100: 3, 50: 2, 20: 4, 10: 10, 5: 20, 2: 100, 1: 100}

# Dictionnaire des quantités de chaque valeur de pièce rendue
change_given = {200: 0, 100: 1, 50: 0, 20: 0, 10: 0, 5: 0, 2: 0, 1: 0}

def min_num_coins(amount, change_given):
  # Initialiser le compteur de pièces à zéro
  num_coins = 0
  # Pour chaque valeur de pièce, tant que la somme est supérieure à la valeur de la pièce
  for value in sorted(coins, reverse=True):
      while amount >= value and coins[value] > 0:
      # Incrémenter le compteur de pièces
        num_coins += 1
      # Soustraire la valeur de la pièce de la somme
        amount -= value
      # Décrémenter la quantité disponible de cette valeur de pièce
        coins[value] -= 1
      # Incrémenter la quantité de cette valeur de pièce rendue
        change_given[value] += 1
  # Retourner le nombre de pièces et les pièces rendues
  return num_coins, change_given

# Demander au client de saisir le montant du produit
amount_owed = int(input("Entrez le montant du produit (en euros): "))
# Demander au client de saisir le montant payé
amount_given = int(input("Entrez le montant payé (en euros): "))

# Calculer la somme due
change_due = amount_given - amount_owed

# Séparer la somme due en euros et centimes
euros, centimes = divmod(change_due, 100)

# Appeler la fonction pour obtenir le nombre minimum de pièces
num_coins, coins_given = min_num_coins(centimes, change_given)

# Afficher le résultat
print(f"Il faut rendre {centimes} € et {euros} centimes en {num_coins} pièce(s)")

# Générer un message qui affiche les pièces rendues au client
change_message = "Pièces rendues: "
for value, quantity in coins_given.items():
  if quantity > 0:
    change_message += f"{quantity} x {value // 100} €, "
change_message = change_message[:-2]

# Afficher le message
print(change_message)
</code>```

The error I get when I want to get the number of coins (the example is: the product costs 5€, the customer gives 10€, the distributor gives back 5€ but says he gives 5€ in one coin).

Here is the message I get:
20 € and 0 cents must be returned in 1 coin(s)
Coins returned: 1 x €1, 1 x €0.

Body:
I have an exercise where I need to know how much the distributor will give back to the customer who bought a product. (constraint: the refund has to be done just with 50 cents, 1€(100 cents) and 2€(200 cents) coins

I can do the calculation to find out how much the distributor should refund.
But the problem I encounter is to try to display the number of coins that make up the total refunded to the customer

Here is what I have done so far :

coins = {200: 5, 100: 3, 50: 2, 20: 4, 10: 10, 5: 20, 2: 100, 1: 100}

# Dictionnaire des quantités de chaque valeur de pièce rendue
change_given = {200: 0, 100: 1, 50: 0, 20: 0, 10: 0, 5: 0, 2: 0, 1: 0}

def min_num_coins(amount, change_given):
  # Initialiser le compteur de pièces à zéro
  num_coins = 0
  # Pour chaque valeur de pièce, tant que la somme est supérieure à la valeur de la pièce
  for value in sorted(coins, reverse=True):
      while amount >= value and coins[value] > 0:
      # Incrémenter le compteur de pièces
        num_coins += 1
      # Soustraire la valeur de la pièce de la somme
        amount -= value
      # Décrémenter la quantité disponible de cette valeur de pièce
        coins[value] -= 1
      # Incrémenter la quantité de cette valeur de pièce rendue
        change_given[value] += 1
  # Retourner le nombre de pièces et les pièces rendues
  return num_coins, change_given

# Demander au client de saisir le montant du produit
amount_owed = int(input("Entrez le montant du produit (en euros): "))
# Demander au client de saisir le montant payé
amount_given = int(input("Entrez le montant payé (en euros): "))

# Calculer la somme due
change_due = amount_given - amount_owed

# Séparer la somme due en euros et centimes
euros, centimes = divmod(change_due, 100)

# Appeler la fonction pour obtenir le nombre minimum de pièces
num_coins, coins_given = min_num_coins(centimes, change_given)

# Afficher le résultat
print(f"Il faut rendre {centimes} € et {euros} centimes en {num_coins} pièce(s)")

# Générer un message qui affiche les pièces rendues au client
change_message = "Pièces rendues: "
for value, quantity in coins_given.items():
  if quantity > 0:
    change_message += f"{quantity} x {value // 100} €, "
change_message = change_message[:-2]

# Afficher le message
print(change_message)

The error I get when I want to get the number of coins (the example is: the product costs 5€, the customer gives 10€, the distributor gives back 5€ but says he gives 5€ in one coin).

Here is the message I get:
20 € and 0 cents must be returned in 1 coin(s)
Coins returned: 1 x €1, 1 x €0.


问:
Change background of collapsed menu when clicked with React Bootstrap
I am building a responsive website using React Bootstrap. I would like to change the color of the drop down menu once collapsed, and remain transparent once it is not collapsed.

The drop down menu once collapsed is transparent so I changed the css for navbar-collapse.

.navbar-collapse { background-color: #8d8d8d !important;  }

Which changed the color but once it is not collapsed its still remains gray. So my question is...how do I change the color only when its collapsed? or clicked?

Problem:

Hameburger Menu

No Hameburger Menu

Expectations:

Hameburger Menu

No Hameburger Menu

This is my code of the NavBar as well

```<code>    <Navbar collapseOnSelect className="ms-auto navbar navbar-light navbarSupportedContent" expand="lg">
        <Navbar.Toggle className="ms-auto navbar-toggler "/>
        <Navbar.Collapse className='collapse navbar-collapse navbar.collapsing'>

        {menuToBeRendered.map((menu) => {
            const isActive = location.pathname === menu.path
            return <Nav className={`d-flex menu-item nav-link ${isActive && 'active-menu-item'}`}>
                <Nav.Item className='ms-auto'>

                    <Link to={menu.path}>{menu.name}</Link>
                    <i className={menu.icon}></i>
                </Nav.Item>
            </Nav>
        })}
        </Navbar.Collapse>
    </Navbar>
</code>```

I hope I explained this correctly. Thanks to anyone that may assist me.

Body:
I am building a responsive website using React Bootstrap. I would like to change the color of the drop down menu once collapsed, and remain transparent once it is not collapsed.

The drop down menu once collapsed is transparent so I changed the css for navbar-collapse.

.navbar-collapse { background-color: #8d8d8d !important;  }

Which changed the color but once it is not collapsed its still remains gray. So my question is...how do I change the color only when its collapsed? or clicked?

Problem:

Hameburger Menu

No Hameburger Menu

Expectations:

Hameburger Menu

No Hameburger Menu

This is my code of the NavBar as well

    <Navbar collapseOnSelect className="ms-auto navbar navbar-light navbarSupportedContent" expand="lg">
        <Navbar.Toggle className="ms-auto navbar-toggler "/>
        <Navbar.Collapse className='collapse navbar-collapse navbar.collapsing'>

        {menuToBeRendered.map((menu) => {
            const isActive = location.pathname === menu.path
            return <Nav className={`d-flex menu-item nav-link ${isActive && 'active-menu-item'}`}>

                    <Link to={menu.path}>{menu.name}</Link>

        })}
        </Navbar.Collapse>
    </Navbar>

I hope I explained this correctly. Thanks to anyone that may assist me.


问:
Convert pattern string to Interpolated string with dollar sign
```<code>var pattern = getPattern(); //read from the config, something like "{x} abc {y}"

var x = $pattern; //not compiling
</code>```

Is there a way to convert a pattern in string Interpolated string?

Body:
var pattern = getPattern(); //read from the config, something like "{x} abc {y}"

var x = $pattern; //not compiling

Is there a way to convert a pattern in string Interpolated string?


问:
yield inhibits new web pages from display
I've successfully scrapped a multi page library using “scrapy”. But when I added a yield block only the first web page  was scrapped. The page count continued to increase  but the web page didn't change What is wrong?
Here is the structure of part of the program.

```<code>enter code here
</code>```

.current page = 1
while  current_ page < =- last_page
product_container =  #the container of all the books to be scraped from the current web                                    page

```<code>enter code here
 for product in product_container:
    get:
      book title,
      authors into authorDic,
      narrators into narratorDic
    yield{
          title': book_title,
          'author': authorsDic,
          'narrantor': narratorsDic,
    }
 current_page +=1
 get next_ page
 next_page.clickl()
 '''

</code>```

Body:
I've successfully scrapped a multi page library using “scrapy”. But when I added a yield block only the first web page  was scrapped. The page count continued to increase  but the web page didn't change What is wrong?
Here is the structure of part of the program.

enter code here

.current page = 1
while  current_ page < =- last_page
product_container =  #the container of all the books to be scraped from the current web                                    page

enter code here
 for product in product_container:
    get:
      book title,
      authors into authorDic,
      narrators into narratorDic
    yield{
          title': book_title,
          'author': authorsDic,
          'narrantor': narratorsDic,
    }
 current_page +=1
 get next_ page
 next_page.clickl()
 '''


问:
Retrofit call repeats to infinite and doesn't stop
I am trying to make an API call with Retrofit 2.9.0 and use the response in a Jetpack Compose activity. The problem is that the call repeats to infinite and updates the UI on every frame. I have never used the retrofit library before so I'm sorry if the code is messy. I will attach a GIF with how the app behaves and code snippets for everything. Thanks for reading this and wanting to help. <3

What is happening in the app

Here is the class that makes the call to the API:

```<code>public class ApiHandler {

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.quotable.io/").build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.getData();

public void getQuoteRaw()
{
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
             try {
                 MainActivityKt.getModel().setQuoteInfo(response.body().string());

           } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            System.out.println("ERROR");
        }
    });
}
</code>```

The Interface I use to define the getData() method:

```<code>public interface ApiInterface {

@GET("random")
Call<ResponseBody> getData();
</code>```

The ViewModel class for the Compose Activity:

```<code>class MainViewModel: ViewModel() {
var quoteInfo by mutableStateOf("")
</code>```

The Jetpack Compose activity:

```<code>val model = MainViewModel()
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        QuoteappTheme {

            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                Greeting()
            }
        }
    }
}
}

@Composable
fun Greeting(viewModel: MainViewModel = model) {

val apihandle = ApiHandler()
apihandle.getQuoteRaw()
Text(text = viewModel.quoteInfo)
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
QuoteappTheme {
    Greeting()
}
}
</code>```

Body:
I am trying to make an API call with Retrofit 2.9.0 and use the response in a Jetpack Compose activity. The problem is that the call repeats to infinite and updates the UI on every frame. I have never used the retrofit library before so I'm sorry if the code is messy. I will attach a GIF with how the app behaves and code snippets for everything. Thanks for reading this and wanting to help. <3

What is happening in the app

Here is the class that makes the call to the API:

public class ApiHandler {

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.quotable.io/").build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.getData();

public void getQuoteRaw()
{
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
             try {
                 MainActivityKt.getModel().setQuoteInfo(response.body().string());

           } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            System.out.println("ERROR");
        }
    });
}

The Interface I use to define the getData() method:

public interface ApiInterface {

@GET("random")
Call<ResponseBody> getData();

The ViewModel class for the Compose Activity:

class MainViewModel: ViewModel() {
var quoteInfo by mutableStateOf("")

The Jetpack Compose activity:

val model = MainViewModel()
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        QuoteappTheme {

            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {
                Greeting()
            }
        }
    }
}
}

@Composable
fun Greeting(viewModel: MainViewModel = model) {

val apihandle = ApiHandler()
apihandle.getQuoteRaw()
Text(text = viewModel.quoteInfo)
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
QuoteappTheme {
    Greeting()
}
}


问:
Reusing SVG elements while inserting different text?
I want to display balls with 1,2,3,4 inside.  Can I use <use>?  or I must duplicate the stone <g>?

#stone text {
    fill: grey;
    dominant-baseline: middle;
    text-anchor: middle;
    font-size: 0.33pt;
}

#pane {
    background-color: yellow;
    width: 100%;
    height: 100%;
}

.stone-white {
    fill: #F2F4F4;
}

.stone-black {
    fill: #273746;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="pane" viewBox="0 0 22 22" preserveAspectRatio="none">

    <defs>
        <g id="stone">
            <circle cx="0" cy="0" r="0.45" />
            <text>333</text>
        </g>
    </defs>

    <use href="#stone" class="stone-white" x="1" y="1"/>
    <use href="#stone" class="stone-white" x="2" y="2"/>
    <use href="#stone" class="stone-black" x="3" y="2"/>
    <use href="#stone" class="stone-black" x="2" y="4"/>

</svg></code>```

Body:
I want to display balls with 1,2,3,4 inside.  Can I use <use>?  or I must duplicate the stone <g>?

#stone text {
    fill: grey;
    dominant-baseline: middle;
    text-anchor: middle;
    font-size: 0.33pt;
}

#pane {
    background-color: yellow;
    width: 100%;
    height: 100%;
}

.stone-white {
    fill: #F2F4F4;
}

.stone-black {
    fill: #273746;
}

<svg id="pane" viewBox="0 0 22 22" preserveAspectRatio="none">

    <defs>
        <g id="stone">
            <circle cx="0" cy="0" r="0.45" />
            <text>333</text>
        </g>
    </defs>

    <use href="#stone" class="stone-white" x="1" y="1"/>
    <use href="#stone" class="stone-white" x="2" y="2"/>
    <use href="#stone" class="stone-black" x="3" y="2"/>
    <use href="#stone" class="stone-black" x="2" y="4"/>

</svg>


问:
I am getting initialization error :java.util.NoSuchElementException while running runner file using Junit
```<code>java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
at java.base/java.util.Collections.max(Collections.java:713)
at io.cucumber.core.feature.FeatureParser.parseResource(FeatureParser.java:46)
at java.base/java.util.function.BiFunction.lambda$andThen$0(BiFunction.java:70)
at io.cucumber.core.resource.ResourceScanner.lambda$processResource$1(ResourceScanner.java:79)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:75)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:60)
at java.base/java.nio.file.Files.walkFileTree(Files.java:2810)
at io.cucumber.core.resource.PathScanner.findResourcesForPath(PathScanner.java:53)
at io.cucumber.core.resource.PathScanner.findResourcesForUri(PathScanner.java:31)
at io.cucumber.core.resource.ResourceScanner.findResourcesForUri(ResourceScanner.java:61)
at io.cucumber.core.resource.ResourceScanner.scanForResourcesUri(ResourceScanner.java:134)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.loadFeatures(FeaturePathFeatureSupplier.java:62)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.get(FeaturePathFeatureSupplier.java:45)
at io.cucumber.junit.Cucumber.<init>(Cucumber.java:156)
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:484)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
</code>```

I have been doing many workarounds for couple of days but couldn't resolve this issue. Can anyone please help?

Below are the jars I used.

```<code>cucumber-core-7.10.1.jar
 cucumber-expressions-16.1.1.jar
 cucumber-extentsreport-3.1.1.jar
 cucumber-gherkin-5.2.0.jar
 cucumber-gherkin-messages-7.10.1.jar
 cucumber-java-7.10.1.jar
 cucumber-junit-7.10.1.jar
 cucumber-jvm-deps-1.0.6.jar
 cucumber-plugin-7.10.1.jar
 cucumber-reporting-5.7.4.jar
 datatable-7.10.1.jar
 datatable-dependencies-3.0.0.jar
 extentreports-3.1.2.jar
 extentreports-cucumber7-adapter-1.2.0.jar
 gherkin-5.2.0.jar
 gherkin-jvm-deps-1.0.6.jar
 hamcrest-2.2.jar
 hamcrest-core-1.3.jar
 junit-4.13.2.jar
 selenium-java-4.7.2.jar
 selenium-server-4.7.2.jar
 tag-expressions-5.0.1.jar
</code>```

This is my project folder structure
[folder-structure-image][1]
[1]: https://i.stack.imgur.com/abYF2.png

This is my runner file:
package com.qa.myrunner;

```<code>import java.io.*;
import org.junit.runner.RunWith;
import com.vimalselvam.cucumber.listener.Reporter;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = {"E:/Programming/LearnAutomation/SeleniumCucumberBDDV2/src/main/java/com/qa/features/SelectFlight.feature" },
glue = {"/SeleniumCucumberBDDV2/src/main/java/com/qa/stepDefinitions" },
monochrome = true,
dryRun = false)

public class SuiteRunner {

}
</code>```

Body:
java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
at java.base/java.util.Collections.max(Collections.java:713)
at io.cucumber.core.feature.FeatureParser.parseResource(FeatureParser.java:46)
at java.base/java.util.function.BiFunction.lambda$andThen$0(BiFunction.java:70)
at io.cucumber.core.resource.ResourceScanner.lambda$processResource$1(ResourceScanner.java:79)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:75)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:60)
at java.base/java.nio.file.Files.walkFileTree(Files.java:2810)
at io.cucumber.core.resource.PathScanner.findResourcesForPath(PathScanner.java:53)
at io.cucumber.core.resource.PathScanner.findResourcesForUri(PathScanner.java:31)
at io.cucumber.core.resource.ResourceScanner.findResourcesForUri(ResourceScanner.java:61)
at io.cucumber.core.resource.ResourceScanner.scanForResourcesUri(ResourceScanner.java:134)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.loadFeatures(FeaturePathFeatureSupplier.java:62)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.get(FeaturePathFeatureSupplier.java:45)
at io.cucumber.junit.Cucumber.<init>(Cucumber.java:156)
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:484)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

I have been doing many workarounds for couple of days but couldn't resolve this issue. Can anyone please help?

Below are the jars I used.

cucumber-core-7.10.1.jar
 cucumber-expressions-16.1.1.jar
 cucumber-extentsreport-3.1.1.jar
 cucumber-gherkin-5.2.0.jar
 cucumber-gherkin-messages-7.10.1.jar
 cucumber-java-7.10.1.jar
 cucumber-junit-7.10.1.jar
 cucumber-jvm-deps-1.0.6.jar
 cucumber-plugin-7.10.1.jar
 cucumber-reporting-5.7.4.jar
 datatable-7.10.1.jar
 datatable-dependencies-3.0.0.jar
 extentreports-3.1.2.jar
 extentreports-cucumber7-adapter-1.2.0.jar
 gherkin-5.2.0.jar
 gherkin-jvm-deps-1.0.6.jar
 hamcrest-2.2.jar
 hamcrest-core-1.3.jar
 junit-4.13.2.jar
 selenium-java-4.7.2.jar
 selenium-server-4.7.2.jar
 tag-expressions-5.0.1.jar

This is my project folder structure
[folder-structure-image][1]
[1]: https://i.stack.imgur.com/abYF2.png

This is my runner file:
package com.qa.myrunner;

import java.io.*;
import org.junit.runner.RunWith;
import com.vimalselvam.cucumber.listener.Reporter;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = {"E:/Programming/LearnAutomation/SeleniumCucumberBDDV2/src/main/java/com/qa/features/SelectFlight.feature" },
glue = {"/SeleniumCucumberBDDV2/src/main/java/com/qa/stepDefinitions" },
monochrome = true,
dryRun = false)

public class SuiteRunner {

}


问:
Implementing Mobile Controls into React Three Fiber
I'm currently trying to create a desktop AND mobile experience  using React Three Fiber, using this example as a boilerplate: https://codesandbox.io/s/vkgi6. For mobile I've managed to create some buttons which simulate pointerControls interactions for panning the camera.

The problem now, is simulating key presses (such as spacebar); I can't seem to add a ref to Keyboard Controls, and I've tried doing something like this:
How to trigger keypress event in React.js and using ref.dispatchEvent connected to the <App> container itself, but to no avail.

Any suggestions for how to simulate keypresses which get picked up by the Player component (such as Space for causing the player to jump)? Alternatively, anyone know of any great 'dual' joystick control examples for mobile, with one for moving and one for panning?

Thanks


问:
Trying to find a way to convert two lists into a map where one list acts as the key and the other as the value
Trying to find a way to convert two lists into a map where one list acts as the key and the other as the value. I'm new to dart and trying to exercise some of the functions I learned but can't seem to find an effective way to do so.

I tried to convert 1 list to a map and then access the keys in a for loop and replace them with the values from the other list, but apparently that's not possible?

Any suggestions will be appreciated :)
Thanks

EDIT: ok I feel dumb.

This is the solution for anyone wondering.

final theMap = Map.fromIterables(months, salesFigures);


问:
How to get angular material breakpoints in scss?
I use the BreakpointObserver from '@angular/cdk/layout' in my projects which uses pixel values for screen sizes like Breakpoints.Medium or Breakpoints.Small. How can I get these values in my scss?


问:
What is right method for 1-d array/row vector transposition?
I know the simple/worked solution to this question is reshape (-1, 1) for turning row vector (numpy.array) into a column vector (numpy.array).

Specifically, I want to understand why numpy.transpose(a) won't work.

Say,

```<code>vector_of_1 = np.transpose(np.ones(N)) # statement 1
</code>```

And if I define a column vector b, and use the following statement:

```<code>V = b + vector_of_1
</code>```

I would get a weird matrix V.

My fix is to use

```<code>vector_of_1 = np.ones(N).reshape(-1,1)
</code>```

And it works as expected (V being a column vector).

But I want to understand why the transpose method (i.e., statement 1) won't work. Detailed explanation is appreciated.

Body:
I know the simple/worked solution to this question is reshape (-1, 1) for turning row vector (numpy.array) into a column vector (numpy.array).

Specifically, I want to understand why numpy.transpose(a) won't work.

Say,

vector_of_1 = np.transpose(np.ones(N)) # statement 1

And if I define a column vector b, and use the following statement:

V = b + vector_of_1

I would get a weird matrix V.

My fix is to use

vector_of_1 = np.ones(N).reshape(-1,1)

And it works as expected (V being a column vector).

But I want to understand why the transpose method (i.e., statement 1) won't work. Detailed explanation is appreciated.


问:
Graph not displaying using matplotlib in Jupyter Notebook (On VS Code)
I have searched a lot about this problem, but I haven't found the solution to my problem yet.
I want to generate a graph as my output after the cell:

```<code>x= np.linspace(0,20, 100)
plt.plot(x, np.sin(x))

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

I've stumbled on some answers saying to insert before my graph:

```<code>%matplotlib inline
</code>```

This returns just

```<code><Figure size 640x480 with 1 Axes>
</code>```

How could that problem be solved?

Body:
I have searched a lot about this problem, but I haven't found the solution to my problem yet.
I want to generate a graph as my output after the cell:

x= np.linspace(0,20, 100)
plt.plot(x, np.sin(x))

plt.show()

I've stumbled on some answers saying to insert before my graph:

%matplotlib inline

This returns just

How could that problem be solved?


问:
Modify Mxnet nodes in a json file in C++
I have a generic Mxnet model saved into a json file that I load in a C++ script. But depending on the specific case, I need to modify the attributes of many nodes.

Is there a way to do so after (or before) calling LoadJson on that json file?

Thank you.


问:
How to expand multiple Properties in json output (ConvertFrom-Json/ConvertTo-Csv)
Running a AWS CLI command for AWS to export all the subnets. Then running the below in PowerShell. When doing this, there are a couple fields (Tags, CIDR Blocks) that output as just "System.Object[]" in the CSV. If i could get them to expand or 'be selected' would be great. Specifically, I only really want the tag: "Name", but i'll take w/e is easier.

```<code>Get-Content -Path C:\Working\subnets.json  |
    ConvertFrom-Json |
    Select-Object -expand * |
    ConvertTo-Csv -NoTypeInformation |
    Set-Content C:\Working\subnets12.csv
</code>```

json was created from: aws ec2 describe-subnets --output=json
then, copied and pasted everything inside the { } into a text file.
I assume there is a better way to create the json file from bash prompt. And, might even be able to convert to csv from bash instead of PowerShell.

I was expecting to be able to get a CSV that had all the details from the original json file.

Body:
Running a AWS CLI command for AWS to export all the subnets. Then running the below in PowerShell. When doing this, there are a couple fields (Tags, CIDR Blocks) that output as just "System.Object[]" in the CSV. If i could get them to expand or 'be selected' would be great. Specifically, I only really want the tag: "Name", but i'll take w/e is easier.

Get-Content -Path C:\Working\subnets.json  |
    ConvertFrom-Json |
    Select-Object -expand * |
    ConvertTo-Csv -NoTypeInformation |
    Set-Content C:\Working\subnets12.csv

json was created from: aws ec2 describe-subnets --output=json
then, copied and pasted everything inside the { } into a text file.
I assume there is a better way to create the json file from bash prompt. And, might even be able to convert to csv from bash instead of PowerShell.

I was expecting to be able to get a CSV that had all the details from the original json file.


问:
ReactTabulator - can't vertically align column header titles
Trying to configure grouped columns with ReactTabulator. I can get the groups to work but the header titles of columns outside the groups are aligned to the top of the cell, which to me looks bad. I tried the 'columnHeaderVertAlign' property but it isn't working. In the code below, I have 'columnHeaderVertAlign' in the component itself but I've also tried putting it in the 'columns' definition and got the same results. What am I missing?

Here's all my code:

```<code>import React, { Component } from "react";
import 'react-tabulator/lib/css/tabulator.min.css'; // theme
import 'react-tabulator/lib/styles.css';
import { ReactTabulator } from 'react-tabulator'

function TabulatorExample(){
    var data = [
        {id:1, name:"Oli Bob", age:"12", col:"red", dob:""},
        {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"},
        {id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"},
        {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"},
        {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"},
    ];

    const columns = [
        { title: "Name", field: "name" },
        {
            title:"Age info",
            columns:[
                { title: "Age", field: "age", hozAlign: "left", formatter: "progress", width: 150 },
                { title: "Date Of Birth", field: "dob", hozAlign: "center" },
            ],
        },
        { title: "Favourite Color", field: "col" },
        { title: "Rating", field: "rating", hozAlign: "center", formatter: "star" },
        { title: "Passed?", field: "passed", hozAlign: "center", formatter: "tickCross" }
    ];

    return(
        <section>
            <ReactTabulator
                data={data}
                columns={columns}
                layout={"fitDataTable"}
                columnHeaderVertAlign={"bottom"}
            />
        </section>
    );
}

export default TabulatorExample;
</code>```

here's the output of the above

I would like 'Name', 'Favourite Color', 'Rating', and 'Passed?' to be aligned to the bottom of their respective cells.

Body:
Trying to configure grouped columns with ReactTabulator. I can get the groups to work but the header titles of columns outside the groups are aligned to the top of the cell, which to me looks bad. I tried the 'columnHeaderVertAlign' property but it isn't working. In the code below, I have 'columnHeaderVertAlign' in the component itself but I've also tried putting it in the 'columns' definition and got the same results. What am I missing?

Here's all my code:

import React, { Component } from "react";
import 'react-tabulator/lib/css/tabulator.min.css'; // theme
import 'react-tabulator/lib/styles.css';
import { ReactTabulator } from 'react-tabulator'

function TabulatorExample(){
    var data = [
        {id:1, name:"Oli Bob", age:"12", col:"red", dob:""},
        {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"},
        {id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"},
        {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"},
        {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"},
    ];

    const columns = [
        { title: "Name", field: "name" },
        {
            title:"Age info",
            columns:[
                { title: "Age", field: "age", hozAlign: "left", formatter: "progress", width: 150 },
                { title: "Date Of Birth", field: "dob", hozAlign: "center" },
            ],
        },
        { title: "Favourite Color", field: "col" },
        { title: "Rating", field: "rating", hozAlign: "center", formatter: "star" },
        { title: "Passed?", field: "passed", hozAlign: "center", formatter: "tickCross" }
    ];

    return(

            <ReactTabulator
                data={data}
                columns={columns}
                layout={"fitDataTable"}
                columnHeaderVertAlign={"bottom"}
            />

    );
}

export default TabulatorExample;

here's the output of the above

I would like 'Name', 'Favourite Color', 'Rating', and 'Passed?' to be aligned to the bottom of their respective cells.


问:
Predicting values based on a rating in tensorflow.js / tensorflow
I am following the https://codelabs.developers.google.com/codelabs/tfjs-training-regression/index.html#7 tutorial and trying to understand how to use tensorflow.js - I have a pretty simple problem I'm trying to solve, but no idea how to get there. Rather than mpg and horsepower in the tutorial, I have data with

{rating: x, value: y} - Rating being a scale of 1-5, and value being a float. What I'm trying to do is make the model more likely to predict closer to a value that has a rating of 5, rather than randomly. When I evaluated the predictions, I noticed that wasn't happening, because the model doesn't know that I want it to be more biased based on the rating. Can anyone explain how to do this? (And if there is a machine learning term that describes what I'm trying to do?)


问:
boost::program_options conditionally required option
My executable has two modes of operation which are selectable via --mode=foo or --mode=bar. If mode=foo, then --abc option should be required and --xyz should not be specified. If mode=bar, then --xyz option should be required and --abc should not be specified. What is the correct way to code that?


问:
Expo Notification for ios and android err "Trigger of type: calendar is not supported on Android"
Below is a code example. The whole problem is that I can not set up a notification for a specific day and month. I get the error " Error: Failed to schedule the notification. Trigger of type: calendar is not supported on Android." Everything works until I specify a date. Any time specified in hours and minutes works but does not work on the specified dates.

import { StatusBar } from 'expo-status-bar';
import React, {useEffect, useState, useRef} from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import storage from "@react-native-async-storage/async-storage";

//1. import the library
//2. get permission
//3. do push notifications on button click
//4. schedule push notifications

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true
  })
});

export default function App() {

  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    const getPermission = async () => {
      if (Constants.isDevice) {
          const { status: existingStatus } = await Notifications.getPermissionsAsync();
          let finalStatus = existingStatus;
          if (existingStatus !== 'granted') {
            const { status } = await Notifications.requestPermissionsAsync();
            finalStatus = status;
          }
          if (finalStatus !== 'granted') {
            alert('Enable push notifications to use the app!');
            await storage.setItem('expopushtoken', "");
            return;
          }
          const token = (await Notifications.getExpoPushTokenAsync()).data;
          await storage.setItem('expopushtoken', token);
      } else {
        alert('Must use physical device for Push Notifications');
      }

        if (Platform.OS === 'android') {
          Notifications.setNotificationChannelAsync('default', {
            name: 'default',
            importance: Notifications.AndroidImportance.MAX,
            vibrationPattern: [0, 250, 250, 250],
            lightColor: '#FF231F7C',
          });
        }
    }

    getPermission();

    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {});

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  const onClick = async () => {
    await Notifications.scheduleNotificationAsync({
      content: {
        title: "Title 1",
        body: "body 1",
        data: { data: "data goes here" }
      },
      trigger: {
       day: 6,
       month: 0,
       hour: 17,
       minute: 30,
      }
    });

    await Notifications.scheduleNotificationAsync({
      content: {
        title: "Title 2",
        body: "body 2",
        data: { data: "data goes here" }
      },
      trigger: {
       day: 8,
       month: 0,
       hour: 15,
       minute: 25,
      }
    });
  }

  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={onClick}>
        <Text style={{backgroundColor: 'red', padding: 10, color: 'white'}}>Click me to send a push notification</Text>
      </TouchableOpacity>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});```


问:
Found package configuration file: C:/SFML/lib/cmake/SFML/SFMLConfig.cmake but it set SFML_FOUND to FALSE so package "SFML" is considered tobe NOTFOUND
I try to link SFML library to my project. I use the next:

gcc compiler

g++20

MinGW_w64 distro

OS: WIN

CMakeLists.txt

```<code>#--------------------------- MAIN CONFIGURATION ---------------------------#

cmake_minimum_required(VERSION 3.17.0)

project(black_penny)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcoroutines -IC:/SFML/include")
set(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc")
set(SFML_STATIC_LIBRARIES TRUE)

set(
MAIN_SRC
main.cpp
)

add_executable(
$CACHE{CMAKE_PROJECT_NAME}
${MAIN_SRC}
)

#----------------------------- LINK LIBRARIES -----------------------------#

# Adding Boost library;

find_package(Boost REQUIRED)

message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
message(STATUS "Boost_VERSION: ${Boost_VERSION}")
message(STATUS "BOOST_SYSTEM: ${BOOST_SYSTEM}")
message(STATUS "BOOST_FILE_SYSTEM: ${BOOST_FILE_SYSTEM}")

include_directories(${Boost_INCLUDE_DIRS})

target_link_libraries($CACHE{CMAKE_PROJECT_NAME} LINK_PUBLIC ${Boost_LIBRARIES})

# if windows compiler;

if(MINGW)
message(STATUS "MinGW compiler defined!")
SET(
WIN_LIBS
ws2_32
wsock32
)
target_link_libraries($CACHE{CMAKE_PROJECT_NAME} ${WIN_LIBS})
endif()

add_subdirectory(tests)

# add SFML library;

set(SFML_DIR "C:/SFML/lib/cmake/SFML")
find_package(SFML REQUIRED system window graphics network audio)

if (SFML_FOUND)
message(STATUS "SFML was FOUND!")
#find_package(SFML REQUIRED graphics network audio window system)
#set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
target_link_libraries(${EXECUTABLE_NAME} sfml-graphics)
else()
message(STATUS "SFML was NOT FOUND")
endif()
</code>```

CMake output:

```<code>-- Boost_INCLUDE_DIRS: C:/MinGW/include
-- Boost_LIBRARIES:
-- Boost_VERSION: 1.81.0
-- BOOST_SYSTEM:
-- BOOST_FILE_SYSTEM:
-- MinGW compiler defined!
CMake Error at C:/SFML/lib/cmake/SFML/SFMLConfig.cmake:139 (message):
Requested SFML configuration (Static) was not found
Call Stack (most recent call first):
CMakeLists.txt:54 (find_package)

CMake Error at CMakeLists.txt:54 (find_package):
Found package configuration file:

    C:/SFML/lib/cmake/SFML/SFMLConfig.cmake

but it set SFML_FOUND to FALSE so package "SFML" is considered to be NOT
FOUND.

-- Configuring incomplete, errors occurred!
See also "C:/Users/Nikita/Documents/Project/Messanger/BlackPenny/build/CMakeFiles/CMakeOutput.log".
make: \*\*\* \[Makefile:192: cmake_check_build_system\] Error 1
</code>```

I try to download the ready SFML for win64, but it doesn't compile correctrly (don't find some libs mb. I have read that it isn't right build). So I compile sfml by my hands. Steps to compile I have found in the next video: https://www.youtube.com/watch?v=KJZRjcL4FCs&t=388s&ab_channel=AshishThapa

Body:
I try to link SFML library to my project. I use the next:

gcc compiler

g++20

MinGW_w64 distro

OS: WIN

CMakeLists.txt

#--------------------------- MAIN CONFIGURATION ---------------------------#

cmake_minimum_required(VERSION 3.17.0)

project(black_penny)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcoroutines -IC:/SFML/include")
set(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc")
set(SFML_STATIC_LIBRARIES TRUE)

set(
MAIN_SRC
main.cpp
)

add_executable(
$CACHE{CMAKE_PROJECT_NAME}
${MAIN_SRC}
)

#----------------------------- LINK LIBRARIES -----------------------------#

# Adding Boost library;

find_package(Boost REQUIRED)

message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
message(STATUS "Boost_VERSION: ${Boost_VERSION}")
message(STATUS "BOOST_SYSTEM: ${BOOST_SYSTEM}")
message(STATUS "BOOST_FILE_SYSTEM: ${BOOST_FILE_SYSTEM}")

include_directories(${Boost_INCLUDE_DIRS})

target_link_libraries($CACHE{CMAKE_PROJECT_NAME} LINK_PUBLIC ${Boost_LIBRARIES})

# if windows compiler;

if(MINGW)
message(STATUS "MinGW compiler defined!")
SET(
WIN_LIBS
ws2_32
wsock32
)
target_link_libraries($CACHE{CMAKE_PROJECT_NAME} ${WIN_LIBS})
endif()

add_subdirectory(tests)

# add SFML library;

set(SFML_DIR "C:/SFML/lib/cmake/SFML")
find_package(SFML REQUIRED system window graphics network audio)

if (SFML_FOUND)
message(STATUS "SFML was FOUND!")
#find_package(SFML REQUIRED graphics network audio window system)
#set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
target_link_libraries(${EXECUTABLE_NAME} sfml-graphics)
else()
message(STATUS "SFML was NOT FOUND")
endif()

CMake output:

-- Boost_INCLUDE_DIRS: C:/MinGW/include
-- Boost_LIBRARIES:
-- Boost_VERSION: 1.81.0
-- BOOST_SYSTEM:
-- BOOST_FILE_SYSTEM:
-- MinGW compiler defined!
CMake Error at C:/SFML/lib/cmake/SFML/SFMLConfig.cmake:139 (message):
Requested SFML configuration (Static) was not found
Call Stack (most recent call first):
CMakeLists.txt:54 (find_package)

CMake Error at CMakeLists.txt:54 (find_package):
Found package configuration file:

    C:/SFML/lib/cmake/SFML/SFMLConfig.cmake

but it set SFML_FOUND to FALSE so package "SFML" is considered to be NOT
FOUND.

-- Configuring incomplete, errors occurred!
See also "C:/Users/Nikita/Documents/Project/Messanger/BlackPenny/build/CMakeFiles/CMakeOutput.log".
make: \*\*\* \[Makefile:192: cmake_check_build_system\] Error 1

I try to download the ready SFML for win64, but it doesn't compile correctrly (don't find some libs mb. I have read that it isn't right build). So I compile sfml by my hands. Steps to compile I have found in the next video: https://www.youtube.com/watch?v=KJZRjcL4FCs&t=388s&ab_channel=AshishThapa


问:
[0, 1].forEach((e) => {console.log(e)}) producing TypeError

[0, 1].forEach((e) => {
  console.log(e)
})```

The code above is executing well in the inspector and prints out 0 and 1, but when I put it inside a

Body:
[0, 1].forEach((e) => {
  console.log(e)
})

The code above is executing well in the inspector and prints out 0 and 1, but when I put it inside a


问:
How can I change node engine version to install Next Auth with a compatible module? Can it cause breakups?
I'm trying to install Next Auth but apparently, I have a higher node version than next auth supports.

I got this error when I tried to install it with yarn add next-auth command.

```<code>error next-auth@4.18.7: The engine "node" is incompatible with this module. Expected version "^12.19.0 || ^14.15.0 || ^16.13.0 || ^18.12.0". Got "19.3.0"
</code>```

I wonder how can I change the node engine version to a specific previous version I also wonder if would that break the app because I also have a lot of other packages installed in the app.

Body:
I'm trying to install Next Auth but apparently, I have a higher node version than next auth supports.

I got this error when I tried to install it with yarn add next-auth command.

error next-auth@4.18.7: The engine "node" is incompatible with this module. Expected version "^12.19.0 || ^14.15.0 || ^16.13.0 || ^18.12.0". Got "19.3.0"

I wonder how can I change the node engine version to a specific previous version I also wonder if would that break the app because I also have a lot of other packages installed in the app.


问:
Typescript Codegen GraphQL Query Resource Type
Problem:

Is there a way to tell codegen or typescript to remove ? optional chaining.

post.attributes?.Title to post.attributes.Title

since Title is defined in the getPosts query.

Here's the code example.

```<code>export type Post = {
  __typename?: 'Post';
  Body?: Maybe<Scalars['String']>;
  Slug?: Maybe<Scalars['String']>;
  Title?: Maybe<Scalars['String']>;
  createdAt?: Maybe<Scalars['DateTime']>;
  publishedAt?: Maybe<Scalars['DateTime']>;
  updatedAt?: Maybe<Scalars['DateTime']>;
};

export type PostEntity = {
  __typename?: 'PostEntity';
  attributes?: Maybe<Post>;
  id?: Maybe<Scalars['ID']>;
};
</code>```
```<code>import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import _ from 'lodash';

import type { GetPostsQuery, PostEntity } from '../../common/cms/types';

const client = new ApolloClient({
  uri: 'http://127.0.0.1:1337/graphql',
  cache: new InMemoryCache(),
});

// read up on different code gen types
async function getPosts() {
  return await client.query<GetPostsQuery>({
    query: gql`
      query getPosts {
        posts {
          data {
            id
            attributes {
              Title
              Body
            }
          }
        }
      }
    `
  });
}

export default async function NotesPage() {
  const queryResult = await getPosts();

  const posts = queryResult.data.posts?.data

  console.log('posts', posts);

  return (
    <div className='bg-slate-500 h-screen w-screen flex-col justify-center items-center'>
      <div className='space-y-3'>
        {_.map(posts, (post: PostEntity) => (
          <div className='p-2 bg-slate-400' key={post.id}>
            <div>{post.attributes?.Title}</div>
            <div>{post.attributes?.Body}</div>
          </div>
        ))}
      </div>
    </div>
  );
}
</code>```

Body:
Problem:

Is there a way to tell codegen or typescript to remove ? optional chaining.

post.attributes?.Title to post.attributes.Title

since Title is defined in the getPosts query.

Here's the code example.

export type Post = {
  __typename?: 'Post';
  Body?: Maybe<Scalars['String']>;
  Slug?: Maybe<Scalars['String']>;
  Title?: Maybe<Scalars['String']>;
  createdAt?: Maybe<Scalars['DateTime']>;
  publishedAt?: Maybe<Scalars['DateTime']>;
  updatedAt?: Maybe<Scalars['DateTime']>;
};

export type PostEntity = {
  __typename?: 'PostEntity';
  attributes?: Maybe<Post>;
  id?: Maybe<Scalars['ID']>;
};

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import _ from 'lodash';

import type { GetPostsQuery, PostEntity } from '../../common/cms/types';

const client = new ApolloClient({
  uri: 'http://127.0.0.1:1337/graphql',
  cache: new InMemoryCache(),
});

// read up on different code gen types
async function getPosts() {
  return await client.query<GetPostsQuery>({
    query: gql`
      query getPosts {
        posts {
          data {
            id
            attributes {
              Title
              Body
            }
          }
        }
      }
    `
  });
}

export default async function NotesPage() {
  const queryResult = await getPosts();

  const posts = queryResult.data.posts?.data

  console.log('posts', posts);

  return (

        {_.map(posts, (post: PostEntity) => (

{post.attributes?.Title}

{post.attributes?.Body}

        ))}

  );
}


问:
Tab Freeze iOS after redirect
We have embedded a form via iFrame on our website. When the form has been sent, a new URL should be called.

On the desktop (Chrome browser), the redirect works. On iOS on the iPhone, the window freezes when you submit the form.

Do you know what is causing this or what is triggering this error in the code?

Here is our Code:

```<code><script type="text/javascript">
(function () {
    var d = document,
        s = d.createElement('script');
    s.src = 'https://kitarinocockpit.nemborn.com/Script/NemPlads/preregister-v1.0.0.1.js';
    s.id = 'nemplads-script';
    s.setAttribute('data-timestamp', +new Date());
    window.addEventListener('success', function (e) {
        const items = document.location.search.substr(1).split("&");
        for (let index = 0; index < items.length; index++) {
            const getParam = items[index].split("=");
            if (getParam[0] === 'id') {
                document.location.href = 'https://www.kitarino.net/bestatigung-platzanfrage?id=' + decodeURIComponent(getParam[1]);
                break;
            }
        }
    });
    (d.head || d.body).appendChild(s);
})();
</script>
</code>```

Title: Tab Freeze iOS after redirect


问:
Drawing outside the canvas
I am a beginner.
I'm working on a drawing wpf project. I draw lines in a canvas control. I want to control zooming and panning. I save the lines in a list with the actual coordinates which I transform to display them.
It almost works.
On the other hand I don't understand why some lines are drawn outside the canvas?

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;

namespace WPFcanvasZoomMove
{

    public partial class MainWindow : Window
    {

        const double _tX = 1;
        const double _tY = -1;

        double _originX;
        double _originY;

        double _zoom;

        List<Element> _elements;

        public MainWindow()
        {
            InitializeComponent();

            //RenderOptions.ProcessRenderMode=

            _zoom = 1;

            CanvasModel.Background = new SolidColorBrush(Colors.Black);

            CanvasModel.MouseMove += CanvasModel_MouseMove;
            CanvasModel.MouseWheel += CanvasModel_MouseWheel;

            _elements = new List<Element>();
            Element e;

            e = new Element(new Point(-500, 0), new Point(500, 0), new SolidColorBrush(Colors.Blue), 2);
            _elements.Add(e);
            e = new Element(new Point(0, -500), new Point(0, 500), new SolidColorBrush(Colors.Blue), 2);
            _elements.Add(e);
            e = new Element(new Point(50, 70), new Point(100, 30), new SolidColorBrush(Colors.Red), 4);
            _elements.Add(e);

            //e = new Element(new Point(125, 60), new Point(175, -70), new SolidColorBrush(Colors.Green), 10);
            //_elements.Add(e);

        }

        protected override void OnRender(DrawingContext drawingContext)
        {

            CanvasModel.BringIntoView();
            Redraw();

        }

        private void MainWindow_Load(object sender, RoutedEventArgs e)
        {

            //_originX = CanvasModel.ActualWidth / 2;
            //_originY = CanvasModel.ActualHeight / 2;

            _originX = 75;
            _originY = 130;

            lblMouseZoomFactor.Content = $"fZ={_zoom.ToString()}";

            lblMouseDeltaX.Content = $"dX={_originX.ToString()}";
            lblMouseDeltaY.Content = $"dY={_originY.ToString()}";

            Redraw();

        }

        public void Redraw()
        {
            DrawLine();
        }

        public void DrawLine()
        {

            CanvasModel.Children.Clear();
            // Dessiner
            foreach (Element e in _elements)
            {
                //CanvasModel.Children.Add(e.ToWorld(_dX,_dY,_zoom));
                //CanvasModel.Children.Add(e.ToWorld(_originX, _originY, _zoom));
                //CanvasModel.Children.Add(e.ToModel());
                CanvasModel.Children.Add(e.ToWorld(_originX, _originY, _zoom));

            }

        }

        private void CanvasModel_MouseMove(object sender, MouseEventArgs e)
        {

            //Matrice de transformation
            Matrix m;

            //Position de la souris dans le canvas (coordonnées wpf)
            Point ptCanvas = e.GetPosition(this.CanvasModel);
            lblMouseCanvasPositionX.Content = $"Xc={ptCanvas.X.ToString()}";
            lblMouseCanvasPositionY.Content = $"Yc={ptCanvas.Y.ToString()}";

            //Position de la souris dans le Model
            //Translation par rapport à l'origine
            m = new Matrix();
            m.Translate(-_originX, -_originY);
            Point ptModel = m.Transform(ptCanvas);
            ptModel=new Point(ptModel.X, -ptModel.Y);
            lblMouseModelPositionX.Content = $"Xm={ptModel.X.ToString()}";
            lblMouseModelPositionY.Content = $"Ym={ptModel.Y.ToString()}";

            //Position de la souris dans le World
            //Echelle par rapport au zoom
            m = new Matrix();
            m.ScaleAt(_zoom, _zoom, 0, 0);
            Point ptW = m.Transform(ptModel);
            lblMouseWorldPositionX.Content = $"Xw={ptW.X.ToString()}";
            lblMouseWorldPositionY.Content = $"Yw={ptW.Y.ToString()}";

            Redraw();

        }

        private void CanvasModel_MouseWheel(object sender, MouseWheelEventArgs e)
        {

            //Debug.WriteLine($"e.delta={e.Delta}");

            double kz = 1200;
            _zoom += e.Delta / kz;

            lblMouseZoomFactor.Content = $"fZ={_zoom.ToString()}";

            Redraw();
        }

    }

    public class Element
    {

        private Point _PointWorldStart;
        public Point PointWorldStart
        {
            get { return _PointWorldStart; }
            set { _PointWorldStart = value; }
        }

        private Point _PointWorldEnd;
        public Point PointWorldEnd
        {
            get { return _PointWorldEnd; }
            set { _PointWorldEnd = value; }
        }

        private Point _PointModelStart;
        public Point PointModelStart
        {
            get { return _PointModelStart; }
            set { _PointModelStart = value; }
        }

        private Point _PointModelEnd;
        public Point PointModelEnd
        {
            get { return _PointModelEnd; }
            set { _PointModelEnd = value; }
        }

        private SolidColorBrush _Brush;
        public SolidColorBrush Brush
        {
            get { return _Brush; }
            set { _Brush = value; }
        }

        private int _Thickness;
        public int Thickness
        {
            get { return _Thickness; }
            set { _Thickness = value; }
        }

        public Element()
        {
            _PointWorldStart = new Point(0,0);
            _PointWorldEnd = new Point(0, 0);
            //_SolidColorBrush = new SolidColorBrush(Color.FromRgb(0, 0, 255));
            _Brush = new SolidColorBrush(Colors.Black);
            _Thickness = 1;
        }

        public Element(Point PointStart, Point PointEnd, SolidColorBrush Brush, int Thickness)
        {
            _PointWorldStart = PointStart;
            _PointWorldEnd = PointEnd;
            _Brush = Brush;
            _Thickness = Thickness;
        }

        public Line ToModel()
        {
            Line l = new Line();
            l.X1 = _PointWorldStart.X;
            l.Y1 = _PointWorldStart.Y;
            l.X2 = _PointWorldEnd.X;
            l.Y2 = _PointWorldEnd.Y;
            l.StrokeThickness = _Thickness;
            l.Stroke = _Brush;
            return l;
        }

        public Line ToWorld(double deltaX, double deltaY, double zoomFactor)
        {
            Line l = new Line();
            l.X1 = ConvertPoint.ToWorld(_PointWorldStart, deltaX, deltaY, zoomFactor).X;
            l.Y1 = ConvertPoint.ToWorld(_PointWorldStart, deltaX, deltaY, zoomFactor).Y;
            l.X2 = ConvertPoint.ToWorld(_PointWorldEnd, deltaX, deltaY, zoomFactor).X;
            l.Y2 = ConvertPoint.ToWorld(_PointWorldEnd, deltaX, deltaY, zoomFactor).Y;
            l.StrokeThickness = _Thickness;
            l.Stroke = _Brush;
            return l;
        }

    }

    static class ConvertPoint
    {

        public static Point ToWorld(Point Point, double deltaX, double deltaY, double zoomFactor)
        {
            Matrix m;
            Point p = new Point(Point.X,-Point.Y);

            m = new Matrix();
            m.Translate(deltaX,deltaY);
            p = m.Transform(p);

            m = new Matrix();
            m.ScaleAt(zoomFactor, zoomFactor, 0, 0);
            p = m.Transform(p);

            Debug.WriteLine($"p={p.ToString()}");

            return p;
        }

    }

}
</code>```

I would like the drawing to stay in the canvas.

Title: Drawing outside the canvas

Body:
I am a beginner.
I'm working on a drawing wpf project. I draw lines in a canvas control. I want to control zooming and panning. I save the lines in a list with the actual coordinates which I transform to display them.
It almost works.
On the other hand I don't understand why some lines are drawn outside the canvas?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;

namespace WPFcanvasZoomMove
{

    public partial class MainWindow : Window
    {

        const double _tX = 1;
        const double _tY = -1;

        double _originX;
        double _originY;

        double _zoom;

        List<Element> _elements;

        public MainWindow()
        {
            InitializeComponent();

            //RenderOptions.ProcessRenderMode=

            _zoom = 1;

            CanvasModel.Background = new SolidColorBrush(Colors.Black);

            CanvasModel.MouseMove += CanvasModel_MouseMove;
            CanvasModel.MouseWheel += CanvasModel_MouseWheel;

            _elements = new List<Element>();
            Element e;

            e = new Element(new Point(-500, 0), new Point(500, 0), new SolidColorBrush(Colors.Blue), 2);
            _elements.Add(e);
            e = new Element(new Point(0, -500), new Point(0, 500), new SolidColorBrush(Colors.Blue), 2);
            _elements.Add(e);
            e = new Element(new Point(50, 70), new Point(100, 30), new SolidColorBrush(Colors.Red), 4);
            _elements.Add(e);

            //e = new Element(new Point(125, 60), new Point(175, -70), new SolidColorBrush(Colors.Green), 10);
            //_elements.Add(e);

        }

        protected override void OnRender(DrawingContext drawingContext)
        {

            CanvasModel.BringIntoView();
            Redraw();

        }

        private void MainWindow_Load(object sender, RoutedEventArgs e)
        {

            //_originX = CanvasModel.ActualWidth / 2;
            //_originY = CanvasModel.ActualHeight / 2;

            _originX = 75;
            _originY = 130;

            lblMouseZoomFactor.Content = $"fZ={_zoom.ToString()}";

            lblMouseDeltaX.Content = $"dX={_originX.ToString()}";
            lblMouseDeltaY.Content = $"dY={_originY.ToString()}";

            Redraw();

        }

        public void Redraw()
        {
            DrawLine();
        }

        public void DrawLine()
        {

            CanvasModel.Children.Clear();
            // Dessiner
            foreach (Element e in _elements)
            {
                //CanvasModel.Children.Add(e.ToWorld(_dX,_dY,_zoom));
                //CanvasModel.Children.Add(e.ToWorld(_originX, _originY, _zoom));
                //CanvasModel.Children.Add(e.ToModel());
                CanvasModel.Children.Add(e.ToWorld(_originX, _originY, _zoom));

            }

        }

        private void CanvasModel_MouseMove(object sender, MouseEventArgs e)
        {

            //Matrice de transformation
            Matrix m;

            //Position de la souris dans le canvas (coordonnées wpf)
            Point ptCanvas = e.GetPosition(this.CanvasModel);
            lblMouseCanvasPositionX.Content = $"Xc={ptCanvas.X.ToString()}";
            lblMouseCanvasPositionY.Content = $"Yc={ptCanvas.Y.ToString()}";

            //Position de la souris dans le Model
            //Translation par rapport à l'origine
            m = new Matrix();
            m.Translate(-_originX, -_originY);
            Point ptModel = m.Transform(ptCanvas);
            ptModel=new Point(ptModel.X, -ptModel.Y);
            lblMouseModelPositionX.Content = $"Xm={ptModel.X.ToString()}";
            lblMouseModelPositionY.Content = $"Ym={ptModel.Y.ToString()}";

            //Position de la souris dans le World
            //Echelle par rapport au zoom
            m = new Matrix();
            m.ScaleAt(_zoom, _zoom, 0, 0);
            Point ptW = m.Transform(ptModel);
            lblMouseWorldPositionX.Content = $"Xw={ptW.X.ToString()}";
            lblMouseWorldPositionY.Content = $"Yw={ptW.Y.ToString()}";

            Redraw();

        }

        private void CanvasModel_MouseWheel(object sender, MouseWheelEventArgs e)
        {

            //Debug.WriteLine($"e.delta={e.Delta}");

            double kz = 1200;
            _zoom += e.Delta / kz;

            lblMouseZoomFactor.Content = $"fZ={_zoom.ToString()}";

            Redraw();
        }

    }

    public class Element
    {

        private Point _PointWorldStart;
        public Point PointWorldStart
        {
            get { return _PointWorldStart; }
            set { _PointWorldStart = value; }
        }

        private Point _PointWorldEnd;
        public Point PointWorldEnd
        {
            get { return _PointWorldEnd; }
            set { _PointWorldEnd = value; }
        }

        private Point _PointModelStart;
        public Point PointModelStart
        {
            get { return _PointModelStart; }
            set { _PointModelStart = value; }
        }

        private Point _PointModelEnd;
        public Point PointModelEnd
        {
            get { return _PointModelEnd; }
            set { _PointModelEnd = value; }
        }

        private SolidColorBrush _Brush;
        public SolidColorBrush Brush
        {
            get { return _Brush; }
            set { _Brush = value; }
        }

        private int _Thickness;
        public int Thickness
        {
            get { return _Thickness; }
            set { _Thickness = value; }
        }

        public Element()
        {
            _PointWorldStart = new Point(0,0);
            _PointWorldEnd = new Point(0, 0);
            //_SolidColorBrush = new SolidColorBrush(Color.FromRgb(0, 0, 255));
            _Brush = new SolidColorBrush(Colors.Black);
            _Thickness = 1;
        }

        public Element(Point PointStart, Point PointEnd, SolidColorBrush Brush, int Thickness)
        {
            _PointWorldStart = PointStart;
            _PointWorldEnd = PointEnd;
            _Brush = Brush;
            _Thickness = Thickness;
        }

        public Line ToModel()
        {
            Line l = new Line();
            l.X1 = _PointWorldStart.X;
            l.Y1 = _PointWorldStart.Y;
            l.X2 = _PointWorldEnd.X;
            l.Y2 = _PointWorldEnd.Y;
            l.StrokeThickness = _Thickness;
            l.Stroke = _Brush;
            return l;
        }

        public Line ToWorld(double deltaX, double deltaY, double zoomFactor)
        {
            Line l = new Line();
            l.X1 = ConvertPoint.ToWorld(_PointWorldStart, deltaX, deltaY, zoomFactor).X;
            l.Y1 = ConvertPoint.ToWorld(_PointWorldStart, deltaX, deltaY, zoomFactor).Y;
            l.X2 = ConvertPoint.ToWorld(_PointWorldEnd, deltaX, deltaY, zoomFactor).X;
            l.Y2 = ConvertPoint.ToWorld(_PointWorldEnd, deltaX, deltaY, zoomFactor).Y;
            l.StrokeThickness = _Thickness;
            l.Stroke = _Brush;
            return l;
        }

    }

    static class ConvertPoint
    {

        public static Point ToWorld(Point Point, double deltaX, double deltaY, double zoomFactor)
        {
            Matrix m;
            Point p = new Point(Point.X,-Point.Y);

            m = new Matrix();
            m.Translate(deltaX,deltaY);
            p = m.Transform(p);

            m = new Matrix();
            m.ScaleAt(zoomFactor, zoomFactor, 0, 0);
            p = m.Transform(p);

            Debug.WriteLine($"p={p.ToString()}");

            return p;
        }

    }

}

I would like the drawing to stay in the canvas.


问:
inttypes.h: What are the reasons behind PRIdN (for N <= 16 bits)
inttypes.h is a header that defines portable printf specifiers for the types intN_t, int_leastN_t and int_fastN_t etc.

I'm not interested about the PRIdLEASTN and PRIdFASTN definitions, as I never use the types int_leastN_t and int_fastN_t.

However, I regularly use intN_t resp. uintN_t, so I'm interested to know what the rationale behind the macros PRIdN and PRIuN are.

More specifically, I'm interested in PRIu8 PRIu16 and their signed counterparts.

Why?

This site says:

The ISO/IEC 9899:1990 standard specified [...] but placed very little requirement on their size other than that int and short be at least 16 bits and long be at least as long as int and not smaller than 32 bits.

(emphasis not mine)

This means int is always equal or bigger than 16 bits.

Variadic functions use integer promotion if a type smaller than int is given.

So if a type smaller than int is specified, it automatically gets promoted to an int.

Why is then, that PRIu8, PRId8 are made available, if variadic functions will never be able to accept a fixed 8 bit value?

It's standard to specify a signed integer (int) with %d and an unsigned integer with %u (unsigned int), so why the macros?


问:
Rails active record seems out of sync with postgres
I am using rails 7 and postgres 14.5 and active record now seems out of sync with postgres.

I saved a user and I got ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "users_pkey" DETAIL:  Key (id)=(3) already exists. ):

From PostgreSQL: Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_pkey", I ran SELECT setval(pg_get_serial_sequence('users', 'id'), coalesce(max(id)+1, 1), false) FROM users;  which seemed to fix that initial issue and allowed me to save the user.

Then I destroyed the user and tried to save the user again and now I'm getting ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_users_on_email" DETAIL:  Key (email)=(test@test.com) already exists. ):

This is telling me that my active record is out of sync with my postgres.

Any ideas on how I can fix this out of sync issue or at least fix the index issue now?


问:
With jQuery, how can I implement a "page loading" animation?
When I submit a form using jQuery, I want to display an animation image (load.gif or progressbar.gif, etc.) for a few seconds.

How can I show a GIF image in jQuery?

ContentLicense: CC BY-SA 2.5


问:
How to prevent PHP log from showing after html form is submitted
I'm working with a contact form. The PHP code successfully delivers the form data but when I submit the form I get a log display on a new page (the form.php page), and the response message is printed at the bottom of the log and doesn't alert. Also, I would like the form page to simply reload and not redirect to the .php page. This is my first time using php so any help would be greatly appreciated. See attached image, and php below:</p>
```<code>
<form id="form-id" class="form-class" name="Form" method="post" action="form.php" onsubmit="return">

<?php

$name = $_POST['name'];
$role = $_POST['role'];
$company = $_POST['company'];
$country = $_POST['country'];
$email = $_POST['email'];
$message = $_POST['message'];

   $mail = new PHPMailer;
   $mail->isSMTP();
   $mail->SMTPDebug = 2;
   $mail->Host = '';
   $mail->Port = 'num';
   $mail->SMTPAuth = true;
   $mail->Username = 'username';
   $mail->Password = 'password';
   $mail->setFrom('email');
   $mail->addReplyTo('email');
   $mail->addAddress('email', 'Name');
   $mail->Subject = 'New Message: '.$organisation;
   $mail->Body =
   'Name: '.$name."\r\n".
   'Role: '.$role."\r\n".
   'Company: '.$company."\r\n".
   'Country: '.$Country."\r\n".
   'Email: '.$email."\r\n".
   'Message: '.$message.

if ($mail->send()) {
  echo ("Thank you " .$name. ". Message sent.");
}
?>

<div id="center_button"><button onclick="location.href='team&contact#contactus'">Return</button></div>

</code>```

Body:
I'm working with a contact form. The PHP code successfully delivers the form data but when I submit the form I get a log display on a new page (the form.php page), and the response message is printed at the bottom of the log and doesn't alert. Also, I would like the form page to simply reload and not redirect to the .php page. This is my first time using php so any help would be greatly appreciated. See attached image, and php below:

<form id="form-id" class="form-class" name="Form" method="post" action="form.php" onsubmit="return">

<?php

$name = $_POST['name'];
$role = $_POST['role'];
$company = $_POST['company'];
$country = $_POST['country'];
$email = $_POST['email'];
$message = $_POST['message'];

   $mail = new PHPMailer;
   $mail->isSMTP();
   $mail->SMTPDebug = 2;
   $mail->Host = '';
   $mail->Port = 'num';
   $mail->SMTPAuth = true;
   $mail->Username = 'username';
   $mail->Password = 'password';
   $mail->setFrom('email');
   $mail->addReplyTo('email');
   $mail->addAddress('email', 'Name');
   $mail->Subject = 'New Message: '.$organisation;
   $mail->Body =
   'Name: '.$name."\r\n".
   'Role: '.$role."\r\n".
   'Company: '.$company."\r\n".
   'Country: '.$Country."\r\n".
   'Email: '.$email."\r\n".
   'Message: '.$message.

if ($mail->send()) {
  echo ("Thank you " .$name. ". Message sent.");
}
?>

<button onclick="location.href='team&contact#contactus'">Return</button>


问:
Cert Manager working with only example.com not with svc.cluster.local
I was trying to use Cert-manager with Private CA issuer. I have written a custom implementation which works with the CA. When I create a new service with kn like.

kn service create helloworld17-go \

--image gcr.io/knative-samples/helloworld-go

--env TARGET=17-With-http
If the DNS config is set to default, This creates an endpoint:
http://helloworld17-go..example.com
and the certificate is created.

But If I change the DNS to svc.cluster.local then the certificates are not getting created.
Any Config in Knative or Cert-Manager that I am missing?


问:
Connect pageSize and pageSelection - activatedRoute
0

I have a little problem with the Pagination - Cities quest.

I have navbar-with-selection with page and with pageSize.

When I select pageSize: 5, the pages resize correctly (so on the last page in this case, page 16, only 2 cities remain).

PageSize works but "once" when I click on 5 or 10 or 15, but when I change the page pageSize immediately changes back to 5.
enter image description here

enter image description here

How to switch to valueChanges and router.navigate using side effect (tap operator)


问:
Disable stock input if custom checkbox is checked
I created a custom checkbox in inventory tab in woocommerce simple product. The goal is, when "Manage stock" is checked and the "Stock quantity" input is visible, this checkbox (if is checked) to disable the "Stock quantity" input using jquery but i am not able to achieve that.

I was able to make ti work for each variation, in variable product, using thw bellow code but i can't make it work for simple product.

```<code>add_action( 'admin_footer', 'custom_checkbox_variations_js' );
function custom_checkbox_variations_js() {
global $post_type;

if ( 'product' === $post_type ) :
?><script type='text/javascript'>
jQuery( function($) {
    $('#variable_product_options').on( 'change', function(){
        $('input.disable_stock_input').each( function(){
            if($(this).is(':checked') ){

$(this).closest('div').find('.wc_input_stock').prop('disabled',
true);
            }
            else {

$(this).closest('div').find('.wc_input_stock').prop('disabled',
false);
            }
        });
    });
});
</script><?php
endif;
}
</code>```

The screenshot shows the custom checkbox that when is checked the "stock quantity" input should be disabled.

The id of custom checkbox is #disable_stock_input

The custom checkbox has been declared using the bellow code for simple products.

```<code>add_action( 'woocommerce_product_options_stock_status',
'display_product_options_inventory_custom_fields', 20 );
function display_product_options_inventory_custom_fields() {
global $post;

echo '</div><div class="options_group">'; // New separated
section

// Checkbox
woocommerce_wp_checkbox( array(
    'id'          => 'disable_stock_input',
    'name'          => 'disable_stock_input',
    'label'       => __( 'Custom Checkbox', 'woocommerce' ),
    'description' => __( 'Custom Checkbox info', 'woocommerce' ),
    'class'       => 'checkbox disable_stock_input',
    'desc_tip'    => true,
));

// Get the checkbox value
$checkbox = get_post_meta( $post->ID, 'disable_stock_input', true );

add_action( 'woocommerce_process_product_meta',
'save_product_custom_fields' );
function save_product_custom_fields( $post_id ) {
// 1. readonly checkbox
$readonly = isset( $_POST['disable_stock_input'] ) ? esc_attr(
$_POST['disable_stock_input'] ) : '';
update_post_meta( $post_id, 'disable_stock_input', $readonly );
}
</code>```

Ansering my own question, i managed to do that with the bellow code.

```<code>add_action( 'admin_footer', 'custom_admin_product_simple_js' );
function custom_admin_product_simple_js() {
global $post_type;

if ( 'product' === $post_type ) :
?><script type='text/javascript'>
jQuery( function($) {
    $(document).on('click', function(){

if ( $('#disable_stock_input').is(':checked') ) {

    $("#_stock").prop('disabled', true);

} else {

    $("#_stock").prop('disabled', false);

}

})
});
</script><?php
endif;
}
</code>```

Body:
I created a custom checkbox in inventory tab in woocommerce simple product. The goal is, when "Manage stock" is checked and the "Stock quantity" input is visible, this checkbox (if is checked) to disable the "Stock quantity" input using jquery but i am not able to achieve that.

I was able to make ti work for each variation, in variable product, using thw bellow code but i can't make it work for simple product.

add_action( 'admin_footer', 'custom_checkbox_variations_js' );
function custom_checkbox_variations_js() {
global $post_type;

if ( 'product' === $post_type ) :
?><?php
endif;
}

The screenshot shows the custom checkbox that when is checked the "stock quantity" input should be disabled.

The id of custom checkbox is #disable_stock_input

The custom checkbox has been declared using the bellow code for simple products.

add_action( 'woocommerce_product_options_stock_status',
'display_product_options_inventory_custom_fields', 20 );
function display_product_options_inventory_custom_fields() {
global $post;

echo '

'; // New separated
section

// Checkbox
woocommerce_wp_checkbox( array(
    'id'          => 'disable_stock_input',
    'name'          => 'disable_stock_input',
    'label'       => __( 'Custom Checkbox', 'woocommerce' ),
    'description' => __( 'Custom Checkbox info', 'woocommerce' ),
    'class'       => 'checkbox disable_stock_input',
    'desc_tip'    => true,
));

// Get the checkbox value
$checkbox = get_post_meta( $post->ID, 'disable_stock_input', true );

add_action( 'woocommerce_process_product_meta',
'save_product_custom_fields' );
function save_product_custom_fields( $post_id ) {
// 1. readonly checkbox
$readonly = isset( $_POST['disable_stock_input'] ) ? esc_attr(
$_POST['disable_stock_input'] ) : '';
update_post_meta( $post_id, 'disable_stock_input', $readonly );
}

Ansering my own question, i managed to do that with the bellow code.

add_action( 'admin_footer', 'custom_admin_product_simple_js' );
function custom_admin_product_simple_js() {
global $post_type;

if ( 'product' === $post_type ) :
?><?php
endif;
}