问:
Hide element with JQuery and activate button
I am making a product with 3 variables. A customer can pickup the products at our place, or we can deliver the products. Because of practical things, we choose to sell products there should be delivered as packages with 30, 60 or 90 products in.

Before a price can be shown, all 3 variables need to get selected. So here comes the problem. If a person wants to pickup the products at our place only 2 variables need to be selected: Length in m and Pickup or Delivery. But that will not give a price. Therefore I need to insert "Pickup" in "Packages" again to get a price.

But I would like to hide "pickup" in packages, so I do not confuse the visitor to much. The image describes what I am looking for:

The page can [be seen here][2]

This is the code I have until now, but as I see it either my code is not executed or the code is simply wrong. The page is looking excact the same as before I added my code to functions.php, and none of the functions are executed.

Based on my description does anybody have a good idea to what is wrong with my code?

HTML:

```<code><ul class="variable-items-wrapper button-variable-wrapper" data-attribute_name="attribute_pa_packages">
    <li data-wvstooltip="pickup" class="variable-item button-variable-item button-variable-item-pickup" title="pickup" data-value="pickup">
        <span class="variable-item-span variable-item-span-button">pickup</span>
    </li>
</ul>

<ul class="variable-items-wrapper button-variable-wrapper" data-attribute_name="attribute_pa_packages">
    <li data-wvstooltip="pickup" class="variable-item button-variable-item button-variable-item-pickup selected" title="pickup" data-value="pickup">
        <span class="variable-item-span variable-item-span-button">pickup</span></li>
    </li>
</ul>
</code>```

PHP and script:

```<code>function custom_script_name(){
    ?>
    <script>
    jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery] li").click(function(){
        var selectedDelivery = jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery]").find("li.selected").attr("data-value");
        if (selectedDelivery == "pickup"){
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup] span").click();
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide(); // hide the "pickup" option in "Packages" if you like
        }
    });
    </script>
    <?php
    }
    add_action('wp_head', 'custom_script_name');
</code>```

答:
You can try below code it will hide the button but on click pickup, it is selected. just update the jquery and try once. hope it was work</p>

```<code>jQuery(document).ready(function(){
     jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide();
    jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery] li").click(function(){
        var selectedDelivery = jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery]").find("li.selected").attr("data-value");
        if (selectedDelivery == "pickup"){
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup] span").click();
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide(); // hide the "pickup" option in "Packages" if you like
        }
    });
});
</code>```

Body:
I am making a product with 3 variables. A customer can pickup the products at our place, or we can deliver the products. Because of practical things, we choose to sell products there should be delivered as packages with 30, 60 or 90 products in.

Before a price can be shown, all 3 variables need to get selected. So here comes the problem. If a person wants to pickup the products at our place only 2 variables need to be selected: Length in m and Pickup or Delivery. But that will not give a price. Therefore I need to insert "Pickup" in "Packages" again to get a price.

But I would like to hide "pickup" in packages, so I do not confuse the visitor to much. The image describes what I am looking for:

The page can [be seen here][2]

This is the code I have until now, but as I see it either my code is not executed or the code is simply wrong. The page is looking excact the same as before I added my code to functions.php, and none of the functions are executed.

Based on my description does anybody have a good idea to what is wrong with my code?

HTML:

        pickup

        pickup

PHP and script:

function custom_script_name(){
    ?>

    <?php
    }
    add_action('wp_head', 'custom_script_name');

Body:
You can try below code it will hide the button but on click pickup, it is selected. just update the jquery and try once. hope it was work

jQuery(document).ready(function(){
     jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide();
    jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery] li").click(function(){
        var selectedDelivery = jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery]").find("li.selected").attr("data-value");
        if (selectedDelivery == "pickup"){
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup] span").click();
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide(); // hide the "pickup" option in "Packages" if you like
        }
    });
});


来源: stackexchange

问:
Convert date to specific format in javascript?
Hi i want to convert the current date to a format as follows in javascript:
Apr 12, 2011 06:42:03.

Any suggestions?????

答:
You may be interested in http://www.datejs.com/

thanks for the comments guys, I should of really linked more directly to the formatting options.

http://code.google.com/p/datejs/wiki/FormatSpecifiers

ContentLicense: CC BY-SA 3.0


问:
multiple checkboxes with paging in php without using javascript and jquery
Good day, I have an HTML table and I use paging on it so that only a certain amount of items is shown. The problem is that I need to have multiple selections with checkboxes and that works for a single page but I need that to work between pages. So for example on page 1 you choose 3 items and in the next page you choose 5 items and when GET happens I need to have all those items in one place so that I can store them in a variable.</p>

```<code><?php
include("connect.php");     //database connection file
$limit = 7;
if ( isset($_GET['page']) ) {
    $page_no = $_GET['page'];
} else {
    $page_no = 1;
}
$start_from = ($page_no-1)*$limit;
$sql = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
$result = mysqli_query($conn , $sql);
?>

<form method="GET" action="project.php?name=<?php echo
$data['name']; ?>">
    <div class="container">
        <h2>employee information:</h2>
        <table class="table table-striped table-hover">
            <thead>
            <tr>
                <th>EmpId</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
            </thead>
            <tbody>

            <?php
            $info = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
            //query to select the data from database
            $query = mysqli_query ($conn , $info);
            while ( $data = mysqli_fetch_assoc ($query) )
            {       //query to fetch the data
                $_SESSION['emp_name']=$data['name'];
                ?>  <tr>
                <td><?php echo $data['emp_id'];?></td>
                <td>
                    <a href="project.php?id=<?php echo $data['emp_id'];?>&name=<?php echo $data['name']; ?>">
                        <input type="checkbox" name="check_list[]" value="<?php echo $data['name'];?>">
                    </a> <?php echo $data['name'];?>
                </td>
                <td><?php echo $data['email'];?></td>

            </tr>
            <?php           }
            ?>
            </tbody>
        </table>
        <ul class="pagination">
            <?php
            $sql = "SELECT COUNT(*) FROM emp_info";
            $result = mysqli_query($conn , $sql);
            $row = mysqli_fetch_row($result);
            $total_records = $row[0];
            // Number of pages required.
            $total_pages = ceil($total_records /
                $limit);
            $pagLink = "";
            for ( $i = 1; $i <= $total_pages; $i++) {
                if ( $i == $page_no) {
                    $pagLink .= "<p>Pages:</p><li class='active'><a href='datatable.php?id=" . $data['emp_id'] .
                        "&page=" . $i ."'>". $i ."</a></li>";

                } else  {
                    $pagLink .= "<li><a href='datatable.php?page=". $i ."'>". $i ."</a></li>";
                }
            };
            echo $pagLink;
            ?>
        </ul>
    </div>
      <button type="submit" formaction="project.php"
                   name="select_proj">Select Project</button>
      <button type="submit"
                   formaction="addnewproj.php"  name="add_proj">Add New
        Project</button>
</form>
</body>
</html>
</code>```

答:
I recommend reseaching abit of Javascript and more specificly aJax to solve this issue.
You need somewhere to store the information that has been selected in order to use it somewhere else.</p>

ContentLicense: CC BY-SA 4.0

Body:
Good day, I have an HTML table and I use paging on it so that only a certain amount of items is shown. The problem is that I need to have multiple selections with checkboxes and that works for a single page but I need that to work between pages. So for example on page 1 you choose 3 items and in the next page you choose 5 items and when GET happens I need to have all those items in one place so that I can store them in a variable.

<?php
include("connect.php");     //database connection file
$limit = 7;
if ( isset($_GET['page']) ) {
    $page_no = $_GET['page'];
} else {
    $page_no = 1;
}
$start_from = ($page_no-1)*$limit;
$sql = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
$result = mysqli_query($conn , $sql);
?>

<form method="GET" action="project.php?name=<?php echo
$data['name']; ?>">

employee information:

                EmpId
                Name
                Email

            <?php
            $info = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
            //query to select the data from database
            $query = mysqli_query ($conn , $info);
            while ( $data = mysqli_fetch_assoc ($query) )
            {       //query to fetch the data
                $_SESSION['emp_name']=$data['name'];
                ?>

                <?php echo $data['emp_id'];?>

                    <a href="project.php?id=<?php echo $data['emp_id'];?>&name=<?php echo $data['name']; ?>">
                        <input type="checkbox" name="check_list[]" value="<?php echo $data['name'];?>">
                     <?php echo $data['name'];?>

                <?php echo $data['email'];?>

            <?php           }
            ?>

            <?php
            $sql = "SELECT COUNT(*) FROM emp_info";
            $result = mysqli_query($conn , $sql);
            $row = mysqli_fetch_row($result);
            $total_records = $row[0];
            // Number of pages required.
            $total_pages = ceil($total_records /
                $limit);
            $pagLink = "";
            for ( $i = 1; $i <= $total_pages; $i++) {
                if ( $i == $page_no) {
                    $pagLink .= "
Pages:

". $i ."
";

                } else  {
                    $pagLink .= "
". $i ."
";
                }
            };
            echo $pagLink;
            ?>

      <button type="submit" formaction="project.php"
                   name="select_proj">Select Project</button>
      <button type="submit"
                   formaction="addnewproj.php"  name="add_proj">Add New
        Project</button>
</form>


问:
How can I jump to line in Sublime Text?
Does anyone know of a shortcut for jumping to a specific line (given a #) in Sublime Text?

Ex: I run code and get an error at line 5765. I want to be able to jump quickly in Sublime Text to line 5765, without scrolling.

答:
In My Mac， Performance>>Key Bindings add：</p>

```<code>//line duplicate & delete
{ "keys": ["super+y"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Line.sublime-macro"} },
{ "keys": ["super+d"], "command": "duplicate_line" },

//replace
{ "keys": ["super+r"], "command": "show_panel", "args": {"panel": "replace", "reverse": false} },

//goto
{ "keys": ["super+l"], "command": "show_overlay", "args": {"overlay": "goto", "text": ":"} },
{ "keys": ["super+g"], "command": "show_overlay", "args": {"overlay": "goto", "text": "@"} },

//upper or lower
{ "keys": ["super+shift+u"], "command": "swap_case" },

//sidebar toggle
{ "keys": ["super+shift+t"], "command": "toggle_side_bar" },
</code>```

Title: How can I jump to line in Sublime Text?

Body:
In My Mac， Performance>>Key Bindings add：

//line duplicate & delete
{ "keys": ["super+y"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Line.sublime-macro"} },
{ "keys": ["super+d"], "command": "duplicate_line" },

//replace
{ "keys": ["super+r"], "command": "show_panel", "args": {"panel": "replace", "reverse": false} },

//goto
{ "keys": ["super+l"], "command": "show_overlay", "args": {"overlay": "goto", "text": ":"} },
{ "keys": ["super+g"], "command": "show_overlay", "args": {"overlay": "goto", "text": "@"} },

//upper or lower
{ "keys": ["super+shift+u"], "command": "swap_case" },

//sidebar toggle
{ "keys": ["super+shift+t"], "command": "toggle_side_bar" },


问:
Getting Developer Metadata using Google Script API on Google Apps Script
I am trying to get the developer metadata about a spreadsheet using the Google Script API, as found on this website.

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata/search

I have tried the following, however I am getting no response back?  Can anyone see where I am going wrong?

```<code>    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var fileId = ss.getId();
    var token = ScriptApp.getOAuthToken();

    var paramsPost = {
        method: 'post',
        headers: {
            Authorization: 'Bearer ' + token
        },
        muteHttpExceptions: true,
        contentType: 'application/json',
        payload: JSON.stringify({
            dataFilters: [{
                developerMetadataLookup: {
                    locationType: 'COLUMN'
                }
            }]
        })
    };

    var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '?developerMetadata:search';
    var res = UrlFetchApp.fetch(url, paramsPost);
    var data = JSON.parse(res.getContentText());
</code>```

答:
You no longer need to use the REST API directly to access developer metadata.

As of November 14, 2018, methods to access developer metadata were added to the built-in Spreadsheet service. See Release Notes for details.

Body:
I am trying to get the developer metadata about a spreadsheet using the Google Script API, as found on this website.

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata/search

I have tried the following, however I am getting no response back?  Can anyone see where I am going wrong?

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var fileId = ss.getId();
    var token = ScriptApp.getOAuthToken();

    var paramsPost = {
        method: 'post',
        headers: {
            Authorization: 'Bearer ' + token
        },
        muteHttpExceptions: true,
        contentType: 'application/json',
        payload: JSON.stringify({
            dataFilters: [{
                developerMetadataLookup: {
                    locationType: 'COLUMN'
                }
            }]
        })
    };

    var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '?developerMetadata:search';
    var res = UrlFetchApp.fetch(url, paramsPost);
    var data = JSON.parse(res.getContentText());


问:
IIS error The server may not be configured for access to the requested URL
I have the following setup:

windows server 2012

visual developer 2012

IIS 7.
I have changed the authentication type on my web config file from form to windows as follow:-

But when I try to access the ASP.NET MVC site the got the following error:-

Server Error in '/' Application.

Access is denied.
Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.

Error message 401.2.: Unauthorized: Logon failed due to server configuration.  Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server.  Contact the Web server's administrator for additional assistance.

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

What could be the problem?

答:
I have following configuration in web config.

```<code><authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>
</code>```

and on login failure i am redirecting to one page. but on click of any button in the redirected page i was getting this error.

I tried the above answer of @jaydeep and it worked for me.
https://stackoverflow.com/a/39092914/6665971

Now for all other pages it will not authorized and for specific page i am able to redirect using server.transfer function.

Body:
I have following configuration in web config.

<authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>

and on login failure i am redirecting to one page. but on click of any button in the redirected page i was getting this error.

I tried the above answer of @jaydeep and it worked for me.
https://stackoverflow.com/a/39092914/6665971

Now for all other pages it will not authorized and for specific page i am able to redirect using server.transfer function.


问:
I have error for install electron on fedora 30
Hello i have this error if i try to install electron on my fedora 30

```<code>[luisjustin@localhost ~]$ sudo su
[sudo] password for luisjustin:
[root@localhost luisjustin]# npm install -g electron
/usr/bin/electron -> /usr/lib/node_modules/electron/cli.js

> electron@5.0.2 postinstall /usr/lib/node_modules/electron
> node install.js

/usr/lib/node_modules/electron/install.js:49
  throw err
  ^

Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/electron/.electron'
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! electron@5.0.2 postinstall: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the electron@5.0.2 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2019-05-30T01_21_04_805Z-debug.log
[root@localhost luisjustin]#
</code>```

the log in this link: https://pastebin.com/q3dSCQVg

答:
There seems to be an issue with permissions on your machine (/usr/lib directory requires root access). What I suggest you to try is to change the default directory where NPM is installing packages globally. Then you can try to run the installation without root access.

Try this:

On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

To test your new configuration, install a package globally without using sudo:

npm install -g electron

Courtesy:
https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally

Body:
Hello i have this error if i try to install electron on my fedora 30

[luisjustin@localhost ~]$ sudo su
[sudo] password for luisjustin:
[root@localhost luisjustin]# npm install -g electron
/usr/bin/electron -> /usr/lib/node_modules/electron/cli.js

> electron@5.0.2 postinstall /usr/lib/node_modules/electron
> node install.js

/usr/lib/node_modules/electron/install.js:49
  throw err
  ^

Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/electron/.electron'
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! electron@5.0.2 postinstall: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the electron@5.0.2 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2019-05-30T01_21_04_805Z-debug.log
[root@localhost luisjustin]#

the log in this link: https://pastebin.com/q3dSCQVg


问:
How to check if element in list matches with another element in a list of strings?

Input lists

```<code>list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
</code>```

Output list

```<code>output=['Google','AU-KBC Research Centre']
</code>```

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

答:
We can do something like follows:

out = []
excl = set(exclusion_list)
for item in list1:
    for word in item.split():
        if word in excl:
            break
    else:
        out.append(item)
```

Body:
Input lists

list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']

Output list

output=['Google','AU-KBC Research Centre']

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.


问:
Angular 2.0 router not working on reloading the browser
I am using Angular 2.0.0-alpha.30 version. When redirect to a different route, then refresh the browser , its showing Cannot GET /route.

Can you help me with figuring why this error happened.

答:
If you are using Apache or Nginx as a server you need to create a .htaccess</p>

```<code><IfModule mime_module>
      AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
    </IfModule>
    # php -- END cPanel-generated handler, do not edit

    <IfModule mod_rewrite.c>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </IfModule>
</code>```

Body:
If you are using Apache or Nginx as a server you need to create a .htaccess

<IfModule mime_module>
      AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
    </IfModule>
    # php -- END cPanel-generated handler, do not edit

    <IfModule mod_rewrite.c>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </IfModule>


问:
Check if a string has specific ending, erase this ending, then write those strings according to two other conditions
I've got a problem with preparing a readable report from my system.

I have to extract strings from "sil.catalog_no".

Firstly, I have to check if a string has ending like '-UW' and delete it.

After that, I have to extract that string (without -UW already), BUT without first part before first '-' or second '-' depending if before first '-' there is 'US'.

I know it's messed up, but I don't know how to describe it other way.

I have already tried SUBSTRING, LEFT, RIGHT and something with CHARINDEX, but my program/database/sql version(?) seems not to operate on those things and I can't find any other solution than these mentioned. Maybe it's because I don't use them correctly, I don't know.

The examples of strings contained in sil.catalog_no are:

```<code>HU-98010587
US-HU-88136FYT-719-UW
</code>```

So, in first example, I just have to check if there is '-UW' at the end. There isn't one, so I move to second step, and just remove 'HU-' and extract the rest which is '98010587'.

With the second one, I want to check and remove '-US' from the end. Then I want to erase whole 'US-HU-', because there is 'US' first and I want to get '88136FYT-719'.

EDIT:

After re-thinking the problem, I think I would like to know the way to erase specific parts of strings. Looking at image I've provided, I would like to erase all 'HU-', 'EMC-', 'US-', and '-UW' that appear in result.

答:
Another approach (tried on Postgres but also works even where there is no regex, like with SQLite3):

```<code>drop table if exists t;
create table t(s varchar(30));
insert into t values
  ('HU-98010587'),
  ('US-HU-88136FYT-719-UW'),
  ('EMC-C13-PWR-7'),
  ('EMC-CTX-OM4-10M');

with xxx(original,s) as (
  select s,substr(s,1,length(s)-3) from t where s like '%-UW'
  union
  select s,s from t where s not like '%-UW'
  )
select original,substr(s,4) s from xxx where s like 'HU-%'
union
select original,substr(s,7) s from xxx where s like 'US-HU-%'
union
select original,s from xxx where s not like 'HU-%' and s not like 'US-HU-%';
</code>```

To get what you say in your edit I would like to erase all 'HU-', 'EMC-', 'US-', and '-UW' that appear in result:

```<code>select s original,
  replace(
   replace(
    replace(
     replace(s,'HU-','')
     ,'US-','')
    ,'-UW','')
   ,'EMC-','') s
  from t;
</code>```

Body:
I've got a problem with preparing a readable report from my system.

I have to extract strings from "sil.catalog_no".

Firstly, I have to check if a string has ending like '-UW' and delete it.

After that, I have to extract that string (without -UW already), BUT without first part before first '-' or second '-' depending if before first '-' there is 'US'.

I know it's messed up, but I don't know how to describe it other way.

I have already tried SUBSTRING, LEFT, RIGHT and something with CHARINDEX, but my program/database/sql version(?) seems not to operate on those things and I can't find any other solution than these mentioned. Maybe it's because I don't use them correctly, I don't know.

The examples of strings contained in sil.catalog_no are:

HU-98010587
US-HU-88136FYT-719-UW

So, in first example, I just have to check if there is '-UW' at the end. There isn't one, so I move to second step, and just remove 'HU-' and extract the rest which is '98010587'.

With the second one, I want to check and remove '-US' from the end. Then I want to erase whole 'US-HU-', because there is 'US' first and I want to get '88136FYT-719'.

EDIT:

After re-thinking the problem, I think I would like to know the way to erase specific parts of strings. Looking at image I've provided, I would like to erase all 'HU-', 'EMC-', 'US-', and '-UW' that appear in result.

Body:
Another approach (tried on Postgres but also works even where there is no regex, like with SQLite3):

drop table if exists t;
create table t(s varchar(30));
insert into t values
  ('HU-98010587'),
  ('US-HU-88136FYT-719-UW'),
  ('EMC-C13-PWR-7'),
  ('EMC-CTX-OM4-10M');

with xxx(original,s) as (
  select s,substr(s,1,length(s)-3) from t where s like '%-UW'
  union
  select s,s from t where s not like '%-UW'
  )
select original,substr(s,4) s from xxx where s like 'HU-%'
union
select original,substr(s,7) s from xxx where s like 'US-HU-%'
union
select original,s from xxx where s not like 'HU-%' and s not like 'US-HU-%';

To get what you say in your edit I would like to erase all 'HU-', 'EMC-', 'US-', and '-UW' that appear in result:

select s original,
  replace(
   replace(
    replace(
     replace(s,'HU-','')
     ,'US-','')
    ,'-UW','')
   ,'EMC-','') s
  from t;


问:
Empty fields get submitted on form even though I have required validation in them?
I have required validation on three of my fields in my form.

When I submit with nothing in them, they get submitted to the database which crashes my program even though I have required in them.

```<code><button class="btn btn-info btn-lg" type="button" data-toggle="modal"
data-target="#myModal" tabindex="-1">Add</button>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"><button class="close" type="button" data-
dismiss="modal">×</button>
<h4 class="modal-title">Add Work Order/Service Request</h4>
</div>
<div class="modal-body">
  <div class="popup">
  <form action="{{ url_for('background_process') }}" method="POST">

           <input type="text" id="name" name="name" required />

            <input type="url" id="url" name="url" required />

            <input type ="text" id="mdp-demo" name= "mdp-demo" required />

                <a href=# id=process_input><button
 class='btn btn-default'>Submit</button></a>
        </form>
  </div>
  </div>
 </div>
</div>
</code>```

Anyone know the reason for this?

答:
    <!DOCTYPE html>

  <form action="{{ url_for('background_process') }}" method="POST">

           <input type="text" id="name" name="name" required />

            <input type="url" id="url" name="url" required />

            <input type ="text" id="mdp-demo" name= "mdp-demo" required />

                <button
 class='btn btn-default' >Submit</button>
        </form>

```

i have used the same code but it gives me

Body:
I have required validation on three of my fields in my form.

When I submit with nothing in them, they get submitted to the database which crashes my program even though I have required in them.

<button class="btn btn-info btn-lg" type="button" data-toggle="modal"
data-target="#myModal" tabindex="-1">Add</button>

<button class="close" type="button" data-
dismiss="modal">×</button>

Add Work Order/Service Request

  <form action="{{ url_for('background_process') }}" method="POST">

           <input type="text" id="name" name="name" required />

            <input type="url" id="url" name="url" required />

            <input type ="text" id="mdp-demo" name= "mdp-demo" required />

                <button
 class='btn btn-default'>Submit</button>
        </form>

Anyone know the reason for this?

Body:
    <!DOCTYPE html><html>
<head>

</head>

<body>

<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">

<div class="modal-body">
  <div class="popup">
  <form action="{{ url_for('background_process') }}" method="POST">

           <input type="text" id="name" name="name" required />

            <input type="url" id="url" name="url" required />

            <input type ="text" id="mdp-demo" name= "mdp-demo" required />

                <a href=# id=process_input><button
 class='btn btn-default' >Submit</button></a>
        </form>
  </div>
  </div>
 </div>
</div>

</body>
</html>

i have used the same code but it gives me


问:
Generate a Dataframe that follow a mathematical function for each column / row
Is there a way to create/generate a Pandas DataFrame from scratch, such that each record follows a specific mathematical function?

Background: In Financial Mathematics, very basic financial-derivatives (e.g. calls and puts) have closed-form pricing formulas (e.g. Black Scholes). These pricing formulas can be called stochastic functions (because they involve a random term)

I'm trying to create a Monte Carlo simulation of a stock price (and subseuqently an option payoff and price based on the stock price). I need, say, 1000 paths (rows) and 100 time-steps (columns). I want to "initiate" a dataframe that is 1000 by 100 and follows a stochastic equation.

```<code># Psuedo-code
MonteCarloDF = DataFrame(rows=1000, columns=100, customFunc=TRUE,
        appliedBy='by column',
        FUNC={s0=321;
              s_i=prev*exp(r-q*sqrt(sigma))*T +
                 (etc)*NormDist(rnd())*sqr(deltaT)}
        )
</code>```

Column 0 in every row would be 321, and each subsequent column would be figured out based on the FUNC above.

This is an example of something similar done in VBA

```<code>Function MonteCarlo_Vanilla_call(S, K, r, q, vol, T, N)

sum = 0
payoff = 0

For i = 1 To N
 S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd()))
 payoff = Application.Max(S_T - K, 0)
 sum = sum + payoff
Next i

MonteCarlo_Vanilla_call = Exp(-r * T) * sum / N

End Function
</code>```

Every passed in variable is a constant.
In my case, I want each next column in the same row to be just like S_T in the VBA code. That's really the only like that matters. I want to apply a function like S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd())) . Each S_T is the next column in the same row. There's N columns making one simulation. I will have, for example, 1000 simulations.

```<code>321     | 322.125 | 323.277 | ... | column 100 value
321     | 320.704 | 319.839 | ... | column 100 value
321     | 321.471 | 318.456 | ... | column 100 value
...
row 1000| etc     | etc     | ... | value (1000,100)
</code>```

答:
To me your problem is a specific version of the following one: Pandas calculations based on other rows. Since you can pivot it shouldn't matter if we are talking rows or columns.

There is also a question relating to calculations using columns: Pandas complex calculation based on other columns which has a good suggestion of using a rolling window (rolling function) or using shift function: Calculate the percentage increase or decrease based on the previous column value of the same row in pandas dataframe

Speed considerations of similar calculations (or numpy vs pandas discussion): Numpy, Pandas: what is the fastest way to calculate dataset row value basing on previous N values?

To sum it all up - it seems that your question is somewhat of a duplicate.

Body:
Is there a way to create/generate a Pandas DataFrame from scratch, such that each record follows a specific mathematical function?

Background: In Financial Mathematics, very basic financial-derivatives (e.g. calls and puts) have closed-form pricing formulas (e.g. Black Scholes). These pricing formulas can be called stochastic functions (because they involve a random term)

I'm trying to create a Monte Carlo simulation of a stock price (and subseuqently an option payoff and price based on the stock price). I need, say, 1000 paths (rows) and 100 time-steps (columns). I want to "initiate" a dataframe that is 1000 by 100 and follows a stochastic equation.

# Psuedo-code
MonteCarloDF = DataFrame(rows=1000, columns=100, customFunc=TRUE,
        appliedBy='by column',
        FUNC={s0=321;
              s_i=prev*exp(r-q*sqrt(sigma))*T +
                 (etc)*NormDist(rnd())*sqr(deltaT)}
        )

Column 0 in every row would be 321, and each subsequent column would be figured out based on the FUNC above.

This is an example of something similar done in VBA

Function MonteCarlo_Vanilla_call(S, K, r, q, vol, T, N)

sum = 0
payoff = 0

For i = 1 To N
 S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd()))
 payoff = Application.Max(S_T - K, 0)
 sum = sum + payoff
Next i

MonteCarlo_Vanilla_call = Exp(-r * T) * sum / N

End Function

Every passed in variable is a constant.
In my case, I want each next column in the same row to be just like S_T in the VBA code. That's really the only like that matters. I want to apply a function like S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd())) . Each S_T is the next column in the same row. There's N columns making one simulation. I will have, for example, 1000 simulations.

321     | 322.125 | 323.277 | ... | column 100 value
321     | 320.704 | 319.839 | ... | column 100 value
321     | 321.471 | 318.456 | ... | column 100 value
...
row 1000| etc     | etc     | ... | value (1000,100)


问:
how can I distinguish from detail_page to the list_page?
How can I distinguish the

I have a Vue project, when I from list_page go to its detail_page, then I can use the this.$router.go(-1) to go back to the list_page.

and I can from other_pages to the the list_page, but how can I distinguish  the two ways to the list_page?

答: You can use router.push method like router.push('/path-string'). Here path-string will be from 'router.js' where you have defined all routers. This method will change current route path.</p>


问:
Why so many instances of ASP.NET Development Server?
I am debugging a large web application solution, with the main web application project as a single startup project, configured to use IIS for debugging.  Whenever I run this application inside Visual Studio 2010, I still get multiple instances (sometimes over 15) of the  ASP.NET Development Server starting up as well.  Why does this occur? </p>

答:
My setup is similar to yours (except I use CassiniDev ( http://cassinidev.codeplex.com/ ))

Go to all your secondary sites project properties : click "use Custom Web Server", set something in "Server Url" (for exemple http://your-iis-server:your_port/your_project, but it may be even invalid)..

This will prevent the automatic startup of Cassini for the secondary web sites.

Leave your main site in the original configuration.


问:
How to pass form fields into 'templated' HTML file
I would like to get form data from a pre-built HTML template using a Django form without changing the display.

I know I could use something like:

```<code>name = request.POST.get('first_name')
</code>```

But would like to handle the data using a ModelForm

forms.py

```<code>class BioDataForm(forms.ModelForm):

    first_name = forms.CharField(max_length=100, label='first_name')
    last_name =forms.CharField(max_length=100, label='last_name')
    mobile = forms.CharField(max_length=100, label='mobile_number')
    email = forms.EmailField(max_length=100, label='personal_email')
    gender = forms.CharField(max_length=100, widget=forms.Select(attrs={'class': 'form-control', 'id': 'gender'}))
    marital_status = forms.CharField(max_length=100, widget=forms.Select(attrs={'class': 'form-control', 'id': 'marital_status'}))
    date_of_birth = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.SelectDateWidget())
    address = forms.CharField(max_length=100)

    class Meta:
        model = BioData
        exclude = ('state',)
        fields = ['first_name', 'last_name', 'mobile', 'email',
                'gender', 'marital_status', 'date_of_birth', 'address']
</code>```

Sample HTML

```<code><div class="row form-group">
   <div class="col-md-6 col-sm-12 margin-bottom-20-m">
       <label for="first_name" class="form-control-label kt-black-text">First Name</label>
       <input type="text" class="form-control" id="first_name" name="e_first_name" required>
   </div>
   <div class="col-md-6 col-sm-12">
       <label for="last_name" class="form-control-label kt-black-text">Last Name</label>
       <input type="text" class="form-control" id="last_name" name="e_last_name" required>
   </div>
</div>
</code>```

答:
iterate form in template : </p>

```<code><div class="row form-group">
   {% for field in form %}
   <div class="col-md-6 col-sm-12 margin-bottom-20-m">
       <label for="{{ field.id_for_label }}" class="form-control-label kt-black-text">{{ field.label }}</label>
       {{ field }}
   </div>
   {% endfor %}
</div>
</code>```

Body:
I would like to get form data from a pre-built HTML template using a Django form without changing the display.

I know I could use something like:

name = request.POST.get('first_name')

But would like to handle the data using a ModelForm

forms.py

class BioDataForm(forms.ModelForm):

    first_name = forms.CharField(max_length=100, label='first_name')
    last_name =forms.CharField(max_length=100, label='last_name')
    mobile = forms.CharField(max_length=100, label='mobile_number')
    email = forms.EmailField(max_length=100, label='personal_email')
    gender = forms.CharField(max_length=100, widget=forms.Select(attrs={'class': 'form-control', 'id': 'gender'}))
    marital_status = forms.CharField(max_length=100, widget=forms.Select(attrs={'class': 'form-control', 'id': 'marital_status'}))
    date_of_birth = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.SelectDateWidget())
    address = forms.CharField(max_length=100)

    class Meta:
        model = BioData
        exclude = ('state',)
        fields = ['first_name', 'last_name', 'mobile', 'email',
                'gender', 'marital_status', 'date_of_birth', 'address']

Sample HTML

       First Name
       <input type="text" class="form-control" id="first_name" name="e_first_name" required>

       Last Name
       <input type="text" class="form-control" id="last_name" name="e_last_name" required>

Body:
iterate form in template :

<div class="row form-group">
   {% for field in form %}
   <div class="col-md-6 col-sm-12 margin-bottom-20-m">
       <label for="{{ field.id_for_label }}" class="form-control-label kt-black-text">{{ field.label }}</label>
       {{ field }}
   </div>
   {% endfor %}
</div>


问:
Gradle .execute method showing error after gradle update
My project was running perfect with gradle plugin version 3.0.1 after updating to version 3.4.1 I am going through sync failure.

Previously I was using wrapper 4.10.1 which is now updated to 5.1.1.

```<code>afterEvaluate(new Action<Project>() {

@Override
void execute(Project project) {
    tasks.getByName("assembleRelease").doLast {
        tasks.copyReleaseBuild.execute() //error is here
        tasks.copyReleaseBuildToXX.execute()
        tasks.copyReleaseBuildToXXXX.execute()
    }
}
</code>```

copyReleaseBuild task is written something like below...

```<code>task copyReleaseBuild(type: Copy) {
    def releaseDir = getProjectProperty('releaseDir')
    if (releaseDir?.trim()) {
    //if release folder is provided
    def releaseAarFile =
            getProjectProperty('sourceCodeDir') + "/android-corekit/kit/build/outputs/aar/kit-release.aar"
    from releaseAarFile
    into releaseDir
    }

task copyReleaseBuildToXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapper/libs"
    }

task copyReleaseBuildToXXXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapperapp/libs"
    }
}
</code>```

I have been trying to resolve from last two days but nothing is working as I lack knowledge of groovy.

Please check error log I am getting while building the project...

答:
It happens because you are using an updated version of gradle (check the migration to gradle v5)

The following properties and methods of TaskInternal have been removed — use task dependencies, task rules, reusable utility methods, or the Worker API in place of executing a task directly.

execute()

executer

getValidators()

addValidator()

Now you can't call the execute method directly, but you have to use the tasks dependencies to obtain the same result.

Just define in your build.gradle:

```<code>task copyReleaseBuild {
    dependsOn 'assembleRelease'
    //...
}
</code>```

and remove this:

```<code>afterEvaluate(new Action<Project>() {

@Override
void execute(Project project) {
    tasks.getByName("assembleRelease").doLast {
        tasks.copyReleaseBuild.execute() //error is here
    }
}
</code>```

Body:
My project was running perfect with gradle plugin version 3.0.1 after updating to version 3.4.1 I am going through sync failure.

Previously I was using wrapper 4.10.1 which is now updated to 5.1.1.

afterEvaluate(new Action<Project>() {

@Override
void execute(Project project) {
    tasks.getByName("assembleRelease").doLast {
        tasks.copyReleaseBuild.execute() //error is here
        tasks.copyReleaseBuildToXX.execute()
        tasks.copyReleaseBuildToXXXX.execute()
    }
}

copyReleaseBuild task is written something like below...

task copyReleaseBuild(type: Copy) {
    def releaseDir = getProjectProperty('releaseDir')
    if (releaseDir?.trim()) {
    //if release folder is provided
    def releaseAarFile =
            getProjectProperty('sourceCodeDir') + "/android-corekit/kit/build/outputs/aar/kit-release.aar"
    from releaseAarFile
    into releaseDir
    }

task copyReleaseBuildToXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapper/libs"
    }

task copyReleaseBuildToXXXX(type: Copy) {
        from "./build/outputs/aar/kit-release.aar"
        into "../kitwrapperapp/libs"
    }
}

I have been trying to resolve from last two days but nothing is working as I lack knowledge of groovy.

Please check error log I am getting while building the project...

Body:
It happens because you are using an updated version of gradle (check the migration to gradle v5)

The following properties and methods of TaskInternal have been removed — use task dependencies, task rules, reusable utility methods, or the Worker API in place of executing a task directly.

execute()

executer

getValidators()

addValidator()

Now you can't call the execute method directly, but you have to use the tasks dependencies to obtain the same result.

Just define in your build.gradle:

task copyReleaseBuild {
    dependsOn 'assembleRelease'
    //...
}

and remove this:

afterEvaluate(new Action<Project>() {

@Override
void execute(Project project) {
    tasks.getByName("assembleRelease").doLast {
        tasks.copyReleaseBuild.execute() //error is here
    }
}


问:
Change Google Watermark GoogleMaps SDK
Is there any way to change the "Google" watermark Style in the bottom left corner of the Map in the GoogleMaps SDK? I have seen some Apps that change this logo to be white whitout black borders and I cant find any information about how to achieve this. I have only find a page to set the style of the map but not the logo.

答:
You can not directly change color of logo. Hiding/overlapping logo is legally not allowed.

But you can change style of a map layout. see https://mapstyle.withgoogle.com/

Download your json file for selected theme, put that in raw folder in res and write following code.

```<code>mMap = googleMap;
MapStyleOptions mapStyle = MapStyleOptions.loadRawResourceStyle(this,
R.raw.map_style_json);
mMap.setMapStyle(mapStyle);
</code>```

--

According to your style color combinations, logo will be colored automatically.(e.g Dark theme -> light logo and vice a versa)

Title: Change Google Watermark GoogleMaps SDK

Body:
You can not directly change color of logo. Hiding/overlapping logo is legally not allowed.

But you can change style of a map layout. see https://mapstyle.withgoogle.com/

Download your json file for selected theme, put that in raw folder in res and write following code.

mMap = googleMap;
MapStyleOptions mapStyle = MapStyleOptions.loadRawResourceStyle(this,
R.raw.map_style_json);
mMap.setMapStyle(mapStyle);

--

According to your style color combinations, logo will be colored automatically.(e.g Dark theme -> light logo and vice a versa)


问:
How do you iterate through every file/directory recursively in standard C++?
How do you iterate through every file/directory recursively in standard C++?</p>

答:
We are in 2019. We have filesystem standard library in C++. The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories.

There is an important note on this link if you are considering portability issues. It says:

The filesystem library facilities may be unavailable if a hierarchical file system is not accessible to the implementation, or if it does not provide the necessary capabilities. Some features may not be available if they are not supported by the underlying file system (e.g. the FAT filesystem lacks symbolic links and forbids multiple hardlinks). In those cases, errors must be reported.

The filesystem library was originally developed as boost.filesystem, was published as the technical specification ISO/IEC TS 18822:2015, and finally merged to ISO C++ as of C++17. The boost implementation is currently available on more compilers and platforms than the C++17 library.

@adi-shavit has answered this question when it was part of std::experimental and he has updated this answer in 2017. I want to give more details about the library and show more detailed example.

std::filesystem::recursive_directory_iterator is an LegacyInputIterator that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once.

If you don't want to recursively iterate over the entries of subdirectories, then directory_iterator should be used.

Both iterators returns an object of directory_entry. directory_entry has various useful member functions like is_regular_file, is_directory, is_socket, is_symlink etc. The path() member function returns an object of std::filesystem::path and it can be used to get file extension, filename, root name.

Consider the example below. I have been using Ubuntu and compiled it over the terminal using

g++ example.cpp --std=c++17 -lstdc++fs -Wall

```<code>#include <iostream>
#include <string>
#include <filesystem>

void listFiles(std::string path)
{
    for (auto& dirEntry: std::filesystem::recursive_directory_iterator(path)) {
        if (!dirEntry.is_regular_file()) {
            std::cout << "Directory: " << dirEntry.path() << std::endl;
            continue;
        }
        std::filesystem::path file = dirEntry.path();
        std::cout << "Filename: " << file.filename() << " extension: " << file.extension() << std::endl;

    }
}

int main()
{
    listFiles("./");
    return 0;
}
</code>```

Body:
We are in 2019. We have filesystem standard library in C++. The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories.

There is an important note on this link if you are considering portability issues. It says:

The filesystem library facilities may be unavailable if a hierarchical file system is not accessible to the implementation, or if it does not provide the necessary capabilities. Some features may not be available if they are not supported by the underlying file system (e.g. the FAT filesystem lacks symbolic links and forbids multiple hardlinks). In those cases, errors must be reported.

The filesystem library was originally developed as boost.filesystem, was published as the technical specification ISO/IEC TS 18822:2015, and finally merged to ISO C++ as of C++17. The boost implementation is currently available on more compilers and platforms than the C++17 library.

@adi-shavit has answered this question when it was part of std::experimental and he has updated this answer in 2017. I want to give more details about the library and show more detailed example.

std::filesystem::recursive_directory_iterator is an LegacyInputIterator that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once.

If you don't want to recursively iterate over the entries of subdirectories, then directory_iterator should be used.

Both iterators returns an object of directory_entry. directory_entry has various useful member functions like is_regular_file, is_directory, is_socket, is_symlink etc. The path() member function returns an object of std::filesystem::path and it can be used to get file extension, filename, root name.

Consider the example below. I have been using Ubuntu and compiled it over the terminal using

g++ example.cpp --std=c++17 -lstdc++fs -Wall

#include <iostream>
#include <string>
#include <filesystem>

void listFiles(std::string path)
{
    for (auto& dirEntry: std::filesystem::recursive_directory_iterator(path)) {
        if (!dirEntry.is_regular_file()) {
            std::cout << "Directory: " << dirEntry.path() << std::endl;
            continue;
        }
        std::filesystem::path file = dirEntry.path();
        std::cout << "Filename: " << file.filename() << " extension: " << file.extension() << std::endl;

    }
}

int main()
{
    listFiles("./");
    return 0;
}


问:
2x one-to-many relationships in OO
Imagine these relationships:

1 A has many B's

1 B has many C's...

In reverse:

C has 1 B

B has 1A

By transitivity, C has 1 A

To model this relationship in DB, we have:

```<code>TableA
a_id

TableB
b_id
a_id (fk to TableA)

TableC
c_id
b_id (fk to TableB)
</code>```

To model this relationship in OO, we have:

```<code>objA
objB
objC
</code>```

And...
- objB has reference to objA
- objC has reference to objB

If objC has a method that needs to call a method of objA, what will you do?

Option 1.

```<code>b.getA().runMethodX()
</code>```

Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense.  Doing so is just like doing procedural programming.  Agree/Disagree?

Option 2.

Let objC has direct reference to objA and objB through constructor injection / setter

Is this a good idea?  but then objB that objC has reference to also has reference to objA.  Is this okay?  Or as long as it is not a case of cyclic object references, it is acceptable?

Option 3.

Move the method in question to objA, and pass objC in by parameter.

I'm not sure if this considers as an option.  I think it'll not work in every case.  Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.

Option 4.  (Delegation)

add runMethodXinA() to B, it calls

```<code>a.runMethodX()
</code>```

C calls

```<code>b.runMethodXinA()
</code>```

I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?

What are your though?  Any other options?  Comments?  Suggestions?

答:
from your list of choices, the choice is option 4, as it obeys the Law of Demeter

option 1 violates the Law of Demeter

option 2 introduces redundant references and violates the Law of Demeter indirectly

option 3 pollutes object A with knowledge of object C, which arguably also violates the Law of Demeter (in reverse)

that leaves option 4

there may be an option 5, but that is beyond the scope of the original question ;-)

OwnerDisplayName: Henry

Title: 2x one-to-many relationships in OO

Body:
Imagine these relationships:

1 A has many B's

1 B has many C's...

In reverse:

C has 1 B

B has 1A

By transitivity, C has 1 A

To model this relationship in DB, we have:

TableA
a_id

TableB
b_id
a_id (fk to TableA)

TableC
c_id
b_id (fk to TableB)

To model this relationship in OO, we have:

objA
objB
objC

And...
- objB has reference to objA
- objC has reference to objB

If objC has a method that needs to call a method of objA, what will you do?

Option 1.

b.getA().runMethodX()

Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense.  Doing so is just like doing procedural programming.  Agree/Disagree?

Option 2.

Let objC has direct reference to objA and objB through constructor injection / setter

Is this a good idea?  but then objB that objC has reference to also has reference to objA.  Is this okay?  Or as long as it is not a case of cyclic object references, it is acceptable?

Option 3.

Move the method in question to objA, and pass objC in by parameter.

I'm not sure if this considers as an option.  I think it'll not work in every case.  Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.

Option 4.  (Delegation)

add runMethodXinA() to B, it calls

a.runMethodX()

C calls

b.runMethodXinA()

I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?

What are your though?  Any other options?  Comments?  Suggestions?

LastEditorDisplayName: cletus

OwnerDisplayName: Steven A. Lowe

ContentLicense: CC BY-SA 2.5


问:
How to filter in laravel using middleware?
I am trying to finer all active courses and here is what I've tried.

Middleware is called Status

```<code>public function handle($request, Closure $next)
    {
      $status = $request->status();
      if($status == 'active'){
        return view('admin.courses.index');
      }

        return $next($request);
    }
</code>```

My route calls the middleware

```<code>Route::get('admin/courses/?active', 'Admin\CoursesController@index')->middleware('status');
</code>```

My view has a button that calls the route

```<code><a href="{{ route('admin.courses.index') }}" style="margin-left:10px;" class="btn btn-success">
            Active <span class="badge badge-light">{{$course_count_active}}</span>
          <span class="sr-only">total courses</span></a>
</code>```

This code is not filtering the records and I'm not sure what I'm doing wrong.

答:
First of all the correct syntax for giving parameter is {parameter?}

Now second want to ask you did you register your middleware in kernel.php file (i guess you did but still need to confirm)

now your button giving no parameter to route

```<code>{{ route('admin.courses.index') }}
</code>```

which means your middleware will run $next($request)

so if you need to see the view part(which you saying filter) , do it like that {{ route('admin.courses.index',['status'=>'active']) }}

now last give named route, if you don't give name route then you can't call route(), give name route like below

```<code>Route::get('admin/courses/{status?}', 'Admin\CoursesController@index')->name('admin.courses.index')->middleware('status');
</code>```

and give parameter name status like above

Update

Another mistake you can't get parameter as you did.

```<code>$status = $request->status();
</code>```

simply write below

```<code>$status = $request->status;
</code>```

Update

So now you facing error setCooking on member function because you return view('someview') form middleware which is not a good practice at all.

in the middleware use redirect() to some route.
so I suggest you make a route in which you return view.

and redirect to this route from middleware will solve your problem.

Body:
I am trying to finer all active courses and here is what I've tried.

Middleware is called Status

public function handle($request, Closure $next)
    {
      $status = $request->status();
      if($status == 'active'){
        return view('admin.courses.index');
      }

        return $next($request);
    }

My route calls the middleware

Route::get('admin/courses/?active', 'Admin\CoursesController@index')->middleware('status');

My view has a button that calls the route

            Active {{$course_count_active}}
          total courses

This code is not filtering the records and I'm not sure what I'm doing wrong.

Body:
First of all the correct syntax for giving parameter is {parameter?}

Now second want to ask you did you register your middleware in kernel.php file (i guess you did but still need to confirm)

now your button giving no parameter to route

{{ route('admin.courses.index') }}

which means your middleware will run $next($request)

so if you need to see the view part(which you saying filter) , do it like that {{ route('admin.courses.index',['status'=>'active']) }}

now last give named route, if you don't give name route then you can't call route(), give name route like below

Route::get('admin/courses/{status?}', 'Admin\CoursesController@index')->name('admin.courses.index')->middleware('status');

and give parameter name status like above

Update

Another mistake you can't get parameter as you did.

$status = $request->status();

simply write below

$status = $request->status;

Update

So now you facing error setCooking on member function because you return view('someview') form middleware which is not a good practice at all.

in the middleware use redirect() to some route.
so I suggest you make a route in which you return view.

and redirect to this route from middleware will solve your problem.


问:
Convert a dataframe to a list of lists based on common features
I have a large data frame which I would like to transform into a list of lists. The lists would be split by the column names of the data frame.
The data frame looks like this.

```<code>df1 <- data.frame(TP1.expression =c(3, 8, 2),
                  TP1.pval = c(0.04, 0.03, 0.01),
                  TP1.log2fc = c(1, 0.3, 2.1),
                  TP2.expression =c(2, 4, 2.1),
                  TP2.pval = c(0.024, 0.02, 0.01),
                  TP2.log2fc = c(-1, 0.1, 3.1),
                  row.names = c('GeneA', 'GeneB', 'GeneC'))
</code>```

I would like to transform df1 into a list of lists. The list structure would ideally be as followed.

```<code>list1
   TP1
      TP1.expression       3, 8, 2
      TP1.pval             0.04, 0.03, 0.01
      TP1.log2fc           1, 0.3, 2.1
   TP2
      TP2.expression       2, 4, 2.1
      TP2.pval             0.024, 0.02, 0.01
      TP2.log2fc           -1, 0.1, 3.1
</code>```

So the list would split be the integer found between TP and the . characters.

I have managed to split the data frame into smaller data frames and the re-combined these into a list but the method used was too specific. I am looking for something more generic to turn into a function.

The example below will seperate df1 into five different data frames which can then be re-sorted into a list. I am looking for cleaner ways of doing this.

```<code>tp <- c(1, 2, 3, 10, 14)
timepoint <- 'TP'
for (i in tp) {
  common <- paste0(timepoint, i)
  assign(common, df1[, grep(paste0(common, "\\."),   colnames(df1), ignore.case = T)])
  X <- list(TP1, TP2, TP3, TP10, TP14)
}

</code>```

Help would be very appreciated.

答:
We could use split.default to split the columns based on names of the dataframe and then use as.list to create lists of list.

```<code>lapply(split.default(df1, sub("(TP\\d+).*", "\\1", names(df1))), as.list)

#$TP1
#$TP1$TP1.expression
#[1] 3 8 2

#$TP1$TP1.pval
#[1] 0.04 0.03 0.01

#$TP1$TP1.log2fc
#[1] 1.0 0.3 2.1

#$TP2
#$TP2$TP2.expression
#[1] 2.0 4.0 2.1

#$TP2$TP2.pval
#[1] 0.024 0.020 0.010

#$TP2$TP2.log2fc
#[1] -1.0  0.1  3.1
</code>```

Body:
I have a large data frame which I would like to transform into a list of lists. The lists would be split by the column names of the data frame.
The data frame looks like this.

df1 <- data.frame(TP1.expression =c(3, 8, 2),
                  TP1.pval = c(0.04, 0.03, 0.01),
                  TP1.log2fc = c(1, 0.3, 2.1),
                  TP2.expression =c(2, 4, 2.1),
                  TP2.pval = c(0.024, 0.02, 0.01),
                  TP2.log2fc = c(-1, 0.1, 3.1),
                  row.names = c('GeneA', 'GeneB', 'GeneC'))

I would like to transform df1 into a list of lists. The list structure would ideally be as followed.

list1
   TP1
      TP1.expression       3, 8, 2
      TP1.pval             0.04, 0.03, 0.01
      TP1.log2fc           1, 0.3, 2.1
   TP2
      TP2.expression       2, 4, 2.1
      TP2.pval             0.024, 0.02, 0.01
      TP2.log2fc           -1, 0.1, 3.1

So the list would split be the integer found between TP and the . characters.

I have managed to split the data frame into smaller data frames and the re-combined these into a list but the method used was too specific. I am looking for something more generic to turn into a function.

The example below will seperate df1 into five different data frames which can then be re-sorted into a list. I am looking for cleaner ways of doing this.

tp <- c(1, 2, 3, 10, 14)
timepoint <- 'TP'
for (i in tp) {
  common <- paste0(timepoint, i)
  assign(common, df1[, grep(paste0(common, "\\."),   colnames(df1), ignore.case = T)])
  X <- list(TP1, TP2, TP3, TP10, TP14)
}

Help would be very appreciated.

Body:
We could use split.default to split the columns based on names of the dataframe and then use as.list to create lists of list.

lapply(split.default(df1, sub("(TP\\d+).*", "\\1", names(df1))), as.list)

#$TP1
#$TP1$TP1.expression
#[1] 3 8 2

#$TP1$TP1.pval
#[1] 0.04 0.03 0.01

#$TP1$TP1.log2fc
#[1] 1.0 0.3 2.1

#$TP2
#$TP2$TP2.expression
#[1] 2.0 4.0 2.1

#$TP2$TP2.pval
#[1] 0.024 0.020 0.010

#$TP2$TP2.log2fc
#[1] -1.0  0.1  3.1


问:
Environment variable not being picked up by Node/Express/Nuxt app
I am trying to setup SendGrid with my Vue/Nuxt app, however I can only get it to to work by hardcoding the API key. When I try to use the preferred environment variable method, I get an unauthorized error. This is because the app is not picking up the variable, instead it returns Undefined.

How do I make the app get the variable?

My API KEY is kept in a filed called sendgrid.env in the project root.

I then have a Node/Express app running within my Nuxt project with the following code:

```<code>const express = require('express')
const app = express()

app.get('/', (req, res, next) => {
  res.send('API root')
})

app.get('/sendmail', (req, res, next) => {

// using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
    to: 'somebody@something.net',
    from: 'no-reply@somewhereelse.com',
    subject: 'Test SendGrid',
    text: 'This is a test of the SendGrid app on Node',
    html: '<strong>This is a test of the SendGrid app on Node</strong>',
};

sgMail.send(msg);

res.send('SendMail API');

})

// export the server middleware
module.exports = {
  path: '/api',
  handler: app
}
</code>```

I have tested the code using Curl and also by hardcoding the API Key, so the key is correct, it's just the environment variable that's not being picked up.

What am I doing wrong?

答:
Do you have "dotenv": "^6.2.0" in the dependencies section of your package.json file?

And require('dotenv').config(); in your main JS file?

Those lines are required to get it work.

Body:
I am trying to setup SendGrid with my Vue/Nuxt app, however I can only get it to to work by hardcoding the API key. When I try to use the preferred environment variable method, I get an unauthorized error. This is because the app is not picking up the variable, instead it returns Undefined.

How do I make the app get the variable?

My API KEY is kept in a filed called sendgrid.env in the project root.

I then have a Node/Express app running within my Nuxt project with the following code:

const express = require('express')
const app = express()

app.get('/', (req, res, next) => {
  res.send('API root')
})

app.get('/sendmail', (req, res, next) => {

// using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
    to: 'somebody@something.net',
    from: 'no-reply@somewhereelse.com',
    subject: 'Test SendGrid',
    text: 'This is a test of the SendGrid app on Node',
    html: 'This is a test of the SendGrid app on Node',
};

sgMail.send(msg);

res.send('SendMail API');

})

// export the server middleware
module.exports = {
  path: '/api',
  handler: app
}

I have tested the code using Curl and also by hardcoding the API Key, so the key is correct, it's just the environment variable that's not being picked up.

What am I doing wrong?


问:
Ignore output - it should not print on screen
I can add LogOnAsAService privilege to a specific user or groups. While running the function, it is showing output.

My requirement is it should not print the output.

I have below working function for logon as a service right.

```<code>#region LogOnAsService-Right
Function LogOnAsService-Right
{
param(
[string] $Servername = ("{0}.{1}" -f $env:COMPUTERNAME.ToLower(), $env:USERDNSDOMAIN.ToLower()),
[string] $username = ("{0}\{1}" -f $env:USERDOMAIN, $env:USERNAME)
)
try{
Invoke-Command -ComputerName $Servername -Script {
param([string] $username)
$tempPath = [System.IO.Path]::GetTempPath()
$import = Join-Path -Path $tempPath -ChildPath "import.inf"
if(Test-Path $import) { Remove-Item -Path $import -Force }
$export = Join-Path -Path $tempPath -ChildPath "export.inf"
if(Test-Path $export) { Remove-Item -Path $export -Force }
$secedt = Join-Path -Path $tempPath -ChildPath "secedt.sdb"
if(Test-Path $secedt) { Remove-Item -Path $secedt -Force }
try {
Write-Host ("Granting SeServiceLogonRight to user account: {0} on host: {1}." -f $username, $Servername)
$sid = ((New-Object System.Security.Principal.NTAccount($username)).Translate([System.Security.Principal.SecurityIdentifier])).Value
secedit /export /cfg $export
$sids = (Select-String $export -Pattern "SeServiceLogonRight").Line
foreach ($line in @("[Unicode]", "Unicode=yes", "[System Access]", "[Event Audit]", "[Registry Values]", "[Version]", "signature=`"`$CHICAGO$`"", "Revision=1", "[Profile Description]", "Description=GrantLogOnAsAService security template", "[Privilege Rights]", "$sids,*$sid")){
Add-Content $import $line
}
secedit /import /db $secedt /cfg $import
secedit /configure /db $secedt
gpupdate /force
Remove-Item -Path $import -Force
Remove-Item -Path $export -Force
Remove-Item -Path $secedt -Force
} catch {
Write-Host ("Failed to grant SeServiceLogonRight to user account: {0} on host: {1}." -f $username, $Servername)
$error[0]
}
} -ArgumentList $username

}
catch
{
$_.exception.message
}
}
#endregion
</code>```

Expected result: It should not print every step on the screen.

Actual result - It is printing every step:

```
The task has completed successfully.
See log %windir%\security\logs\scesrv.log for detail info.
Completed 1 percent (0/63)  Process Privilege Rights area
Completed 3 percent (1/63)  Process Privilege Rights area
Completed 4 percent (2/63)  Process Privilege Rights area
Completed 6 percent (3/63)  Process Privilege Rights area
Completed 7 percent (4/63)  Process Privilege Rights area
Completed 9 percent (5/63)  Process Privilege Rights area
Completed 11 percent (6/63)     Process Privilege Rights area
Completed 12 percent (7/63)     Process Privilege Rights area
Completed 14 percent (8/63)     Process Privilege Rights area
Completed 15 percent (9/63)     Process Privilege Rights area
Completed 17 percent (10/63)    Process Privilege Rights area
Completed 19 percent (11/63)    Process Privilege Rights area
Completed 20 percent (12/63)    Process Privilege Rights area
Completed 22 percent (13/63)    Process Privilege Rights area
Completed 23 percent (14/63)    Process Privilege Rights area
Completed 25 percent (15/63)    Process Privilege Rights area
Completed 25 percent (15/63)    Process Group Membership area
Completed 49 percent (30/63)    Process Group Membership area
Completed 49 percent (30/63)    Process Registry Keys area
Completed 49 percent (30/63)    Process File Security area
Completed 49 percent (30/63)    Process Services area
Completed 65 percent (40/63)    Process Services area
Completed 73 percent (45/63)    Process Services area
Completed 73 percent (45/63)    Process Security Policy area
Completed 77 percent (48/63)    Process Security Policy area
Completed 84 percent (52/63)    Process Security Policy area
Completed 88 percent (55/63)    Process Security Policy area
Completed 93 percent (58/63)    Process Security Policy area
Completed 100 percent (63/63)   Process Security Policy area

The task has completed successfully.
See log %windir%\security\logs\scesrv.log for detail info.
Updating policy...

Computer Policy update has completed successfully.

User Policy update has completed successfully.
```

答:
The output is coming from the second secedit.

Secedit has an optional paramater called /quiet which suppresses screen and log output. You can still view analysis results by using the Security Configuration and Analysis snap-in to the Microsoft Management Console (MMC).

like:

```<code>Secedit /configure /db <database file name> [/cfg <configuration file name>] [/overwrite] [/areas SECURITYPOLICY | GROUP_MGMT | USER_RIGHTS | REGKEYS | FILESTORE | SERVICES] [/log <log file name>] [/quiet]
</code>```

In your case:

```<code>secedit /configure /db $secedt /quiet
</code>```

Or forcefully, you can make PS to do that using Out-Null or redirect it to $Null

```<code>secedit /configure /db $secedt | Out-Null

secedit /configure /db $secedt > $null
</code>```

All should work.

Hope it helps.

Body:
I can add LogOnAsAService privilege to a specific user or groups. While running the function, it is showing output.

My requirement is it should not print the output.

I have below working function for logon as a service right.

#region LogOnAsService-Right
Function LogOnAsService-Right
{
param(
[string] $Servername = ("{0}.{1}" -f $env:COMPUTERNAME.ToLower(), $env:USERDNSDOMAIN.ToLower()),
[string] $username = ("{0}\{1}" -f $env:USERDOMAIN, $env:USERNAME)
)
try{
Invoke-Command -ComputerName $Servername -Script {
param([string] $username)
$tempPath = [System.IO.Path]::GetTempPath()
$import = Join-Path -Path $tempPath -ChildPath "import.inf"
if(Test-Path $import) { Remove-Item -Path $import -Force }
$export = Join-Path -Path $tempPath -ChildPath "export.inf"
if(Test-Path $export) { Remove-Item -Path $export -Force }
$secedt = Join-Path -Path $tempPath -ChildPath "secedt.sdb"
if(Test-Path $secedt) { Remove-Item -Path $secedt -Force }
try {
Write-Host ("Granting SeServiceLogonRight to user account: {0} on host: {1}." -f $username, $Servername)
$sid = ((New-Object System.Security.Principal.NTAccount($username)).Translate([System.Security.Principal.SecurityIdentifier])).Value
secedit /export /cfg $export
$sids = (Select-String $export -Pattern "SeServiceLogonRight").Line
foreach ($line in @("[Unicode]", "Unicode=yes", "[System Access]", "[Event Audit]", "[Registry Values]", "[Version]", "signature=`"`$CHICAGO$`"", "Revision=1", "[Profile Description]", "Description=GrantLogOnAsAService security template", "[Privilege Rights]", "$sids,*$sid")){
Add-Content $import $line
}
secedit /import /db $secedt /cfg $import
secedit /configure /db $secedt
gpupdate /force
Remove-Item -Path $import -Force
Remove-Item -Path $export -Force
Remove-Item -Path $secedt -Force
} catch {
Write-Host ("Failed to grant SeServiceLogonRight to user account: {0} on host: {1}." -f $username, $Servername)
$error[0]
}
} -ArgumentList $username

}
catch
{
$_.exception.message
}
}
#endregion

Expected result: It should not print every step on the screen.

Actual result - It is printing every step:

The task has completed successfully.
See log %windir%\security\logs\scesrv.log for detail info.
Completed 1 percent (0/63)  Process Privilege Rights area
Completed 3 percent (1/63)  Process Privilege Rights area
Completed 4 percent (2/63)  Process Privilege Rights area
Completed 6 percent (3/63)  Process Privilege Rights area
Completed 7 percent (4/63)  Process Privilege Rights area
Completed 9 percent (5/63)  Process Privilege Rights area
Completed 11 percent (6/63)     Process Privilege Rights area
Completed 12 percent (7/63)     Process Privilege Rights area
Completed 14 percent (8/63)     Process Privilege Rights area
Completed 15 percent (9/63)     Process Privilege Rights area
Completed 17 percent (10/63)    Process Privilege Rights area
Completed 19 percent (11/63)    Process Privilege Rights area
Completed 20 percent (12/63)    Process Privilege Rights area
Completed 22 percent (13/63)    Process Privilege Rights area
Completed 23 percent (14/63)    Process Privilege Rights area
Completed 25 percent (15/63)    Process Privilege Rights area
Completed 25 percent (15/63)    Process Group Membership area
Completed 49 percent (30/63)    Process Group Membership area
Completed 49 percent (30/63)    Process Registry Keys area
Completed 49 percent (30/63)    Process File Security area
Completed 49 percent (30/63)    Process Services area
Completed 65 percent (40/63)    Process Services area
Completed 73 percent (45/63)    Process Services area
Completed 73 percent (45/63)    Process Security Policy area
Completed 77 percent (48/63)    Process Security Policy area
Completed 84 percent (52/63)    Process Security Policy area
Completed 88 percent (55/63)    Process Security Policy area
Completed 93 percent (58/63)    Process Security Policy area
Completed 100 percent (63/63)   Process Security Policy area

The task has completed successfully.
See log %windir%\security\logs\scesrv.log for detail info.
Updating policy...

Computer Policy update has completed successfully.

User Policy update has completed successfully.

Body:
The output is coming from the second secedit.

Secedit has an optional paramater called /quiet which suppresses screen and log output. You can still view analysis results by using the Security Configuration and Analysis snap-in to the Microsoft Management Console (MMC).

like:

Secedit /configure /db <database file name> [/cfg <configuration file name>] [/overwrite] [/areas SECURITYPOLICY | GROUP_MGMT | USER_RIGHTS | REGKEYS | FILESTORE | SERVICES] [/log <log file name>] [/quiet]

In your case:

secedit /configure /db $secedt /quiet

Or forcefully, you can make PS to do that using Out-Null or redirect it to $Null

secedit /configure /db $secedt | Out-Null

secedit /configure /db $secedt > $null

All should work.

Hope it helps.


问:
Redirecting "/*" but exclude "/myfolder/*"
I need to redirect all traffic to a certain URL but excluding one recursive folder.

How do I translate that to code?

I've read many examples of .htaccess conditions but none fit my exact purpose.

I know it's a basic question.

答:
To implement a straight exception from a general rule all you need is a specific condition excluding the redirection rule to get applied for a specific request pattern. I fail to see why existing answers do not help here. Anyway, here is another answer. You might still have to adjust this, your question is a bit vague and general.

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} !^/myfolder/
RewriteRule ^ /target [END]
</code>```

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

In case you want to redirect to a separate host:

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} !^/myfolder/
RewriteRule ^ https://example.com/target [R=301]
</code>```

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Body:
To implement a straight exception from a general rule all you need is a specific condition excluding the redirection rule to get applied for a specific request pattern. I fail to see why existing answers do not help here. Anyway, here is another answer. You might still have to adjust this, your question is a bit vague and general.

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/myfolder/
RewriteRule ^ /target [END]

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

In case you want to redirect to a separate host:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/myfolder/
RewriteRule ^ https://example.com/target [R=301]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


问:
How can I access an entities score information and or existence from the luis.ai RecognizerAsync method which returns the RecognizerResult
The sample bot built through azure has a basis from this documentation

https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=csharp

I am trying to refactor parts of the functionality of the dialog and I need access to parts of the json that I assume should come back from the luis call.  However, when I try to access from $instance I get an error that I cannot access child elements of the response.

Here is an exmaple of the json:

```<code>+       Entities    {{
  "$instance": {
    "To": [
      {
        "startIndex": 10,
        "endIndex": 15,
        "text": "paris",
        "type": "To",
        "score": 0.987954
      }
    ]
  },
  "To": [
    {
      "$instance": {
        "Airport": [
          {
            "startIndex": 10,
            "endIndex": 15,
            "text": "paris",
            "type": "Airport"
          }
        ]
      },
      "Airport": [
        [
          "Paris"
        ]
      ]
    }
  ]
}}  Newtonsoft.Json.Linq.JObject
</code>```

Here is the code accessing the json:

bookingDetails.Origin = recognizerResult.Entities["From"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();
```

I understand how this accesses the Entity from luis.ai call but how can I access the other parts of the json response?

As well, is there a way to access whether or not an entity came back for the intent in general such as a bool valued response?

Lastly, accessing the json in general via the above method seems not ideal. Is there a more formatted way to access what would be the json return and with the new asp.net core 2+ is there a way to do it without using newtonsoft?

答:
You are correct that accessing the JSON via the above method is not ideal. What I would do it use a tool such as QuickType to create a class from JSON, or at least the basis of a class that you can tweak. You can then use the NewtonSoft JSON library (or an alternative JSON library since you don't want to use NewtonSoft) to Deserialize the JSON into an object and access the Score property of the object.

Alternatively, as shown in the guide that you linked you can obtain the score from the GetTopScoringIntent method call.

Regarding checking if any entities were returned you can plug the JSON shown on the LUIS API reference page under the 200 response into the quicktype tool I linked above to create a class then check against the Entities collection to see if it has any items - you could use LINQs .Any() method for this.

Edit

The OP ended up using LUISGen to output a class to deserialize the response from the LUIS API.

Go to the LUIS portal.

Navigate into the relevant LUIS app.

Go the the Manage tab.

On the left, select the Versions item.

Check the box next to the version you want to export.

From the dropdown, select Export as JSON.

Save the JSON into the root directory of your project.

Open a command prompt in the root directory of your project.

Run the following commands:

```<code>dotnet tool install -g LUISGen

LUISGen <exported-luis-app>.json -cs ClassToGenerate -o
</code>```

Add the generated file to your project in Visual Studio.

Right click on the project > Add existing item

Using the generated class in code:

```<code>var result = recognizer.Recognize<ClassToGenerate>("<user-input-text>", CancellationToken.None);
</code>```

Body:
The sample bot built through azure has a basis from this documentation

https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=csharp

I am trying to refactor parts of the functionality of the dialog and I need access to parts of the json that I assume should come back from the luis call.  However, when I try to access from $instance I get an error that I cannot access child elements of the response.

Here is an exmaple of the json:

+       Entities    {{
  "$instance": {
    "To": [
      {
        "startIndex": 10,
        "endIndex": 15,
        "text": "paris",
        "type": "To",
        "score": 0.987954
      }
    ]
  },
  "To": [
    {
      "$instance": {
        "Airport": [
          {
            "startIndex": 10,
            "endIndex": 15,
            "text": "paris",
            "type": "Airport"
          }
        ]
      },
      "Airport": [
        [
          "Paris"
        ]
      ]
    }
  ]
}}  Newtonsoft.Json.Linq.JObject

Here is the code accessing the json:

bookingDetails.Origin = recognizerResult.Entities["From"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();

I understand how this accesses the Entity from luis.ai call but how can I access the other parts of the json response?

As well, is there a way to access whether or not an entity came back for the intent in general such as a bool valued response?

Lastly, accessing the json in general via the above method seems not ideal. Is there a more formatted way to access what would be the json return and with the new asp.net core 2+ is there a way to do it without using newtonsoft?

Body:
You are correct that accessing the JSON via the above method is not ideal. What I would do it use a tool such as QuickType to create a class from JSON, or at least the basis of a class that you can tweak. You can then use the NewtonSoft JSON library (or an alternative JSON library since you don't want to use NewtonSoft) to Deserialize the JSON into an object and access the Score property of the object.

Alternatively, as shown in the guide that you linked you can obtain the score from the GetTopScoringIntent method call.

Regarding checking if any entities were returned you can plug the JSON shown on the LUIS API reference page under the 200 response into the quicktype tool I linked above to create a class then check against the Entities collection to see if it has any items - you could use LINQs .Any() method for this.

Edit

The OP ended up using LUISGen to output a class to deserialize the response from the LUIS API.

Go to the LUIS portal.

Navigate into the relevant LUIS app.

Go the the Manage tab.

On the left, select the Versions item.

Check the box next to the version you want to export.

From the dropdown, select Export as JSON.

Save the JSON into the root directory of your project.

Open a command prompt in the root directory of your project.

Run the following commands:

dotnet tool install -g LUISGen

LUISGen <exported-luis-app>.json -cs ClassToGenerate -o

Add the generated file to your project in Visual Studio.

Right click on the project > Add existing item

Using the generated class in code:

var result = recognizer.Recognize<ClassToGenerate>("<user-input-text>", CancellationToken.None);


问:
Custom Shortcode pulling in Custom Post Type / Categories
I have created a custom post type called 'stories', with categories. there are 5 categories, one of them is 'Fostering'.

I want to pull in all custom 'stories' posts with the category of 'fostering' into a page, I currently have this in my functions.php

```<code>function register_shortcodes() {
    add_shortcode( 'stories', 'stories_function' );
}
add_action( 'init', 'register_shortcodes' );

function stories_function($atts) {
    global $wp_query,
        $post;

    $atts = shortcode_atts( array(
        'cat' => ''
    ), $atts );

    $loop = new WP_Query( array(
        'posts_per_page'    => 3,
        'post_type'         => 'stories',
        'orderby'           => 'rand',
        'order'             => 'ASC',
        'tax_query'         => array( array(
            'taxonomy'  => 'category',
            'field'     => 'slug',
            'terms'     => array( sanitize_title( $atts['cat'] ) )
        ) )
    ) );

    if( ! $loop->have_posts() ) {
        return false;
    }

    while( $loop->have_posts() ) {
        $loop->the_post();
        echo the_title();
        echo the_content();
    }

    wp_reset_postdata();
}
</code>```

and the shortcode I am using is [stories category="fostering"] but nothing is being pulled in, I have dummy data in this custom post type with the category of 'Fostering' applied.

答:
Try this code as you missed to pass cat => Fostering and make sure Fostering is slug of category else pass correct slug of that category

```<code>function register_shortcodes() {
    add_shortcode( 'stories', 'stories_function' );
}
add_action( 'init', 'register_shortcodes' );

function stories_function($atts) {
    global $wp_query,
        $post;

    $atts = shortcode_atts( array(
        'cat' => 'fostering'
    ), $atts );

    $loop = new WP_Query( array(
        'posts_per_page'    => 3,
        'post_type'         => 'stories',
        'orderby'           => 'rand',
        'order'             => 'ASC',
        'tax_query'         => array( array(
            'taxonomy'  => 'story_category',
            'field'     => 'slug',
            'terms'     => array( sanitize_title( $atts['cat'] ) )
        ) )
    ) );

    if( ! $loop->have_posts() ) {
        return false;
    }

    while( $loop->have_posts() ) {
        $loop->the_post();
        echo the_title();
        echo the_content();
    }

    wp_reset_postdata();
}
</code>```

Body:
I have created a custom post type called 'stories', with categories. there are 5 categories, one of them is 'Fostering'.

I want to pull in all custom 'stories' posts with the category of 'fostering' into a page, I currently have this in my functions.php

function register_shortcodes() {
    add_shortcode( 'stories', 'stories_function' );
}
add_action( 'init', 'register_shortcodes' );

function stories_function($atts) {
    global $wp_query,
        $post;

    $atts = shortcode_atts( array(
        'cat' => ''
    ), $atts );

    $loop = new WP_Query( array(
        'posts_per_page'    => 3,
        'post_type'         => 'stories',
        'orderby'           => 'rand',
        'order'             => 'ASC',
        'tax_query'         => array( array(
            'taxonomy'  => 'category',
            'field'     => 'slug',
            'terms'     => array( sanitize_title( $atts['cat'] ) )
        ) )
    ) );

    if( ! $loop->have_posts() ) {
        return false;
    }

    while( $loop->have_posts() ) {
        $loop->the_post();
        echo the_title();
        echo the_content();
    }

    wp_reset_postdata();
}

and the shortcode I am using is [stories category="fostering"] but nothing is being pulled in, I have dummy data in this custom post type with the category of 'Fostering' applied.

Body:
Try this code as you missed to pass cat => Fostering and make sure Fostering is slug of category else pass correct slug of that category

function register_shortcodes() {
    add_shortcode( 'stories', 'stories_function' );
}
add_action( 'init', 'register_shortcodes' );

function stories_function($atts) {
    global $wp_query,
        $post;

    $atts = shortcode_atts( array(
        'cat' => 'fostering'
    ), $atts );

    $loop = new WP_Query( array(
        'posts_per_page'    => 3,
        'post_type'         => 'stories',
        'orderby'           => 'rand',
        'order'             => 'ASC',
        'tax_query'         => array( array(
            'taxonomy'  => 'story_category',
            'field'     => 'slug',
            'terms'     => array( sanitize_title( $atts['cat'] ) )
        ) )
    ) );

    if( ! $loop->have_posts() ) {
        return false;
    }

    while( $loop->have_posts() ) {
        $loop->the_post();
        echo the_title();
        echo the_content();
    }

    wp_reset_postdata();
}


问:
Laravel: Accessing model attributes in the constructor method
How to use __construct on laravel eloquent and get attributes. I tired:

```<code>public function __construct() {
    parent::__construct();
    dd($this->attributes);
}
</code>```

My code return null. But on abstract class Model filled all attributes:

```<code>public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->initializeTraits();

    $this->syncOriginal();

    $this->fill($attributes);
}
</code>```

It's possible get access to model attributes in the constructor method?

答:
Try with accessors.

https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators

Define it like:

```<code>public function getFirstNameAttribute($value)
{
     return ucfirst($value);
}
</code>```

And use $this->first_namesomething like this.

Body:
How to use __construct on laravel eloquent and get attributes. I tired:

public function __construct() {
    parent::__construct();
    dd($this->attributes);
}

My code return null. But on abstract class Model filled all attributes:

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->initializeTraits();

    $this->syncOriginal();

    $this->fill($attributes);
}

It's possible get access to model attributes in the constructor method?

Body:
Try with accessors.

https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators

Define it like:

public function getFirstNameAttribute($value)
{
     return ucfirst($value);
}

And use $this->first_namesomething like this.