问:
How do I reduce an std::variant to one value?
I have a C++ 17 std::variant. How can I reduce it to a single instance of one type using lambdas?

I am looking for something like this:

```<code>std::variant<int, std::string> v = getIntOrString();

std::string x = reduce(
  v,
  [](int i) {
    return "It's an int: " + std::to_string(i);
  },
  [](std::string i) {
    return "It's a string: " + i;
  });
</code>```

答:
Building on the example at cppreference, you'd use std::visit:

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

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

int main() {
    using v_type = std::variant<int, std::string>;
    v_type v1{1}, v2{"2"};

    auto v_to_str = overloaded{
        [](int i) { return std::to_string(i) + " was an int"; },
        [](std::string const& s) { return s + " was already a string"; }
    };

    std::cout << std::visit(v_to_str, v1) << '\n'
              << std::visit(v_to_str, v2);

}
</code>```

Live Example

Body:
I have a C++ 17 std::variant. How can I reduce it to a single instance of one type using lambdas?

I am looking for something like this:

std::variant<int, std::string> v = getIntOrString();

std::string x = reduce(
  v,
  [](int i) {
    return "It's an int: " + std::to_string(i);
  },
  [](std::string i) {
    return "It's a string: " + i;
  });

Body:
Building on the example at cppreference, you'd use std::visit:

#include <variant>
#include <string>
#include <iostream>

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

int main() {
    using v_type = std::variant<int, std::string>;
    v_type v1{1}, v2{"2"};

    auto v_to_str = overloaded{
        [](int i) { return std::to_string(i) + " was an int"; },
        [](std::string const& s) { return s + " was already a string"; }
    };

    std::cout << std::visit(v_to_str, v1) << '\n'
              << std::visit(v_to_str, v2);

}

Live Example


来源: stackexchange

问:
animation in index.html in Angular App
I am trying to animate a fadeout effect in the 'App Loading' screen when Angular loads the app. However, I cannot find a way through. Here is the code:

```<code><div class="container">
<my-app>
  <div class="loadingComp">
    <div class="sk-folding-cube">
      <div class="sk-cube1 sk-cube"></div>
      <div class="sk-cube2 sk-cube"></div>
      <div class="sk-cube4 sk-cube"></div>
      <div class="sk-cube3 sk-cube"></div>
    </div>
    <span>App loading, please wait.</span>
  </div>
  </my-app>
</code>```

tried the CSS below, but in vain:

```<code>my-app:empty + .loadingComp {
  opacity: 1;
}

my-app:not(:empty) + .loadingComp {
 opacity: 0;
 animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</code>```

Even tried with Angular Animations, but not working. Any suggestion ??

答:
Thank you Nehal for your time. I solved it using jQuery, but a different method. I assigned an 'id' to the 'my-app' selector and used it in jQuery.

I used this:

```<code>$("body").on('DOMSubtreeModified', "#myApp", function () {
  $('.loadingComp').fadeOut(function () {
    $(this).remove();
  });
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: animation in index.html in Angular App

Body:
I am trying to animate a fadeout effect in the 'App Loading' screen when Angular loads the app. However, I cannot find a way through. Here is the code:

<my-app>

    App loading, please wait.

  </my-app>

tried the CSS below, but in vain:

my-app:empty + .loadingComp {
  opacity: 1;
}

my-app:not(:empty) + .loadingComp {
 opacity: 0;
 animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Even tried with Angular Animations, but not working. Any suggestion ??

Body:
Thank you Nehal for your time. I solved it using jQuery, but a different method. I assigned an 'id' to the 'my-app' selector and used it in jQuery.

I used this:

$("body").on('DOMSubtreeModified', "#myApp", function () {
  $('.loadingComp').fadeOut(function () {
    $(this).remove();
  });
});


问:
Not all properties displayed
When we're trying to export data to other functions via the pipeline, we observe some strange behavior in PowerShell.

Example code:

```<code>$Array = @()

$Obj1 = [PSCustomObject]@{
    Member1   = 'First'
    Member2   = 'Second'
}

$Obj2 = [PSCustomObject]@{
    Member1   = 'First'
    Member2   = 'Second'
    Member3   = 'Third'
}

$Array = $Obj1, $Obj2
$Array | Out-GridView -Title 'Not showing Member3'

$Array = $Obj2, $Obj1
$Array | Out-GridView -Title 'All members correctly displayed'
</code>```

In the example above you can see that when the first object only contains 2 properties, the Out-GridView CmdLet (and others) only show 2 properties, even though the second object has 3 properties. However, when the first object in the array has 3 properties it does display them all correctly.

Is there a way around this? Because it's not possible to predict up front how many properties on an object there will be and if the object with the most properties will be the first one in the array.

答:
I had the same experience once and created the following reusable 'Union' function:

```<code># 2021-08-25 Removed Union function
</code>```

Usage:

```<code>$Obj1, $Obj2 | <b>Union</b> | Out-GridView -Title 'Showing all members'</code>```

It is also supposed to work with complex objects. Some standard cmdlets output multiple object types at once and if you view them (e.g. Out-GridView) or dump them in a file (e.g. Export-Csv) you might miss a lot of properties. Take as another example:

```<code>Get-WmiObject -Namespace root/hp/instrumentedBIOS -Class hp_biosSetting | <b>Union</b> | Export-Csv ".\HPBIOS.csv"</code>```

Added 2014-09-19:

Maybe this is already between the lines in the comments $Array | Select * | … will not resolve the issue but specifically selecting the properties $Array | Select Member1, Member2, Member3 | … does.

Besides, although in most cases the Union function will work, there are some exceptions to that as it will only align the first object with the rest.
Consider the following object:

```<code>$List = @(
    New-Object PSObject -Property @{Id = 2}
    New-Object PSObject -Property @{Id = 1}
    New-Object PSObject -Property @{Id = 3; Name = "Test"}
)
</code>```

If you Union this object everything appears to be fine and if you e.g. ExportTo-CSV and work with the export .csv file from then on you will never have any issue.

```<code>$List | Union
Id Name
-- ----
 2
 1
 3 Test
</code>```

Still there is a catch as only the first object is aligned. If you e.g. sort the result on Id (Sort Id) or take just the last 2 (Select -Last 2) entries, the Name is not listed because the second object doesn’t contain the Name property:

```<code>$List | Union | Sort Id
Id
--
 1
 2
 3
</code>```

Therefor I have rewritten the Union-Object (Alias Union) function`):

Union-Object

```<code># 2021-08-25 Removed Union-Object function
</code>```

Syntax:

```<code>$Array | Union | Out-GridView -Title 'All members correctly displayed'
</code>```

Update 2021-08-25

Based on az1d helpful feedback on an error caused by equal property names with different casing, I have created a new UnifyProperties function.

(I will no longer use the name UnionObject for his)

```<code>function UnifyProperties {
  $Names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
  $InputCollected = @($Input)
  $InputCollected.ForEach({
    foreach ($Name in $_.psobject.Properties.Name) { $Null = $Names.Add($Name) }
  })
  $inputCollected | Select-Object @($Names)
}
</code>```

Usage:

```<code>[pscustomobject] @{ one = 1; two = 2; three = 3 },
[pscustomobject] @{ ONE = 10; THREE = 30; FOUR = 4 } |
    UnifyProperties

one two three FOUR
--- --- ----- ----
  1   2     3
 10        30 4
</code>```

See also: #13906 Add -UnifyProperties parameter to Select-Object

ContentLicense: CC BY-SA 4.0

Title: Not all properties displayed

Body:
When we're trying to export data to other functions via the pipeline, we observe some strange behavior in PowerShell.

Example code:

$Array = @()

$Obj1 = [PSCustomObject]@{
    Member1   = 'First'
    Member2   = 'Second'
}

$Obj2 = [PSCustomObject]@{
    Member1   = 'First'
    Member2   = 'Second'
    Member3   = 'Third'
}

$Array = $Obj1, $Obj2
$Array | Out-GridView -Title 'Not showing Member3'

$Array = $Obj2, $Obj1
$Array | Out-GridView -Title 'All members correctly displayed'

In the example above you can see that when the first object only contains 2 properties, the Out-GridView CmdLet (and others) only show 2 properties, even though the second object has 3 properties. However, when the first object in the array has 3 properties it does display them all correctly.

Is there a way around this? Because it's not possible to predict up front how many properties on an object there will be and if the object with the most properties will be the first one in the array.

Body:
I had the same experience once and created the following reusable 'Union' function:

# 2021-08-25 Removed Union function

Usage:

$Obj1, $Obj2 | Union | Out-GridView -Title 'Showing all members'

It is also supposed to work with complex objects. Some standard cmdlets output multiple object types at once and if you view them (e.g. Out-GridView) or dump them in a file (e.g. Export-Csv) you might miss a lot of properties. Take as another example:

Get-WmiObject -Namespace root/hp/instrumentedBIOS -Class hp_biosSetting | Union | Export-Csv ".\HPBIOS.csv"

Added 2014-09-19:

Maybe this is already between the lines in the comments $Array | Select * | … will not resolve the issue but specifically selecting the properties $Array | Select Member1, Member2, Member3 | … does.

Besides, although in most cases the Union function will work, there are some exceptions to that as it will only align the first object with the rest.
Consider the following object:

$List = @(
    New-Object PSObject -Property @{Id = 2}
    New-Object PSObject -Property @{Id = 1}
    New-Object PSObject -Property @{Id = 3; Name = "Test"}
)

If you Union this object everything appears to be fine and if you e.g. ExportTo-CSV and work with the export .csv file from then on you will never have any issue.

$List | Union
Id Name
-- ----
 2
 1
 3 Test

Still there is a catch as only the first object is aligned. If you e.g. sort the result on Id (Sort Id) or take just the last 2 (Select -Last 2) entries, the Name is not listed because the second object doesn’t contain the Name property:

$List | Union | Sort Id
Id
--
 1
 2
 3

Therefor I have rewritten the Union-Object (Alias Union) function`):

Union-Object

# 2021-08-25 Removed Union-Object function

Syntax:

$Array | Union | Out-GridView -Title 'All members correctly displayed'

Update 2021-08-25

Based on az1d helpful feedback on an error caused by equal property names with different casing, I have created a new UnifyProperties function.

(I will no longer use the name UnionObject for his)

function UnifyProperties {
  $Names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
  $InputCollected = @($Input)
  $InputCollected.ForEach({
    foreach ($Name in $_.psobject.Properties.Name) { $Null = $Names.Add($Name) }
  })
  $inputCollected | Select-Object @($Names)
}

Usage:

[pscustomobject] @{ one = 1; two = 2; three = 3 },
[pscustomobject] @{ ONE = 10; THREE = 30; FOUR = 4 } |
    UnifyProperties

one two three FOUR
--- --- ----- ----
  1   2     3
 10        30 4

See also: #13906 Add -UnifyProperties parameter to Select-Object


问:
Error H10: Application Error on Heroku
I am new on working with Rails and Heroku. I tried pushing my app onto Heroku and the push was successful but for some reason I receive an application error on my Heroku Site:

```<code>"An error occurred in the application and your page could not be served."
</code>```

Would be great if someone could help. Passing along some information about my app and the environment.

In my Gem file I have the following databases running:

```<code>group :development, :test do
gem "sqlite3", "~> 1.3.6"
end

group :production do
gem 'pg'
end

group :assets do
gem 'sass-rails',   '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'therubyracer'
gem 'uglifier', '>= 1.0.3'
end
</code>```

In the Database.yml the following databases are setup:

```<code>development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000

test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000

production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
</code>```

To begin with I don't understand why the .yml file still shows Sqlite3 in the production server? Shouldn't it change to pgres. In the Heroku Logs this is the key error message that displays:

```<code> 2012-10-23T19:22:36+00:00 heroku[router]: Error H10 (App crashed) -> GET thawing-dusk-  8202.herokuapp.com/analysis dyno= queue= wait= service= status=503 bytes=
</code>```

Hope someone can help me out with this!

Thanks,

答: check is there any process which takes more than 30 seconds, if yes then your app will crashed with H10 error.</p>

Title: Error H10: Application Error on Heroku

Body:
I am new on working with Rails and Heroku. I tried pushing my app onto Heroku and the push was successful but for some reason I receive an application error on my Heroku Site:

"An error occurred in the application and your page could not be served."

Would be great if someone could help. Passing along some information about my app and the environment.

In my Gem file I have the following databases running:

group :development, :test do
gem "sqlite3", "~> 1.3.6"
end

group :production do
gem 'pg'
end

group :assets do
gem 'sass-rails',   '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'therubyracer'
gem 'uglifier', '>= 1.0.3'
end

In the Database.yml the following databases are setup:

development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000

test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000

production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000

To begin with I don't understand why the .yml file still shows Sqlite3 in the production server? Shouldn't it change to pgres. In the Heroku Logs this is the key error message that displays:

 2012-10-23T19:22:36+00:00 heroku[router]: Error H10 (App crashed) -> GET thawing-dusk-  8202.herokuapp.com/analysis dyno= queue= wait= service= status=503 bytes=

Hope someone can help me out with this!

Thanks,


问:
Date format conversion issue PHP
See the below code returns the output as "Jun".

```<code>$date_removed =strtotime('2017-06-07 06:06:44');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
</code>```

But the below code returns "Dec" as output.

```<code>$date_removed =strtotime('0000-00-00 00:00:00');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
</code>```

Here the month value is null. So the return value should be null. Please let me know the issue in my code?

答:
you could try to do it like this:</p>

```<code>try {
    $dt = new \DateTime('0000-00-00 00:00:00');
} catch (Exception $e) {
    var_dump($e);
}
</code>```

Title: Date format conversion issue PHP

Body:
See the below code returns the output as "Jun".

$date_removed =strtotime('2017-06-07 06:06:44');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;

But the below code returns "Dec" as output.

$date_removed =strtotime('0000-00-00 00:00:00');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;

Here the month value is null. So the return value should be null. Please let me know the issue in my code?

Body:
you could try to do it like this:

try {
    $dt = new \DateTime('0000-00-00 00:00:00');
} catch (Exception $e) {
    var_dump($e);
}


问:
Form Authentication with wrong credentials leads to HTTP 405 (Method Not Allowed)
I have a Spring web application which should be protected by Form Authentication (I cannot use Spring Security for some reasons).

If I request a protected resource I will be redirected to the login form and can enter the credentials. When the credentials are correct, I will be redirected to the requestet resource. Everything like it should be.

But when I enter wrong credentials I get a HTTP 405 message, not the error page. Why?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Authentication</web-resource-name>
            <url-pattern>/test/auth/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>users</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.html</form-login-page>
            <form-error-page>/loginerror.html</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <role-name>users</role-name>
    </security-role>

</web-app>
```

<p><strong>login.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

<form method="post" action="j_security_check">
    <table>
        <tr>
            <td colspan="2">Please type in your user name and password</td>
        </tr>
        <tr>
            <td>Name:</td>
            <td><input type="text" name="j_username" width="40"/></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name="j_password" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Login" /></td>
        </tr>
    </table>
</form>

</body>
</html>
</code>```

loginerror.html

<!DOCTYPE html>

error!

```

<p><strong>Log</strong></p>

<pre class="lang-none prettyprint-override"><code>WARN [http-nio-8080-exec-79] o.s.web.servlet.PageNotFound: Request method 'POST' not supported
</code>```

Controller

@RestController
@RequestMapping("/test")
public class TestController {

    private final static Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        printAuth();
        return "test";
    }

    @RequestMapping(value = "/auth/test", method = RequestMethod.GET)
    public String testAuth() {
        printAuth();
        return "testAuth";
    }

    @RequestMapping(value = "/auth/test2", method = RequestMethod.GET)
    public String testAuth2() {
        printAuth();
        return "testAuth2";
    }

    private void printAuth() {
        Principal principal = request.getUserPrincipal();
        LOG.debug("Request: " + request);
        LOG.debug("Principal: " + principal);
        LOG.debug("Principal name :" + principal.getName());
        LOG.debug("User in Role 'users': " + request.isUserInRole("users"));
    }

}
```

Update:

I tried the same authentication with a spimple "non Spring" application and it works fine. So I assume that the Spring servlet "catches" the request somehow. Is it possible to avoid that?

答:
Like I assumed in my update the Spring servlet is responsible for this problem. Therefore I had to make shure that an another servlet serves the login pages instead of the Spring servlet.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/WEB-INF/classes/static/login/*</url-pattern>
    </servlet-mapping>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Authentication</web-resource-name>
            <url-pattern>/test/auth/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>users</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/WEB-INF/classes/static/login/login.html</form-login-page>
            <form-error-page>/WEB-INF/classes/static/login/loginerror.html</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <role-name>users</role-name>
    </security-role>

</web-app>
```

Body:
I have a Spring web application which should be protected by Form Authentication (I cannot use Spring Security for some reasons).

If I request a protected resource I will be redirected to the login form and can enter the credentials. When the credentials are correct, I will be redirected to the requestet resource. Everything like it should be.

But when I enter wrong credentials I get a HTTP 405 message, not the error page. Why?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Authentication</web-resource-name>
            <url-pattern>/test/auth/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>users</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.html</form-login-page>
            <form-error-page>/loginerror.html</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <role-name>users</role-name>
    </security-role>

</web-app>

login.html

<!DOCTYPE html>

<form method="post" action="j_security_check">

            Please type in your user name and password

            Name:
            <input type="text" name="j_username" width="40"/>

            Password:
            <input type="password" name="j_password" />

            <input type="submit" value="Login" />

</form>

loginerror.html

<!DOCTYPE html>

error!

Log

WARN [http-nio-8080-exec-79] o.s.web.servlet.PageNotFound: Request method 'POST' not supported

Controller

@RestController
@RequestMapping("/test")
public class TestController {

    private final static Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        printAuth();
        return "test";
    }

    @RequestMapping(value = "/auth/test", method = RequestMethod.GET)
    public String testAuth() {
        printAuth();
        return "testAuth";
    }

    @RequestMapping(value = "/auth/test2", method = RequestMethod.GET)
    public String testAuth2() {
        printAuth();
        return "testAuth2";
    }

    private void printAuth() {
        Principal principal = request.getUserPrincipal();
        LOG.debug("Request: " + request);
        LOG.debug("Principal: " + principal);
        LOG.debug("Principal name :" + principal.getName());
        LOG.debug("User in Role 'users': " + request.isUserInRole("users"));
    }

}

Update:

I tried the same authentication with a spimple "non Spring" application and it works fine. So I assume that the Spring servlet "catches" the request somehow. Is it possible to avoid that?


问:
Can I use require("path").join to safely concatenate urls?
Is this safe to use require("path").join to concatenate URLs, for example:

```<code>require("path").join("http://example.com", "ok");
//returns 'http://example.com/ok'

require("path").join("http://example.com/", "ok");
//returns 'http://example.com/ok'
</code>```

If not, what way would you suggest for doing this without writing code full of ifs?

答:
If you're using lodash, you can use this simple oneliner:

```<code>// returns part1/part2/part3
['part1/', '/part2', '/part3/'].map((s) => _.trim(s, '/')).join('/')
</code>```

inspired by @Peter Dotchev's answer

Body:
Is this safe to use require("path").join to concatenate URLs, for example:

require("path").join("http://example.com", "ok");
//returns 'http://example.com/ok'

require("path").join("http://example.com/", "ok");
//returns 'http://example.com/ok'

If not, what way would you suggest for doing this without writing code full of ifs?

Body:
If you're using lodash, you can use this simple oneliner:

// returns part1/part2/part3
['part1/', '/part2', '/part3/'].map((s) => _.trim(s, '/')).join('/')

inspired by @Peter Dotchev's answer


问:
How to redirect subdomain to main domain maintaining the same URL?
My main domain(www.mysite.com) is pointing to a folder in my server (/home/user_name/htdocs/mysite.com).

I have recently created a subdomain(m.mysite.com) through my hosting account. But it is pointing it to a new folder (/home/user_name/htdocs/m.mysite.com) in my server. I am not able to edit the path to which this new subdomain points to. All my files are hosted in my main folder path.

My Requirement -

When a user visits m.mysite.com he should be redirected to mysite.com but the URL in the browser should still say m.mysite.com

I'm handling the mobile view by detecting the subdomain using $_SERVER['SERVER_NAME']

答:
I think you could set up an htaccess file under m.mysite.com with a RewriteRule that points all requests to a different URL.</p>

```<code>RewriteEngine On
RewriteRule ^(.*)$ http://www.mysite.com/$1</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think you could set up an htaccess file under m.mysite.com with a RewriteRule that points all requests to a different URL.

RewriteEngine On
RewriteRule ^(.*)$ http://www.mysite.com/$1


问:
Show bootstrap modal on the center of a scrolled down page
I am using ace admin template to develop a website, but I have problem placing bootstrap modal on the center of iframe page when I scrolled it down, like this.

```<code>$('#modalId').modal({
    show:true,
    backdrop:'static'
})
</code>```

how to make the modal pop up on the center of current view?

答:
```<code>$('#modalId').modal({
    show:true,
}).css({
    'margin-top': function (){
        return window.gui.getTopWindow(window).scrollY;
    }
});
</code>```

Body:
I am using ace admin template to develop a website, but I have problem placing bootstrap modal on the center of iframe page when I scrolled it down, like this.

$('#modalId').modal({
    show:true,
    backdrop:'static'
})

how to make the modal pop up on the center of current view?


问:
Exclude from brace expansion
I know that

```<code>echo {1..10}
</code>```

do

```<code>1 2 3 4 5 6 7 8 9 10
</code>```

but i do not want 6 and 7. Is it possible to exclude it?

答:
Maybe you can use the following:</p>

```<code>echo {1..5} {8..10}
</code>```

Title: Exclude from brace expansion

Body:
I know that

echo {1..10}

do

1 2 3 4 5 6 7 8 9 10

but i do not want 6 and 7. Is it possible to exclude it?

Body:
Maybe you can use the following:

echo {1..5} {8..10}


问:
java reason: actual and formal argument lists differ in length
I need help creating a setter method for my code. I have created two setter methods for both of my string values, but I am A) not sure if they are implemented correct, and B) not sure how to call them so that they appear on the screen. Essentially I would like to be able to just call my lion and hippo classes and have them already have a name and a size, and not have to implement them inside my main function directly by inserting something like
 Hippo h = new Hippo("Tom", "42")

```<code>package game2;

public class Game2 {

    public static void main(String[] args) {
        //I am getting the error here, what I want to do is figure out how to
        //get this to work and then declare a name and size for the animal
        Hippo h = new Hippo();
        Lion l = new Lion();
    }

}
</code>```

```<code>package game2;

public abstract class Animal {
    private String name;
    private String Size;

    public String getName() {
        return name;
    }

    public String getSize() {
        return Size;
    }

    public void setName(String name) {
        name = "Tom";
    }

    public void setSize(String name) {
        name = "42";
    }

    public Animal(String theName, String theSize) {
        name = theName;
        Size = theSize;
    }
 }
</code>```

```<code>package game2;

public class Hippo extends Animal {

    public Hippo(String name, String Size) {
        super(name, Size);
    }
}
</code>```

```<code>package game2;

public class Lion extends Animal{

    public Lion(String name, String Size) {
        super(name, Size);
    }
}
</code>```

答:
Both Hippo's and Lion's constructors expect two string arguments - the name and the size. You need to pass them when you call the respective constructors. E.g.:

```<code>Hippo h = new Hippo("Happy", "Huge");
Lion l = new Lion("Leo", "Big");
</code>```

Body:
I need help creating a setter method for my code. I have created two setter methods for both of my string values, but I am A) not sure if they are implemented correct, and B) not sure how to call them so that they appear on the screen. Essentially I would like to be able to just call my lion and hippo classes and have them already have a name and a size, and not have to implement them inside my main function directly by inserting something like
 Hippo h = new Hippo("Tom", "42")

package game2;

public class Game2 {

    public static void main(String[] args) {
        //I am getting the error here, what I want to do is figure out how to
        //get this to work and then declare a name and size for the animal
        Hippo h = new Hippo();
        Lion l = new Lion();
    }

}

package game2;

public abstract class Animal {
    private String name;
    private String Size;

    public String getName() {
        return name;
    }

    public String getSize() {
        return Size;
    }

    public void setName(String name) {
        name = "Tom";
    }

    public void setSize(String name) {
        name = "42";
    }

    public Animal(String theName, String theSize) {
        name = theName;
        Size = theSize;
    }
 }

package game2;

public class Hippo extends Animal {

    public Hippo(String name, String Size) {
        super(name, Size);
    }
}

package game2;

public class Lion extends Animal{

    public Lion(String name, String Size) {
        super(name, Size);
    }
}

Body:
Both Hippo's and Lion's constructors expect two string arguments - the name and the size. You need to pass them when you call the respective constructors. E.g.:

Hippo h = new Hippo("Happy", "Huge");
Lion l = new Lion("Leo", "Big");


问:
PHP Session Stop working
I don't know why my session suddenly stops.
Here is my code.

File 1:

```<code><?php session_start();
$_SESSION['user_session'] = 'test';
?>
</code>```

File 2:

```<code><?php
session_start();
echo '```' . print_r($_SESSION, TRUE) . '```';

?>
</code>```

I use PHP 7, I already tried other remedies but cant use my session.

答:
You have first create session for user session

You can use to it

```<code>session_start();
echo $_SESSION['user_session'];
</code>```

Title: PHP Session Stop working

Body:
I don't know why my session suddenly stops.
Here is my code.

File 1:

<?php session_start();
$_SESSION['user_session'] = 'test';
?>

File 2:

<?php
session_start();
echo '
' . print_r($_SESSION, TRUE) . '
';

?>

I use PHP 7, I already tried other remedies but cant use my session.

Body:
You have first create session for user session

You can use to it

session_start();
echo $_SESSION['user_session'];


问:
Coded flowchart and unable to return OutArgument
I am create flow chart workflow using code (instead of design time)

Code

```<code>static Flowchart CreateFlowChart()
{
    Variable<string> response = new Variable<string>();
    Variable<string> isApproved = new Variable<string>();

    FlowStep approved = new FlowStep
    {
        Action = new Assign
        {
            To = new OutArgument<string> (isApproved),
            Value = new InArgument<string>((context) => response.Get(context))
        }
    };

    FlowStep rejected = new FlowStep
    {
        Action = new Assign
        {
            DisplayName = "Approved",
            To = new OutArgument<string>(isApproved),
            Value = new InArgument<string>((context) => response.Get(context))
        }
    };

    FlowDecision flowDecision = new FlowDecision
    {

        Condition = ExpressionServices.Convert<bool>((ctx) => response.Get(ctx).ToString() == "approved"),
        True = approved,
        False = rejected
    };

    FlowStep LineManagerApproval = new FlowStep
    {
        Action = new ReadLine
        {
            BookmarkName = readLineBookmark,
            Result = new OutArgument<string>(response)
        },

        Next = flowDecision
    };

    Flowchart flowChart = new Flowchart
    {
        DisplayName = "Line Manager Approval Process",
        Variables = { response, isApproved },
        StartNode = LineManagerApproval,
        Nodes =
        {
            LineManagerApproval,
            flowDecision,
            approved,
            rejected
        }
    };
    return flowChart;
}
</code>```

I am setting OutArgument<string> in my activity post to flow decision.

When workflow completes i am expecting to have e.OutPuts["isApproved"] but e.OutPuts always give count 0;

```<code>application.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
{

    Console.WriteLine("Workflow {0} Completed.", e.InstanceId);
    //bool isApproved = (bool)e.Outputs["isApproved"];

};
</code>```

Basically i am struggling to return OutArgument from flow chart.
Any help please?

答: IsApproved should be set as an outArgument at the workflow level.  You seem to have it set as a Variable.</p>

Body:
I am create flow chart workflow using code (instead of design time)

Code

static Flowchart CreateFlowChart()
{
    Variable<string> response = new Variable<string>();
    Variable<string> isApproved = new Variable<string>();

    FlowStep approved = new FlowStep
    {
        Action = new Assign
        {
            To = new OutArgument<string> (isApproved),
            Value = new InArgument<string>((context) => response.Get(context))
        }
    };

    FlowStep rejected = new FlowStep
    {
        Action = new Assign
        {
            DisplayName = "Approved",
            To = new OutArgument<string>(isApproved),
            Value = new InArgument<string>((context) => response.Get(context))
        }
    };

    FlowDecision flowDecision = new FlowDecision
    {

        Condition = ExpressionServices.Convert<bool>((ctx) => response.Get(ctx).ToString() == "approved"),
        True = approved,
        False = rejected
    };

    FlowStep LineManagerApproval = new FlowStep
    {
        Action = new ReadLine
        {
            BookmarkName = readLineBookmark,
            Result = new OutArgument<string>(response)
        },

        Next = flowDecision
    };

    Flowchart flowChart = new Flowchart
    {
        DisplayName = "Line Manager Approval Process",
        Variables = { response, isApproved },
        StartNode = LineManagerApproval,
        Nodes =
        {
            LineManagerApproval,
            flowDecision,
            approved,
            rejected
        }
    };
    return flowChart;
}

I am setting OutArgument<string> in my activity post to flow decision.

When workflow completes i am expecting to have e.OutPuts["isApproved"] but e.OutPuts always give count 0;

application.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
{

    Console.WriteLine("Workflow {0} Completed.", e.InstanceId);
    //bool isApproved = (bool)e.Outputs["isApproved"];

};

Basically i am struggling to return OutArgument from flow chart.
Any help please?


问:
LinearLayout only show first item
I got problem with LinearLayout, it only shows the first child. I found a solution but i not work.

Here my xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

here is the result when i change position of Button and ImageView

and

答:
You have defined ImageView's width as MATCH_PARENT so it will take the whole of it's parent and while the parent is HORIZONTAL then the second view will never shown. this may help you

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/qrcode_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/primary_darker"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:orientation="horizontal">

    <android.support.v7.widget.AppCompatImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/qrCode_imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/generate_code_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/generate_code"
        android:layout_marginRight="@dimen/de_btn_padding"
        android:layout_marginLeft="@dimen/de_btn_padding"/>

</LinearLayout>
</code>```

Title: LinearLayout only show first item

Body:
I got problem with LinearLayout, it only shows the first child. I found a solution but i not work.

Here my xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

here is the result when i change position of Button and ImageView

and

Body:
You have defined ImageView's width as MATCH_PARENT so it will take the whole of it's parent and while the parent is HORIZONTAL then the second view will never shown. this may help you

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/qrcode_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/primary_darker"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:orientation="horizontal">

    <android.support.v7.widget.AppCompatImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/qrCode_imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/generate_code_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/generate_code"
        android:layout_marginRight="@dimen/de_btn_padding"
        android:layout_marginLeft="@dimen/de_btn_padding"/>

</LinearLayout>


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
You should define an interface once you need to force a behaviour for your class.

An Animal's behaviour may involve Walking, Eating, Running, etc. Therefore, you define them as interfaces.

Another practical example is the ActionListener (or Runnable) interface. You would implement them when you need to keep track of a particular event. Therefore, you need to provide the implementation for the actionPerformed(Event e) method in your class (or subclass). Similarly, for the Runnable interface, you provide the implementation for the public void run() method.

Also, you can have these interfaces implemented by any number of classes.

Another instance where Interfaces are used (in Java) is to implement the multiple inheritance offered in C++.

LastEditorDisplayName: ALassek

OwnerDisplayName: Pat


问:
ESLint not ignoring global variables given in .eslintrc.json
I am trying to get eslint to ignore a file I'm importing globally using webpack.ProvidePlugin, yet the file is still being linted.

```<code>//file arrangement
- vendor
  `- google.js
- ...
- webpack.config.js

//relevant webpack configurations
resolve: {
  extensions: ['.js', '.json'],
  alias: {
    'google': path.resolve(__dirname, './vendor/google.js')
  }
},

....
plugins: [
  new webpack.ProvidePlugin({
    'google': 'google'
  })
]

 /*google is successfully available globally*/

//.eslintrc.json
{
  "extends": ["standard", "standard-react"],
  "globals": {
    "google": true
  }
}

//package.json script
"dev": "webpack-dev-server --port 5888",
 ...
"lint": "eslint js/**/*.js webpack.config.js"
</code>```

And yet I am still getting hundreds of linting errors from google.js. It's minified but the webpack docs say that though that's preferred it probably isn't necessary and also the eslint docs don't mention it at all.

I've also tried the comment style of ignoring mentioned in the docs

```<code>//google.js
/*global google:true*/
</code>```

Why is ESLint still giving me all of these linting errors?

答:
The global option only refers to using a global variable and has no effect on whether a file is linted or not.

If you don't want to lint a specific file, you can use a .eslintignore file to exclude files matching a pattern from the linting process. It is very similar to a .gitignore.

You probably want to exclude all vendor files, so you can use the pattern suggested in Ignoring files from linting.

```<code>**/vendor/*.js
</code>```

This will give you a warning for the files that are being ignored, because you're using a glob, which gets expanded by your shell and therefore you are explicitly passing the file to ESLint (see Ignored File Warnings). You can get rid of that warning by passing a directory instead, and ESLint will lint every JavaScript file in the directory, so your glob is not needed.

```<code>"lint": "eslint js/ webpack.config.js"
</code>```

Body:
I am trying to get eslint to ignore a file I'm importing globally using webpack.ProvidePlugin, yet the file is still being linted.

//file arrangement
- vendor
  `- google.js
- ...
- webpack.config.js

//relevant webpack configurations
resolve: {
  extensions: ['.js', '.json'],
  alias: {
    'google': path.resolve(__dirname, './vendor/google.js')
  }
},

....
plugins: [
  new webpack.ProvidePlugin({
    'google': 'google'
  })
]

 /*google is successfully available globally*/

//.eslintrc.json
{
  "extends": ["standard", "standard-react"],
  "globals": {
    "google": true
  }
}

//package.json script
"dev": "webpack-dev-server --port 5888",
 ...
"lint": "eslint js/**/*.js webpack.config.js"

And yet I am still getting hundreds of linting errors from google.js. It's minified but the webpack docs say that though that's preferred it probably isn't necessary and also the eslint docs don't mention it at all.

I've also tried the comment style of ignoring mentioned in the docs

//google.js
/*global google:true*/

Why is ESLint still giving me all of these linting errors?

Body:
The global option only refers to using a global variable and has no effect on whether a file is linted or not.

If you don't want to lint a specific file, you can use a .eslintignore file to exclude files matching a pattern from the linting process. It is very similar to a .gitignore.

You probably want to exclude all vendor files, so you can use the pattern suggested in Ignoring files from linting.

**/vendor/*.js

This will give you a warning for the files that are being ignored, because you're using a glob, which gets expanded by your shell and therefore you are explicitly passing the file to ESLint (see Ignored File Warnings). You can get rid of that warning by passing a directory instead, and ESLint will lint every JavaScript file in the directory, so your glob is not needed.

"lint": "eslint js/ webpack.config.js"


问:
Force a URL-path for mod_rewrite's RewriteRule Substitution
When performing rewrites with mod_rewrite's RewriteRule, the substitution is evaluated and a guess made as to whether it's a URL or a file-system path, based on whether the root directory of the substitution exists on the file system. Here's the relevant section from the documentation:

URL-path

Note that mod_rewrite tries to guess whether you have specified a file-system path or a URL-path by checking to see if the first segment of the path exists at the root of the file-system. For example, if you specify a Substitution string of /www/file.html, then this will be treated as a URL-path unless a directory named www exists at the root or your file-system (or, in the case of using rewrites in a .htaccess file, relative to your document root), in which case it will be treated as a file-system path.

So my question is, how do I rewrite to a URI, where the root directory does exist in the file-system, but I want it to be treated as a URL?

Is there any way other than specifying the full URL? Also according to the docs:

Absolute URL

If an absolute URL is specified, mod_rewrite checks to see whether the hostname matches the current host. If it does, the scheme and hostname are stripped out and the resulting path is treated as a URL-path. Otherwise, an external redirect is performed for the given URL.

So I can get round it like this:

```<code>RewriteRule ^/example.html$ %{REQUEST_SCHEME}://%{HTTP_HOST}/var/example.html
</code>```

Which is not ideal for readability of the code. I really want to be able to do:

```<code>RewriteRule ^/example.html$ /var/example.html
</code>```

Without that being evaluated as a file-system path when /var exists. There doesn't seem to be a flag to force this. There is also a risk of a matching path being created later and breaking rules, which I would like to avoid without so much verbosity.

I am also aware I can solve this by putting the rules in .htaccess instead of the Apache config, so the search is made from the document root as described in the quote above, but that's not what I'm looking for.

Is there any other way?

Update

Thanks to Dusan Bajic's answer, it turns out the [PT] flag can help here, as hinted at in the sentence I missed off the first quote from the docs:

If you wish other URL-mapping directives (such as Alias) to be applied to the resulting URL-path, use the [PT] flag as described below.

By using the [PT] flag (docs here), it will cause the substitution "to be treated as a URI instead [of a file-path]", which sounds like it should answer this question, but unfortunately there are other implications to using the [PT] flag:

It implies [L] so no further processing of rewrite rules will occur.

It causes URL mapping to run again, which is what it is for, and may not be desirable when simply wishing to force a substitution to be interpreted as a URL-path.

So I am leaving this question open without an accepted answer for now, as the desired solution will not have the above issues. An accepted answer will cause the substitution to be treated as a URL-path, as it would be if the root directory of the substitution did not exist in the file-system, without affecting the processing in any other way.

Update 2

I realised that another option to help with this, when the URL is within the document root, is to always add %{DOCUMENT_ROOT} at the start of the substitution. So it makes it like this:

```<code>RewriteRule ^/example.html$ %{DOCUMENT_ROOT}/var/example.html
</code>```

This also prevents later rules that process the URL from working though, so it's similar to the [PT] option without causing the URL mapping to run again.

答:
You overlooked the last sentence of the quoted paragraph:

If you wish other URL-mapping directives (such as Alias) to be applied
  to the resulting URL-path, use the [PT] flag as described below.

It seems like it does not apply to your (very sensible btw.) question, but if you dig further into [PT]:

The target (or substitution string) in a RewriteRule is assumed to be
  a file path, by default. The use of the [PT] flag causes it to be
  treated as a URI instead.

For example (if you turn on LogLevel debug rewrite:trace6):

```<code>RewriteRule ^/boo$ /opt/mock.png
</code>```

Will log:

```<code>[...] init rewrite engine with requested uri /boo
[...] applying pattern '^/boo$' to uri '/boo'
[...] rewrite '/boo' -> '/opt/mock.png'
[...] local path result: /opt/mock.png
[...] go-ahead with /opt/mock.png [OK]
</code>```

but

```<code>RewriteRule ^/boo$ /opt/mock.png [PT]
</code>```

Will log:

```<code>[...] init rewrite engine with requested uri /boo
[...] applying pattern '^/boo$' to uri '/boo'
[...] rewrite '/boo' -> '/opt/mock.png'
[...] forcing '/opt/mock.png' to get passed through to next API URI-to-filename handler
</code>```

Body:
When performing rewrites with mod_rewrite's RewriteRule, the substitution is evaluated and a guess made as to whether it's a URL or a file-system path, based on whether the root directory of the substitution exists on the file system. Here's the relevant section from the documentation:

URL-path

Note that mod_rewrite tries to guess whether you have specified a file-system path or a URL-path by checking to see if the first segment of the path exists at the root of the file-system. For example, if you specify a Substitution string of /www/file.html, then this will be treated as a URL-path unless a directory named www exists at the root or your file-system (or, in the case of using rewrites in a .htaccess file, relative to your document root), in which case it will be treated as a file-system path.

So my question is, how do I rewrite to a URI, where the root directory does exist in the file-system, but I want it to be treated as a URL?

Is there any way other than specifying the full URL? Also according to the docs:

Absolute URL

If an absolute URL is specified, mod_rewrite checks to see whether the hostname matches the current host. If it does, the scheme and hostname are stripped out and the resulting path is treated as a URL-path. Otherwise, an external redirect is performed for the given URL.

So I can get round it like this:

RewriteRule ^/example.html$ %{REQUEST_SCHEME}://%{HTTP_HOST}/var/example.html

Which is not ideal for readability of the code. I really want to be able to do:

RewriteRule ^/example.html$ /var/example.html

Without that being evaluated as a file-system path when /var exists. There doesn't seem to be a flag to force this. There is also a risk of a matching path being created later and breaking rules, which I would like to avoid without so much verbosity.

I am also aware I can solve this by putting the rules in .htaccess instead of the Apache config, so the search is made from the document root as described in the quote above, but that's not what I'm looking for.

Is there any other way?

Update

Thanks to Dusan Bajic's answer, it turns out the [PT] flag can help here, as hinted at in the sentence I missed off the first quote from the docs:

If you wish other URL-mapping directives (such as Alias) to be applied to the resulting URL-path, use the [PT] flag as described below.

By using the [PT] flag (docs here), it will cause the substitution "to be treated as a URI instead [of a file-path]", which sounds like it should answer this question, but unfortunately there are other implications to using the [PT] flag:

It implies [L] so no further processing of rewrite rules will occur.

It causes URL mapping to run again, which is what it is for, and may not be desirable when simply wishing to force a substitution to be interpreted as a URL-path.

So I am leaving this question open without an accepted answer for now, as the desired solution will not have the above issues. An accepted answer will cause the substitution to be treated as a URL-path, as it would be if the root directory of the substitution did not exist in the file-system, without affecting the processing in any other way.

Update 2

I realised that another option to help with this, when the URL is within the document root, is to always add %{DOCUMENT_ROOT} at the start of the substitution. So it makes it like this:

RewriteRule ^/example.html$ %{DOCUMENT_ROOT}/var/example.html

This also prevents later rules that process the URL from working though, so it's similar to the [PT] option without causing the URL mapping to run again.

Body:
You overlooked the last sentence of the quoted paragraph:

If you wish other URL-mapping directives (such as Alias) to be applied
  to the resulting URL-path, use the [PT] flag as described below.

It seems like it does not apply to your (very sensible btw.) question, but if you dig further into [PT]:

The target (or substitution string) in a RewriteRule is assumed to be
  a file path, by default. The use of the [PT] flag causes it to be
  treated as a URI instead.

For example (if you turn on LogLevel debug rewrite:trace6):

RewriteRule ^/boo$ /opt/mock.png

Will log:

[...] init rewrite engine with requested uri /boo
[...] applying pattern '^/boo$' to uri '/boo'
[...] rewrite '/boo' -> '/opt/mock.png'
[...] local path result: /opt/mock.png
[...] go-ahead with /opt/mock.png [OK]

but

RewriteRule ^/boo$ /opt/mock.png [PT]

Will log:

[...] init rewrite engine with requested uri /boo
[...] applying pattern '^/boo$' to uri '/boo'
[...] rewrite '/boo' -> '/opt/mock.png'
[...] forcing '/opt/mock.png' to get passed through to next API URI-to-filename handler


答:
If you want to decide the name and size after you have created your animal, you need a parameterless constructor. Currently all the constructors require you to pass 2 arguments. So write one!

Here is an example:

```<code>public Hippo() {
    setSize(insert default size here);
    setName(insert default name here);

}
</code>```

Then, you can create a hippo like this:

```<code>Hippo hippo = new Hippo();
hippo.setName("Tom");
</code>```

Title: java reason: actual and formal argument lists differ in length

Body:
If you want to decide the name and size after you have created your animal, you need a parameterless constructor. Currently all the constructors require you to pass 2 arguments. So write one!

Here is an example:

public Hippo() {
    setSize(insert default size here);
    setName(insert default name here);

}

Then, you can create a hippo like this:

Hippo hippo = new Hippo();
hippo.setName("Tom");


问:
How to show the same tab content for multiple tabs in jquery / javascript.
For example i have tabs like 1,2, 3, 4,5 now when user selected 2,3,4 tabs we need to show the same content and the remaining tabs different. How i can do this one . </p>

答: You can use bootstrap accordion or collapse and for same content tabs set the same content id.</p>


问:
why im unable to get posted data using ajax in laravel
I'm getting some junk data instead of my posted data in laravel 5.4

here is my route

```<code>Route::post('capture-rating',function(Request $request){

       dd($request);
});
</code>```

my $.ajax looks like this

```<code>    var rating = 4;
     $.ajax({
        url:'capture-rating',
        type:'post',
        //dataType:'json',

        data:{rating:rating},

        success:function(data){
            console.log(data);
        }
     });
</code>```

here is network tab console image

i'm getting this junk data why i don't know?

```<code><script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if ('sf-dump-compact' == oldClass) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if ('sf-dump-expanded' == oldClass) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } a.lastChild.innerHTML = arrow; s.className = newClass; if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (a[s].className !== newClass) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; function collapse(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if ('sf-dump-expanded' == oldClass) { toggle(a, recursive); return true; } return false; }; function expand(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if ('sf-dump-compact' == oldClass) { toggle(a, recursive); return true; } return false; }; function collapseAll(root) { var a = root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true); expand(a); return true; } return false; } function reveal(node) { var previous, parents = []; while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) { parents.push(previous); } if (0 !== parents.length) { parents.forEach(function (parent) { expand(parent); }); return true; } return false; } function highlight(root, activeNode, nodes) { resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function (node) { if (!/\bsf-dump-highlight\b/.test(node.className)) { node.className = node.className + ' sf-dump-highlight'; } }); if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) { activeNode.className = activeNode.className + ' sf-dump-highlight-active'; } } function resetHighlightedNodes(root) { Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) { strNode.className = strNode.className.replace(/\b sf-dump-highlight\b/, ''); strNode.className = strNode.className.replace(/\b sf-dump-highlight-active\b/, ''); }); } return function (root, x) { root = doc.getElementById(root); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), options = {"maxDepth":1,"maxStringLength":160,"fileLinkFormat":false}, elt = root.getElementsByTagName('A'), len = elt.length, i = 0, s, h, t = []; while (i < len) t.push(elt[i++]); for (i in x) { options[i] = x[i]; } function a(e, f) { addEventListener(root, e, function (e) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } else if (e.target.nextElementSibling && 'A' == e.target.nextElementSibling.tagName) { f(e.target.nextElementSibling, e, true); } }); }; function isCtrlKey(e) { return e.ctrlKey || e.metaKey; } function xpathString(str) { var parts = str.match(/[^'"]+|['"]/g).map(function (part) { if ("'" == part) { return '"\'"'; } if ('"' == part) { return "'\"'"; } return "'" + part + "'"; }); return "concat(" + parts.join(",") + ", '')"; } addEventListener(root, 'mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a, e, c) { if (c) { e.target.style.cursor = "pointer"; } else if (a = idRx.exec(a.className)) { try { refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } catch (e) { } } }); a('click', function (a, e, c) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if ('sf-dump-compact' == r.className) { toggle(s, isCtrlKey(e)); } } if (c) { } else if (doc.getSelection) { try { doc.getSelection().removeAllRanges(); } catch (e) { doc.getSelection().empty(); } } else { doc.selection.empty(); } } else if (/\bsf-dump-str-toggle\b/.test(a.className)) { e.preventDefault(); e = a.parentNode.parentNode; e.className = e.className.replace(/sf-dump-str-(expand|collapse)/, a.parentNode.className); } }); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; if ('SAMP' == elt.tagName) { elt.className = 'sf-dump-expanded'; a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children'; a.innerHTML += '<span>▼</span>'; a.className += ' sf-dump-toggle'; x = 1; if ('sf-dump' != elt.parentNode.className) { x += elt.parentNode.getAttribute('data-depth')/1; } elt.setAttribute('data-depth', x); if (x > options.maxDepth) { toggle(a); } } else if ('sf-dump-ref' == elt.className && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling; elt.appendChild(a); s.parentNode.insertBefore(a, s); if (/^[@#]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>▶</span>'; } else { elt.innerHTML = '<span>▶</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from && root.children.length > 1) { root.setAttribute('tabindex', 0); SearchState = function () { this.nodes = []; this.idx = 0; }; SearchState.prototype = { next: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : this.idx; return this.current(); }, previous: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx > 0 ? this.idx - 1 : this.idx; return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function () { if (this.isEmpty()) { return null; } return this.nodes[this.idx]; }, reset: function () { this.nodes = []; this.idx = 0; }, count: function () { return this.nodes.length; }, }; function showCurrent(state) { var currentNode = state.current(); if (currentNode) { reveal(currentNode); highlight(root, currentNode, state.nodes); } counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper sf-dump-search-hidden'; search.innerHTML = ' <input type="text" class="sf-dump-search-input"> <span class="sf-dump-search-count">0 of 0<\/span> <button type="button" class="sf-dump-search-input-previous" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"> <path d="M1683 1331l-166 165q-19 19-45 19t-45-19l-531-531-531 531q-19 19-45 19t-45-19l-166-165q-19-19-19-45.5t19-45.5l742-741q19-19 45-19t45 19l742 741q19 19 19 45.5t-19 45.5z"\/> <\/svg> <\/button> <button type="button" class="sf-dump-search-input-next" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"> <path d="M1683 808l-742 741q-19 19-45 19t-45-19l-742-741q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z"\/> <\/svg> <\/button> '; root.insertBefore(search, root.firstChild); var state = new SearchState(); var searchInput = search.querySelector('.sf-dump-search-input'); var counter = search.querySelector('.sf-dump-search-count'); var searchInputTimer = 0; var previousSearchQuery = ''; addEventListener(searchInput, 'keyup', function (e) { var searchQuery = e.target.value; /* Don't perform anything if the pressed key didn't change the query */ if (searchQuery === previousSearchQuery) { return; } previousSearchQuery = searchQuery; clearTimeout(searchInputTimer); searchInputTimer = setTimeout(function () { state.reset(); collapseAll(root); resetHighlightedNodes(root); if ('' === searchQuery) { counter.textContent = '0 of 0'; return; } var xpathResult = doc.evaluate('//pre[@id="' + root.id + '"]//span[@class="sf-dump-str" or @class="sf-dump-key" or @class="sf-dump-public" or @class="sf-dump-protected" or @class="sf-dump-private"][contains(child::text(), ' + xpathString(searchQuery) + ')]', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (node = xpathResult.iterateNext()) state.nodes.push(node); showCurrent(state); }, 400); }); Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) { addEventListener(btn, 'click', function (e) { e.preventDefault(); var direction = -1 !== e.target.className.indexOf('next') ? 'next' : 'previous'; 'next' === direction ? state.next() : state.previous(); searchInput.focus(); collapseAll(root); showCurrent(state); }) }); addEventListener(root, 'keydown', function (e) { var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className); if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) { /* F3 or CMD/CTRL + F */ e.preventDefault(); search.className = search.className.replace(/\bsf-dump-search-hidden\b/, ''); searchInput.focus(); } else if (isSearchActive) { if (27 === e.keyCode) { /* ESC key */ search.className += ' sf-dump-search-hidden'; e.preventDefault(); resetHighlightedNodes(root); searchInput.value = ''; } else if ( (isCtrlKey(e) && 71 === e.keyCode) /* CMD/CTRL + G */ || 13 === e.keyCode /* Enter */ || 114 === e.keyCode /* F3 */ ) { e.preventDefault(); e.shiftKey ? state.previous() : state.next(); collapseAll(root); showCurrent(state); } } }); } if (0 >= options.maxStringLength) { return; } try { elt = root.querySelectorAll('.sf-dump-str'); len = elt.length; i = 0; t = []; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; s = elt.innerText || elt.textContent; x = s.length - options.maxStringLength; if (0 < x) { h = elt.innerHTML; elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength); elt.className += ' sf-dump-str-collapse'; elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+ '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>'; } } } catch (e) { } }; })(document); </script><style> pre.sf-dump { display: block; white-space: pre; padding: 5px; } pre.sf-dump:after { content: ""; visibility: hidden; display: block; height: 0; clear: both; } pre.sf-dump span { display: inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump abbr { text-decoration: none; border: none; cursor: help; } pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; color: inherit; } pre.sf-dump .sf-dump-ellipsis { display: inline-block; overflow: visible; text-overflow: ellipsis; max-width: 5em; white-space: nowrap; overflow: hidden; vertical-align: top; } pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis { max-width: none; } pre.sf-dump code { display:inline; padding:0; background:none; } .sf-dump-str-collapse .sf-dump-str-collapse { display: none; } .sf-dump-str-expand .sf-dump-str-expand { display: none; } .sf-dump-public.sf-dump-highlight, .sf-dump-protected.sf-dump-highlight, .sf-dump-private.sf-dump-highlight, .sf-dump-str.sf-dump-highlight, .sf-dump-key.sf-dump-highlight { background: rgba(111, 172, 204, 0.3); border: 1px solid #7DA0B1; border-radius: 3px; } .sf-dump-public.sf-dump-highlight-active, .sf-dump-protected.sf-dump-highlight-active, .sf-dump-private.sf-dump-highlight-active, .sf-dump-str.sf-dump-highlight-active, .sf-dump-key.sf-dump-highlight-active { background: rgba(253, 175, 0, 0.4); border: 1px solid #ffa500; border-radius: 3px; } pre.sf-dump .sf-dump-search-hidden { display: none; } pre.sf-dump .sf-dump-search-wrapper { float: right; font-size: 0; white-space: nowrap; max-width: 100%; text-align: right; } pre.sf-dump .sf-dump-search-wrapper > * { vertical-align: top; box-sizing: border-box; height: 21px; font-weight: normal; border-radius: 0; background: #FFF; color: #757575; border: 1px solid #BBB; } pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input { padding: 3px; height: 21px; font-size: 12px; border-right: none; width: 140px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: #000; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous { background: #F2F2F2; outline: none; border-left: none; font-size: 0; line-height: 0; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next > svg, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous > svg { pointer-events: none; width: 12px; height: 12px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-count { display: inline-block; padding: 0 5px; margin: 0; border-left: none; line-height: 21px; font-size: 12px; }pre.sf-dump, pre.sf-dump .sf-dump-default{background-color:#fff; color:#222; line-height:1.2em; font-weight:normal; font:12px Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:100000}pre.sf-dump .sf-dump-num{color:#a71d5d}pre.sf-dump .sf-dump-const{color:#795da3}pre.sf-dump .sf-dump-str{color:#df5000}pre.sf-dump .sf-dump-cchr{color:#222}pre.sf-dump .sf-dump-note{color:#a71d5d}pre.sf-dump .sf-dump-ref{color:#a0a0a0}pre.sf-dump .sf-dump-public{color:#795da3}pre.sf-dump .sf-dump-protected{color:#795da3}pre.sf-dump .sf-dump-private{color:#795da3}pre.sf-dump .sf-dump-meta{color:#b729d9}pre.sf-dump .sf-dump-key{color:#df5000}pre.sf-dump .sf-dump-index{color:#a71d5d}</style><pre class=sf-dump id=sf-dump-160511467 data-indent-pad="  "><abbr title="Illuminate\Support\Facades\Request" class=sf-dump-note>Request</abbr> {<a class=sf-dump-ref>#172</a>}
</code>```

still i haven't found the solution please help me

答:
Try this:-

```<code>Url should be like this
var src  = "{{ route(capture-rating') }}";
var rating = 4;
 $.ajax({
    url:src
    type:'post',
    //dataType:'json',

    data:{rating:rating},

    success:function(data){
         alert(data);
    }
 });

Route::post('capture-rating',function(Request $request){
    if($request->ajax()){
       $data = $request->all();
       echo "```"; print_r($data);
                or
       dd($data);
    }
});
```

Hope it helps!

Body:
I'm getting some junk data instead of my posted data in laravel 5.4

here is my route

Route::post('capture-rating',function(Request $request){

       dd($request);
});

my $.ajax looks like this

    var rating = 4;
     $.ajax({
        url:'capture-rating',
        type:'post',
        //dataType:'json',

        data:{rating:rating},

        success:function(data){
            console.log(data);
        }
     });

here is network tab console image

i'm getting this junk data why i don't know?

Request {#172}

still i haven't found the solution please help me

Body:
Try this:-

Url should be like this
var src  = "{{ route(capture-rating') }}";
var rating = 4;
 $.ajax({
    url:src
    type:'post',
    //dataType:'json',

    data:{rating:rating},

    success:function(data){
         alert(data);
    }
 });

Route::post('capture-rating',function(Request $request){
    if($request->ajax()){
       $data = $request->all();
       echo "<pre>"; print_r($data);
                or
       dd($data);
    }
});

Hope it helps!


问:
Validate mobile number into 10 digit numbers in php jquery
I am trying to validate phone number jquery when alphabets are pressed it as to display error message. Below code takes enters digits but doesnt validate to 10 digits. How to validate to 10 digit number. </p>

```<code><script type="text/javascript" >
 $(function() {
   $("#phno").bind("keypress", function (event) {
                if (event.charCode != 0) {
                       var regex = new RegExp("^[0-9]{10}$");
                    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                    if (!regex.test(key)) {
                      alert("Please enter valid Student Phone No");
                        event.preventDefault();
                        return false;
                    }
                }
            });
 });
</code>```

答:
Simply use this...</p>

```<code>var num = '1234567890';
if(!isNaN(num) && num.length ==10){ alert('Validated');  }
else { alert('Not a 10 digit number'); }
</code>```

Body:
Simply use this...

var num = '1234567890';
if(!isNaN(num) && num.length ==10){ alert('Validated');  }
else { alert('Not a 10 digit number'); }


问:
Dynamic formation of variable name in PHP?
The code below dynamically concatenates keys to an existing array $options_pool. So the final form should be: $options_pool[ $base_key ][ $first_key ][ $second_key ]... This is so I can dynamically assign a value to the elements of the array $options_pool which is multidimensional.

```<code>foreach( $this->post_vars as $name => $value ) {
    //Look for $name key in array $options_pool if it exists.
    //Use multi_array_key_exists() to handle the task
    //It should return something like "fruit:mango:apple_mango"
    //Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
    $match_key = multi_array_key_exists( $name, $options_pool );
    $option_keys = explode( ':', $match_key );
    $option_keys_length = count( $option_keys );
    $option_name_array = array();
    if( 0 < $option_keys_length ) {
     for( $c = $option_keys_length; $c > 0; $c-- ) {
         $sub_keys = '$options_pool';
         for( $c_sub = 0; $c_sub < $c ; $c_sub++ ) {
             $sub_keys .= '[ $option_keys[ '.  $c_sub . ' ] ]';
         }
         $option_name_array[] = $sub_keys;
     }
     foreach( $option_name_array as $f_var_name ) {
          //the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
          $f_var_name = $value;
       }
    }
}

//The $options_pool array
$options_pool = array( 'car' => '', 'animals' => '', 'fruit' => array( 'mango' => array( 'apple_mango' => '' ));
</code>```

I think the logic is correct except that this portion of the code:

```<code>foreach( $option_name_array as $f_var_name ) {
    $f_var_name = $value; //particularly this line
}
</code>```

doesn't work? I've tested printing the value of $f_var_name and the result is correct but it doesn't really call the array?

答:
Try this...</p>

```<code>foreach( $option_name_array as $key => $f_var_name ) {
    $option_name_array[$key] = $value; //particularly this line
}
</code>```

Body:
The code below dynamically concatenates keys to an existing array $options_pool. So the final form should be: $options_pool[ $base_key ][ $first_key ][ $second_key ]... This is so I can dynamically assign a value to the elements of the array $options_pool which is multidimensional.

foreach( $this->post_vars as $name => $value ) {
    //Look for $name key in array $options_pool if it exists.
    //Use multi_array_key_exists() to handle the task
    //It should return something like "fruit:mango:apple_mango"
    //Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
    $match_key = multi_array_key_exists( $name, $options_pool );
    $option_keys = explode( ':', $match_key );
    $option_keys_length = count( $option_keys );
    $option_name_array = array();
    if( 0 < $option_keys_length ) {
     for( $c = $option_keys_length; $c > 0; $c-- ) {
         $sub_keys = '$options_pool';
         for( $c_sub = 0; $c_sub < $c ; $c_sub++ ) {
             $sub_keys .= '[ $option_keys[ '.  $c_sub . ' ] ]';
         }
         $option_name_array[] = $sub_keys;
     }
     foreach( $option_name_array as $f_var_name ) {
          //the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
          $f_var_name = $value;
       }
    }
}

//The $options_pool array
$options_pool = array( 'car' => '', 'animals' => '', 'fruit' => array( 'mango' => array( 'apple_mango' => '' ));

I think the logic is correct except that this portion of the code:

foreach( $option_name_array as $f_var_name ) {
    $f_var_name = $value; //particularly this line
}

doesn't work? I've tested printing the value of $f_var_name and the result is correct but it doesn't really call the array?

Body:
Try this...

foreach( $option_name_array as $key => $f_var_name ) {
    $option_name_array[$key] = $value; //particularly this line
}


问:
Symfony 3 routing subdomains
I have to bundles, frontend and backend. I want the subdomain "admin.domain.com" to work as "admin.domain.com/whateverpage" and controlled by the backend bundle controllers. All other subdomains should work like "sub1.domain.com/{dynamicwhateverpage}" or "sub2.domain.com/{dynamicwhateverpage}" and be controlled by the frontend bundle controllers.

I got it to work with "admin.domain.com/backend/whateverpage" and "sub1.domain.com/frontend/{dynamicwhateverpage}". The backend and frontend in the URL of course should not be visible to the users. Is there a way to rewrite with htaccess? Or is there even a better way to achieve this kind of rewriting?

答:
Symfony can match routing based on host. This should also work when importing routes, though I have not tested it;

```<code>/**
 * @Route("/", name="project_page", host="{project}.example.com")
 */
public function projectPageAction($project) {
    // ...
}
</code>```

Just make sure your none dynamic routes are loaded before the all capturing one, or make sure the project one can't match eg. admin.

Earlier Routes Always Win

Why would you ever care about requirements? If a request matches two routes, then the first route always wins.

Title: Symfony 3 routing subdomains

Body:
Symfony can match routing based on host. This should also work when importing routes, though I have not tested it;

/**
 * @Route("/", name="project_page", host="{project}.example.com")
 */
public function projectPageAction($project) {
    // ...
}

Just make sure your none dynamic routes are loaded before the all capturing one, or make sure the project one can't match eg. admin.

Earlier Routes Always Win

Why would you ever care about requirements? If a request matches two routes, then the first route always wins.


问:
javascript function doesn't responding
Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().

```<code>function checkJs()
{
   debugger;
   alert("your output!!!");
}
</code>```

My code:

```<code><div id="mydivid" style="background-color:lightblue;">
   STAGE
</div>
<input type="button" id="btnid" value="Load Data" />
</code>```

When i click a button , Its just call the jQuery click function

```<code>$(document).ready(function () {
   $("#btnid").click(function (event) {
      debugger;
      $.getScript('mydata.js', function() {
         // debugger;
          checkJs();
      });

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

I used initialy 1.12.4.js library file in the head tag

and i added my external js file in head tag.

what is the problem in my code. why the button click did not reached the external method.

答:
You can directly call your function without getScript if you have already included the mydata.js in head.

If not, and want to do it with getScript then make sure you are giving correct path, load js in done callback and if still not then check if calls goes to fail callback.

```<code> $(document).ready(function () {
    $("#btnid").click(function (event) {
      debugger;

       $.getScript('mydata.js').done(function(data, textStatus, jqxhr) {
          checkJs();
       }).fail(function(){
           if(arguments[0].readyState==0){
           //script failed to load
           }else{
             //script loaded but failed to parse
             alert(arguments[2].toString());
           }
       })
    });
});
</code>```

Done callback has 3 parameters with has following values in it.

data: has the returned data(script)

textStatus: it returns the status in plain text, e.g. "Success"

jqxhr : its jqXHR object, which is a superset of the XMLHTTPRequest object and has the "status" property which returns status code.

Title: javascript function doesn't responding

Body:
Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().

function checkJs()
{
   debugger;
   alert("your output!!!");
}

My code:

   STAGE

<input type="button" id="btnid" value="Load Data" />

When i click a button , Its just call the jQuery click function

$(document).ready(function () {
   $("#btnid").click(function (event) {
      debugger;
      $.getScript('mydata.js', function() {
         // debugger;
          checkJs();
      });

   });
});

I used initialy 1.12.4.js library file in the head tag

and i added my external js file in head tag.

what is the problem in my code. why the button click did not reached the external method.

Body:
You can directly call your function without getScript if you have already included the mydata.js in head.

If not, and want to do it with getScript then make sure you are giving correct path, load js in done callback and if still not then check if calls goes to fail callback.

 $(document).ready(function () {
    $("#btnid").click(function (event) {
      debugger;

       $.getScript('mydata.js').done(function(data, textStatus, jqxhr) {
          checkJs();
       }).fail(function(){
           if(arguments[0].readyState==0){
           //script failed to load
           }else{
             //script loaded but failed to parse
             alert(arguments[2].toString());
           }
       })
    });
});

Done callback has 3 parameters with has following values in it.

data: has the returned data(script)

textStatus: it returns the status in plain text, e.g. "Success"

jqxhr : its jqXHR object, which is a superset of the XMLHTTPRequest object and has the "status" property which returns status code.


问:
Bottom navigation overlapping recycler view contents in android
I am using bottom navigation view and displaying three tabs,In one of the tab i have added recycler view, but the contents are overlapped by bottom navigation.Not able to scroll recycler view.Is there any way that i can  hide the bottom navigation when i scroll item on recycler view.

```<code><?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:sv="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:context=".activity.patient.PatientsActivity">

        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <RelativeLayout
            android:id="@+id/asd"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:orientation="vertical">

            <co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView
                android:id="@+id/appointmentsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:rrvEmptyLayoutId="@layout/empty_view"
                app:rrvLayoutType="LinearLayout"
                app:rrvSwipeToDelete="true" />

            <android.support.design.widget.BottomNavigationView
                android:id="@+id/bottom_navigation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                app:itemBackground="@color/white"
                app:layout_behavior=".BottomNavigationBehavior"
                app:menu="@menu/bottom_navigation_main" />
        </RelativeLayout>
    </android.support.design.widget.CoordinatorLayout> </android.support.v4.widget.DrawerLayout>
</code>```

image

答:
First i think you could add an:

android:layout_above="@id/bottom_navigation"

To the Recyclerview

For the Scrolling part i would suggest looking for a ScrollingBehaviour
like in this question:
How to scroll up/down of bottom bar on scrolling of RecyclerView

Body:
I am using bottom navigation view and displaying three tabs,In one of the tab i have added recycler view, but the contents are overlapped by bottom navigation.Not able to scroll recycler view.Is there any way that i can  hide the bottom navigation when i scroll item on recycler view.

<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:sv="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:context=".activity.patient.PatientsActivity">

        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <RelativeLayout
            android:id="@+id/asd"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:orientation="vertical">

            <co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView
                android:id="@+id/appointmentsList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:rrvEmptyLayoutId="@layout/empty_view"
                app:rrvLayoutType="LinearLayout"
                app:rrvSwipeToDelete="true" />

            <android.support.design.widget.BottomNavigationView
                android:id="@+id/bottom_navigation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                app:itemBackground="@color/white"
                app:layout_behavior=".BottomNavigationBehavior"
                app:menu="@menu/bottom_navigation_main" />
        </RelativeLayout>
    </android.support.design.widget.CoordinatorLayout> </android.support.v4.widget.DrawerLayout>

image