问:
Not able to redirect back to alexa after successful login from my application
When I click "Enable" for my skill from https://alexa.amazon.com I am redirected to my application login page, after entering email/password and successful authentication I am redirecting user to

https://pitangui.amazon.com/api/skill/link/M2SH60C21FLV91?vendorId=M2SH60C21FLV91&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&token_type=Bearer

but it gives me JSON response

"{"httpRedirectLocation":"https://skills-store.amazon.com/api/skill/link/M2SH60C21FLV91?access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&token_type=Bearer"}"

and page stops, it does not enable and redirect back to alexa giving success message.

I have to manually copy-paste the url which I get in above json response, then only my account is linked.

Can anyone help why I am not directly redirect and getting the successfully linked page? Why I have to manually copy-paste the url?

Thanks in advance.

答:
you cannot pass accesstoken as a query param in the redirect url. Appending # before the accesstoken will work.

```<code>...IRSDA#access_token=WFA...
</code>```

Body:
When I click "Enable" for my skill from https://alexa.amazon.com I am redirected to my application login page, after entering email/password and successful authentication I am redirecting user to

<a href="https://pitangui.amazon.com/api/skill/link/M2SH60C21FLV91?vendorId=M2SH60C21FLV91&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&token_type=Bearer" rel="nofollow noreferrer">https://pitangui.amazon.com/api/skill/link/M2SH60C21FLV91?vendorId=M2SH60C21FLV91&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&token_type=Bearer

but it gives me JSON response

"{"httpRedirectLocation":"<a href="https://skills-store.amazon.com/api/skill/link/M2SH60C21FLV91?access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&token_type=Bearer" rel="nofollow noreferrer">https://skills-store.amazon.com/api/skill/link/M2SH60C21FLV91?access_token=WFA0UWlxcTFCZVZnTmJmUmdldUF3dVFwdG1VSGM0aWJSODB1OUVkNTdUST06a2F1c2hhbEBuaWNoZXRlY2guaW46NjM2NDY0MzM2OTAwNzU3NjYy&state=A2SAAEAEOlVnPYTaS9OqN_iQmxOIpEBkLSBUPLDHJGzHc_ALJ02fPLzMm9OYOMG9mpSuDVg3_O3fgpSE5iCfh3XCLBs0oTay3Eqr6CEXpU7eDf_11PeUJCk839z0cxc8djFlxbLUr_CINPUNtVoHfzpn3Ztwl4OE-2dcKmqLiza6C9cr7Ca8-8UmEdshagKsue4lYkyWFiFwx-Yg452QHIY0DpnG1rtbanQgW5MjgbTaR3-MPy7QBIodnF_SnbtXpWb69_R3HOlGHPoaJgIbi2yr1lc-fIJbJ8B8Zbzm0mMi2IocOg4fDrFlwQ6ZRUXzeWB6ZapbxfeO4UR3h8Cr3P9_efaRFFgD4NZPL3DkAdlSF2XlAmKIpg5xr3u25jt-vHZi50QWJYgZYLDCJFqrnDoGSVIwLGz1vKFnZCkAYm7ioJ_emq5JtkfBVQaxg2mH2_pcvadbE8DgufJCt0QkDMp94eyRbYKp2uKsdVZNuV_PwGdb1AFVQhzDqbiE0pyMfbjSpWjcTM8CAbdfSGsbxJ3ipcSV6LSjbokH1KP5vLAAVr5wQIRSDA&token_type=Bearer"}"

and page stops, it does not enable and redirect back to alexa giving success message.

I have to manually copy-paste the url which I get in above json response, then only my account is linked.

Can anyone help why I am not directly redirect and getting the successfully linked page? Why I have to manually copy-paste the url?

Thanks in advance.

Body:
you cannot pass accesstoken as a query param in the redirect url. Appending # before the accesstoken will work.

...IRSDA#access_token=WFA...


来源: stackexchange

问:
Using ajax in aspx page rather than reloading the whole page?
I am a very junior programmer in aspx, and I need help.

I have currently one aspx page. This page contains 3 tables.

The first table is the main table, which contains rows with data. When you click on one row, the other 2 table shows up with the details. Below is the picture.

This is working fine with the window.location code.

I want this project to upgrade with ajax. When you click on one row, show the data, but without reloading the page.

What would be the best practice, dissable to 3 aspx page? If anyone can provide a good example/practice article that would be great.

The onclick method for every row:

```<code> var table = document.getElementById("table1");
            var rows = table.getElementsByTagName("tr");
            var customerId = getParameterByName('customerid');
            var table1Index = '<%= (FindHeaderIndex("table1Columns", "Agreement_NUM")) %>';
            for (i = 0; i < rows.length - 1; i++) { //length - 1 to avoid footer row
                var currentRow = table.rows[i];
                var createClickHandler =
                    function (row) {
                        return function () {
                            var table1Number = row.getElementsByTagName("td")[table1Index].innerHTML;
                            window.location = "Project.aspx" + "?" + "customerid=" + customerId + "&" + "table1Number=" + table1Number;
                        };
                    };
                currentRow.onclick = createClickHandler(currentRow);
            }
</code>```

get parameters

```<code> function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }
</code>```

body

```<code><body>
    <div id="container">
        <asp:Panel runat="server" ID="mainPanel"></asp:Panel>
        <asp:Panel runat="server" ScrollBars="Auto" Height="40%" ID="detailsPanel"></asp:Panel>
        <asp:Label runat="server" ID="errorLabel" CssClass="errorMessage" />
    </div>
</body>
</code>```

答:
This is something I've used before.  Instead of simply reloading the page, you can "ajaxify" the process by making an Ajax call to load the new page state and then parse that, grab any updated Html and update the current view.

Add this function to your script...

```<code>function updateElementsById(newDataUrl) {
    if (arguments.length < 2) return;
    var $container = $("<div/>");
    $container.load(newDataUrl, function() {
        var idList = Array.prototype.slice.call(arguments, 1);
        idList.forEach(function(id) {
            $(id).html($div.find(id).html());
        });
    });
}
</code>```

Now, in order to update tables 2 and 3 (I'll assume the ids of table2 and table3) you'd call the function like this...

```<code>var url = "Project.aspx?customerid=" + customerId + "&table1Number=" + table1Number;

updateElementsById(url, "#table2", "#table3");
</code>```

That should be enough to get you working.  Let me know if you have any issues.

Incidentally, this is a nice-and-easy bit of a hack really.  If you want a real solution then you should look at returning data to Ajax calls, but that means making some sort of API to serve the data you need.  You could take the current code that gets the relevant data and put that in a class that does all your data access, and then use that class in the page and also have a controller or generic handler return the data for you.

There are lots of alternatives.  It depends on your needs and the use case.

ContentLicense: CC BY-SA 3.0

Body:
I am a very junior programmer in aspx, and I need help.

I have currently one aspx page. This page contains 3 tables.

The first table is the main table, which contains rows with data. When you click on one row, the other 2 table shows up with the details. Below is the picture.

This is working fine with the window.location code.

I want this project to upgrade with ajax. When you click on one row, show the data, but without reloading the page.

What would be the best practice, dissable to 3 aspx page? If anyone can provide a good example/practice article that would be great.

The onclick method for every row:

 var table = document.getElementById("table1");
            var rows = table.getElementsByTagName("tr");
            var customerId = getParameterByName('customerid');
            var table1Index = '<%= (FindHeaderIndex("table1Columns", "Agreement_NUM")) %>';
            for (i = 0; i < rows.length - 1; i++) { //length - 1 to avoid footer row
                var currentRow = table.rows[i];
                var createClickHandler =
                    function (row) {
                        return function () {
                            var table1Number = row.getElementsByTagName("td")[table1Index].innerHTML;
                            window.location = "Project.aspx" + "?" + "customerid=" + customerId + "&" + "table1Number=" + table1Number;
                        };
                    };
                currentRow.onclick = createClickHandler(currentRow);
            }

get parameters

 function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }

body

        <asp:Panel runat="server" ID="mainPanel"></asp:Panel>
        <asp:Panel runat="server" ScrollBars="Auto" Height="40%" ID="detailsPanel"></asp:Panel>
        <asp:Label runat="server" ID="errorLabel" CssClass="errorMessage" />

Body:
This is something I've used before.  Instead of simply reloading the page, you can "ajaxify" the process by making an Ajax call to load the new page state and then parse that, grab any updated Html and update the current view.

Add this function to your script...

function updateElementsById(newDataUrl) {
    if (arguments.length < 2) return;
    var $container = $("<div/>");
    $container.load(newDataUrl, function() {
        var idList = Array.prototype.slice.call(arguments, 1);
        idList.forEach(function(id) {
            $(id).html($div.find(id).html());
        });
    });
}

Now, in order to update tables 2 and 3 (I'll assume the ids of table2 and table3) you'd call the function like this...

var url = "Project.aspx?customerid=" + customerId + "&table1Number=" + table1Number;

updateElementsById(url, "#table2", "#table3");

That should be enough to get you working.  Let me know if you have any issues.

Incidentally, this is a nice-and-easy bit of a hack really.  If you want a real solution then you should look at returning data to Ajax calls, but that means making some sort of API to serve the data you need.  You could take the current code that gets the relevant data and put that in a class that does all your data access, and then use that class in the page and also have a controller or generic handler return the data for you.

There are lots of alternatives.  It depends on your needs and the use case.


问:
Close FaceBox from code behind
I am having trouble closing jQuery Facebox from code behind. I am inserting a new record through FaceBox, on successful insertion the FaceBox needs to be closed. How can i achieve this?</p>

答:
Solved:

Aspx page:

      //Add data fields and button from an user control

Aspx.cs page:

Page page = HttpContext.Current.Handler as Page;
        if (page != null)
        {
           ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg",       "close_facebox()", true);
        }

Js function:

function close_facebox() {
            $('#addlink').css('display', 'none');
            $('#addlink').overlay().close();
  }

ContentLicense: CC BY-SA 2.5

Title: Close FaceBox from code behind


问:
How to keep same style of `portrait` to `landscape` for iPad
Some reasons, I require to keep the same style as portrait to landscape too. How to achieve that using css3 media query?

Because there is some of functionality disabled for touch pads.

I tried but it still shows the desktop view

```<code>@media screen and (max-device-width:1024px){}
</code>```

答:
You might like to check this too. Below are the ios related ones.

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/**********
iPad 3
**********/

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}```

Body:
Some reasons, I require to keep the same style as portrait to landscape too. How to achieve that using css3 media query?

Because there is some of functionality disabled for touch pads.

I tried but it still shows the desktop view

@media screen and (max-device-width:1024px){}


问:
how can I able to see what messages are currently processing in rabbitmq
I am new to celery and rabbitmq and I am trying to find out when I send a message from celery to rabbitmq why it is not showing up in the rabbitmq queue but the messages gets processed?

Here is a list of queue that have been created

答: The default message delivery mode is nack =true. That means when a producer sends a message to rabbitMQ server, it will buffer it in the message queue. But if there is any active consumer, then the message will be removed from the queue as soon as the message is sent. The other mode of delivery is manual acknowledging of the message. for that you should use nack=false. So the message is removed from the queue only when the consumer acknowledge the message.


问:
Change body of ServerWebExchange response in WebFilter
I am trying to make an application in spring webflux. But there is a lot of stuff that I can't find in the documentation.

I have a webfilter where I want to add a wrapper around the response. Example:

Reponse before:

```<code>{
    "id": 1,
    "name": "asdf"
}
</code>```

Response after:

```<code>{
    "status": "success",
    "data": {
        "id": 1,
        "name": "asdf"
    }
}
</code>```

This is the WebFilter at the moment:

```<code>@Component
public class ResponseWrapperFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        // Add wrapper to the response content...

        return webFilterChain.filter(serverWebExchange);
    }
}
</code>```

But I can't find a way to get or edit the body of the response.

How can I change the response output in a WebFilter?

答:
As stated in the javadoc, WebFilter is made for application-agnostic, cross-cutting concerns. WebFilters usually mutate the request headers, add attributes to the exchange or handle the response altogether without delegating to the rest of the chain.

I don't think that what you're trying to achieve is easily doable or even something that should be achieved this way. At the raw exchange level, you're dealing with a Flux<DataBuffer>, which is the response body split randomly in groups of bytes.

You could somehow wrap the response in a filter and use Flux.concat to prepend and append data to the actual response written by the handler. But there are a lot of questions regarding encoding, infinite streams, etc.

Maybe this is a concern that should be achieved at the Encoder level, since there you could restrict that behavior to a particular media type.

Body:
I am trying to make an application in spring webflux. But there is a lot of stuff that I can't find in the documentation.

I have a webfilter where I want to add a wrapper around the response. Example:

Reponse before:

{
    "id": 1,
    "name": "asdf"
}

Response after:

{
    "status": "success",
    "data": {
        "id": 1,
        "name": "asdf"
    }
}

This is the WebFilter at the moment:

@Component
public class ResponseWrapperFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        // Add wrapper to the response content...

        return webFilterChain.filter(serverWebExchange);
    }
}

But I can't find a way to get or edit the body of the response.

How can I change the response output in a WebFilter?


问:
jQuery attr() method to change a class name
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}</code>```

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

```

答:
Syntax error

```<code>function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);

    $('h1').attr('class', fontChange);
  });
}
myFontStyle();
</code>```

https://jsfiddle.net/zu2ku6w8/

Body:
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();

.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

Body:
Syntax error

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);

    $('h1').attr('class', fontChange);
  });
}
myFontStyle();

https://jsfiddle.net/zu2ku6w8/


问:
What's the best way to send scheduled e-mails from a Java-based web app?
I'm implementing a little web application using Java and the Wicket framework. Each user of the application has a list of events, each of which has a "due time."

I would like to send an e-mail to the user when any of his/her events is due. How should I implement this notification feature?

I can write a separate service to check the database every minute and send the e-mails; I just want to see if there is an easier and better way to do it.

答:
I think a seperate prozess that periodically checks for emails to be send is the best option here. You could use the Quartz sheduler or write a job that gets started by the OS periodicaly.

Another, rather hacky option would be to extend the wicket request cycle processor and do email check there. But this would rely on the fact that you actually get requests often enough to not miss an check intervall. I would only choose this if you can not create jobs on the OS level for some reason.


问:
mysql database from linux command line with dot in database name
I have mysql database which has dot in database name

database name = "abc.domain.com"

my query for linux command line is

```<code>mysql -u"root" -p"123" -h 0 -e"USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = `abc.domain.com` AND table_name=`bugs`;" | column -t > /tmp/describe
</code>```

in above command I am writing database name in between backticks ``  it understand as linux command.

In mysql it is working fine.

how to solve this problem?

答:
Try this:

```<code>/bin/sh -c mysql -u"root" -p"123" -h 0 -e"USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = \\\`abc.domain.com\\\` AND table_name=\\\`bugs\\\`;" | column -t > /tmp/describe
</code>```

Or

```<code>    $ export F='USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = `abc.domain.com` AND table_name=`bugs`;'
    $ printenv F
    USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = `abc.domain.com` AND table_name=`bugs`;
   /bin/sh -c mysql -u"root" -p"123" -h 0 -e $F | column -t > /tmp/describe
</code>```

EDIT1:

Access denied for user 'root'@'localhost' (using password: NO)

It's not advisable to use root without password How to Reset the Root Password

Body:
I have mysql database which has dot in database name

database name = "abc.domain.com"

my query for linux command line is

mysql -u"root" -p"123" -h 0 -e"USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = `abc.domain.com` AND table_name=`bugs`;" | column -t > /tmp/describe

in above command I am writing database name in between backticks ``  it understand as linux command.

In mysql it is working fine.

how to solve this problem?

Body:
Try this:

/bin/sh -c mysql -u"root" -p"123" -h 0 -e"USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = \\\`abc.domain.com\\\` AND table_name=\\\`bugs\\\`;" | column -t > /tmp/describe

Or

    $ export F='USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = `abc.domain.com` AND table_name=`bugs`;'
    $ printenv F
    USE information_schema;select column_name, column_type from information_schema.columns where TABLE_SCHEMA = `abc.domain.com` AND table_name=`bugs`;
   /bin/sh -c mysql -u"root" -p"123" -h 0 -e $F | column -t > /tmp/describe

EDIT1:

Access denied for user 'root'@'localhost' (using password: NO)

It's not advisable to use root without password How to Reset the Root Password


问:
How to read blob (pickle) files from GCS in a Google Cloud DataFlow job?
I try to run a DataFlow pipeline remotely which will use a pickle file.
Locally, I can use the code below to invoke the file.

```<code>with open (known_args.file_path, 'rb') as fp:
     file = pickle.load(fp)
</code>```

However, I find it not valid when the path is about cloud storage(gs://...):

```<code>IOError: [Errno 2] No such file or directory: 'gs://.../.pkl'
</code>```

I kind of understand why it is not working but I cannot find the right way to do it.

答:
If you have pickle files in your GCS bucket, then you can load them as BLOBs and process them further like in your code (using pickle.load()):

```<code>class ReadGcsBlobs(beam.DoFn):
    def process(self, element, *args, **kwargs):
        from apache_beam.io.gcp import gcsio
        gcs = gcsio.GcsIO()
        yield (element, gcs.open(element).read())

# usage example:
files = (p
         | "Initialize" >> beam.Create(["gs://your-bucket-name/pickle_file_path.pickle"])
         | "Read blobs" >> beam.ParDo(ReadGcsBlobs())
        )
</code>```

Body:
I try to run a DataFlow pipeline remotely which will use a pickle file.
Locally, I can use the code below to invoke the file.

with open (known_args.file_path, 'rb') as fp:
     file = pickle.load(fp)

However, I find it not valid when the path is about cloud storage(gs://...):

IOError: [Errno 2] No such file or directory: 'gs://.../.pkl'

I kind of understand why it is not working but I cannot find the right way to do it.

Body:
If you have pickle files in your GCS bucket, then you can load them as BLOBs and process them further like in your code (using pickle.load()):

class ReadGcsBlobs(beam.DoFn):
    def process(self, element, *args, **kwargs):
        from apache_beam.io.gcp import gcsio
        gcs = gcsio.GcsIO()
        yield (element, gcs.open(element).read())

# usage example:
files = (p
         | "Initialize" >> beam.Create(["gs://your-bucket-name/pickle_file_path.pickle"])
         | "Read blobs" >> beam.ParDo(ReadGcsBlobs())
        )

ContentLicense: CC BY-SA 4.0


问:
Bootstrap tab activation with JQuery
I have the following code:

```<code><ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>
</code>```

And the following script:

```<code>$(document).ready(function(){
    activaTab('aaa');
});

function activaTab(tab){
    $('.tab-pane a[href="#' + tab + '"]').tab('show');
};
</code>```

In this case when the page is ready, the second tab will be activated but I always get a JavaScript error in the line $('.tab-pane a[href="#' + tab + '"]').tab();

Can anyone help me, please?

答:
why not select active tab first then active the selected tab content ?

       1. Add class 'active' to the
 element of tab first .

       2. then use set 'active' class to selected div.

```<code>    $(document).ready( function(){
        SelectTab(1); //or use other method  to set active class to tab
        ShowInitialTabContent();

    });
    function SelectTab(tabindex)
    {
        $('.nav-tabs li ').removeClass('active');
        $('.nav-tabs li').eq(tabindex).addClass('active');
        //tabindex start at 0
    }
    function FindActiveDiv()
    {
        var DivName = $('.nav-tabs .active a').attr('href');
        return DivName;
    }
    function RemoveFocusNonActive()
    {
        $('.nav-tabs  a').not('.active').blur();
        //to >  remove  :hover :focus;
    }
    function ShowInitialTabContent()
    {
        RemoveFocusNonActive();
        var DivName = FindActiveDiv();
        if (DivName)
        {
            $(DivName).addClass('active');
        }
    }
</code>```

Title: Bootstrap tab activation with JQuery

Body:
I have the following code:

AAA

BBB

CCC

...Content...

...Content...

...Content...

And the following script:

$(document).ready(function(){
    activaTab('aaa');
});

function activaTab(tab){
    $('.tab-pane a[href="#' + tab + '"]').tab('show');
};

In this case when the page is ready, the second tab will be activated but I always get a JavaScript error in the line $('.tab-pane a[href="#' + tab + '"]').tab();

Can anyone help me, please?

Body:
why not select active tab first then active the selected tab content ?

       1. Add class 'active' to the < li > element of tab first .

       2. then use set 'active' class to selected div.

    $(document).ready( function(){
        SelectTab(1); //or use other method  to set active class to tab
        ShowInitialTabContent();

    });
    function SelectTab(tabindex)
    {
        $('.nav-tabs li ').removeClass('active');
        $('.nav-tabs li').eq(tabindex).addClass('active');
        //tabindex start at 0
    }
    function FindActiveDiv()
    {
        var DivName = $('.nav-tabs .active a').attr('href');
        return DivName;
    }
    function RemoveFocusNonActive()
    {
        $('.nav-tabs  a').not('.active').blur();
        //to >  remove  :hover :focus;
    }
    function ShowInitialTabContent()
    {
        RemoveFocusNonActive();
        var DivName = FindActiveDiv();
        if (DivName)
        {
            $(DivName).addClass('active');
        }
    }


问:
How to get data from text table string in C# more reliably and quickly
I'm copying some data from SAP GUI screen to clipboard. It looks like below when I paste it on Notepad or any text editor.

I want only 3 fields[Created by, PO date, Document] from the clipboard text table string.

Currently I'm managing to read data as below.

```<code>public class DocData
{
    public string CreatedBy { get; set; }
    public string PODate { get; set; }
    public string Document { get; set; }
}

private void GetDocumentData()
{
  var clipboardData = Clipboard.GetText(TextDataFormat.Text);
  List<DocData> docDataList = new List<DocData>();
  for (int separatorCounter = 20; separatorCounter < clipboardData.Count(); separatorCounter = separatorCounter + 13)
  {
   DocData docData = new DocData();
   int index = GetNthIndex(clipboardData, '|', separatorCounter);
   if (index != -1)
   {
    var dataString = clipboardData.Substring(index + 1);
    var sepIndex = dataString.IndexOf('|');
    if (sepIndex != -1)
    {
     docData.CreatedBy = dataString.Substring(0, sepIndex).Trim();
    }
   }
   index = GetNthIndex(clipboardData, '|', separatorCounter + 2);
   if (index != -1)
   {
    var dataString = clipboardData.Substring(index + 1);
    var sepIndex = dataString.IndexOf('|');
    if (sepIndex != -1)
    {
     docData.PODate = dataString.Substring(0, sepIndex).Trim();
    }
   }
   index = GetNthIndex(clipboardData, '|', separatorCounter + 4);
   if (index != -1)
   {
    var dataString = clipboardData.Substring(index + 1);
    var sepIndex = dataString.IndexOf('|');
    if (sepIndex != -1)
    {
     docData.Document = dataString.Substring(0, sepIndex).Trim();
    }
   }
   if (!string.IsNullOrEmpty(docData.Document))
   {
    docDataList.Add(docData);
   }
  }
 }
</code>```

Can anyone suggest better way to do this without manipulating string too much.

答:
Here is one approach to your problem. This example first splits your text by lines, then uses header to find locations of data you need, and then iterates through lines and gets data.

Haven't tested it (I could if you pasted text instead of that screenshot :)), but it should work. Take a look at comments in code for explanation.

If you have additional questions, feel free to ask.

EDIT: Added missing method

```<code>//result list
List<DocData> docDataList = new List<DocData>();

//get clipboard data
string clipboardData = Clipboard.GetText(TextDataFormat.Text);

//split it to array of lines using Environment.NewLine (\r\n);
string[] reportLines = clipboardData.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

if (reportLines.Length < 4) //just an example of checking if there's enough lines
    throw new Exception("wrong number of lines");

//get correct indexes by reading header (positioned on third line, index 2) - in case order changes
int createdIndex = GetColumnIndex(reportLines[2], "Created by");
int PODateIndex = GetColumnIndex(reportLines[2], "PO Date");
int documentIndex = GetColumnIndex(reportLines[2], "Document");

//when you have indexes, loop through remaining lines, starting at fifth (index 4) and get data from that "columns"
for (int i = 4; i<reportLines.Length; i++)
{
    //now split current line by pipes
    string[] lineData = reportLines[i].Split('|');
    //create instance of your class and add data from specific indexes
    DocData docData = new DocData()
    {
        CreatedBy = lineData[createdIndex].Trim(), //also, trim ending spaces,
        PODate = lineData[PODateIndex].Trim(),
        Document = lineData[documentIndex].Trim()
    };
    docDataList.Add(docData);
}

public int GetColumnIndex(string headerLine, string columnName)
{
    List<string> headerNames = headerLine.Split('|').ToList(); //split header columns using pipe |.

    //get index of column by trimming and searching throught header column names
    return headerNames.IndexOf(headerNames.FirstOrDefault(h => h.Trim().Equals(columnName, StringComparison.InvariantCultureIgnoreCase)));

}
</code>```

Body:
I'm copying some data from SAP GUI screen to clipboard. It looks like below when I paste it on Notepad or any text editor.

I want only 3 fields[Created by, PO date, Document] from the clipboard text table string.

Currently I'm managing to read data as below.

public class DocData
{
    public string CreatedBy { get; set; }
    public string PODate { get; set; }
    public string Document { get; set; }
}

private void GetDocumentData()
{
  var clipboardData = Clipboard.GetText(TextDataFormat.Text);
  List<DocData> docDataList = new List<DocData>();
  for (int separatorCounter = 20; separatorCounter < clipboardData.Count(); separatorCounter = separatorCounter + 13)
  {
   DocData docData = new DocData();
   int index = GetNthIndex(clipboardData, '|', separatorCounter);
   if (index != -1)
   {
    var dataString = clipboardData.Substring(index + 1);
    var sepIndex = dataString.IndexOf('|');
    if (sepIndex != -1)
    {
     docData.CreatedBy = dataString.Substring(0, sepIndex).Trim();
    }
   }
   index = GetNthIndex(clipboardData, '|', separatorCounter + 2);
   if (index != -1)
   {
    var dataString = clipboardData.Substring(index + 1);
    var sepIndex = dataString.IndexOf('|');
    if (sepIndex != -1)
    {
     docData.PODate = dataString.Substring(0, sepIndex).Trim();
    }
   }
   index = GetNthIndex(clipboardData, '|', separatorCounter + 4);
   if (index != -1)
   {
    var dataString = clipboardData.Substring(index + 1);
    var sepIndex = dataString.IndexOf('|');
    if (sepIndex != -1)
    {
     docData.Document = dataString.Substring(0, sepIndex).Trim();
    }
   }
   if (!string.IsNullOrEmpty(docData.Document))
   {
    docDataList.Add(docData);
   }
  }
 }

Can anyone suggest better way to do this without manipulating string too much.

Body:
Here is one approach to your problem. This example first splits your text by lines, then uses header to find locations of data you need, and then iterates through lines and gets data.

Haven't tested it (I could if you pasted text instead of that screenshot :)), but it should work. Take a look at comments in code for explanation.

If you have additional questions, feel free to ask.

EDIT: Added missing method

//result list
List<DocData> docDataList = new List<DocData>();

//get clipboard data
string clipboardData = Clipboard.GetText(TextDataFormat.Text);

//split it to array of lines using Environment.NewLine (\r\n);
string[] reportLines = clipboardData.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

if (reportLines.Length < 4) //just an example of checking if there's enough lines
    throw new Exception("wrong number of lines");

//get correct indexes by reading header (positioned on third line, index 2) - in case order changes
int createdIndex = GetColumnIndex(reportLines[2], "Created by");
int PODateIndex = GetColumnIndex(reportLines[2], "PO Date");
int documentIndex = GetColumnIndex(reportLines[2], "Document");

//when you have indexes, loop through remaining lines, starting at fifth (index 4) and get data from that "columns"
for (int i = 4; i<reportLines.Length; i++)
{
    //now split current line by pipes
    string[] lineData = reportLines[i].Split('|');
    //create instance of your class and add data from specific indexes
    DocData docData = new DocData()
    {
        CreatedBy = lineData[createdIndex].Trim(), //also, trim ending spaces,
        PODate = lineData[PODateIndex].Trim(),
        Document = lineData[documentIndex].Trim()
    };
    docDataList.Add(docData);
}

public int GetColumnIndex(string headerLine, string columnName)
{
    List<string> headerNames = headerLine.Split('|').ToList(); //split header columns using pipe |.

    //get index of column by trimming and searching throught header column names
    return headerNames.IndexOf(headerNames.FirstOrDefault(h => h.Trim().Equals(columnName, StringComparison.InvariantCultureIgnoreCase)));

}


问:
Trying to access unlisted children of root node with phpSmug
I've modified the example-oauth.php file that comes with phpSmug to list the immediate children of the root node, but only public folders (those with at least one public album) and public albums are listed. I know my authorization (Access=Full) is correct, because when I try to list all user albums, I do get them all (code not shown). When I use the live example on the SmugMug site, I do get all immediate children of the root node. So, it seems the problem is within phpSmug, not with the SmugMug API itself. Also, I am replacing a Chrome App that also works as it should. (The Chrome App does not use phpSmug, of course.)

Any idea what's wrong and how I can fix it?

Here's my modified example. Lines that I added or changed are marked with the initials MJR. Note again that I didn't write most of this program, but only added and changed a few lines.

```<code>/* Last updated with phpSmug 4.0
 *
 * This example file shows you how to authenticate using OAuth and then display
 * the first 25 images in the first public gallery found of the authenticated
 * user's account.
 *
 * You'll want to set the following variables below:
 *
 * - $APIKey with one provided by SmugMug: http://www.smugmug.com/hack/apikeys
 * - $OAuthSecret with one provided when you obtained your API key
 * - $AppName with your application name, version and URL, eg
 *
 * The $AppName is NOT required, but it's encouraged as it will allow SmugMug to
 * diagnose any issues users may have with your application if they request help
 * on the SmugMug forums. A good format to use is "APP NAME/VER (URL)".
 *
 */

$APIKey = 'YOUR_API_KEY';  // MJR -- my own data was entered
$OAuthSecret = 'YOUR_OAUTH_SECRET';  // MJR -- my own data was entered
$AppName = 'YOUR_APP_NAME/VER (URL)';
?>
<html>
<head>
    <title>phpSmug OAuth Login Example</title>
    <style type="text/css">
        body { background-color: #fff; color: #444; font-family: sans-serif }
        div { width: 750px; margin: 0 auto; text-align: center; }
        img { border: 0;}
    </style>
</head>
<body>
    <div>
        <a href="http://phpsmug.com"><img src="phpSmug-logo.svg" /></a>
        <h1>OAuth Login Example</h1>
<?php

try {
    $options = [
        'AppName' => $AppName,
        '_verbosity' => 1, # Reduce verbosity to reduce the amount of data in the response and to make using it easier.
        'OAuthSecret' => $OAuthSecret, # You need to pass your OAuthSecret in order to authenticate with OAuth.
        'verify' => false // MJR: Added because SSL certificates are not set up
    ];

    $client = new phpSmug\Client($APIKey, $options);

    // Perform the 3 step OAuth Authorisation process.
    // NOTE: This is a very simplified example that does NOT store the final token.
    // You will need to ensure your application does.
    if (!isset($_SESSION['SmugGalReqToken'])) {

        // Step 1: Get a request token using an optional callback URL back to ourselves
        $callback = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
        $request_token = $client->getRequestToken($callback);
        $_SESSION['SmugGalReqToken'] = serialize($request_token);

        // Step 2: Get the User to login to SmugMug and authorise this demo
        echo '<p>Click <a href="'.$client->getAuthorizeURL(['Access' => 'Full']).'"><strong>HERE</strong></a> to Authorize This Demo.</p>'; // MJR
        // Alternatively, automatically direct your visitor by commenting out the above line in favour of this:
        //header("Location:".$client->getAuthorizeURL());
    } else {
        $reqToken = unserialize($_SESSION['SmugGalReqToken']);
        unset($_SESSION['SmugGalReqToken']);

        // Step 3: Use the Request token obtained in step 1 to get an access token
        $client->setToken($reqToken['oauth_token'], $reqToken['oauth_token_secret']);
        $oauth_verifier = $_GET['oauth_verifier'];  // This comes back with the callback request.
        $token = $client->getAccessToken($oauth_verifier);  // The results of this call is what your application needs to store.
        // Get the username of the authenticated user
        $username = $client->get('!authuser')->User->NickName;

        // List top level folders and albums.  // MJR
        $user = $client->get('!authuser'); // MJR
        $root = $client->get($user->User->Uris->Node); // MJR
        $children = $client->get($root->Node->Uris->ChildNodes); // MJR
        foreach ($children->Node as $v) { // MJR
            echo "<br> $v->Type \"$v->Name\" $v->Uri"; // MJR
        } // MJR

    }
} catch (Exception $e) {
    echo "{$e->getMessage()} (Error Code: {$e->getCode()})";
}
?>
    </div>
</body>
</html>
</code>```

答:
Your changes should work, and do for me. One thing I did have to do was bump the count of nodes returned as ChildNodes returns only the first 10 nodes by default and my first private album is right at the very end.

Is your first private album/folder outside the first 10? If so, try changing your changes to:

```<code>// List top level folders and albums.  // MJR
$user = $client->get('!authuser'); // MJR
$root = $client->get($user->User->Uris->Node); // MJR
$children = $client->get($root->Node->Uris->ChildNodes, ['count' => 50]); // MJR
foreach ($children->Node as $v) { // MJR
    echo "<br> $v->Type \"$v->Name\" $v->Uri"; // MJR
} // MJR
</code>```

You'll see I've added ['count' => 50] to the options. You may need to increase this if you've got more than 50 albums/folders.

Alternatively, you can iterate through the pages using the info in $children->Pages.

Body:
I've modified the example-oauth.php file that comes with phpSmug to list the immediate children of the root node, but only public folders (those with at least one public album) and public albums are listed. I know my authorization (Access=Full) is correct, because when I try to list all user albums, I do get them all (code not shown). When I use the live example on the SmugMug site, I do get all immediate children of the root node. So, it seems the problem is within phpSmug, not with the SmugMug API itself. Also, I am replacing a Chrome App that also works as it should. (The Chrome App does not use phpSmug, of course.)

Any idea what's wrong and how I can fix it?

Here's my modified example. Lines that I added or changed are marked with the initials MJR. Note again that I didn't write most of this program, but only added and changed a few lines.

/* Last updated with phpSmug 4.0
 *
 * This example file shows you how to authenticate using OAuth and then display
 * the first 25 images in the first public gallery found of the authenticated
 * user's account.
 *
 * You'll want to set the following variables below:
 *
 * - $APIKey with one provided by SmugMug: http://www.smugmug.com/hack/apikeys
 * - $OAuthSecret with one provided when you obtained your API key
 * - $AppName with your application name, version and URL, eg
 *
 * The $AppName is NOT required, but it's encouraged as it will allow SmugMug to
 * diagnose any issues users may have with your application if they request help
 * on the SmugMug forums. A good format to use is "APP NAME/VER (URL)".
 *
 */

$APIKey = 'YOUR_API_KEY';  // MJR -- my own data was entered
$OAuthSecret = 'YOUR_OAUTH_SECRET';  // MJR -- my own data was entered
$AppName = 'YOUR_APP_NAME/VER (URL)';
?>

    <title>phpSmug OAuth Login Example</title>

OAuth Login Example

<?php

try {
    $options = [
        'AppName' => $AppName,
        '_verbosity' => 1, # Reduce verbosity to reduce the amount of data in the response and to make using it easier.
        'OAuthSecret' => $OAuthSecret, # You need to pass your OAuthSecret in order to authenticate with OAuth.
        'verify' => false // MJR: Added because SSL certificates are not set up
    ];

    $client = new phpSmug\Client($APIKey, $options);

    // Perform the 3 step OAuth Authorisation process.
    // NOTE: This is a very simplified example that does NOT store the final token.
    // You will need to ensure your application does.
    if (!isset($_SESSION['SmugGalReqToken'])) {

        // Step 1: Get a request token using an optional callback URL back to ourselves
        $callback = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
        $request_token = $client->getRequestToken($callback);
        $_SESSION['SmugGalReqToken'] = serialize($request_token);

        // Step 2: Get the User to login to SmugMug and authorise this demo
        echo '
Click getAuthorizeURL(['Access' => 'Full']).'">HERE to Authorize This Demo.
'; // MJR
        // Alternatively, automatically direct your visitor by commenting out the above line in favour of this:
        //header("Location:".$client->getAuthorizeURL());
    } else {
        $reqToken = unserialize($_SESSION['SmugGalReqToken']);
        unset($_SESSION['SmugGalReqToken']);

        // Step 3: Use the Request token obtained in step 1 to get an access token
        $client->setToken($reqToken['oauth_token'], $reqToken['oauth_token_secret']);
        $oauth_verifier = $_GET['oauth_verifier'];  // This comes back with the callback request.
        $token = $client->getAccessToken($oauth_verifier);  // The results of this call is what your application needs to store.
        // Get the username of the authenticated user
        $username = $client->get('!authuser')->User->NickName;

        // List top level folders and albums.  // MJR
        $user = $client->get('!authuser'); // MJR
        $root = $client->get($user->User->Uris->Node); // MJR
        $children = $client->get($root->Node->Uris->ChildNodes); // MJR
        foreach ($children->Node as $v) { // MJR
            echo "
 $v->Type \"$v->Name\" $v->Uri"; // MJR
        } // MJR

    }
} catch (Exception $e) {
    echo "{$e->getMessage()} (Error Code: {$e->getCode()})";
}
?>

Body:
Your changes should work, and do for me. One thing I did have to do was bump the count of nodes returned as ChildNodes returns only the first 10 nodes by default and my first private album is right at the very end.

Is your first private album/folder outside the first 10? If so, try changing your changes to:

// List top level folders and albums.  // MJR
$user = $client->get('!authuser'); // MJR
$root = $client->get($user->User->Uris->Node); // MJR
$children = $client->get($root->Node->Uris->ChildNodes, ['count' => 50]); // MJR
foreach ($children->Node as $v) { // MJR
    echo "<br> $v->Type \"$v->Name\" $v->Uri"; // MJR
} // MJR

You'll see I've added ['count' => 50] to the options. You may need to increase this if you've got more than 50 albums/folders.

Alternatively, you can iterate through the pages using the info in $children->Pages.


问:
How to make apps from MS app reg portal show up in my Azure AD?
Im trying to start working with the v2.0 endpoint, I registered my web app in the new Application registration portal, but I cannot find it anywhere in my Azure AD. Should I not be able to see it there?

I tried creating an app both with my work azure account, and with an account I created specifically in the tenant. Neither works. Am I missing something?a

答:
You could find it Azure Active Directory-->Enterprise applications-->All applications.

But you only could see Azure AD only applications. Currently, Converged applications could not see on Azure Portal, please refer to this feedback.

Update from comment:

The blade enterprise applications represents service principals in the AAD tenant, not applications. Once you sign into the app & consent or manually provision a service principal, you'll see it in this list.


问:
Do you have any good examples of "architecture for architecture's sake"?
Just listening to this week's podcast and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.

Java often gets a bad press in this respect, and an increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.

My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views).

答:
This was on reddit recently, with a good "yo dawg" joke.

Introducing: RequestProcessorFactoryFactory

Reddit discussion here

OwnerDisplayName: Nick Pierpoint

LastEditorDisplayName: Nick Pierpoint

OwnerDisplayName: uzhin


问:
iPhone: Splash screen in app - Good or Bad?
I'm going to submit a Lifestyle app to the App Store. I'm confused whether to add a Splash Screen to the App or not ?

Please advise me whether it's a good or bad idea as far as usability and App Store's submission guidelines are concerned.

答:
Its bad - you shouldn't do that!
Please read the Start Instantly Section of the Apple HI Guidelines

Avoid displaying an About window or a
  splash screen. In general, try to
  avoid providing any type of startup
  experience that prevents people from
  using your application immediately.

http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html


问:
How i can split array in js?
How i can split string in js for result:

```<code>result = ["post_address", "location", "area"]
</code>```

This is problem? Need help with re

```<code>let re = ???
let arr = "post_address[location][area]".split(re)
</code>```

答:
Simply split by /\[|\]/ and the remove the empty strings.

var output = "post_address[location][area]".split(/\[|\]/).filter((s)=>s.length > 0);

console.log(output);```

Title: How i can split array in js?

Body:
How i can split string in js for result:

result = ["post_address", "location", "area"]

This is problem? Need help with re

let re = ???
let arr = "post_address[location][area]".split(re)


问:
Javascript sort by digits sum doesn't work even with compare function. Why?
I have a function that sorts an array of integers by their digits sum, in case of equal digit sum than it sort by the numbers values. This is the function:

```<code>function s(g){
    var r=0;
    while(g)r+=g%10,g/=10;
    return r;
}
function digitalSumSort(a) {
    a.sort(function(x,y){
        return s(x)!=s(y)?s(x)-s(y):x-y;
    });
    return a;
}
</code>```

It sometimes works ok, but it failed at this test data:

Input: [100, 22, 4, 11, 31, 103]

Output: [100, 11, 31, 4, 22, 103]

Expected Output: [100, 11, 4, 22, 31, 103]

I couldn't figure out why it does that, and how to fix it?

Note: it is important that the code contains as least as possible characters!

Edit:
This question has already been answered but I recently made the same mistake and thought of this. Is there a way to make a var act as an integer (instead of a double) when given a numeric value. I learned the trick with using floor, but sometimes I just want integer operations instead of double (with some systems they are faster, and I may have other reasons).

答:
Thanks to @JJJ who comented "Hint: print out what s() returns (console.log(s(22)) and so on)."

I finally noticed that the function s() return incorrect values.

This code works:

```<code>function s(g){
    var r=0;
    while(g)r+=g%10,g=Math.floor(g/10);
    return r;
}
function digitalSumSort(a) {
    a.sort(function(x,y){
        return s(x)!=s(y)?s(x)-s(y):x-y;
    });
    return a;
}
</code>```

Body:
I have a function that sorts an array of integers by their digits sum, in case of equal digit sum than it sort by the numbers values. This is the function:

function s(g){
    var r=0;
    while(g)r+=g%10,g/=10;
    return r;
}
function digitalSumSort(a) {
    a.sort(function(x,y){
        return s(x)!=s(y)?s(x)-s(y):x-y;
    });
    return a;
}

It sometimes works ok, but it failed at this test data:

Input: [100, 22, 4, 11, 31, 103]

Output: [100, 11, 31, 4, 22, 103]

Expected Output: [100, 11, 4, 22, 31, 103]

I couldn't figure out why it does that, and how to fix it?

Note: it is important that the code contains as least as possible characters!

Edit:
This question has already been answered but I recently made the same mistake and thought of this. Is there a way to make a var act as an integer (instead of a double) when given a numeric value. I learned the trick with using floor, but sometimes I just want integer operations instead of double (with some systems they are faster, and I may have other reasons).

Body:
Thanks to @JJJ who comented "Hint: print out what s() returns (console.log(s(22)) and so on)."

I finally noticed that the function s() return incorrect values.

This code works:

function s(g){
    var r=0;
    while(g)r+=g%10,g=Math.floor(g/10);
    return r;
}
function digitalSumSort(a) {
    a.sort(function(x,y){
        return s(x)!=s(y)?s(x)-s(y):x-y;
    });
    return a;
}


问:
What is an interpreter output files generated (like .obj)
hey there my question is that what is the output of interpreter. for example in compiler the output file is .obj and .exe but what about interpreter what is the out put i tried to look for it in the internet but end up with nothing. If any one have any idea please help.

I also search here and i did not found the answer for this question.

答: There is no such thing as 'output of the interpreter'. The interpreter executes compiled bytecode, or possibly source code, and its output is whatever the program being interpreted outputs. It doesn't produce yet another object file.</p>


问:
Add columns dynamically and Later Parse values in the respective columns
I have an SP which accepts the Inputtable as parameter, My Inputtable is as shown in the code

```<code>`create table inputTable ( id int,ItemQty varchar(100))
insert into inputTable(id, ItemQty) values(1,'a,b,c')
insert into inputTable(id, ItemQty) values(2,'x,y')
insert into inputTable(id, ItemQty) values(3,'l,m,n,o,p')
insert into inputTable(id, ItemQty) values(4,'a,b')
insert into inputTable(id, ItemQty) values(5,'m')`
</code>```

and SP i have written is like below

```<code>`ALTER PROCEDURE [dbo].[Column_Dynamics] (@tablename varchar(50))

AS
BEGIN

-----
declare @maxcount as int
set @maxcount='select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename

exec('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename)
print @maxcount
exec @maxcount
print @maxcount

declare @var varchar(100)
IF EXISTS(SELECT * FROM   sys.columns WHERE  object_id = Object_id(@tablename))
set @var='alter table '+ @tablename +' ADD column QTY1'
exec(@var)
select * from @tablename
select max(len(ItemQty))-max(len(replace(ItemQty, ',', ''))-1) from inputtable

END`
</code>```

My table is :

step 1 ) I want to add the columns dynamically to inputtable like QTY1,QTY2,QTY3,QTY4,QTY5 because maximum count of ItemQty column is 5, by considering comma as delimiter as shown in figure1

**step 2) ** Parse values in the respective columns(by considering the delimiter comma (,).as shown in figure2

Later SP: I got till here, But Not getting the second step, that is update Parse values in the respective columns.

```<code>ALTER PROCEDURE dynamic_tbl (@tablename varchar(50))

AS
BEGIN

DECLARE @ColumnCount int
DECLARE @rowcount TABLE (Value int);
INSERT INTO @rowcount
EXEC('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename);
SELECT @ColumnCount = Value FROM @rowcount;

    Declare @ColumnName nvarchar(10)='qty_'
    Declare @count int =0
    IF(@ColumnCount>0)
    BEGIN
        IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'dyn_tbl'))
        BEGIN
        DROP TABLE dyn_tbl
        END

        select * into dyn_tbl from inputtable
        SET @count=@count +1;
        WHile(@ColumnCount>=@count)
        BEGIN
            SET @ColumnName='qty_'+CONVERT(varchar(2),@count)
            EXEC ('ALTER TABLE dyn_tbl ADD ['+@ColumnName +'] varchar(20)')

            declare @myvar as varchar(max)

            set @myvar='update '+@tablename+' set '+@ColumnName +' =itemQty'

--exec dynamic_tbl 'dyn_tbl'

--select * from dyn_tbl

            --CAST('<A>'+REPLACE(ITEMQTY, ',', '</A><A>')+'</A>' AS XML)
            print @myvar

            exec(@myvar)

            SET @count=@count +1;
        END
    END

----
END
</code>```

答:
Use This

First Create a function

```<code>CREATE FUNCTION [dbo].[fn_split](
@str VARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE @pos INT
SELECT @str = @str + @delimiter
WHILE LEN(@str) > 0
    BEGIN
        SELECT @pos = CHARINDEX(@delimiter,@str)
        IF @pos = 1
            INSERT @returnTable (item)
                VALUES (NULL)
        ELSE
            INSERT @returnTable (item)
                VALUES (SUBSTRING(@str, 1, @pos-1))
        SELECT @str = SUBSTRING(@str, @pos+1, LEN(@str)-@pos)
    END
RETURN
END
GO
</code>```

and use function like this

```<code>Declare @test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)

insert into @test
(ID, Data)
Values
(1,'a,b,c')

insert into @test
(ID, Data )
values(2,'x,y')

insert into @test
(ID, Data )
values(3,'l,m,n,o,p')

insert into @test
(ID, Data )
values(4,'a,b')

insert into @test
(ID, Data )
values(5,'m')

select ID,data AS ItemQty,
ISNULL((select item from fn_split(Data,',') where idx in (1)),'') as QTY1 ,
ISNULL((select item from fn_split(Data,',') where idx in (2)),'') as QTY2,
ISNULL((select item from fn_split(Data,',') where idx in (3)),'') as QTY3,
ISNULL((select item from fn_split(Data,',') where idx in (4)),'') as QTY5 ,
ISNULL((select item from fn_split(Data,',') where idx in (5)),'') as QTY5
 from @test
</code>```

Output Same as your Image

instead of using

```<code>insert into @test
(ID, Data)
Values
(1,'a,b,c')
</code>```

you can also assgin it like this

```<code>insert into @test
    (ID, Data)
    Values
    (Select Column1, Column2 From YourTable)
</code>```

Body:
I have an SP which accepts the Inputtable as parameter, My Inputtable is as shown in the code

`create table inputTable ( id int,ItemQty varchar(100))
insert into inputTable(id, ItemQty) values(1,'a,b,c')
insert into inputTable(id, ItemQty) values(2,'x,y')
insert into inputTable(id, ItemQty) values(3,'l,m,n,o,p')
insert into inputTable(id, ItemQty) values(4,'a,b')
insert into inputTable(id, ItemQty) values(5,'m')`

and SP i have written is like below

`ALTER PROCEDURE [dbo].[Column_Dynamics] (@tablename varchar(50))

AS
BEGIN

-----
declare @maxcount as int
set @maxcount='select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename

exec('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename)
print @maxcount
exec @maxcount
print @maxcount

declare @var varchar(100)
IF EXISTS(SELECT * FROM   sys.columns WHERE  object_id = Object_id(@tablename))
set @var='alter table '+ @tablename +' ADD column QTY1'
exec(@var)
select * from @tablename
select max(len(ItemQty))-max(len(replace(ItemQty, ',', ''))-1) from inputtable

END`

My table is :

step 1 ) I want to add the columns dynamically to inputtable like QTY1,QTY2,QTY3,QTY4,QTY5 because maximum count of ItemQty column is 5, by considering comma as delimiter as shown in figure1

**step 2) ** Parse values in the respective columns(by considering the delimiter comma (,).as shown in figure2

Later SP: I got till here, But Not getting the second step, that is update Parse values in the respective columns.

ALTER PROCEDURE dynamic_tbl (@tablename varchar(50))

AS
BEGIN

DECLARE @ColumnCount int
DECLARE @rowcount TABLE (Value int);
INSERT INTO @rowcount
EXEC('select MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename);
SELECT @ColumnCount = Value FROM @rowcount;

    Declare @ColumnName nvarchar(10)='qty_'
    Declare @count int =0
    IF(@ColumnCount>0)
    BEGIN
        IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'dyn_tbl'))
        BEGIN
        DROP TABLE dyn_tbl
        END

        select * into dyn_tbl from inputtable
        SET @count=@count +1;
        WHile(@ColumnCount>=@count)
        BEGIN
            SET @ColumnName='qty_'+CONVERT(varchar(2),@count)
            EXEC ('ALTER TABLE dyn_tbl ADD ['+@ColumnName +'] varchar(20)')

            declare @myvar as varchar(max)

            set @myvar='update '+@tablename+' set '+@ColumnName +' =itemQty'

--exec dynamic_tbl 'dyn_tbl'

--select * from dyn_tbl

            --CAST(''+REPLACE(ITEMQTY, ',', '')+'' AS XML)
            print @myvar

            exec(@myvar)

            SET @count=@count +1;
        END
    END

----
END

Body:
Use This

First Create a function

CREATE FUNCTION [dbo].[fn_split](
@str VARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE @pos INT
SELECT @str = @str + @delimiter
WHILE LEN(@str) > 0
    BEGIN
        SELECT @pos = CHARINDEX(@delimiter,@str)
        IF @pos = 1
            INSERT @returnTable (item)
                VALUES (NULL)
        ELSE
            INSERT @returnTable (item)
                VALUES (SUBSTRING(@str, 1, @pos-1))
        SELECT @str = SUBSTRING(@str, @pos+1, LEN(@str)-@pos)
    END
RETURN
END
GO

and use function like this

Declare @test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)

insert into @test
(ID, Data)
Values
(1,'a,b,c')

insert into @test
(ID, Data )
values(2,'x,y')

insert into @test
(ID, Data )
values(3,'l,m,n,o,p')

insert into @test
(ID, Data )
values(4,'a,b')

insert into @test
(ID, Data )
values(5,'m')

select ID,data AS ItemQty,
ISNULL((select item from fn_split(Data,',') where idx in (1)),'') as QTY1 ,
ISNULL((select item from fn_split(Data,',') where idx in (2)),'') as QTY2,
ISNULL((select item from fn_split(Data,',') where idx in (3)),'') as QTY3,
ISNULL((select item from fn_split(Data,',') where idx in (4)),'') as QTY5 ,
ISNULL((select item from fn_split(Data,',') where idx in (5)),'') as QTY5
 from @test

Output Same as your Image

instead of using

insert into @test
(ID, Data)
Values
(1,'a,b,c')

you can also assgin it like this

insert into @test
    (ID, Data)
    Values
    (Select Column1, Column2 From YourTable)


问:
Creating a new user in the mysql Command line interface
I went inside the mysql CLI in Bash via:

mysql -u root -p

I then tried to create a new user limited to localhost, with this following command, which was failed:

```<code>create user "${domain}"@"localhost" identified by -p;
</code>```

Why was the command failed?

Edit: My aim is to create (or paste) the user's password in command execution (this is why I left -p empty. The code is part of a greater script file and I don't want to expose any password in that file.

答:
This is the correct way to create a user for localhost:

```<code>CREATE USER 'myuserinlocalhost'@'localhost' IDENTIFIED BY 'passwordinlocalhost';
</code>```

Here is how it can look like with PDO:

```<code>$sql = "CREATE USER '?'@'localhost' IDENTIFIED BY ?";
    $statement = $this->db->prepare($sql);
    $data = array($user,$password);
    $statement->execute($data);
</code>```

Body:
I went inside the mysql CLI in Bash via:

mysql -u root -p

I then tried to create a new user limited to localhost, with this following command, which was failed:

create user "${domain}"@"localhost" identified by -p;

Why was the command failed?

Edit: My aim is to create (or paste) the user's password in command execution (this is why I left -p empty. The code is part of a greater script file and I don't want to expose any password in that file.

Body:
This is the correct way to create a user for localhost:

CREATE USER 'myuserinlocalhost'@'localhost' IDENTIFIED BY 'passwordinlocalhost';

Here is how it can look like with PDO:

$sql = "CREATE USER '?'@'localhost' IDENTIFIED BY ?";
    $statement = $this->db->prepare($sql);
    $data = array($user,$password);
    $statement->execute($data);


问:
Xamarin -- Set zoom in AVCapture not working
Hello I am trying to increase the zoom of the camera to its max level in my application.

However after setting the AvCapture to its max value it remains at its lowest zoom level on the screen. Below is my code.

```<code>void Initialize()
{

var videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);

device.LockForConfiguration(out error);
if (error == null)
{
    Console.WriteLine("Supports Preset");
    var test = device.RampingVideoZoom;
    var d = device.VideoZoomFactor;
    device.VideoZoomFactor = device.ActiveFormat.VideoMaxZoomFactor;
}
device.UnlockForConfiguration();

while(device.RampingVideoZoom == true)
{
    Console.WriteLine("Zooming camera"); //This line is never written
}

//See below for value this returns in Console
Console.WriteLine("Current Format");
Console.WriteLine(device.ActiveFormat);

}
</code>```

Current Format

```<code><AVCaptureDeviceFormat: 0x1c48049a0 'vide'/'420v' 1920x1080, { 3- 30 fps}, HRSI:4096x2304, fov:59.680, supports vis, max zoom:16.00 (upscales @1.94), AF System:2, ISO:22.0-704.0, SS:0.000005-0.333333>
</code>```

This code does not affect the zoom of the camera AT ALL.

What am I doing wrong?

答:
videoMaxZoomFactor Definition

A maximum factor of 1.0 indicates that the format is not capable of zooming.

There is no mistake in your code.

As the Documentation said ,if device.ActiveFormat.VideoMaxZoomFactor == 1 ,the zoom is not available.

You can debug the value of device.ActiveFormat.VideoMaxZoomFactor to see if it euqals to 1.

Body:
Hello I am trying to increase the zoom of the camera to its max level in my application.

However after setting the AvCapture to its max value it remains at its lowest zoom level on the screen. Below is my code.

void Initialize()
{

var videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);

device.LockForConfiguration(out error);
if (error == null)
{
    Console.WriteLine("Supports Preset");
    var test = device.RampingVideoZoom;
    var d = device.VideoZoomFactor;
    device.VideoZoomFactor = device.ActiveFormat.VideoMaxZoomFactor;
}
device.UnlockForConfiguration();

while(device.RampingVideoZoom == true)
{
    Console.WriteLine("Zooming camera"); //This line is never written
}

//See below for value this returns in Console
Console.WriteLine("Current Format");
Console.WriteLine(device.ActiveFormat);

}

Current Format

<AVCaptureDeviceFormat: 0x1c48049a0 'vide'/'420v' 1920x1080, { 3- 30 fps}, HRSI:4096x2304, fov:59.680, supports vis, max zoom:16.00 (upscales @1.94), AF System:2, ISO:22.0-704.0, SS:0.000005-0.333333>

This code does not affect the zoom of the camera AT ALL.

What am I doing wrong?


问:
Which hook should I use to display shipping methods?
I need to display my shipping methods. Which hook should I use to do this?

functions.php:

```<code>add_filter('which_hook_should_i_use', 'my_shipping_function');
function my_shipping_function() {
    //what code do I need to write?
}
</code>```

答:
I did this way:</p>

```<code>function ed_package_rates( $rates, $package ) {

foreach ( $rates as $rate ) {
    $first_product_id = array_values(  WC()->cart->get_cart()  );
    $product_id = $first_product_id[0]['product_id'];

    $rate_label = mb_strtolower(str_replace(' ', '_', $rate->label));
    $rate->cost = get_post_meta($product_id,'_my_shipping_method_'. $rate_label, true) ; // to form meta_key
  }
  return $rates ;
}
add_filter('woocommerce_package_rates', 'my_package_rates', 10, 2);
</code>```

Body:
I need to display my shipping methods. Which hook should I use to do this?

functions.php:

add_filter('which_hook_should_i_use', 'my_shipping_function');
function my_shipping_function() {
    //what code do I need to write?
}

Body:
I did this way:

function ed_package_rates( $rates, $package ) {

foreach ( $rates as $rate ) {
    $first_product_id = array_values(  WC()->cart->get_cart()  );
    $product_id = $first_product_id[0]['product_id'];

    $rate_label = mb_strtolower(str_replace(' ', '_', $rate->label));
    $rate->cost = get_post_meta($product_id,'_my_shipping_method_'. $rate_label, true) ; // to form meta_key
  }
  return $rates ;
}
add_filter('woocommerce_package_rates', 'my_package_rates', 10, 2);


问:
WPF UserControl Context Menu Visibility Binding
My user control context menu visibility can't bind a dependency property. Any idea?

Here is my WPF code

```<code><UserControl.ContextMenu>
    <ContextMenu Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}">
    <MenuItem Command="local:GCommands.Edit" />
    <MenuItem Command="local:GCommands.Delete" />
    <MenuItem Command="local:GCommands.ExportFcsFiles" />
    <MenuItem Command="local:GCommands.BatchExportStatistics" />
    <Separator/>
    <MenuItem Command="local:GCommands.SaveAs" Header="Save As..." />
    </ContextMenu>
</UserControl.ContextMenu>
</code>```

If I set Visibility="Hidden" it will work for me.
like this:

```<code><ContextMenu Visibility="Hidden"/>
</code>```

If use this it won't work

```<code><ContextMenu Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}">
</code>```

I'm pretty sure Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}" has not problem, cuz it works for others.

here is my dependency property

```<code>public bool IsInCompactMode
        {
            get {return (bool)GetValue(IsInCompactModeProperty); }
            set {SetValue(IsInCompactModeProperty, value); }
        }
        public static readonly DependencyProperty IsInCompactModeProperty =
            DependencyProperty.Register("IsInCompactMode", typeof(bool), typeof(WellControl), new PropertyMetadata(false));
</code>```

I tried this way, it seems it still doesn't work, this is really weird!!!

```<code><ContextMenu x:Name="menu" IsOpen="{Binding ElementName=wellControl, Path=IsInCompactMode}">
</code>```

I'm really confuse about it, what's wrong? "Binding ElementName=wellControl, Path=IsInCompactMode" works for other part of the user control, just doesn't work for the weird context menu? it doesn't make sence

答:
You should add the Update Trigger : "UpdateSourceTrigger=PropertyChanged"</p>

```<code><DataGrid.ContextMenu >
    <ContextMenu Visibility="{Binding IsSelectionEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,Converter={StaticResource BooleanToVisibilityConverter}}" >
        <ContextMenu.Items>
            <MenuItem Header="Create Layer" Command="{Binding DefineLayerName }" />
        </ContextMenu.Items>
    </ContextMenu>
</DataGrid.ContextMenu>
</code>```

Body:
My user control context menu visibility can't bind a dependency property. Any idea?

Here is my WPF code

<UserControl.ContextMenu>
    <ContextMenu Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}">
    <MenuItem Command="local:GCommands.Edit" />
    <MenuItem Command="local:GCommands.Delete" />
    <MenuItem Command="local:GCommands.ExportFcsFiles" />
    <MenuItem Command="local:GCommands.BatchExportStatistics" />
    <Separator/>
    <MenuItem Command="local:GCommands.SaveAs" Header="Save As..." />
    </ContextMenu>
</UserControl.ContextMenu>

If I set Visibility="Hidden" it will work for me.
like this:

<ContextMenu Visibility="Hidden"/>

If use this it won't work

<ContextMenu Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}">

I'm pretty sure Visibility="{Binding ElementName=wellControl, Path=IsInCompactMode, Converter={StaticResource BooleanToVisibilityConverter}}" has not problem, cuz it works for others.

here is my dependency property

public bool IsInCompactMode
        {
            get {return (bool)GetValue(IsInCompactModeProperty); }
            set {SetValue(IsInCompactModeProperty, value); }
        }
        public static readonly DependencyProperty IsInCompactModeProperty =
            DependencyProperty.Register("IsInCompactMode", typeof(bool), typeof(WellControl), new PropertyMetadata(false));

I tried this way, it seems it still doesn't work, this is really weird!!!

<ContextMenu x:Name="menu" IsOpen="{Binding ElementName=wellControl, Path=IsInCompactMode}">

I'm really confuse about it, what's wrong? "Binding ElementName=wellControl, Path=IsInCompactMode" works for other part of the user control, just doesn't work for the weird context menu? it doesn't make sence

Body:
You should add the Update Trigger : "UpdateSourceTrigger=PropertyChanged"

<DataGrid.ContextMenu >
    <ContextMenu Visibility="{Binding IsSelectionEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,Converter={StaticResource BooleanToVisibilityConverter}}" >
        <ContextMenu.Items>
            <MenuItem Header="Create Layer" Command="{Binding DefineLayerName }" />
        </ContextMenu.Items>
    </ContextMenu>
</DataGrid.ContextMenu>


问:
cannot display PDF file from assets folder as MODE_WORLD_READABLE no longer supported
The following code is working absolutely fine in devices with API 22 but in devices with API 24 it gives the following error:

```<code>java.lang.SecurityException: MODE_WORLD_READABLE no longer supported
</code>```

Here is my code:

```<code>private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), filename);

    try {
        in = assetManager.open(filename);
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/pdf");

        startActivity(intent);
    } catch (Exception e)
    {
        Log.e("cra",e.toString());
        Toast.makeText(PdfFilesList.this, "cra: "+e.toString(), Toast.LENGTH_SHORT).show();
    }
}
</code>```

If I change MODE_WORLD_READABLE  to MODE_PRIVATE then it stops working in all devices.
devices with API 22 give the following error

```<code>11-16 12:00:53.133 16531-31103/? E/DisplayData: openFd: java.io.FileNotFoundException: Permission denied
11-16 12:00:53.134 16531-31103/? E/PdfLoader: Can't load file (doesn't open)  Display Data [PDF : 818 New Jeevan Nidhi.pdf] +FileOpenable, uri: file:///data/data/com.user.plansmart/files/818%20New%20Jeevan%20Nidhi.pdf
</code>```

Device with API 24 throw the following exception

```<code>11-16 12:05:00.100 2682-2682/com.user.plansmart E/cra: android.os.FileUriExposedException: file:///data/user/0/com.user.plansmart/files/827%20Jeevan%20Rakshak.pdf exposed beyond app through Intent.getData()
</code>```

Can someone help me in resolving the issue.

Thanks.

答:
You should use a FileProvider to serve your files with Intent.ACTION_VIEW.

Code doing so you can find plenty on this site.

Body:
The following code is working absolutely fine in devices with API 22 but in devices with API 24 it gives the following error:

java.lang.SecurityException: MODE_WORLD_READABLE no longer supported

Here is my code:

private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), filename);

    try {
        in = assetManager.open(filename);
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/pdf");

        startActivity(intent);
    } catch (Exception e)
    {
        Log.e("cra",e.toString());
        Toast.makeText(PdfFilesList.this, "cra: "+e.toString(), Toast.LENGTH_SHORT).show();
    }
}

If I change MODE_WORLD_READABLE  to MODE_PRIVATE then it stops working in all devices.
devices with API 22 give the following error

11-16 12:00:53.133 16531-31103/? E/DisplayData: openFd: java.io.FileNotFoundException: Permission denied
11-16 12:00:53.134 16531-31103/? E/PdfLoader: Can't load file (doesn't open)  Display Data [PDF : 818 New Jeevan Nidhi.pdf] +FileOpenable, uri: file:///data/data/com.user.plansmart/files/818%20New%20Jeevan%20Nidhi.pdf

Device with API 24 throw the following exception

11-16 12:05:00.100 2682-2682/com.user.plansmart E/cra: android.os.FileUriExposedException: file:///data/user/0/com.user.plansmart/files/827%20Jeevan%20Rakshak.pdf exposed beyond app through Intent.getData()

Can someone help me in resolving the issue.

Thanks.


问:
MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050
Using the command:

```<code>CREATE TABLE IF NOT EXISTS `test`.`t1` (
    `col` VARCHAR(16) NOT NULL
) ENGINE=MEMORY;
</code>```

Running this twice in the MySQL Query Browser results in:

Table 't1' already exists Error 1050

I would have thought that creating the table "IF NOT EXISTS" would not throw errors. Am I missing something or is this a bug? I am running version 5.1. Thanks.

答:
```<code>create database if not exists `test`;

USE `test`;

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

/*Table structure for table `test` */

***CREATE TABLE IF NOT EXISTS `tblsample` (
  `id` int(11) NOT NULL auto_increment,
  `recid` int(11) NOT NULL default '0',
  `cvfilename` varchar(250)  NOT NULL default '',
  `cvpagenumber`  int(11) NULL,
  `cilineno` int(11)  NULL,
  `batchname`  varchar(100) NOT NULL default '',
  `type` varchar(20) NOT NULL default '',
  `data` varchar(100) NOT NULL default '',
   PRIMARY KEY  (`id`)
);***
</code>```

Body:
Using the command:

CREATE TABLE IF NOT EXISTS `test`.`t1` (
    `col` VARCHAR(16) NOT NULL
) ENGINE=MEMORY;

Running this twice in the MySQL Query Browser results in:

Table 't1' already exists Error 1050

I would have thought that creating the table "IF NOT EXISTS" would not throw errors. Am I missing something or is this a bug? I am running version 5.1. Thanks.


问:
Getting double quotes in Html element name
I'm trying to change visibility of some divs by click.

I'm adding "main" divs and "sub" divs using a php foreach loop on an array.

After that I add events using javascript to the elements having a specific class.

The problem is that the javascript function gets the name of the element with double quotes at the start and in the end.

I could solve by using a "substring" but I'm pretty new to web programming and I need to understand why this happens or I'll never improve my skills.

Below there is all my code.

```<code><!DOCTYPE html>
<html>
<head>
<style>
.Class1 {
    position:relative;
    display: inline-block;
    width: 48%;
    margin: 3px;
    border: 3px solid #CCC;
}

.Class2 {
    position:absolute;
    bottom:0;
    right:0;
    border: 1px solid #CCC;
    margin:1px;
    background: #FFC;
}
.H_p {
    border: 1px solid #CCC;
    display: inline-block;
}
.Opt {
    border: 1px solid #CCC;
    display: none;
}
</style>
</head>
<body>
<?php
$Divs = array('Div1'=>'Class1',
    'Div2'=>'Class1',
    'Div3'=>'Class1',
    'Div4'=>'Class1',
    'Div5'=>'Class1');

$AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
foreach ($Divs as $Name=>$Class){
    echo '
    <div class="'.$Class.'">';
    echo $Name.'<br/>';
    echo '
        <p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';
    echo '
            <div id=Opt'.$Name.' name="Opt'.$Name.'" class="Opt" >';
    foreach ($AskToShow as $H_Name=>$Id){
        echo'
                <p id="H_'.$Id.'" class="H_p">'.$H_Name.'</p>';
    }
    echo '
            </div>';
    echo '
    </div>';
}
?>
<script>
    var MyClass = document.getElementsByClassName("Class2");

    var myFunction = function() {
        var SenderId = this.id;
        alert (SenderId);
        var SubId = SenderId.substring(SenderId.indexOf('_')+1)
        alert (SubId);
        var SubSH = document.getElementById(SubId);
        if (!SubSH){
            alert("Empty"); //This is the alert shown!!
        }else{
            alert(SubSH.name);
        }
        if (SubSH.style.display == 'none'){
            document.getElementById(SubId).style.display = 'block';
        }else{
            document.getElementById(SubId).style.display = 'none';
        }
    };

    for (var i = 0; i < MyClass.length; i++) {
        MyClass[i].addEventListener('click', myFunction, false);
    }
</script>
</body>
</html>
</code>```

答:
```<code> <p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';
</code>```

There you used the wrong quote type ”.

Hope this fixes it.

Body:
I'm trying to change visibility of some divs by click.

I'm adding "main" divs and "sub" divs using a php foreach loop on an array.

After that I add events using javascript to the elements having a specific class.

The problem is that the javascript function gets the name of the element with double quotes at the start and in the end.

I could solve by using a "substring" but I'm pretty new to web programming and I need to understand why this happens or I'll never improve my skills.

Below there is all my code.

<!DOCTYPE html>

<?php
$Divs = array('Div1'=>'Class1',
    'Div2'=>'Class1',
    'Div3'=>'Class1',
    'Div4'=>'Class1',
    'Div5'=>'Class1');

$AskToShow=array("Field1"=>"1.1.1", "Field2"=>"1.2.1", "Field3"=>"1.3.1");
foreach ($Divs as $Name=>$Class){
    echo '

';
    echo $Name.'
';
    echo '

Show optionals
';
    echo '

';
    foreach ($AskToShow as $H_Name=>$Id){
        echo'

'.$H_Name.'
';
    }
    echo '

';
    echo '

';
}
?>

Body:
 <p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';

There you used the wrong quote type ”.

Hope this fixes it.


问:
How to detect if browser cookies are enabled in ASP.Net MVC 5?
I've to detect in my ASP.Net MVC application if cookies are disabled in the client's browser. All my searches result in asp.net WebForms with Page_Load etc., instead of an ASP.Net MVC application.

How can I detect on the server side if browser cookies are enabled?

答:
Below code can be used in asp.net MVC

Step 1: Create cookie if doesn't exist

```<code>public ActionResult CreateCookie()
{

  //Check if cookie Enabled on Page Load
  if (Request.Cookies["UserInfo"] != null)
  {
    // Cookie is enabled
    // TODO , write your code
  }
  else
  {
    // Create a new cookie, if cookie is null

    HttpCookie userCookie = new HttpCookie("UserInfo");
    userCookie["Name"] = "example";
    userCookie["Company"] = "example";
    userCookie.Expires.AddDays(50); // cookie will expire after 50 days
    Response.Cookies.Add(userCookie);

    return RedirectToAction("CookieEnabled");

 }

   return View();
}
</code>```

Step 2: Check if cookie enabled

```<code>public ActionResult CookieEnabled()
{
    if (Request.Cookies["UserInfo"] != null)
    {
        // Cookie is enabled
        // TODO , write your code
    }

    else
    {
        // Cookie is disabled
        // TODO , write your code
    }

    return View();
}
</code>```

Note: You can also check this in client side using JavaScript, check this article.

Body:
Below code can be used in asp.net MVC

Step 1: Create cookie if doesn't exist

public ActionResult CreateCookie()
{

  //Check if cookie Enabled on Page Load
  if (Request.Cookies["UserInfo"] != null)
  {
    // Cookie is enabled
    // TODO , write your code
  }
  else
  {
    // Create a new cookie, if cookie is null

    HttpCookie userCookie = new HttpCookie("UserInfo");
    userCookie["Name"] = "example";
    userCookie["Company"] = "example";
    userCookie.Expires.AddDays(50); // cookie will expire after 50 days
    Response.Cookies.Add(userCookie);

    return RedirectToAction("CookieEnabled");

 }

   return View();
}

Step 2: Check if cookie enabled

public ActionResult CookieEnabled()
{
    if (Request.Cookies["UserInfo"] != null)
    {
        // Cookie is enabled
        // TODO , write your code
    }

    else
    {
        // Cookie is disabled
        // TODO , write your code
    }

    return View();
}

Note: You can also check this in client side using JavaScript, check this article.


答:
```<code><p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';
</code>```

You are using ” (RIGHT DOUBLE QUOTATION MARK) to delimit your attribute values. Only " (QUOTATION MARK) and ' (APOSTROPHE) are allowed.

The RIGHT DOUBLE QUOTATION MARK is, therefore, being treated as data and not as a delimiter.

This code example shows the three characters at a large font size so you can clearly see the difference between them.

body { font-size: 50px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>”<br>"<br>'</code>```

This is often caused by writing HTML using a word processor instead of a text editor.

Title: Getting double quotes in Html element name

Body:
<p id=”Btn_Opt'.$Name.'” class="Class2" >Show optionals</p>';

You are using ” (RIGHT DOUBLE QUOTATION MARK) to delimit your attribute values. Only " (QUOTATION MARK) and ' (APOSTROPHE) are allowed.

The RIGHT DOUBLE QUOTATION MARK is, therefore, being treated as data and not as a delimiter.

This code example shows the three characters at a large font size so you can clearly see the difference between them.

body { font-size: 50px; }

”<br>"<br>'

This is often caused by writing HTML using a word processor instead of a text editor.


问:
How to get the particular div values using jQuery
Here I have one row, in that one row I have three div, my requirement is suppose if I am click the free plan button means I want to take only the that particular div values like Plan Name: Free Plan and Bonus Contact details up to : 00, I tried but I am not able to take the exact values if anyone know means please update my answer.Please see below I have posted my code what I tried, I spent too much to this but still I am not getting my answer.

```<code><section id="pricing-table">
  <div class="row pricelistNew">
    <div class="pricing">
      <div class="col-md-4 col-sm-12 col-xs-12">
        <div class="pricing-table">
          <div class="pricing-header">
            <p class="pricing-title myTitle">Easy Plan </p>
            <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>
            <a class="btn btn-custom payNow">Easy Plan</a>
          </div>

          <div class="pricing-list">
            <ul>
              <li>Contacts details up to : 25</li>
              <li>Bonus Contact details up to : 2</li>
              <li>Area Master Assistance : No</li>
              <li>Contact details through sms : Yes</li>
            </ul>
          </div>
        </div>
      </div>

      <div class="col-md-4 col-sm-12 col-xs-12">
        <div class="pricing-table">
          <div class="pricing-header">
            <p class="pricing-title myTitle">Cool Plan </p>
            <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>
            <a class="btn btn-custom payNow">Cool Plan</a>
          </div>

          <div class="pricing-list">
            <ul>
              <li>Contacts details up to : 48</li>
              <li>Bonus Contact details up to : 4</li>
              <li>Area Master Assistance : Yes</li>
              <li>Contact details through sms : Yes</li>
            </ul>
          </div>
        </div>
      </div>

      <div class="col-md-4 col-sm-12 col-xs-12">
        <div class="pricing-table">
          <div class="pricing-header">
            <p class="pricing-title myTitle">Free Plan </p>
            <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>
            <a class="btn btn-custom payNow">Free Plan</a>
          </div>

          <div class="pricing-list">
            <ul>
              <li>Contacts details up to : 5</li>
              <li>Bonus Contact details up to : 00</li>
              <li>Area Master Assistance : No</li>
              <li>Contact details through sms : Yes</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
</code>```

My jQuery code

```<code>$(function() {
  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricelistNew");
    name = $list.find(".myTitle").text();
    console.log(name);
  });
});
</code>```

Here I am getting all title names like

Easy Plan Cool Plan Free Plan

答:
Replace your script with this..</p>

```<code>$(function() {
  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();

    console.log(name);
  });
});
</code>```

Body:
Here I have one row, in that one row I have three div, my requirement is suppose if I am click the free plan button means I want to take only the that particular div values like Plan Name: Free Plan and Bonus Contact details up to : 00, I tried but I am not able to take the exact values if anyone know means please update my answer.Please see below I have posted my code what I tried, I spent too much to this but still I am not getting my answer.

Easy Plan

₹ 1000
Including All Tax

            Easy Plan

Contacts details up to : 25

Bonus Contact details up to : 2

Area Master Assistance : No

Contact details through sms : Yes

Cool Plan

₹ 2000
Including All Tax

            Cool Plan

Contacts details up to : 48

Bonus Contact details up to : 4

Area Master Assistance : Yes

Contact details through sms : Yes

Free Plan

₹ 0
Including All Tax

            Free Plan

Contacts details up to : 5

Bonus Contact details up to : 00

Area Master Assistance : No

Contact details through sms : Yes

My jQuery code

$(function() {
  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricelistNew");
    name = $list.find(".myTitle").text();
    console.log(name);
  });
});

Here I am getting all title names like

Easy Plan Cool Plan Free Plan

Body:
Replace your script with this..

$(function() {
  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();

    console.log(name);
  });
});


问:
jQuery attr() method to change a class name
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}</code>```

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

```

答:
Mainly, the .attr() method isn't intended for the classes manipulation. Use:

```<code>$(selector).addClass('className') for adding class to element(s)
$(selector).removeClass('className') for removing class from element(s)
$(selector).toggleClass('className') for toggling class appereance in element(s)
</code>```

Body:
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();

.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

Body:
Mainly, the .attr() method isn't intended for the classes manipulation. Use:

$(selector).addClass('className') for adding class to element(s)
$(selector).removeClass('className') for removing class from element(s)
$(selector).toggleClass('className') for toggling class appereance in element(s)