问:
Why IIS doesn't handle relative path the same way IIS Express does?
When you are testing a web application in visual studio using IIS Express, you'll be able to add a reference to a script file like this (inside an ASPX file):

```<code><head>
    <script src="/Javascript/jquery-2.1.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
</code>```

However, when you are deploying the exact same application on an standard IIS server (using a web deployment package), you'll get an missing error 404 because the browser won't be able to resolve the url.

To fix it, I could simply remove the slash from the path:

```<code><script src="Javascript/jquery-2.1.1.min.js" type="text/javascript" charset="utf-8"></script>
</code>```

However, this question ain't about how to fix the link since this question has been asked and answered many time.  What I would like to understand is why does IIS Express handle those url correctly while IIS Express ain't able to?  Is it question of security (ex: browser has access to you local file while working on your own computer which ain't the case on remote server) or is it a matter of settings the doesn't get exported in the web package?

答:
From what I can tell from the answer you made in the comments, I understand that your IIS server is configured with something like http://localhost/mysite/Javascript/... while your IIS Express setup is more like http://localhost:8888/Javascript/...*

If it is really the case, the difference comes from the fact that a relative URL beginning with / means it is relative to the host name part of the url while a relative url without the initial / is relative to the actual page folder.

In the current example, if the page is demo.htm,

Server
Base Page
Relative Url
Result Url

IIS
http://localhost/mysite/demo.htm
/Javascript/jquery-2.1.1.min.js
http://localhost/Javascript/jquery-2.1.1.min.js

IISExpress
http://localhost:8888/demo.htm
/Javascript/jquery-2.1.1.min.js
http://localhost/Javascript/jquery-2.1.1.min.js

IIS
http://localhost/mysite/demo.htm
Javascript/jquery-2.1.1.min.js
http://localhost/mysite/Javascript/jquery-2.1.1.min.js

IISExpress
http://localhost:8888/demo.htm
Javascript/jquery-2.1.1.min.js
http://localhost/Javascript/jquery-2.1.1.min.js

Since I suppose your Javascript folder is part of your site, as you can see in the previous table, a Url with the front slash would not point at the right Url. On the other hand, using the front slash to access a root folder would work from anywhere within a website.

On a side note, another way of having both behave the same way would be to modify the project's properties for IIS Express (or directly the applicationHost.config file) so that it also uses a virtual directory instead of mapping directly to root.

Body:
When you are testing a web application in visual studio using IIS Express, you'll be able to add a reference to a script file like this (inside an ASPX file):

However, when you are deploying the exact same application on an standard IIS server (using a web deployment package), you'll get an missing error 404 because the browser won't be able to resolve the url.

To fix it, I could simply remove the slash from the path:

However, this question ain't about how to fix the link since this question has been asked and answered many time.  What I would like to understand is why does IIS Express handle those url correctly while IIS Express ain't able to?  Is it question of security (ex: browser has access to you local file while working on your own computer which ain't the case on remote server) or is it a matter of settings the doesn't get exported in the web package?


来源: stackexchange

问:
Removal of strings after a term and not before
I'm looking at removing specific terms before certain words in a dataframe column.

```<code>data = {'Code':['001', '002', '003', '004', '005', '006','007'],
        'Territory':['Kinshasa West', 'West Kivu', 'East Tamaki', 'Sydney North','Sydney South','Brisbane East Suburb','Wattle Downs East']}

df = pd.DataFrame(data)
df

  Code             Territory
0  001         Kinshasa West
1  002             West Kivu
2  003           East Tamaki
3  004          Sydney North
4  005          Sydney South
5  006  Brisbane East Suburb
6  007     Wattle Downs East
</code>```

I'm interested in removing words "West", "East", "North", "South" only if they are the last words in the column value. However, they should not be removed if they come before the last word.

Expected output:

```<code>  Code             Territory
0  001              Kinshasa
1  002             West Kivu
2  003           East Tamaki
3  004                Sydney
4  005                Sydney
5  006  Brisbane East Suburb
6  007          Wattle Downs
</code>```

I'm able to filter out the specific terms from the column values but making use of word positions is the issue at the moment.

答:
Does the data start out as a list?  You can use string manipulation on the list or convert it to a list and modify the dictionary</p>
```<code>data = {'Code':['001', '002', '003', '004', '005', '006','007'],
        'Territory':['Kinshasa West', 'West Kivu', 'East Tamaki', 'Sydney North','Sydney South','Brisbane East Suburb','Wattle Downs East']}

list1 = list(data.values())

for index,value in enumerate(list1[1]):
    if(value.endswith("West")):
        list1[1][index] = value.replace("West", "")

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking at removing specific terms before certain words in a dataframe column.

data = {'Code':['001', '002', '003', '004', '005', '006','007'],
        'Territory':['Kinshasa West', 'West Kivu', 'East Tamaki', 'Sydney North','Sydney South','Brisbane East Suburb','Wattle Downs East']}

df = pd.DataFrame(data)
df

  Code             Territory
0  001         Kinshasa West
1  002             West Kivu
2  003           East Tamaki
3  004          Sydney North
4  005          Sydney South
5  006  Brisbane East Suburb
6  007     Wattle Downs East

I'm interested in removing words "West", "East", "North", "South" only if they are the last words in the column value. However, they should not be removed if they come before the last word.

Expected output:

  Code             Territory
0  001              Kinshasa
1  002             West Kivu
2  003           East Tamaki
3  004                Sydney
4  005                Sydney
5  006  Brisbane East Suburb
6  007          Wattle Downs

I'm able to filter out the specific terms from the column values but making use of word positions is the issue at the moment.

Body:
Does the data start out as a list?  You can use string manipulation on the list or convert it to a list and modify the dictionary

data = {'Code':['001', '002', '003', '004', '005', '006','007'],
        'Territory':['Kinshasa West', 'West Kivu', 'East Tamaki', 'Sydney North','Sydney South','Brisbane East Suburb','Wattle Downs East']}

list1 = list(data.values())

for index,value in enumerate(list1[1]):
    if(value.endswith("West")):
        list1[1][index] = value.replace("West", "")


问:
How to get cs files for xml schemas (xsd)
I'm new in C# developpment and I want to know the procedure to get one CS file for each XSD schema I have.

I have 3 xsd files (A.xsd, B.xsd and Common.xsd). Both A and B have Common as import. I've tried "xsd.exe" and "xsd2code.exe" without success.

"xsd.exe"

Cannot generate classes because no top-level elements with complex type were found into "Common.xsd".

Files "A.cs" and "B.cs" are generate but the code of "Common.xsd" is in each files.

"xsd2code.exe"

"Common.cs" is well generated with the namespace I've choosen, "MyNamespace.Common".

Other files could not be generated because of unspecified types however I use the "MyNamespace.Common" as custom usings ("/cu" option).

Does someone have an idea?

Thanks in advance.

答:
You need to reference all the schemas that are in the import or include chain.

Try this:

```<code>xsd /c A.xsd B.xsd Common.xsd
</code>```

Edit: However this will mean that all the classes are in one file.

If you want them split out into different files you have two options:

Manually split them out. I know this is a generated file but if your source schemas are fairly static then it's a one off exercise.

Use svcutil.exe instead. However this is much more complicated and actually you may not even be able to do this unless your schemas all abide by certain guidelines. If you are interested see below for the process.

If you fancy option 2 above then here is the general process:

Extract the types from Common.xsd using the /dconly flag on svcutil. This will generate a class file with your common types.

Compile this class into an assembly

Extract the types from A.xsd using the /r flag and referencing your CommonTypes.dll assembly.

Do the same for B.xsd

However, this approach is based on svcutil using the DataContractSerializer to do the work, as the /r flag is not available to XmlSerializer. And this will only work if the your schemas adhere to the rather strict DCS rules (can be found here: http://msdn.microsoft.com/en-us/library/ms733112.aspx).

If these rules are not adhered to then svcutil will fall back to using XmlSerializer which does not support /r flag.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
You need to reference all the schemas that are in the import or include chain.

Try this:

xsd /c A.xsd B.xsd Common.xsd

Edit: However this will mean that all the classes are in one file.

If you want them split out into different files you have two options:

Manually split them out. I know this is a generated file but if your source schemas are fairly static then it's a one off exercise.

Use svcutil.exe instead. However this is much more complicated and actually you may not even be able to do this unless your schemas all abide by certain guidelines. If you are interested see below for the process.

If you fancy option 2 above then here is the general process:

Extract the types from Common.xsd using the /dconly flag on svcutil. This will generate a class file with your common types.

Compile this class into an assembly

Extract the types from A.xsd using the /r flag and referencing your CommonTypes.dll assembly.

Do the same for B.xsd

However, this approach is based on svcutil using the DataContractSerializer to do the work, as the /r flag is not available to XmlSerializer. And this will only work if the your schemas adhere to the rather strict DCS rules (can be found here: http://msdn.microsoft.com/en-us/library/ms733112.aspx).

If these rules are not adhered to then svcutil will fall back to using XmlSerializer which does not support /r flag.

Hope this helps.


问:
How to reload userform when button is clicked?
I have 2 userforms that are working as expected apart from the fact that when I close form2 and refill form1 and press "add" it does not take me back to the start of form2. It shows the last part that I was at previously.

When I press the close button on form2 I want it to reload the next time Add on form1 is clicked.

'Public because we want it to be active for all macros.
'Aim to stopped a loop when user click on a button
Public stopped, Non As Boolean

Public Sub closebut_Click()
Load Addform
Addform.Hide
End Sub

Private Sub savebut_Click()

Dim ws As Worksheet
Dim newrow As ListRow

Set ws = ThisWorkbook.Worksheets("New Product")

Set tbl = ws.ListObjects("NewMat")

erow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Offset(1, 0).Row

ws.Cells(erow, 1).Value = Me.EAN.Value
ws.Cells(erow, 2).Value = Me.MatCode.Value
ws.Cells(erow, 3).Value = Me.Des.Value

Do While stopped = True

Loop
Me.Label1.Visible = False
Me.Label2.Visible = False
Me.Label3.Visible = False
Me.Label4.Visible = True
Me.EAN.Visible = False
Me.MatCode.Visible = False
Me.Des.Visible = False
Me.closebut.Visible = True
Me.savebut.Visible = False

End Sub

Private Sub UserForm_initialize()

Do While stopped = True

Loop
Me.Label1.Visible = True
Me.Label2.Visible = True
Me.Label3.Visible = True
Me.Label4.Visible = False
Me.EAN.Visible = True
Me.MatCode.Visible = True
Me.Des.Visible = True
Me.closebut.Visible = False
Me.savebut.Visible = True
End Sub
```

答:
In Userform2 evets select UserForm_Deactivate and write Unload Me it will be closed Userform2 , when you open Userform2 it will reload. may it help you

```<code>Private Sub UserForm_Deactivate()
Unload Me
End Sub
</code>```

Body:
In Userform2 evets select UserForm_Deactivate and write Unload Me it will be closed Userform2 , when you open Userform2 it will reload. may it help you

Private Sub UserForm_Deactivate()
Unload Me
End Sub


问:
How can I get a random item from multiple arrays based on a checkbox?
I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "

" + test[Math.floor(Math.random() * test.length)] + "

" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox"> txt<br>
<input type="checkbox"> test<br>
<input type="checkbox"> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p></code>```

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

答:
//Object of arrays
let options = {
  txt : ["txt1", "txt2", "txt3"],
  test : ["test1", "test2", "test3"],
  ran : ["ran1", "ran2", "ran3"]
};

function myFunc() {

  //Get all checkboxes
  let checkedBoxes = document.querySelectorAll('input[type=checkbox]:checked');

  //array for texts from arrays
  let texts = [];

  //loop through selected checkboxes
  checkedBoxes.forEach(function(ele) {

    // select respective array from object based on checkbox value
    let cOpt = options[ele.value];

    // random index for texts array - to randomize array text line
    let index = Math.floor(Math.random() * checkedBoxes.length);

    // to make sure we didn't set a text to that index already
    while( texts[index] !== undefined ) {
      index = Math.floor(Math.random() * checkedBoxes.length);
    }

    // set selected array text to a random index in texts array
    texts[index] = cOpt[Math.floor(Math.random() * cOpt.length)];

  });

  // text.join() to covert texts array into string
  document.getElementById("tst").innerHTML = texts.join('

');

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" value="txt"> txt<br>
<input type="checkbox" value="test"> test<br>
<input type="checkbox" value="ran"> ran<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p></code>```

You need to make some adjustments in your approach. i.e set values to checkboxes, create a js obj with all arrays being its property.

Make sure checkboxes values and properties keys are the same.

I have added comments in the code so you can easily understand the purpose of each line.

Body:
I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "

" + test[Math.floor(Math.random() * test.length)] + "

" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}

<input type="checkbox"> txt

<input type="checkbox"> test

<input type="checkbox"> ran

<button onclick="myFunc()">One Character</button>

  sum text lol

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

Body:
//Object of arrays
let options = {
  txt : ["txt1", "txt2", "txt3"],
  test : ["test1", "test2", "test3"],
  ran : ["ran1", "ran2", "ran3"]
};

function myFunc() {

  //Get all checkboxes
  let checkedBoxes = document.querySelectorAll('input[type=checkbox]:checked');

  //array for texts from arrays
  let texts = [];

  //loop through selected checkboxes
  checkedBoxes.forEach(function(ele) {

    // select respective array from object based on checkbox value
    let cOpt = options[ele.value];

    // random index for texts array - to randomize array text line
    let index = Math.floor(Math.random() * checkedBoxes.length);

    // to make sure we didn't set a text to that index already
    while( texts[index] !== undefined ) {
      index = Math.floor(Math.random() * checkedBoxes.length);
    }

    // set selected array text to a random index in texts array
    texts[index] = cOpt[Math.floor(Math.random() * cOpt.length)];

  });

  // text.join() to covert texts array into string
  document.getElementById("tst").innerHTML = texts.join('<br><br>');

}

<input type="checkbox" value="txt"> txt<br>
<input type="checkbox" value="test"> test<br>
<input type="checkbox" value="ran"> ran<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p>

You need to make some adjustments in your approach. i.e set values to checkboxes, create a js obj with all arrays being its property.

Make sure checkboxes values and properties keys are the same.

I have added comments in the code so you can easily understand the purpose of each line.


问:
Why my panel is hiding the body of my views?
i want to build a built a navigation with BottomTabNavigator but i dont know what happen i never see the body of my screens, something is hidding the body, i created a demo to demostrate you the wrong, but its too simple.

this is the file App.js

```<code>import React from 'react'
//import { Provider } from 'react-native-paper'
import { Provider, useSelector } from 'react-redux'
import { createStore } from 'redux'
import { NavigationContainer } from '@react-navigation/native'
import { View, Text } from 'react-native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'

const Stack = createStackNavigator()

function HomeScreen() {
  return (
    <View
      style={{
        flexDirection: 'row',
        height: 100,
        padding: 20,
      }}
    >
      <View style={{ backgroundColor: 'blue', flex: 0.3 }} />
      <View style={{ backgroundColor: 'red', flex: 0.5 }} />
      <Text>Hello World!</Text>
    </View>
  )
}

function SettingsScreen() {
  return (
    <View
      style={{
        backgroundColor: 'red',
        flex: 1,
        color: 'green',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Text>Settings!</Text>
    </View>
  )
}

const Tab = createBottomTabNavigator()

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="main">
        <Stack.Screen name="loginScreen" component={SettingsScreen} />
        <Stack.Screen name="main" component={MyTabs} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}
</code>```

i am trying to do, before to user is logged i would like to hidde the tabs

something is hidding

edit 1: why i have 2 headers?

答:
On the web, @react-navigation/bottom-tabs mistakenly treat screens in the tab as inactive and detaches them.

The solution is to disable detach inactive screens for bottom tab.

import React from "react";
//import { Provider } from 'react-native-paper'
import { Provider, useSelector } from "react-redux";
import { createStore } from "redux";
import { NavigationContainer } from "@react-navigation/native";
import { View, Text } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

const Stack = createStackNavigator();

function HomeScreen() {
  return (
    <View
      style={{
        flexDirection: "row",
        height: 100,
        padding: 20,
      }}
    >
      <View style={{ backgroundColor: "blue", flex: 0.3 }} />
      <View style={{ backgroundColor: "red", flex: 0.5 }} />
      <Text>Hello World!</Text>
    </View>
  );
}

function SettingsScreen() {
  return (
    <View
      style={{
        backgroundColor: "red",
        flex: 1,
        color: "green",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Text>Settings!</Text>
    </View>
  );
}

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator detachInactiveScreens={false}>
      <Tab.Screen name="Home" component={HomeScreen} options={{headerShown:false}} />
      <Tab.Screen name="Settings" component={SettingsScreen} options={{headerShown:false}}/>
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="main"  >
        <Stack.Screen name="loginScreen" component={SettingsScreen}  options={{headerShown:false}}/>
        <Stack.Screen name="main" component={MyTabs} options={{headerShown:false}}  />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

```

Body:
i want to build a built a navigation with BottomTabNavigator but i dont know what happen i never see the body of my screens, something is hidding the body, i created a demo to demostrate you the wrong, but its too simple.

this is the file App.js

import React from 'react'
//import { Provider } from 'react-native-paper'
import { Provider, useSelector } from 'react-redux'
import { createStore } from 'redux'
import { NavigationContainer } from '@react-navigation/native'
import { View, Text } from 'react-native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'

const Stack = createStackNavigator()

function HomeScreen() {
  return (
    <View
      style={{
        flexDirection: 'row',
        height: 100,
        padding: 20,
      }}
    >
      <View style={{ backgroundColor: 'blue', flex: 0.3 }} />
      <View style={{ backgroundColor: 'red', flex: 0.5 }} />
      <Text>Hello World!</Text>
    </View>
  )
}

function SettingsScreen() {
  return (
    <View
      style={{
        backgroundColor: 'red',
        flex: 1,
        color: 'green',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Text>Settings!</Text>
    </View>
  )
}

const Tab = createBottomTabNavigator()

function MyTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="main">
        <Stack.Screen name="loginScreen" component={SettingsScreen} />
        <Stack.Screen name="main" component={MyTabs} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

i am trying to do, before to user is logged i would like to hidde the tabs

something is hidding

edit 1: why i have 2 headers?


问:
Woocommerce mini-cart ajax apply coupon
I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.

functions:

```<code>function apply_coupon_code(){
    $coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
    WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
</code>```

Input:

```<code><?php if (empty (WC()->cart->get_coupons())): ?>
<span id="coupon-form">
<?php if ( wc_coupons_enabled() ) { ?>

        <form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
            <?php } else { ?>
        <form id="apply-promo-code" class="widget_shopping_cart__coupon">
            <?php } ?>
            <label id="promo-code" for="coupon-code">Promo Code:</label>
                <input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
                    <button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
                    <?php do_action( 'woocommerce_cart_coupon' ); ?>
                    <?php do_action( 'woocommerce_cart_actions' ); ?>
            </form>
            <?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
    <span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
        Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>

            <?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
            <?php wc_cart_totals_coupon_html( $coupon ); ?>
    </span>
<?php endforeach; ?>
</code>```

jQuery:

```<code>    jQuery(document).on('click', 'button#minicart-apply-button', function() {

        var coupon = jQuery( 'input#minicart-coupon' ).val();
        var button = ( this );
        var data = {
            action: "apply_coupon_code",
            coupon_code: "coupon"
        };

       jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: wc_add_to_cart_params.ajax_url,
        data: data,
        success: function (response) {
                console.log(response);
            },
            error: function (errorThrown) {
                console.log(errorThrown);
            }
        });

    });
</code>```

答:
You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.

function apply_coupon_code(){
    $coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
    WC()->cart->apply_coupon($coupon_code);
    ob_start();
    woocommerce_mini_cart();
    $cart_html = ob_get_clean();
    return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );
```
<p>The output buffer is used here as <code>woocommerce_mini_cart</code> uses <code>wc_get_template</code> which just echoes out the content. The output buffer will allow you to capture this as a string.</p>
<p>Now you need to tell jQuery that you're expecting HTML back from the server...</p>
<pre class="lang-js prettyprint-override"><code>jQuery(document).on('click', 'button#minicart-apply-button', function() {
    var coupon = jQuery( 'input#minicart-coupon' ).val();
    var button = ( this );
    var data = {
        action: "apply_coupon_code",
        coupon_code: "coupon"
    };

    jQuery.ajax({
        type: 'POST',
        dataType: 'html',
        url: wc_add_to_cart_params.ajax_url,
        data: data,
        success: function (response) {
                console.log(response);
         },
        error: function (errorThrown) {
                console.log(errorThrown);
        }
    });
});
</code>```

Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...

success: function (response) {
    console.log(response);
    jQuery('.mini-cart-wrapper').html(response);
},
```

Title: Woocommerce mini-cart ajax apply coupon

Body:
I have been going in circles with this I have added an apply coupon field to mini-cart.php and am trying to get it to run without refreshing the whole page. Any suggestions would be amazing help.

functions:

function apply_coupon_code(){
    $coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
    WC()->cart->apply_coupon($coupon_code);
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );

Input:

<?php if (empty (WC()->cart->get_coupons())): ?>

<?php if ( wc_coupons_enabled() ) { ?>

        <form class="widget_shopping_cart_content" action="<?php echo $cart_url ?>" method="post">
            <?php } else { ?>
        <form id="apply-promo-code" class="widget_shopping_cart__coupon">
            <?php } ?>
            Promo Code:
                <input id="minicart-coupon" class="input-text" type="text" value="" name="coupon_code"/>
                    <button type="submit" id="minicart-apply-button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply', 'woocommerce' ); ?></button>
                    <?php do_action( 'woocommerce_cart_coupon' ); ?>
                    <?php do_action( 'woocommerce_cart_actions' ); ?>
            </form>
            <?php endif; ?>
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
    <span id="widget-shopping-cart-remove-coupon" class="mini_cart_coupon-<?php echo esc_attr( sanitize_title( $code ) ); ?>">
        Promo Code: <?php echo esc_attr( sanitize_title( $code ) ); ?>

            <?php $remove_url = $cart_url.'?remove_coupon='.$coupon->code; ?>
            <?php wc_cart_totals_coupon_html( $coupon ); ?>

<?php endforeach; ?>

jQuery:

    jQuery(document).on('click', 'button#minicart-apply-button', function() {

        var coupon = jQuery( 'input#minicart-coupon' ).val();
        var button = ( this );
        var data = {
            action: "apply_coupon_code",
            coupon_code: "coupon"
        };

       jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: wc_add_to_cart_params.ajax_url,
        data: data,
        success: function (response) {
                console.log(response);
            },
            error: function (errorThrown) {
                console.log(errorThrown);
            }
        });

    });

Body:
You can get the new mini cart HTML inside your ajax callback on the server and then return that as a response to the jQuery ajax call then simply replace the whole mini cart HTML on the front-end with the updated HTML.

function apply_coupon_code(){
    $coupon_code = isset( $_POST["coupon_code"] ) ? $_POST["coupon_code"] : '';
    WC()->cart->apply_coupon($coupon_code);
    ob_start();
    woocommerce_mini_cart();
    $cart_html = ob_get_clean();
    return $cart_html;
}
add_action( 'wp_ajax_apply_coupon_code', 'apply_coupon_code' );
add_action( 'wp_ajax_nopriv_apply_coupon_code', 'apply_coupon_code' );

The output buffer is used here as woocommerce_mini_cart uses wc_get_template which just echoes out the content. The output buffer will allow you to capture this as a string.

Now you need to tell jQuery that you're expecting HTML back from the server...

jQuery(document).on('click', 'button#minicart-apply-button', function() {
    var coupon = jQuery( 'input#minicart-coupon' ).val();
    var button = ( this );
    var data = {
        action: "apply_coupon_code",
        coupon_code: "coupon"
    };

    jQuery.ajax({
        type: 'POST',
        dataType: 'html',
        url: wc_add_to_cart_params.ajax_url,
        data: data,
        success: function (response) {
                console.log(response);
         },
        error: function (errorThrown) {
                console.log(errorThrown);
        }
    });
});

Now response will have the new HTML for the mini-cart, so you can replace it using jQuery's html() function...

success: function (response) {
    console.log(response);
    jQuery('.mini-cart-wrapper').html(response);
},


问:
cameranode rotate as iOS device moving
It's 360 degree video player project.

I add a cameranode(SCNNode) to a rootnode, the cameranode was put at the center(0,0,0) of the SCNSphere, It can play video by now.

Now I have to use devicemotion. I need to rotate the camera when device moves. Not just rotate a certain angle. (Not just device move, When I'm holding a device, my moving regard as the device moving. because I found if I use deviceMotion.attitude.roll, the cameranode only moves when device moves by itself, not when I circle around with device)

When device is located in (x1,y1,z1) position, the cameranode would rotate as the device moving, and when the device located in (x1,y1,z1) position again, the view should be as same as the last we left.

Here's what I've done:

```<code>if (self.motionManager.gyroAvailable) {
        self.motionManager.gyroUpdateInterval = 1.0/60.0;
        [self.motionManager startGyroUpdatesToQueue:self.queue withHandler:^(CMGyroData *gyroData, NSError *error){
            if (error) {
                [self.motionManager stopGyroUpdates];
                NSLog(@"Gyroscope encountered error:%@",error);
            }else {
                CGFloat tempX = 0;
                CGFloat tempY = 0;
                CGFloat tempZ = 0;
                if ((fabs(gyroData.rotationRate.y)/60) > 0.002) {
                    tempY = gyroData.rotationRate.y/60;
                }
                tempX = gyroData.rotationRate.x/60;
                tempZ = gyroData.rotationRate.z/60;
                [self.cameraNode runAction:[SCNAction rotateByX:-tempY y:tempX z:tempZ duration:0]];
            }
        }];
    }else {
        NSLog(@"This device has no gyroscope");
    }
</code>```

The math could be wrong, I don't know why would I divide 60, but it seems the nearest value I need when I use [self.cameraNode runAction:[SCNAction rotateByX:-tempY y:tempX z:tempZ duration:0]];

Here's the problem?

which data should I use?

CMGyroData or CMDeviceMotion. If use CMDeviceMotion, which specific value should I use? deviceMotion.attitude, deviceMotion.attitude.quaternion, deviceMotion.gravity

which is the right method to rotate a cameranode? There are many methods, I'm not sure.

+ (SCNAction *)rotateByX:(CGFloat)xAngle y:(CGFloat)yAngle z:(CGFloat)zAngle duration:(NSTimeInterval)duration;

+ (SCNAction *)rotateToX:(CGFloat)xAngle y:(CGFloat)yAngle z:(CGFloat)zAngle duration:(NSTimeInterval)duration;

答:
For iOS 15 using extension from initial answer

```<code>override func viewDidAppear(_ animated: Bool) {
    // let motionManager = CMMotionManager() // definition made globally
// CoreMotion
motionManager.startDeviceMotionUpdates()
motionManager.deviceMotionUpdateInterval = 1.0 / 60.0

//this following line is changed to avoid deprecated term
let interfaceOrientation = keyWindow!.windowScene?.interfaceOrientation

// .xTrueNorthZVertical // always aligns to the real north
// .xArbitraryZVertical // will use this one for initial direction
motionManager.startDeviceMotionUpdates(using: .xArbitraryZVertical, to: OperationQueue.main, withHandler: { (motion: CMDeviceMotion?, err: Error?) in
    guard let m = motion else { return }
    // self.cameraNode.orientation = m.gaze(atOrientation: UIApplication.shared.statusBarOrientation) // before iOS 13
    self.cameraNode.orientation = m.gaze(atOrientation: interfaceOrientation!) // for iOS13 and later
})
}

extension (change name UIApplication) {

var keyWindow: UIWindow? {
    // Get connected scenes
    return UIApplication.shared.connectedScenes
        // Keep only active scenes, onscreen and visible to the user
        .filter { $0.activationState == .foregroundActive }
        // Keep only the first `UIWindowScene`
        .first(where: { $0 is UIWindowScene })
        // Get its associated windows
        .flatMap({ $0 as? UIWindowScene })?.windows
        // Finally, keep only the key window
        .first(where: \.isKeyWindow)
}
</code>```

Title: cameranode rotate as iOS device moving

Body:
It's 360 degree video player project.

I add a cameranode(SCNNode) to a rootnode, the cameranode was put at the center(0,0,0) of the SCNSphere, It can play video by now.

Now I have to use devicemotion. I need to rotate the camera when device moves. Not just rotate a certain angle. (Not just device move, When I'm holding a device, my moving regard as the device moving. because I found if I use deviceMotion.attitude.roll, the cameranode only moves when device moves by itself, not when I circle around with device)

When device is located in (x1,y1,z1) position, the cameranode would rotate as the device moving, and when the device located in (x1,y1,z1) position again, the view should be as same as the last we left.

Here's what I've done:

if (self.motionManager.gyroAvailable) {
        self.motionManager.gyroUpdateInterval = 1.0/60.0;
        [self.motionManager startGyroUpdatesToQueue:self.queue withHandler:^(CMGyroData *gyroData, NSError *error){
            if (error) {
                [self.motionManager stopGyroUpdates];
                NSLog(@"Gyroscope encountered error:%@",error);
            }else {
                CGFloat tempX = 0;
                CGFloat tempY = 0;
                CGFloat tempZ = 0;
                if ((fabs(gyroData.rotationRate.y)/60) > 0.002) {
                    tempY = gyroData.rotationRate.y/60;
                }
                tempX = gyroData.rotationRate.x/60;
                tempZ = gyroData.rotationRate.z/60;
                [self.cameraNode runAction:[SCNAction rotateByX:-tempY y:tempX z:tempZ duration:0]];
            }
        }];
    }else {
        NSLog(@"This device has no gyroscope");
    }

The math could be wrong, I don't know why would I divide 60, but it seems the nearest value I need when I use [self.cameraNode runAction:[SCNAction rotateByX:-tempY y:tempX z:tempZ duration:0]];

Here's the problem?

which data should I use?

CMGyroData or CMDeviceMotion. If use CMDeviceMotion, which specific value should I use? deviceMotion.attitude, deviceMotion.attitude.quaternion, deviceMotion.gravity

which is the right method to rotate a cameranode? There are many methods, I'm not sure.

+ (SCNAction *)rotateByX:(CGFloat)xAngle y:(CGFloat)yAngle z:(CGFloat)zAngle duration:(NSTimeInterval)duration;

+ (SCNAction *)rotateToX:(CGFloat)xAngle y:(CGFloat)yAngle z:(CGFloat)zAngle duration:(NSTimeInterval)duration;

Body:
For iOS 15 using extension from initial answer

override func viewDidAppear(_ animated: Bool) {
    // let motionManager = CMMotionManager() // definition made globally
// CoreMotion
motionManager.startDeviceMotionUpdates()
motionManager.deviceMotionUpdateInterval = 1.0 / 60.0

//this following line is changed to avoid deprecated term
let interfaceOrientation = keyWindow!.windowScene?.interfaceOrientation

// .xTrueNorthZVertical // always aligns to the real north
// .xArbitraryZVertical // will use this one for initial direction
motionManager.startDeviceMotionUpdates(using: .xArbitraryZVertical, to: OperationQueue.main, withHandler: { (motion: CMDeviceMotion?, err: Error?) in
    guard let m = motion else { return }
    // self.cameraNode.orientation = m.gaze(atOrientation: UIApplication.shared.statusBarOrientation) // before iOS 13
    self.cameraNode.orientation = m.gaze(atOrientation: interfaceOrientation!) // for iOS13 and later
})
}

extension (change name UIApplication) {

var keyWindow: UIWindow? {
    // Get connected scenes
    return UIApplication.shared.connectedScenes
        // Keep only active scenes, onscreen and visible to the user
        .filter { $0.activationState == .foregroundActive }
        // Keep only the first `UIWindowScene`
        .first(where: { $0 is UIWindowScene })
        // Get its associated windows
        .flatMap({ $0 as? UIWindowScene })?.windows
        // Finally, keep only the key window
        .first(where: \.isKeyWindow)
}


问:
openpyxl - How to retrieve multiple columns of one row from an Excel file?
I'm looking for the correct way to print cell values from one desired row, but I only want the cell values that are in specific columns. e.g. columns 'A','C','F' etc.

Below is the code I currently have, I get no errors with this but am at a loss with how to progress with my desired outcome.

```<code>path_file = 'Readfrom.xlsx'
spreadsheet = load_workbook(path_file)

spreadsheet = spreadsheet.active

desire_columns = spreadsheet['A']

disire_row = spreadsheet['5']

for cell in disire_row:
    print(cell.value)
</code>```

答:
```<code>path_file = 'Readfrom.xlsx'
wb = load_workbook(path_file) #  Changed variable name

ws = wb.active # Changed variable name

desired_columns = ws['A'] #  Minor change in variable name

desired_row = ws['5'] #  Minor change in variable name

for column in desired_columns: #  Iterate over columns
    cell = ws[f"{column}{desired_row}"] #  Create the cell reference
    print(cell.value)
</code>```

You must read your pseudocode over and over again and you will find the answer.

I have also corrected your variables, hope you dont mind. Use the common variables as much as possible so that other programmers can easily understand your code. Also, the spreadsheet variable is specially confusing as it initialized as the workbook and later as a worksheet. Think about if you decide later that you want to save the workbook (remember to back up the excel file), or you have multiple sheets in the workbook.

Also read "for loop" to further your study.
https://www.w3schools.com/python/python_for_loops.asp

Body:
I'm looking for the correct way to print cell values from one desired row, but I only want the cell values that are in specific columns. e.g. columns 'A','C','F' etc.

Below is the code I currently have, I get no errors with this but am at a loss with how to progress with my desired outcome.

path_file = 'Readfrom.xlsx'
spreadsheet = load_workbook(path_file)

spreadsheet = spreadsheet.active

desire_columns = spreadsheet['A']

disire_row = spreadsheet['5']

for cell in disire_row:
    print(cell.value)

Body:
path_file = 'Readfrom.xlsx'
wb = load_workbook(path_file) #  Changed variable name

ws = wb.active # Changed variable name

desired_columns = ws['A'] #  Minor change in variable name

desired_row = ws['5'] #  Minor change in variable name

for column in desired_columns: #  Iterate over columns
    cell = ws[f"{column}{desired_row}"] #  Create the cell reference
    print(cell.value)

You must read your pseudocode over and over again and you will find the answer.

I have also corrected your variables, hope you dont mind. Use the common variables as much as possible so that other programmers can easily understand your code. Also, the spreadsheet variable is specially confusing as it initialized as the workbook and later as a worksheet. Think about if you decide later that you want to save the workbook (remember to back up the excel file), or you have multiple sheets in the workbook.

Also read "for loop" to further your study.
https://www.w3schools.com/python/python_for_loops.asp


问:
Upgrade from velocity 1.4 to recent - What to expect?
I have to maintain an old legacy codebase that uses velocity 1.4 for several things.
The customer is pretty conservative when it comes to updates, so we have to cope with
this ancient dependencies.
I'd like to solve a problem with recursive macros, which is not possible in this version.

So I thought that an update may be the solution.

Has anyone an idea what incompatibilities have been introduced?

答: Upgrading from 1.4 to 1.7 (which allows for recursive macros) requires no code and template changes in my experience. The only thing you may get are deprecation warnings (e.g. 'XMLToolboxManager has been deprecated.', 1.7 deprecates even more, so you may just want to upgrade to 1.6 if you just need macro recursion), but everything should still work as before.</p>


问:
"Application not found" Error while trying to login to JetBrains account from IntelliJ Idea
When I click on Login, it shows this error

答:
This is Windows-specific issue. It happens if the default browser is not set or the html file association and/or http protocol associations are not correctly set. The same error may occur when double-clicking an Internet Shortcut (.URL) file in the system.

To resolve the problem, use Default Programs to reset the default Web browser preference.


问:
I find myself pasting code into subclasses. Is there something else I can do besides inheritance?
I have the parent class Encryption.java, which is mainly just a bunch of functions for encryption. Then I have 5 subclasses that extend that class. They all look mostly the same, except for two things: Each subclass needs a different KEYSET map, and there is also one unique function to each subclass. I'm not sure if I need inheritance or something else, the only thing changing is the KEYSET and one function

Here is an example of the subclasses

```<code>public class Keyset_1 extends Encryption{

    private byte variant;
    private String side;

    private final Map<String,String> KEYSET = new HashMap<String,String>(){
        {
            put("awk_1_acq", "0123456789ABCDEF0123456789ABCDEF");
            put("awk_2_acq", "0123456789ABCDEF0123456789ABCDEF");
            ...
        }
    };

    //constructor is same in each subclass
    public Keyset_1(byte b, String side) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException {
        super();
        this.variant = b;
        this.side = side;
    }

    //Empty method in parent class, overridden here
    @Override
    public byte[] getZCMKVariant(){
        byte[] key;
        if (side.equalsIgnoreCase("acq"))
            key = ISOUtil.hex2byte(KEYSET.get("zcmk_acq"));
        else
            key = ISOUtil.hex2byte(KEYSET.get("zcmk_iss"));
        applyVariant(key, variant);
        return key;
    }
}
</code>```

答:
Generally as a rule of thumb, if you are copying code and pasting it into subclasses, that code should be in a parent class. The only thing that should be in the subclasses are unique attributes to them, so in your case this would only be the unique function in each of them.

For the KEYSET map, if it is hard coded you'll want to use the protected keyword. This will allow each of the subclasses to have their own maps, and all you'll need to do is place the actual data into the maps during their instantiation.

Basically, if you're copy and pasting anything between multiple subclasses, the correct way to handle this in OOP would be to have a shared parent class between subclasses with the same code (the code you are copy and pasting).

Also, if you end up needing something like multiple inheritance, you may need to resort to using interfaces.

In terms of alternatives to inheritance, you could use delegation, but I believe in your case it may be easier to simply use more inheritance.

Body:
I have the parent class Encryption.java, which is mainly just a bunch of functions for encryption. Then I have 5 subclasses that extend that class. They all look mostly the same, except for two things: Each subclass needs a different KEYSET map, and there is also one unique function to each subclass. I'm not sure if I need inheritance or something else, the only thing changing is the KEYSET and one function

Here is an example of the subclasses

public class Keyset_1 extends Encryption{

    private byte variant;
    private String side;

    private final Map<String,String> KEYSET = new HashMap<String,String>(){
        {
            put("awk_1_acq", "0123456789ABCDEF0123456789ABCDEF");
            put("awk_2_acq", "0123456789ABCDEF0123456789ABCDEF");
            ...
        }
    };

    //constructor is same in each subclass
    public Keyset_1(byte b, String side) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException {
        super();
        this.variant = b;
        this.side = side;
    }

    //Empty method in parent class, overridden here
    @Override
    public byte[] getZCMKVariant(){
        byte[] key;
        if (side.equalsIgnoreCase("acq"))
            key = ISOUtil.hex2byte(KEYSET.get("zcmk_acq"));
        else
            key = ISOUtil.hex2byte(KEYSET.get("zcmk_iss"));
        applyVariant(key, variant);
        return key;
    }
}


问:
Export Application in Processing 4 fails with error message
I'm trying to export the game I'm working on in Processing 4 as a windows executable.
The code itself is working fine, I can post all of it if necessary, but when I try and export it I get the following error:

java.lang.NullPointerException: Cannot invoke "String.split(String)" because the return value of "processing.app.Preferences.get(String)" is null

I checked all the preferences in the preferences.txt file, most of them have a value, except the proxy related lines and run.options.

I searched the web but couldn't find any answer as to what could be causing this.

I'm running Processing 4.0b4 in java mode on Windows 10 Pro 21H2 and trying to export to Windows (Intel 64-bit)

my java version:

```<code>openjdk 17.0.2 2022-01-18
OpenJDK Runtime Environment Temurin-17.0.2+8 (build 17.0.2+8)
OpenJDK 64-Bit Server VM Temurin-17.0.2+8 (build 17.0.2+8, mixed mode, sharing)
</code>```

The full exception:

```<code>Exporting application...

java.lang.NullPointerException: Cannot invoke "String.split(String)" because the return value of "processing.app.Preferences.get(String)" is null
at processing.mode.java.JavaBuild.exportApplication(JavaBuild.java:584)
at processing.mode.java.JavaMode.handleExportApplication(JavaMode.java:187)
at processing.mode.java.ExportPrompt.trigger(ExportPrompt.java:494)
at processing.mode.java.ExportPrompt.trigger(ExportPrompt.java:156)
at processing.mode.java.JavaEditor.handleExportApplication(JavaEditor.java:516)
at processing.mode.java.JavaEditor.lambda$buildFileMenu$0(JavaEditor.java:239)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.AbstractButton.doClick(AbstractButton.java:374)
at java.desktop/javax.swing.AbstractButton.doClick(AbstractButton.java:354)
at java.desktop/javax.swing.plaf.basic.BasicMenuItemUI$Actions.actionPerformed(BasicMenuItemUI.java:983)
at java.desktop/javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1810)
at java.desktop/javax.swing.JComponent.processKeyBinding(JComponent.java:2947)
at java.desktop/javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:710)
at java.desktop/javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:717)
at java.desktop/javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:717)
at java.desktop/javax.swing.JMenuBar.processKeyBinding(JMenuBar.java:688)
at java.desktop/javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:311)
at java.desktop/javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:297)
at java.desktop/javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.java:3040)
at java.desktop/javax.swing.JComponent.processKeyBindings(JComponent.java:3032)
at java.desktop/javax.swing.JComponent.processKeyEvent(JComponent.java:2909)
at processing.app.syntax.JEditTextArea.processKeyEvent(JEditTextArea.java:1991)
at processing.mode.java.JavaTextArea.processKeyEvent(JavaTextArea.java:140)
at java.desktop/java.awt.Component.processEvent(Component.java:6403)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1952)
at java.desktop/java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:883)
at java.desktop/java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1150)
at java.desktop/java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:1020)
at java.desktop/java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:848)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4882)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
</code>```

答:
After doing nothing differently for like a week, trying multiple times during all this time and getting the same error, I tried one last time tonight and for no apparent reason, it decided to work, since than it has been working consistently.

I have absolutely no idea what changed, but I guess it's working now.

(Though I don't know what I need to do if it stops working again...)

Body:
I'm trying to export the game I'm working on in Processing 4 as a windows executable.
The code itself is working fine, I can post all of it if necessary, but when I try and export it I get the following error:

java.lang.NullPointerException: Cannot invoke "String.split(String)" because the return value of "processing.app.Preferences.get(String)" is null

I checked all the preferences in the preferences.txt file, most of them have a value, except the proxy related lines and run.options.

I searched the web but couldn't find any answer as to what could be causing this.

I'm running Processing 4.0b4 in java mode on Windows 10 Pro 21H2 and trying to export to Windows (Intel 64-bit)

my java version:

openjdk 17.0.2 2022-01-18
OpenJDK Runtime Environment Temurin-17.0.2+8 (build 17.0.2+8)
OpenJDK 64-Bit Server VM Temurin-17.0.2+8 (build 17.0.2+8, mixed mode, sharing)

The full exception:

Exporting application...

java.lang.NullPointerException: Cannot invoke "String.split(String)" because the return value of "processing.app.Preferences.get(String)" is null
at processing.mode.java.JavaBuild.exportApplication(JavaBuild.java:584)
at processing.mode.java.JavaMode.handleExportApplication(JavaMode.java:187)
at processing.mode.java.ExportPrompt.trigger(ExportPrompt.java:494)
at processing.mode.java.ExportPrompt.trigger(ExportPrompt.java:156)
at processing.mode.java.JavaEditor.handleExportApplication(JavaEditor.java:516)
at processing.mode.java.JavaEditor.lambda$buildFileMenu$0(JavaEditor.java:239)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.AbstractButton.doClick(AbstractButton.java:374)
at java.desktop/javax.swing.AbstractButton.doClick(AbstractButton.java:354)
at java.desktop/javax.swing.plaf.basic.BasicMenuItemUI$Actions.actionPerformed(BasicMenuItemUI.java:983)
at java.desktop/javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1810)
at java.desktop/javax.swing.JComponent.processKeyBinding(JComponent.java:2947)
at java.desktop/javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:710)
at java.desktop/javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:717)
at java.desktop/javax.swing.JMenuBar.processBindingForKeyStrokeRecursive(JMenuBar.java:717)
at java.desktop/javax.swing.JMenuBar.processKeyBinding(JMenuBar.java:688)
at java.desktop/javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:311)
at java.desktop/javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:297)
at java.desktop/javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.java:3040)
at java.desktop/javax.swing.JComponent.processKeyBindings(JComponent.java:3032)
at java.desktop/javax.swing.JComponent.processKeyEvent(JComponent.java:2909)
at processing.app.syntax.JEditTextArea.processKeyEvent(JEditTextArea.java:1991)
at processing.mode.java.JavaTextArea.processKeyEvent(JavaTextArea.java:140)
at java.desktop/java.awt.Component.processEvent(Component.java:6403)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1952)
at java.desktop/java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:883)
at java.desktop/java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1150)
at java.desktop/java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:1020)
at java.desktop/java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:848)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4882)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


问:
Check if user input exist in database using php and mongodb
I want to check first if the email exists then check the password but I only want to use PHP and MongoDB not any other language or tool because I'm just a beginner.

when I enter an input the page change to an empty page and nothing happen.  I know my error is from the line of the array $findemail and downward.

am I using the $cursor in the right way and if so am I accessing the $findemail in the right way using $d['email'] to compare it with $email

```<code><?php
//Include libraries
require __DIR__ . '/vendor/autoload.php';

//Create instance of MongoDB client
$mongoClient = (new MongoDB\Client);

//Select a database
$db = $mongoClient->EcommerceWeb;

//Select a collection
$collection = $db->Employees_Data;

//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

$findemail = [
"email" => $email,
"password" => $password
 ];

$cursor = $db->$collection->find($findemail);

foreach ($cursor as $d ){

if($d['email'] == $email and $d['passwprd'] == $password){
    echo "success";
 }
else {
    echo "fail";
}
    }
</code>```

答:
Try to this:</p>
```<code>$cursor = $collection->findOne($findemail);

if($cursor){
    if($cursor->email == $email and $cursor->password == $password){
        echo "success";
    }
}
</code>```

Body:
I want to check first if the email exists then check the password but I only want to use PHP and MongoDB not any other language or tool because I'm just a beginner.

when I enter an input the page change to an empty page and nothing happen.  I know my error is from the line of the array $findemail and downward.

am I using the $cursor in the right way and if so am I accessing the $findemail in the right way using $d['email'] to compare it with $email

<?php
//Include libraries
require __DIR__ . '/vendor/autoload.php';

//Create instance of MongoDB client
$mongoClient = (new MongoDB\Client);

//Select a database
$db = $mongoClient->EcommerceWeb;

//Select a collection
$collection = $db->Employees_Data;

//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

$findemail = [
"email" => $email,
"password" => $password
 ];

$cursor = $db->$collection->find($findemail);

foreach ($cursor as $d ){

if($d['email'] == $email and $d['passwprd'] == $password){
    echo "success";
 }
else {
    echo "fail";
}
    }

Body:
Try to this:

$cursor = $collection->findOne($findemail);

if($cursor){
    if($cursor->email == $email and $cursor->password == $password){
        echo "success";
    }
}


问:
How do i use captcha in the asp.net application for test input in simple way
I'm working on asp.net web application where I need to use CAPTCHA to test input enter into textbox please let me know very simple way to implement CAPTCHA in asp.net.</p>

答:
Simple Google search returns this article:

http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx

I'd recommend working through this tutorial, then if you have any problems, then ask questions. Like @Stack72 has stated, people won't just do it all for you, but will help if you get stuck!


问:
Open color picker when editing CSS in WebStorm
Given I'm editing CSS in WebStorm, how can I open a color picker ?

For example

```<code>.bar {
    backround: // shortcut to open color picker that will fill in HEX value
}
</code>```

答:
Case 1. First of all, check that "Gutter Icons" is enabled in your IDE !

Case 2. This solution is for rare situations, e.g. editing React|Native JSX+SVG+TS and when "Gutter Icons" occasionally didn't appeared:

Invoke color picker even it not proposed by IDE:

Select HEX value in your code. Yellow balloon on the left
will appear:

Profit!

Body:
Given I'm editing CSS in WebStorm, how can I open a color picker ?

For example

.bar {
    backround: // shortcut to open color picker that will fill in HEX value
}


问:
Simple MySQL JSON query takes very long time to resolve
A very simple query like select * from vw_Json_Data where Ts < date_sub( now(), interval 1 day ) order by Ts desc limit 1 took > 5 minutes to resolve!

Monitoring the query using mysqladmin processlist showed that it was spending all that time 'Creating sort index'. How to reduce the query time something sensible (< 1 sec)?

The view vw_Json_Data is created as follows:

```<code>create table My_Json_Data (
  Id int auto_increment primary key,
  Tag_Id int, -- foreign key to the Tag table
  Ts datetime,
  Json_Data json
);

create table Tag (
  Tag_Id int auto_increment primary key,
  Val int
);

create or replace view vw_Json_Data as select * from Tag inner join My_Json_Data using( Tag_Id );
</code>```

Currently, the Tag table contains about 2 million rows and the My_Json_Data contains 500,000 rows. Therefore, this should not be a problem for MySQL at all, albeit the Json_Data in My_Json_Data are quite complex and long JSON strings.

答:
I personally have a my own rules for using JSON in a relational DB (2 is the solution):

1.) Try to use JSON to store "complex" data not to query it. (Sometimes it's unavoidable, e.g. when you come into a live production DB`).

2.) If you need to query it in a relational database reference the queried data in a separate non-JSON column as well as in the JSON column. (From my experience and testing, this really optimizes speed as the DB scales). Trade off: extra data for a faster query (minimize extra data by only adding what needs to be queried).

3.) Remember to focus on the relationship aspect. If there is no relations between tables/data, is a relational DB the best choice. Other non-relational DBS with well documented and highly used features are out there. (E.G. Cassandra, Mongo DB).

Serverless relational DBs are awesome and have taken away some of the luster behind NoSQL (Serverless helped to solve scalability issues / storing complex data).

Body:
A very simple query like select * from vw_Json_Data where Ts < date_sub( now(), interval 1 day ) order by Ts desc limit 1 took > 5 minutes to resolve!

Monitoring the query using mysqladmin processlist showed that it was spending all that time 'Creating sort index'. How to reduce the query time something sensible (< 1 sec)?

The view vw_Json_Data is created as follows:

create table My_Json_Data (
  Id int auto_increment primary key,
  Tag_Id int, -- foreign key to the Tag table
  Ts datetime,
  Json_Data json
);

create table Tag (
  Tag_Id int auto_increment primary key,
  Val int
);

create or replace view vw_Json_Data as select * from Tag inner join My_Json_Data using( Tag_Id );

Currently, the Tag table contains about 2 million rows and the My_Json_Data contains 500,000 rows. Therefore, this should not be a problem for MySQL at all, albeit the Json_Data in My_Json_Data are quite complex and long JSON strings.


问:
Invalid postback or callback argument, for dropdownlist
I get the following error when accessing my dropdownlist.

Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Here is the dropdownlist code:

```<code>                         <div class="col s4">
                            <asp:DropDownList ID="organizationDropDownList" runat="server" AutoPostBack="true"
                                              SelectMethod="GetOrganizations" DataTextField="Name" DataValueField="Id"  AppendDataBoundItems="True"  SelectedValue='<%# Bind("OrganizationId") %>'>
                                <asp:ListItem Value="-1">Select Student's School</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="organizationRequiredFieldValidator" runat="server"
                             ControlToValidate="organizationDropDownList" InitialValue="-1" ErrorMessage="<%$ Resources:Global, StudentSchoolRequired %>"
                            ToolTip="<%$ Resources:Global, StudentSchoolRequired %>" ValidationGroup="validationGroup">*</asp:RequiredFieldValidator>
                        </div>
</code>```

答:
It looks like you’re adding the listitems to the dropdownlist somewhere in your codebehind. Or even from javascript?

Anyhow, if such a value is selected, the framework doesn’t allow this, because it thinks it detects ‘tampering’ with the possible values of the list.

If you want to add values to the list, you should also register them using the scriptmanager via the method ‘RegisterForEventValidation’. (So this needs to be done for every possible value).

But maybe an easier solution would be populating the dropdownlist with an ObjectDataSource (for example).
The framework takes care of registering the values for event validation..

Body:
I get the following error when accessing my dropdownlist.

Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Here is the dropdownlist code:

                            <asp:DropDownList ID="organizationDropDownList" runat="server" AutoPostBack="true"
                                              SelectMethod="GetOrganizations" DataTextField="Name" DataValueField="Id"  AppendDataBoundItems="True"  SelectedValue='<%# Bind("OrganizationId") %>'>
                                <asp:ListItem Value="-1">Select Student's School</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="organizationRequiredFieldValidator" runat="server"
                             ControlToValidate="organizationDropDownList" InitialValue="-1" ErrorMessage="<%$ Resources:Global, StudentSchoolRequired %>"
                            ToolTip="<%$ Resources:Global, StudentSchoolRequired %>" ValidationGroup="validationGroup">*</asp:RequiredFieldValidator>


问:
How do I save the page state with JavaScript execution results and restore it later?
I'm developing a chrome extension for YouTube. The extension writes alternative subtitles with different behavior. The subtitle file is taken from YouTube by the link.

In order for me to be able to show subtitles by the time the video starts playing, I have to download the subtitle files before the video loads.
At low Internet speed, JSON files of subtitles are loaded simultaneously with the YouTube page for a very long time.

I use this approach. To prevent my extension from competing with YouTube scripts, my extension:

calls window.stop() at the very beginning of page loading.

After stopping the download, I download the files I need.

Then the extension reloads the page.

But I would not want to reload the page if there are entries in window.history.
Of course, I would just like to block the page rendering thread for example by window.renderPause() and then resume by window.renderResume(). I would not use window.stop(). But JavaScript does not provide such an opportunity.
How do I save the page state with JavaScript execution results and restore it later?
This code doesn't work for youtube. JavaScript of YouTube does not start.

```<code>let clonedHtml = document.documentElement.cloneNode(true);
let clonedWindow = Object.assign({}, window);
document.documentElement.innerHTML = "";
window = clonedWindow;
document.replaceChild(clonedHtml, document.documentElement);
</code>```

I can not use window.history.back() or window.history.forward() because window.stop() does not allow to load a page.

答:
Do you want to prevent the video from starting before your subtitle files are loaded? Restoring the page state itself will be very complex, there is no generic solution which works for all websites.

To load your subtitles before youtube scripts load:

Use [chrome.webRequest.onBeforeRequest][1] and replace youtube's subtitle URL with your own subtitle URL (or replace the file content afterRequest)

Checkout this answer which hooks the page load event where you can fetch and inject your subtitles before anything else loads.

Both methods won't require an additional page reload.
[1]: https://developer.chrome.com/docs/extensions/reference/webRequest/

Body:
I'm developing a chrome extension for YouTube. The extension writes alternative subtitles with different behavior. The subtitle file is taken from YouTube by the link.

In order for me to be able to show subtitles by the time the video starts playing, I have to download the subtitle files before the video loads.
At low Internet speed, JSON files of subtitles are loaded simultaneously with the YouTube page for a very long time.

I use this approach. To prevent my extension from competing with YouTube scripts, my extension:

calls window.stop() at the very beginning of page loading.

After stopping the download, I download the files I need.

Then the extension reloads the page.

But I would not want to reload the page if there are entries in window.history.
Of course, I would just like to block the page rendering thread for example by window.renderPause() and then resume by window.renderResume(). I would not use window.stop(). But JavaScript does not provide such an opportunity.
How do I save the page state with JavaScript execution results and restore it later?
This code doesn't work for youtube. JavaScript of YouTube does not start.

let clonedHtml = document.documentElement.cloneNode(true);
let clonedWindow = Object.assign({}, window);
document.documentElement.innerHTML = "";
window = clonedWindow;
document.replaceChild(clonedHtml, document.documentElement);

I can not use window.history.back() or window.history.forward() because window.stop() does not allow to load a page.


问:
Escaping metacharacters in a Raku regex (like Perl's quotemeta() or \Q...\E)?
How can I escape metacharacters in a Raku regex the way I would with Perl's quotemeta function (\Q..\E)?

That is, the Perl code

my $sentence = 'The quick brown fox jumped over the lazy dog';
my $substring = 'quick.*?fox';
$sentence =~ s{$substring}{big bad wolf};
print $sentence
```

treats each of ., *, and ? as metacharacters and thus prints The big bad wolf jumped over the lazy dog.  But if I change the second-to-last line to $sentence =~ s{\Q$substring\E}{big bad wolf};, then Perl treats .*? as literal characters and thus prints The quick brown fox jumped over the lazy dog.

How can I treat characters literally in a Raku regex?

答:
Your question's answer:

You can treat characters in a Raku regex literally by surrounding them with quotes (e.g., '.*?') or by using using regular variable interpolation (e.g., $substring inside the regex where $substring is a string contaning metacharacters).

Thus, to translate the Perl program with \Q...\E from your question into Raku, you could write:

my $sentence = 'The quick brown fox jumped over the lazy dog';
my $substring = 'quick.*?fox';
$sentence ~~ s/$substring/big bad wolf/;
print $sentence
```
<p>This would treat <code>.*?</code> as literal characters, not metacharacters.  If you wanted to avoid interpolation with literal text rather than a variable, you could change the substitution regex to <code>s/quick '.*?' fox/big bad wolf/</code>.  Conversely, if you want to use the <code>$substring</code> variable as part of a regex (that is, if you <strong>do</strong> want <code>.*?</code> to be metacharacters) you'd need to to change the substitution regex to <code>s/<$substring>/big bad wolf/</code>.  For more details, you can consult the Rexex interpolation docs.</p>
<h1>How you could have found this answer without waiting for SO</h1>
<p>What should you do when you don't know how to do something in Raku?  Asking either on the IRC channel or here on Stack Overflow is an option – and asking a clear Q on SO has the benefit of making the answer more searchable for anyone else who has the same question in the future.</p>
<p>But both IRC and SO are asynchronous – so you'll probably need to wait a bit for an answer. There are other ways that folks interested in Raku frequently get good/great answers to their questions more <em>easily</em> and <em>quickly</em> than they could from IRC/SO, and the remainder of this answer provides some guidance about these ways. (I've numbered the steps in the general order I'd recommend, but there's no reason you <em>need</em> to follow that order).</p>
<h2>Easily get better answers more quickly than asking SO Qs</h2>
<h3>Step -1: Let Raku answer the question for you</h3>
<p>Raku strives to have awesome error messages, and sometimes you'll be lucky enough to try something in a way that doesn't work but where Raku can tell what you were <em>trying</em> to do.</p>
<p>In those cases, Raku will just tell you how to do what you wanted to do.  And, in fact, <code>\Q...\E</code> is one such case.  If you'd tried to do it the Perl way</p>
<pre class="lang-raku prettyprint-override"><code>/\Q$substring\E/
</code>```

you'd have gotten the same answer I gave above (use $substring or quotes) in the form of the following error message:

```<code>Unsupported use of \Q as quotemeta.  In Raku please use: quotes or
literal variable match.
</code>```

So, sometimes, Raku will solve the problem for you!  But that's not something that will happen all the time and, any time you're tempted to ask a SO question, it's a good bet that Raku didn't answer your question for you.  So here are the steps you'd take in that case:

Step 0: check the docs

The first true step should, of course, be to search the Raku docs for anything useful.  I bet you did this – the docs currently don't return any relevant results for \Q..\E. In fact, the only true positive match of \Q...\E in those results is from the Perl to Raku guide - in a nutshell: "using String::ShellQuote (because \Q…\E is not completely right) ...". And that's obviously not what you're interested in.

The docs website doesn't always yield a good answer to simple questions. Sometimes, as we clearly see with the \Q...\E case, it doesn't yield any answer at all for the relevant search term.

Step 1: Search Stack Overflow

Again, you probably did this, but it's good to keep in mind: You can limit your SO search questions/answers tagged as related to Raku by adding [raku] to your query.  Here, a query of [raku] "\Q...\E" wouldn't have yielded anything relevant – but, thanks to your question, it will in the future :)

Step 2: Archived/historical "spec" docs

Raku's design was written up in a series of "spec" docs written principally by Larry Wall over a 2 decade period.

(The word "specs" is short for "specification speculations". It's both ultra authoritative detailed and precise specifications of the Raku language, authored primarily by Larry Wall himself, and mere speculations -- because it was all subject to implementation. And the two aspects are left entangled, and now out-of-date. So don't rely on them 100% -- but don't ignore them either.)

The "specs", aka design docs, are a fantastic resource. You can search them using google by entering your search terms in the search box at design.raku.org.

A search for \Q...\E lists 7 pages. The only useful match is Synopsis 5: Regexes and Rules ("24 Jun 2002 — \Q$var\E / ...").  If I click it and then do an in-page search for \Q, I get 2 matches that, together, answer your question (at least with respect to variables – they don't mention literal strings):

In Raku / $var / is like a Perl / \Q$var\E /

\Q...\E sequences are gone.

Step 3: IRC chat logs

In this case, searching the design docs answered your question.  But what if it hadn't/we didn't understand the answer?

In that case, searching the IRC logs can be a great option (as previously discussed in the Quicker answers section of an answer to a past Q. The IRC logs are an incredibly rich mine of info with outstanding search features. Please read that section for clear general guidance.

In this particular case, if we'd searched for \Q in the old Raku channel, we would have gotten a bunch of useful matches.  None of the first few fully answer your question, but several do (or at least make the answer clear) if read in context – but it's the need to read the surrounding context that makes me put searching the IRC logs below the previous steps.

Body:
How can I escape metacharacters in a Raku regex the way I would with Perl's quotemeta function (\Q..\E)?

That is, the Perl code

my $sentence = 'The quick brown fox jumped over the lazy dog';
my $substring = 'quick.*?fox';
$sentence =~ s{$substring}{big bad wolf};
print $sentence

treats each of ., *, and ? as metacharacters and thus prints The big bad wolf jumped over the lazy dog.  But if I change the second-to-last line to $sentence =~ s{\Q$substring\E}{big bad wolf};, then Perl treats .*? as literal characters and thus prints The quick brown fox jumped over the lazy dog.

How can I treat characters literally in a Raku regex?

Body:
Your question's answer:

You can treat characters in a Raku regex literally by surrounding them with quotes (e.g., '.*?') or by using using regular variable interpolation (e.g., $substring inside the regex where $substring is a string contaning metacharacters).

Thus, to translate the Perl program with \Q...\E from your question into Raku, you could write:

my $sentence = 'The quick brown fox jumped over the lazy dog';
my $substring = 'quick.*?fox';
$sentence ~~ s/$substring/big bad wolf/;
print $sentence

This would treat .*? as literal characters, not metacharacters.  If you wanted to avoid interpolation with literal text rather than a variable, you could change the substitution regex to s/quick '.*?' fox/big bad wolf/.  Conversely, if you want to use the $substring variable as part of a regex (that is, if you do want .*? to be metacharacters) you'd need to to change the substitution regex to s/<$substring>/big bad wolf/.  For more details, you can consult the Rexex interpolation docs.

How you could have found this answer without waiting for SO

What should you do when you don't know how to do something in Raku?  Asking either on the IRC channel or here on Stack Overflow is an option – and asking a clear Q on SO has the benefit of making the answer more searchable for anyone else who has the same question in the future.

But both IRC and SO are asynchronous – so you'll probably need to wait a bit for an answer. There are other ways that folks interested in Raku frequently get good/great answers to their questions more easily and quickly than they could from IRC/SO, and the remainder of this answer provides some guidance about these ways. (I've numbered the steps in the general order I'd recommend, but there's no reason you need to follow that order).

Easily get better answers more quickly than asking SO Qs

Step -1: Let Raku answer the question for you

Raku strives to have awesome error messages, and sometimes you'll be lucky enough to try something in a way that doesn't work but where Raku can tell what you were trying to do.

In those cases, Raku will just tell you how to do what you wanted to do.  And, in fact, \Q...\E is one such case.  If you'd tried to do it the Perl way

/\Q$substring\E/

you'd have gotten the same answer I gave above (use $substring or quotes) in the form of the following error message:

Unsupported use of \Q as quotemeta.  In Raku please use: quotes or
literal variable match.

So, sometimes, Raku will solve the problem for you!  But that's not something that will happen all the time and, any time you're tempted to ask a SO question, it's a good bet that Raku didn't answer your question for you.  So here are the steps you'd take in that case:

Step 0: check the docs

The first true step should, of course, be to search the Raku docs for anything useful.  I bet you did this – the docs currently don't return any relevant results for \Q..\E. In fact, the only true positive match of \Q...\E in those results is from the Perl to Raku guide - in a nutshell: "using String::ShellQuote (because \Q…\E is not completely right) ...". And that's obviously not what you're interested in.

The docs website doesn't always yield a good answer to simple questions. Sometimes, as we clearly see with the \Q...\E case, it doesn't yield any answer at all for the relevant search term.

Step 1: Search Stack Overflow

Again, you probably did this, but it's good to keep in mind: You can limit your SO search questions/answers tagged as related to Raku by adding [raku] to your query.  Here, a query of [raku] "\Q...\E" wouldn't have yielded anything relevant – but, thanks to your question, it will in the future :)

Step 2: Archived/historical "spec" docs

Raku's design was written up in a series of "spec" docs written principally by Larry Wall over a 2 decade period.

(The word "specs" is short for "specification speculations". It's both ultra authoritative detailed and precise specifications of the Raku language, authored primarily by Larry Wall himself, and mere speculations -- because it was all subject to implementation. And the two aspects are left entangled, and now out-of-date. So don't rely on them 100% -- but don't ignore them either.)

The "specs", aka design docs, are a fantastic resource. You can search them using google by entering your search terms in the search box at design.raku.org.

A search for \Q...\E lists 7 pages. The only useful match is Synopsis 5: Regexes and Rules ("24 Jun 2002 — \Q$var\E / ...").  If I click it and then do an in-page search for \Q, I get 2 matches that, together, answer your question (at least with respect to variables – they don't mention literal strings):

In Raku / $var / is like a Perl / \Q$var\E /

\Q...\E sequences are gone.

Step 3: IRC chat logs

In this case, searching the design docs answered your question.  But what if it hadn't/we didn't understand the answer?

In that case, searching the IRC logs can be a great option (as previously discussed in the Quicker answers section of an answer to a past Q. The IRC logs are an incredibly rich mine of info with outstanding search features. Please read that section for clear general guidance.

In this particular case, if we'd searched for \Q in the old Raku channel, we would have gotten a bunch of useful matches.  None of the first few fully answer your question, but several do (or at least make the answer clear) if read in context – but it's the need to read the surrounding context that makes me put searching the IRC logs below the previous steps.