问:
python function for creating pairs based on ordered items in list
```<code>dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
       (1,"Do anything fun this weekend?"),(2,"I mostly slept"),
       (2,"but I also played games"),(1,"That sounds fun")]
</code>```

Using python, I am trying to create a conversation pair dataset where each pair in the set will have speaker 1 and the subsequent response from speaker 2.
With the example dat above, I would need to iterate through the list and 1) merge sentences from the same speaker if they are subsequent and 2) create the pair as below example;

Output:

```<code>((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))
</code>```

How do I write a function that takes in sequential data like this to create conversation pairs?

答:
```<code>conv = []
ls, lm = dat[0]
for s, m in dat[1:]:
    if s == ls:
        lm += ' ' + m
    else:
        conv.append((ls, lm))
        ls, lm = s, m
else:
    conv.append((ls, lm))
    if conv[-1][0] == 1:
        conv.append((2, None))
output = tuple([(conv[i], conv[i+1]) for i in range(0,len(conv) - 1, 2)])
</code>```

Output:

```<code>[((1, 'hello how are you?'), (2, 'I am doing well, thanks!')), ((1, 'Do anything fun this weekend?'), (2, 'I mostly slept but I also played games')), ((1, 'That sounds fun'), (2, None))]
</code>```

use this snippet of code, hope this solves your purpose

Body:
dat = [(1,"hello"),(1,"how are you?"),(2,"I am doing well, thanks!"),
       (1,"Do anything fun this weekend?"),(2,"I mostly slept"),
       (2,"but I also played games"),(1,"That sounds fun")]

Using python, I am trying to create a conversation pair dataset where each pair in the set will have speaker 1 and the subsequent response from speaker 2.
With the example dat above, I would need to iterate through the list and 1) merge sentences from the same speaker if they are subsequent and 2) create the pair as below example;

Output:

((1,"hello how are you"),(2,"I am doing well, thanks!"))
((1,"Do anything fun this weekend?",(2,"I mostly slept but I also played games"))
((1,"That sounds fun"),(2,None))

How do I write a function that takes in sequential data like this to create conversation pairs?

Body:
conv = []
ls, lm = dat[0]
for s, m in dat[1:]:
    if s == ls:
        lm += ' ' + m
    else:
        conv.append((ls, lm))
        ls, lm = s, m
else:
    conv.append((ls, lm))
    if conv[-1][0] == 1:
        conv.append((2, None))
output = tuple([(conv[i], conv[i+1]) for i in range(0,len(conv) - 1, 2)])

Output:

[((1, 'hello how are you?'), (2, 'I am doing well, thanks!')), ((1, 'Do anything fun this weekend?'), (2, 'I mostly slept but I also played games')), ((1, 'That sounds fun'), (2, None))]

use this snippet of code, hope this solves your purpose


来源: stackexchange

问:
How to add multiple polygons in leaflet map using r loop?
I'm trying to add multiple polygon to leaflet world map, according to a number of lists of country code. And I was trying to use R loop to add the polygon. Here's the code that I manually add polygons from list 1:

```<code>library(sp)
library(raster)
library(leaflet)
library(maps)
library(tidyverse)

countries_1 <- c('PAK','TUR','BGR')

adm1 <- getData('GADM', country='PAK', level=0)
adm2 <- getData('GADM', country= 'TUR', level=0)
adm3 <- getData('GADM', country= 'BGR', level=0)

leaflet() %>%
  addTiles() %>%
  addPolygons(data=adm1, weight = 3, fillColor = 'purple', color = 'purple') %>%
  addPolygons(data=adm2, weight = 3, fillColor = 'purple', color = 'purple') %>%
  addPolygons(data=adm3, weight = 3, fillColor = 'purple', color = 'purple')
</code>```

I am thinking using the loop to add multiple polygon layers so that for list_n:

```<code> countries_n <- ('ctry1','ctry2','ctry3',...'ctryn')

 for (i in country_n) {

   countries <-  basemap %>% addPolygons(data=getData('GADM',country = i, level = 0),
  weight = 3, fillColor = 'purple', color = 'purple')

  }
</code>```

The question is how can I embed the loop to "leflet() %>%" ?

*Note here:
If try to add multiple data in addPolygons(), it will plot only the first element in the data, in below case, only country 'PAK' will be ploted:

```<code>addPolygons(data=c('PAK','TUR'), weight = 3, fillColor = 'purple', color = 'purple')
</code>```

答:
Here's a solution using packages sf and mapview. Note that this is currently only possible using the develop version of mapview (see commented out devtools::install_github()

```<code># devtools::install_github("r-spatial/mapview@develop")
library(sf)
library(mapview)
library(raster)

countries_1 <- c('PAK','TUR','BGR')

dat_list = lapply(countries_1, function(i) {
  st_as_sf(getData("GADM", country = i, level = 0))
})

m = leaflet() %>% addTiles()

for (i in dat_list) {
  m = mapview::addFeatures(map = m,
                           data = i,
                           weight = 3,
                           fillColor = 'purple',
                           color = 'purple')
}

m
</code>```

Note that addFeatures is type agnostic, so any combination of points, lines and/or polygons will work here.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to add multiple polygon to leaflet world map, according to a number of lists of country code. And I was trying to use R loop to add the polygon. Here's the code that I manually add polygons from list 1:

library(sp)
library(raster)
library(leaflet)
library(maps)
library(tidyverse)

countries_1 <- c('PAK','TUR','BGR')

adm1 <- getData('GADM', country='PAK', level=0)
adm2 <- getData('GADM', country= 'TUR', level=0)
adm3 <- getData('GADM', country= 'BGR', level=0)

leaflet() %>%
  addTiles() %>%
  addPolygons(data=adm1, weight = 3, fillColor = 'purple', color = 'purple') %>%
  addPolygons(data=adm2, weight = 3, fillColor = 'purple', color = 'purple') %>%
  addPolygons(data=adm3, weight = 3, fillColor = 'purple', color = 'purple')

I am thinking using the loop to add multiple polygon layers so that for list_n:

 countries_n <- ('ctry1','ctry2','ctry3',...'ctryn')

 for (i in country_n) {

   countries <-  basemap %>% addPolygons(data=getData('GADM',country = i, level = 0),
  weight = 3, fillColor = 'purple', color = 'purple')

  }

The question is how can I embed the loop to "leflet() %>%" ?

*Note here:
If try to add multiple data in addPolygons(), it will plot only the first element in the data, in below case, only country 'PAK' will be ploted:

addPolygons(data=c('PAK','TUR'), weight = 3, fillColor = 'purple', color = 'purple')

Body:
Here's a solution using packages sf and mapview. Note that this is currently only possible using the develop version of mapview (see commented out devtools::install_github()

# devtools::install_github("r-spatial/mapview@develop")
library(sf)
library(mapview)
library(raster)

countries_1 <- c('PAK','TUR','BGR')

dat_list = lapply(countries_1, function(i) {
  st_as_sf(getData("GADM", country = i, level = 0))
})

m = leaflet() %>% addTiles()

for (i in dat_list) {
  m = mapview::addFeatures(map = m,
                           data = i,
                           weight = 3,
                           fillColor = 'purple',
                           color = 'purple')
}

m

Note that addFeatures is type agnostic, so any combination of points, lines and/or polygons will work here.


问:
Salesforce button uses same Docusign template regardless of related Opportunity
when I use the button, the same Docusign template is used regardless of the associated Opportunity.  If I move the (OPPNAME = 'WorldQuant LLC%') line to the end, a different template is used, but again its the same regardless of Opportunity Name.  I am new to Javascript so feel free to dumb down any answers, thanks.</p>

```<code>var OPPNAME;
var PICKDSTEMPLATE;
OPPNAME == '{!JSENCODE(Opportunity.Name)}';
PICKDSTEMPLATE = '{!Opportunity.Type_of_Opportunity__c}';
if (OPPNAME = 'WorldQuant LLC%')
{
DST = '75E95019-6513-4EE9-8f6B-C2FD9A99B9C2';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corp/Ind')
{
DST='38FE916A-0F28-46FD-BBAB-28CA54621B7E';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corporate from Lead')
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corporate')
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
</code>```

答:
Got this to work with some help:</p>

```<code>var ACCNAME;
var PICKDSTEMPLATE;
ACCNAME = '{!Opportunity.Account}';
PICKDSTEMPLATE = '{!Opportunity.Type_of_Opportunity__c}';
if ((ACCNAME == 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corp/Ind' || PICKDSTEMPLATE == 'Corporate'))
{
DST = '75e95019-6513-4ee9-8f6b-c2fd9a99b9c2';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corp/Ind'))
{
DST='38FE916A-0F28-46FD-BBAB-28CA54621B7E';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corporate from Lead'))
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corporate'))
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
</code>```

Body:
when I use the button, the same Docusign template is used regardless of the associated Opportunity.  If I move the (OPPNAME = 'WorldQuant LLC%') line to the end, a different template is used, but again its the same regardless of Opportunity Name.  I am new to Javascript so feel free to dumb down any answers, thanks.

var OPPNAME;
var PICKDSTEMPLATE;
OPPNAME == '{!JSENCODE(Opportunity.Name)}';
PICKDSTEMPLATE = '{!Opportunity.Type_of_Opportunity__c}';
if (OPPNAME = 'WorldQuant LLC%')
{
DST = '75E95019-6513-4EE9-8f6B-C2FD9A99B9C2';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corp/Ind')
{
DST='38FE916A-0F28-46FD-BBAB-28CA54621B7E';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corporate from Lead')
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
else if (OPPNAME != 'WorldQuant LLC%' && PICKDSTEMPLATE == 'Corporate')
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}

Body:
Got this to work with some help:

var ACCNAME;
var PICKDSTEMPLATE;
ACCNAME = '{!Opportunity.Account}';
PICKDSTEMPLATE = '{!Opportunity.Type_of_Opportunity__c}';
if ((ACCNAME == 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corp/Ind' || PICKDSTEMPLATE == 'Corporate'))
{
DST = '75e95019-6513-4ee9-8f6b-c2fd9a99b9c2';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corp/Ind'))
{
DST='38FE916A-0F28-46FD-BBAB-28CA54621B7E';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corporate from Lead'))
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}
else if ((ACCNAME != 'WorldQuant LLC') && (PICKDSTEMPLATE == 'Corporate'))
{
DST = 'ACB0C25C-38FE-4802-9BEA-8CA5D8AA77A9';
}


问:
Matlab - Creating two arrays that consider all possible values for two objects
I have two physical "objects." I am representing their positions with two different arrays.

• Object 1 moves in the xy-plane only

• Object 2 moves in all three physical dimensions

Objective: Vectorize the four for loops without distorting the data. Also, the intent is to perform this operation for all possible values of object 1 to be compared with object 2.

Here is the code snippet:

```<code>Npos = 21;
Nsam = 200;

% dummy initialisation
AX = rand(1, Npos);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(Nsam);
By = rand(Nsam);
Bz = rand(Nsam);

for qx = 1 : Npos
    for yx = 1 : Npos
        for zx = 1 : Nsam
            for cx = 1 : Nsam
                Tx2Array( qx, yx, zx, cx ) = sqrt( ( AX( qx ) - Bx( zx, cx ) ).^2 + ( AY( yx ) - By( zx, cx ) ).^2 + ( AZ( yx ) - Bz( zx, cx ) ).^2 );
            end
        end
    end
end
% Result is a 21 x 21 x 200 x 200 matrix filled with all real numbers
</code>```

Legend

AX, AY, AZ are 1 x 21 arrays and represent the (x,y=0,z) of Object 1

AY is all zeros, but for readability is still included (hence no fifth loop!)

Bx, By, Bz are all 200 x 200 arrays and represent the (x,y,z) of Object 2

Npos = 21; Nsam = 200;

The formula used above is:

```<code>sqrt( (a1-b1)^2 + (a2-b2)^2 + (a3-b3)^2 )
</code>```

答:
If the arrays are correctly initialized your task will be very simple:

Initialize the arrays with the correct dimensions

```<code>AX = rand( Npos,1);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(1,1,Nsam,Nsam);
By = rand(1,1,Nsam,Nsam);
Bz = rand(1,1,Nsam,Nsam);
</code>```

Then in MATLAB r2016b / Octave you can simply write:

```<code>Tx2Array = sqrt( ( AX - Bx ).^2 + ( AY - By ).^2 + ( AZ - Bz ).^2 );
</code>```

In pre r2016b you can use bsxfun:

```<code>Tx2Array = sqrt(bsxfun(@plus,bsxfun(@plus,bsxfun(@minus,AX , Bx).^2,bsxfun(@minus,AY , By).^2),bsxfun(@minus,AZ , Bz).^2));
</code>```

Body:
I have two physical "objects." I am representing their positions with two different arrays.

• Object 1 moves in the xy-plane only

• Object 2 moves in all three physical dimensions

Objective: Vectorize the four for loops without distorting the data. Also, the intent is to perform this operation for all possible values of object 1 to be compared with object 2.

Here is the code snippet:

Npos = 21;
Nsam = 200;

% dummy initialisation
AX = rand(1, Npos);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(Nsam);
By = rand(Nsam);
Bz = rand(Nsam);

for qx = 1 : Npos
    for yx = 1 : Npos
        for zx = 1 : Nsam
            for cx = 1 : Nsam
                Tx2Array( qx, yx, zx, cx ) = sqrt( ( AX( qx ) - Bx( zx, cx ) ).^2 + ( AY( yx ) - By( zx, cx ) ).^2 + ( AZ( yx ) - Bz( zx, cx ) ).^2 );
            end
        end
    end
end
% Result is a 21 x 21 x 200 x 200 matrix filled with all real numbers

Legend

AX, AY, AZ are 1 x 21 arrays and represent the (x,y=0,z) of Object 1

AY is all zeros, but for readability is still included (hence no fifth loop!)

Bx, By, Bz are all 200 x 200 arrays and represent the (x,y,z) of Object 2

Npos = 21; Nsam = 200;

The formula used above is:

sqrt( (a1-b1)^2 + (a2-b2)^2 + (a3-b3)^2 )

Body:
If the arrays are correctly initialized your task will be very simple:

Initialize the arrays with the correct dimensions

AX = rand( Npos,1);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(1,1,Nsam,Nsam);
By = rand(1,1,Nsam,Nsam);
Bz = rand(1,1,Nsam,Nsam);

Then in MATLAB r2016b / Octave you can simply write:

Tx2Array = sqrt( ( AX - Bx ).^2 + ( AY - By ).^2 + ( AZ - Bz ).^2 );

In pre r2016b you can use bsxfun:

Tx2Array = sqrt(bsxfun(@plus,bsxfun(@plus,bsxfun(@minus,AX , Bx).^2,bsxfun(@minus,AY , By).^2),bsxfun(@minus,AZ , Bz).^2));


问:
Styling form error message - bootstrap/rails
The error messages for my rails form look terrible with bootstrap. Does anyone know a solution for better (nice looking) error messages? I use Rails and Bootstrap.

My form (it's a helper) is like this:

```<code><%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-inline">
    <%= f.text_field :email, class:'input-large', placeholder:'Test' %>
<!--   </div>
  <div class="actions"> -->
    <%= f.submit class:'btn btn-large btn-success' %>
  </div>
<% end %>
</code>```

答:
Bootstrap 4 Alpha 6

I copied the compiled Bootstrap CSS from

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css

Searched for .has-danger, copied all the classes, did a search & replace on .has-danger for .field_with_errors, and I also added .field_with_errors label

```<code>.field_with_errors label,
.field_with_errors .form-control-feedback,
.field_with_errors .form-control-label,
.field_with_errors .col-form-label,
.field_with_errors .form-check-label,
.field_with_errors .custom-control {
  color: #d9534f;
}

.field_with_errors .form-control {
  border-color: #d9534f;
}

.field_with_errors .input-group-addon {
  color: #d9534f;
  border-color: #d9534f;
  background-color: #fdf7f7;
}

.field_with_errors .form-control-danger {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23d9534f' viewBox='-2 -2 7 7'%3E%3Cpath stroke='%23d9534f' d='M0 0l3 3m0-3L0 3'/%3E%3Ccircle r='.5'/%3E%3Ccircle cx='3' r='.5'/%3E%3Ccircle cy='3' r='.5'/%3E%3Ccircle cx='3' cy='3' r='.5'/%3E%3C/svg%3E");
}
</code>```

I wasn't able to get the input groups addons to display correctly, as it wraps the input with a
.

Docs: https://v4-alpha.getbootstrap.com/components/forms/#validation

Honestly some of these classes are not used because Rails doesn't have an obvious way to set classes on error fields.

For the error list, I just used this simple class

```<code>#error_explanation {
  color: red;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The error messages for my rails form look terrible with bootstrap. Does anyone know a solution for better (nice looking) error messages? I use Rails and Bootstrap.

My form (it's a helper) is like this:

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>

<%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:

      <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.text_field :email, class:'input-large', placeholder:'Test' %>

    <%= f.submit class:'btn btn-large btn-success' %>

<% end %>

Body:
Bootstrap 4 Alpha 6

I copied the compiled Bootstrap CSS from

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css

Searched for .has-danger, copied all the classes, did a search & replace on .has-danger for .field_with_errors, and I also added .field_with_errors label

.field_with_errors label,
.field_with_errors .form-control-feedback,
.field_with_errors .form-control-label,
.field_with_errors .col-form-label,
.field_with_errors .form-check-label,
.field_with_errors .custom-control {
  color: #d9534f;
}

.field_with_errors .form-control {
  border-color: #d9534f;
}

.field_with_errors .input-group-addon {
  color: #d9534f;
  border-color: #d9534f;
  background-color: #fdf7f7;
}

.field_with_errors .form-control-danger {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23d9534f' viewBox='-2 -2 7 7'%3E%3Cpath stroke='%23d9534f' d='M0 0l3 3m0-3L0 3'/%3E%3Ccircle r='.5'/%3E%3Ccircle cx='3' r='.5'/%3E%3Ccircle cy='3' r='.5'/%3E%3Ccircle cx='3' cy='3' r='.5'/%3E%3C/svg%3E");
}

I wasn't able to get the input groups addons to display correctly, as it wraps the input with a <div>.

Docs: https://v4-alpha.getbootstrap.com/components/forms/#validation

Honestly some of these classes are not used because Rails doesn't have an obvious way to set classes on error fields.

For the error list, I just used this simple class

#error_explanation {
  color: red;
}


问:
Can't instantiate class even included
I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts.
I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

```<code>  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;

class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>
</code>```

And here is my form.php class where I'd like to instantiate user class.

```<code>    <!Doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form php</title>
</head>
<body>
<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user<br>name: " . $name . "<br>" .
    "age: " . $age . "<br>" . "sex: " . $sex."<br>";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>
</body>
</html>
</code>```

答:
Try

```<code>$newuser = new \infopro\User($name, $age, $sex);
</code>```

Or

```<code><?php
use \infopro\User;
?>
    <!Doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form php</title>
</head>
<body>
<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user<br>name: " . $name . "<br>" .
    "age: " . $age . "<br>" . "sex: " . $sex."<br>";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>
</body>
</html>
</code>```

Title: Can't instantiate class even included

Body:
I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts.
I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;

class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>

And here is my form.php class where I'd like to instantiate user class.

    <!Doctype html>

    <meta charset="UTF-8">
    <title>Form php</title>

<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user
name: " . $name . "
" .
    "age: " . $age . "
" . "sex: " . $sex."
";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>

Body:
Try

$newuser = new \infopro\User($name, $age, $sex);

Or

<?php
use \infopro\User;
?>
    <!Doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form php</title>
</head>
<body>
<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user<br>name: " . $name . "<br>" .
    "age: " . $age . "<br>" . "sex: " . $sex."<br>";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>
</body>
</html>


问:
Unexplained Subversion directory status after checkout
I am working in an SVN repo with a huge branches area.  As a result, I did a shallow (--depth empty) checkout on my branches folder.

Example: C:\svn\branches

Has no subfolders in my working copy.

Suppose I have a branch called MyBranch that I want to checkout.

I run:

svn checkout http://svn/ThisProject/branches/MyBranch C:\svn\branches\MyBranch --depth infinity

Coolio.  I get all the files.  However, svn status looks a little strange:

```
C:\svn\branches> svn status
?       MyBranch
```

Let's check info...

```
C:\svn\branches> svn info .
Path: .
URL: http://svn/ThisProject/branches
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Depth: empty
Last Changed Author: e467443
Last Changed Rev: 1733
Last Changed Date: 2010-12-14 21:42:31 +0800 (Tue, 14 Dec 2010)
```

```
C:\svn\branches> svn info MyBranch
Path: ARPE-TEST2
URL: http://svn/ThisProject/branches/MyBranch
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Last Changed Author: v094424
Last Changed Rev: 1624
Last Changed Date: 2010-12-13 22:46:21 +0800 (Mon, 13 Dec 2010)
```

That's weird.  Let's try an add:

```
C:\svn\branches> svn add MyBranch
svn: warning: 'MyBranch' is already under version control
```

My guess is that branches has Depth: empty so SVN is confused.

Can anyone explain and provide a fix?  Maybe I can ignore.

I am using CollabNet command line tools on Windows.

```
C:\svn\branches> svn --version
svn, version 1.6.12 (r955767)
   compiled Jun 21 2010, 16:00:59
```

答:
You are not in the working directory, the Subversion commands only work when your current working directory is inside the project directory:

```<code>cd MyBranch
svn status
</code>```

You'll find everything starts to work after that.

ContentLicense: CC BY-SA 2.5

Body:
I am working in an SVN repo with a huge branches area.  As a result, I did a shallow (--depth empty) checkout on my branches folder.

Example: C:\svn\branches

Has no subfolders in my working copy.

Suppose I have a branch called MyBranch that I want to checkout.

I run:

svn checkout http://svn/ThisProject/branches/MyBranch C:\svn\branches\MyBranch --depth infinity

Coolio.  I get all the files.  However, svn status looks a little strange:

C:\svn\branches> svn status
?       MyBranch

Let's check info...

C:\svn\branches> svn info .
Path: .
URL: http://svn/ThisProject/branches
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Depth: empty
Last Changed Author: e467443
Last Changed Rev: 1733
Last Changed Date: 2010-12-14 21:42:31 +0800 (Tue, 14 Dec 2010)

C:\svn\branches> svn info MyBranch
Path: ARPE-TEST2
URL: http://svn/ThisProject/branches/MyBranch
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Last Changed Author: v094424
Last Changed Rev: 1624
Last Changed Date: 2010-12-13 22:46:21 +0800 (Mon, 13 Dec 2010)

That's weird.  Let's try an add:

C:\svn\branches> svn add MyBranch
svn: warning: 'MyBranch' is already under version control

My guess is that branches has Depth: empty so SVN is confused.

Can anyone explain and provide a fix?  Maybe I can ignore.

I am using CollabNet command line tools on Windows.

C:\svn\branches> svn --version
svn, version 1.6.12 (r955767)
   compiled Jun 21 2010, 16:00:59

Body:
You are not in the working directory, the Subversion commands only work when your current working directory is inside the project directory:

cd MyBranch
svn status

You'll find everything starts to work after that.


问:
PowerShell script fails
I am trying to use the PowerShell script below with PSv5 to automate some manual processes but it keeps failing and I cannot figure out why. When I try to debug it in ISE, I get the following error and no output file is generated:

Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:15 char:53
+ $HeaderLine, ${$DestinationFile} = Get-Content -Path <<<<  $SourceFile.FullName
+ CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
```

<pre class="lang-bsh prettyprint-override"><code># BEGIN SCRIPT
#
# Collect all the files in the directory
$SoureFiles = Get-ChildItem -Path 'C:\raw' -Filter '*.txt'

# Create the destination file
$DestinationFile = (New-Item -Path 'c:\done' `
-Name ('CombinedSources-' + (Get-Date -Format 'ddMMMyyyy') + '.txt') `
-ItemType File -Force).FullName
$DestinationFile

# Loop source, files, remove header line, append to the destination file
ForEach ($SourceFile in $SoureFiles)
{
$HeaderLine, ${$DestinationFile} = Get-Content -Path $SourceFile.FullName
${$DestinationFile}`
| Out-File -FilePath $DestinationFile -Append
}

# Sort the Destination file content and replace with sorted unique lines
(Get-Content -Path $DestinationFile `
| Sort-Object { [string]$_.split(',')[1,2] } ) `
| Get-Unique `
| Out-File -FilePath $DestinationFile -Force
#
#END SCRIPT
</code>```

答:
SOLVED

The problem was my PowerShell version.  The script was written on a Windows 10 system, which was running PSv5.1.  It never even occurred to me to check the version of PS on my Windows 7 work system (PSv2).  Once I upgraded the PS version on my work system, the script worked perfectly...

Title: PowerShell script fails

Body:
I am trying to use the PowerShell script below with PSv5 to automate some manual processes but it keeps failing and I cannot figure out why. When I try to debug it in ISE, I get the following error and no output file is generated:

Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:15 char:53
+ $HeaderLine, ${$DestinationFile} = Get-Content -Path <<<<  $SourceFile.FullName
+ CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

# BEGIN SCRIPT
#
# Collect all the files in the directory
$SoureFiles = Get-ChildItem -Path 'C:\raw' -Filter '*.txt'

# Create the destination file
$DestinationFile = (New-Item -Path 'c:\done' `
-Name ('CombinedSources-' + (Get-Date -Format 'ddMMMyyyy') + '.txt') `
-ItemType File -Force).FullName
$DestinationFile

# Loop source, files, remove header line, append to the destination file
ForEach ($SourceFile in $SoureFiles)
{
$HeaderLine, ${$DestinationFile} = Get-Content -Path $SourceFile.FullName
${$DestinationFile}`
| Out-File -FilePath $DestinationFile -Append
}

# Sort the Destination file content and replace with sorted unique lines
(Get-Content -Path $DestinationFile `
| Sort-Object { [string]$_.split(',')[1,2] } ) `
| Get-Unique `
| Out-File -FilePath $DestinationFile -Force
#
#END SCRIPT


问:
Exception when removing element from HashMap java.util.ConcurrentModificationException
I am trying to write a logic to find the quickest route, the input is given in format "1-2-30#2-3-25#3-4-30#..." which means from station 1 to 2 it will take 30 minutes. In this code when i am recursively calling searchMapKey() function, if the key is not present, then i am getting execption "Exception in thread "main" java.util.ConcurrentModificationException"</p>

```<code>    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.StringTokenizer;

    public class QuickestRoute {
static int totalWeight = 0;

public static String outpit;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String input1[] = { "1-2-30#2-3-25#3-4-30#4-5-45#5-6-30#6-7-15#7-8-60#8-9-40",
            "10-11-45#11-4-60#4-12-60#12-13-45#13-14-30#14-15-35",
            "1-3-40#3-4-25#4-16-30#16-17-15#17-18-20#18-19-30#19-20-25", "21-12-30#12-17-180#17-22-45" }; };
    String input2 = "12#18";
    String[] output = quickestMetroRoute(input1, input2);
    /*
     * for(int i=0;i<output.length;i++) System.out.println(output[i]);
     */
}

public static String[] quickestMetroRoute(String[] input1, String input2) {
    // Write code here
    Map<String, Integer> input = new HashMap<String, Integer>();
    for (int i = 0; i < input1.length; i++) {
        StringTokenizer str = new StringTokenizer(input1[i], "#");
        while (str.hasMoreTokens()) {
            String[] parts = str.nextToken().split("-");
            String node = parts[0] + "-" + parts[1];
            int weight = Integer.parseInt(parts[2]);
            input.put(node, weight);
        }
    }
     Map<String, Integer> sortedMap = sortByValue(input);
    System.out.println(Collections.singletonList(sortedMap));
    String[] parts = input2.split("#");
    String source = parts[0];
    String destination = parts[1];
    searchMapKey(source, destination, sortedMap);
    /*
     * for (Map.Entry<String, Integer> entry : input.entrySet()) { String
     * key = entry.getKey(); Integer value = entry.getValue(); // ... }
     */
    System.out.println("outpit: " + outpit);
    System.out.println("totalWeight: " + totalWeight);

    return input1;
}

private static void searchMapKey(String source, String destination, Map<String, Integer> input) {
    // TODO Auto-generated method stub
    for (Iterator<Entry<String, Integer>> it = input.entrySet().iterator(); it.hasNext();) {
        Entry<String, Integer> entry = it.next();
        String key = entry.getKey();
        Integer value = entry.getValue();
        // ...
        String[] nodeParts = key.split("-");
        String nodeFirst = nodeParts[0];
        String nodeSecond = nodeParts[1];

        if (nodeFirst.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeSecond)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeSecond, destination, input);
            }
        }
        if (nodeSecond.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeFirst)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeFirst, destination, input);
            }
        }
    }

}

private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {

    // 1. Convert Map to List of Map
    List<Map.Entry<String, Integer>> list =
            new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

    // 2. Sort list with Collections.sort(), provide a custom Comparator
    //    Try switch the o1 o2 position for a different order
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,
                           Map.Entry<String, Integer> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Map.Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    /*
    //classic iterator example
    for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
        Map.Entry<String, Integer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }*/

    return sortedMap;
}

}
</code>```

答:
try this code i have made 2 modifications

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;

public class QuickestRoute {
    static int totalWeight = 0;

    public static String outpit;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String input1[] = { "1-2-30#2-3-25#3-4-30#4-5-45#5-6-30#6-7-15#7-8-60#8-9-40",
                "10-11-45#11-4-60#4-12-60#12-13-45#13-14-30#14-15-35",
                "1-3-40#3-4-25#4-16-30#16-17-15#17-18-20#18-19-30#19-20-25", "21-12-30#12-17-180#17-22-45" };

        String input2 = "12#18";
        String[] output = quickestMetroRoute(input1, input2);
        /*
         * for(int i=0;i<output.length;i++) System.out.println(output[i]);
         */
    }

    public static String[] quickestMetroRoute(String[] input1, String input2) {
        // Write code here
        Map<String, Integer> input = new HashMap<String, Integer>();
        for (int i = 0; i < input1.length; i++) {
            StringTokenizer str = new StringTokenizer(input1[i], "#");
            while (str.hasMoreTokens()) {
                String[] parts = str.nextToken().split("-");
                String node = parts[0] + "-" + parts[1];
                int weight = Integer.parseInt(parts[2]);
                input.put(node, weight);
            }
        }
        Map<String, Integer> sortedMap = sortByValue(input);
        System.out.println(Collections.singletonList(sortedMap));
        String[] parts = input2.split("#");
        String source = parts[0];
        String destination = parts[1];
        searchMapKey(source, destination, sortedMap);
        /*
         * for (Map.Entry<String, Integer> entry : input.entrySet()) { String
         * key = entry.getKey(); Integer value = entry.getValue(); // ... }
         */
        System.out.println("outpit: " + outpit);
        System.out.println("totalWeight: " + totalWeight);

        return input1;
    }

    private static void searchMapKey(String source, String destination, Map<String, Integer> input) {
        // TODO Auto-generated method stub

        ArrayList<Map<String, Integer>> removeList = new ArrayList<Map<String, Integer>>();
        for (Iterator<Entry<String, Integer>> it = input.entrySet().iterator(); it.hasNext();) {
            Entry<String, Integer> entry = it.next();
            String key = entry.getKey();
            Integer value = entry.getValue();
            // ...
            String[] nodeParts = key.split("-");
            String nodeFirst = nodeParts[0];
            String nodeSecond = nodeParts[1];

            if (nodeFirst.equals(source)) {
                totalWeight += value;
                outpit += key;
                if (destination.equals(nodeSecond)) {
                    totalWeight += value;
                    outpit += key;
                    return;
                } else {
                    it.remove();
                    // input.remove(key);
                    Map<String, Integer> next = new HashMap<String, Integer>();
                    next.putAll(input);
                    searchMapKey(nodeSecond, destination, next);
                }
            }
            if (nodeSecond.equals(source)) {
                totalWeight += value;
                outpit += key;
                if (destination.equals(nodeFirst)) {
                    totalWeight += value;
                    outpit += key;
                    return;
                } else {
                    it.remove();
                    // input.remove(key);
                    Map<String, Integer> next = new HashMap<String, Integer>();
                    next.putAll(input);
                    searchMapKey(nodeFirst, destination, next);
                }
            }
        }

    }

    private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {

        // 1. Convert Map to List of Map
        List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

        // 2. Sort list with Collections.sort(), provide a custom Comparator
        // Try switch the o1 o2 position for a different order
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        // 3. Loop the sorted list and put it into a new insertion order Map
        // LinkedHashMap
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        /*
         * //classic iterator example for (Iterator<Map.Entry<String, Integer>>
         * it = list.iterator(); it.hasNext(); ) { Map.Entry<String, Integer>
         * entry = it.next(); sortedMap.put(entry.getKey(), entry.getValue()); }
         */

        return sortedMap;
    }

}
</code>```

your output

```<code>[{6-7=15, 16-17=15, 17-18=20, 19-20=25, 2-3=25, 3-4=25, 18-19=30, 13-14=30, 4-16=30, 1-2=30, 21-12=30, 5-6=30, 14-15=35, 8-9=40, 1-3=40, 10-11=45, 12-13=45, 17-22=45, 4-5=45, 7-8=60, 4-12=60, 11-4=60, 12-17=180}]
outpit: null21-1212-1313-1414-154-124-1616-1717-1817-1811-410-113-41-31-22-32-31-24-55-66-77-88-912-1717-1817-18
totalWeight: 975
</code>```

you are using a recursive function and removing elements in an iterator and again in another call working with them, what i have done is for each time you remove an element, make a copy of it and then forward it to the proceeding recursive call
feel free to ask if it doesn't clears

Body:
I am trying to write a logic to find the quickest route, the input is given in format "1-2-30#2-3-25#3-4-30#..." which means from station 1 to 2 it will take 30 minutes. In this code when i am recursively calling searchMapKey() function, if the key is not present, then i am getting execption "Exception in thread "main" java.util.ConcurrentModificationException"

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.StringTokenizer;

    public class QuickestRoute {
static int totalWeight = 0;

public static String outpit;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String input1[] = { "1-2-30#2-3-25#3-4-30#4-5-45#5-6-30#6-7-15#7-8-60#8-9-40",
            "10-11-45#11-4-60#4-12-60#12-13-45#13-14-30#14-15-35",
            "1-3-40#3-4-25#4-16-30#16-17-15#17-18-20#18-19-30#19-20-25", "21-12-30#12-17-180#17-22-45" }; };
    String input2 = "12#18";
    String[] output = quickestMetroRoute(input1, input2);
    /*
     * for(int i=0;i<output.length;i++) System.out.println(output[i]);
     */
}

public static String[] quickestMetroRoute(String[] input1, String input2) {
    // Write code here
    Map<String, Integer> input = new HashMap<String, Integer>();
    for (int i = 0; i < input1.length; i++) {
        StringTokenizer str = new StringTokenizer(input1[i], "#");
        while (str.hasMoreTokens()) {
            String[] parts = str.nextToken().split("-");
            String node = parts[0] + "-" + parts[1];
            int weight = Integer.parseInt(parts[2]);
            input.put(node, weight);
        }
    }
     Map<String, Integer> sortedMap = sortByValue(input);
    System.out.println(Collections.singletonList(sortedMap));
    String[] parts = input2.split("#");
    String source = parts[0];
    String destination = parts[1];
    searchMapKey(source, destination, sortedMap);
    /*
     * for (Map.Entry<String, Integer> entry : input.entrySet()) { String
     * key = entry.getKey(); Integer value = entry.getValue(); // ... }
     */
    System.out.println("outpit: " + outpit);
    System.out.println("totalWeight: " + totalWeight);

    return input1;
}

private static void searchMapKey(String source, String destination, Map<String, Integer> input) {
    // TODO Auto-generated method stub
    for (Iterator<Entry<String, Integer>> it = input.entrySet().iterator(); it.hasNext();) {
        Entry<String, Integer> entry = it.next();
        String key = entry.getKey();
        Integer value = entry.getValue();
        // ...
        String[] nodeParts = key.split("-");
        String nodeFirst = nodeParts[0];
        String nodeSecond = nodeParts[1];

        if (nodeFirst.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeSecond)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeSecond, destination, input);
            }
        }
        if (nodeSecond.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeFirst)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeFirst, destination, input);
            }
        }
    }

}

private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {

    // 1. Convert Map to List of Map
    List<Map.Entry<String, Integer>> list =
            new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

    // 2. Sort list with Collections.sort(), provide a custom Comparator
    //    Try switch the o1 o2 position for a different order
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,
                           Map.Entry<String, Integer> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Map.Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    /*
    //classic iterator example
    for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
        Map.Entry<String, Integer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }*/

    return sortedMap;
}

}

Body:
try this code i have made 2 modifications

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;

public class QuickestRoute {
    static int totalWeight = 0;

    public static String outpit;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String input1[] = { "1-2-30#2-3-25#3-4-30#4-5-45#5-6-30#6-7-15#7-8-60#8-9-40",
                "10-11-45#11-4-60#4-12-60#12-13-45#13-14-30#14-15-35",
                "1-3-40#3-4-25#4-16-30#16-17-15#17-18-20#18-19-30#19-20-25", "21-12-30#12-17-180#17-22-45" };

        String input2 = "12#18";
        String[] output = quickestMetroRoute(input1, input2);
        /*
         * for(int i=0;i<output.length;i++) System.out.println(output[i]);
         */
    }

    public static String[] quickestMetroRoute(String[] input1, String input2) {
        // Write code here
        Map<String, Integer> input = new HashMap<String, Integer>();
        for (int i = 0; i < input1.length; i++) {
            StringTokenizer str = new StringTokenizer(input1[i], "#");
            while (str.hasMoreTokens()) {
                String[] parts = str.nextToken().split("-");
                String node = parts[0] + "-" + parts[1];
                int weight = Integer.parseInt(parts[2]);
                input.put(node, weight);
            }
        }
        Map<String, Integer> sortedMap = sortByValue(input);
        System.out.println(Collections.singletonList(sortedMap));
        String[] parts = input2.split("#");
        String source = parts[0];
        String destination = parts[1];
        searchMapKey(source, destination, sortedMap);
        /*
         * for (Map.Entry<String, Integer> entry : input.entrySet()) { String
         * key = entry.getKey(); Integer value = entry.getValue(); // ... }
         */
        System.out.println("outpit: " + outpit);
        System.out.println("totalWeight: " + totalWeight);

        return input1;
    }

    private static void searchMapKey(String source, String destination, Map<String, Integer> input) {
        // TODO Auto-generated method stub

        ArrayList<Map<String, Integer>> removeList = new ArrayList<Map<String, Integer>>();
        for (Iterator<Entry<String, Integer>> it = input.entrySet().iterator(); it.hasNext();) {
            Entry<String, Integer> entry = it.next();
            String key = entry.getKey();
            Integer value = entry.getValue();
            // ...
            String[] nodeParts = key.split("-");
            String nodeFirst = nodeParts[0];
            String nodeSecond = nodeParts[1];

            if (nodeFirst.equals(source)) {
                totalWeight += value;
                outpit += key;
                if (destination.equals(nodeSecond)) {
                    totalWeight += value;
                    outpit += key;
                    return;
                } else {
                    it.remove();
                    // input.remove(key);
                    Map<String, Integer> next = new HashMap<String, Integer>();
                    next.putAll(input);
                    searchMapKey(nodeSecond, destination, next);
                }
            }
            if (nodeSecond.equals(source)) {
                totalWeight += value;
                outpit += key;
                if (destination.equals(nodeFirst)) {
                    totalWeight += value;
                    outpit += key;
                    return;
                } else {
                    it.remove();
                    // input.remove(key);
                    Map<String, Integer> next = new HashMap<String, Integer>();
                    next.putAll(input);
                    searchMapKey(nodeFirst, destination, next);
                }
            }
        }

    }

    private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {

        // 1. Convert Map to List of Map
        List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

        // 2. Sort list with Collections.sort(), provide a custom Comparator
        // Try switch the o1 o2 position for a different order
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        // 3. Loop the sorted list and put it into a new insertion order Map
        // LinkedHashMap
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        /*
         * //classic iterator example for (Iterator<Map.Entry<String, Integer>>
         * it = list.iterator(); it.hasNext(); ) { Map.Entry<String, Integer>
         * entry = it.next(); sortedMap.put(entry.getKey(), entry.getValue()); }
         */

        return sortedMap;
    }

}

your output

[{6-7=15, 16-17=15, 17-18=20, 19-20=25, 2-3=25, 3-4=25, 18-19=30, 13-14=30, 4-16=30, 1-2=30, 21-12=30, 5-6=30, 14-15=35, 8-9=40, 1-3=40, 10-11=45, 12-13=45, 17-22=45, 4-5=45, 7-8=60, 4-12=60, 11-4=60, 12-17=180}]
outpit: null21-1212-1313-1414-154-124-1616-1717-1817-1811-410-113-41-31-22-32-31-24-55-66-77-88-912-1717-1817-18
totalWeight: 975

you are using a recursive function and removing elements in an iterator and again in another call working with them, what i have done is for each time you remove an element, make a copy of it and then forward it to the proceeding recursive call
feel free to ask if it doesn't clears


问:
Facebook Workplace Account Management API Not Returning Photos
I am having an issue with the Account Management API for Facebook Workplace. All I am trying to do is build a quick and easy employee directory, that grabs all of our active users and spits out their name, title, dept, and photos. The problem is, the data coming back does not seem to match the Facebook Core Schema as seen in the link above. Some of the schema data comes back, but never photos, no matter what I seem to try.

```<code>private function getEmployees()
{
    $done = false;
    $current_index = 1;
    $current_page = 1;
    $results = [];

    while(!$done) {

        $res = $this->client->request(
            'GET',
            'https://www.facebook.com/company/XXXXXXXXX/scim/Users?count=100&startIndex=' . $current_index,
            [
                'headers' => ['Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->token
                ]
            ]
        );

        $decoded = json_decode($res->getBody());
        $total = $decoded->totalResults;
        $perPage = $decoded->itemsPerPage;

        if (isset($decoded->Resources)) {
            $results = array_merge($results, $decoded->Resources);

            if (($current_page * $perPage) >= $total) {
                $done = true;
            } else {
                $current_page++;
                $current_index += $perPage;
            }
        } else {
            $done = true;
        }

    }

    return $results;
}
</code>```

Which gives back:

```<code>object(stdClass)[392]
public 'schemas' =>
array (size=3)
  0 => string 'urn:scim:schemas:core:1.0' (length=25)
  1 => string 'urn:scim:schemas:extension:enterprise:1.0' (length=41)
  2 => string 'urn:scim:schemas:extension:facebook:starttermdates:1.0' (length=54)
public 'id' => int 10001156699923
public 'userName' => string 'np@lt.com' (length=21)
public 'name' =>
object(stdClass)[393]
  public 'formatted' => string 'Nick P' (length=11)
public 'title' => string 'Lead PHP Engineer' (length=17)
public 'active' => boolean true
public 'phoneNumbers' =>
array (size=1)
  0 =>
    object(stdClass)[394]
      public 'primary' => boolean true
      public 'type' => string 'work' (length=4)
      public 'value' => string '+1631123456' (length=12)
public 'addresses' =>
array (size=1)
  0 =>
    object(stdClass)[395]
      public 'type' => string 'attributes' (length=10)
      public 'formatted' => string 'Manhattan' (length=9)
      public 'primary' => boolean true
public 'urn:scim:schemas:extension:enterprise:1.0' =>
object(stdClass)[396]
  public 'department' => string 'IT' (length=2)
  public 'manager' =>
    object(stdClass)[397]
      public 'managerId' => int 100011017901494
public 'urn:scim:schemas:extension:facebook:starttermdates:1.0' =>
object(stdClass)[398]
  public 'startDate' => int 0
  public 'termDate' => int 0
</code>```

So as you can see, it returns other fields that are part of the 'core' schema, but is missing the 'photos' array and others. I thought this might have been because a user didnt have any photos, but almost all have profile pictures, and many have more. I tried getting their user information specifically but encountered the same result, no photos.

Anybody ever try something similar? Any help much appreciated, this has been a bit of a road block for us.

Thanks

答:
To get profile information, don't use SCIM but graph API
https://graph.facebook.com/community/members will list all members

and https://graph.facebook.com/[email] for one of your member will get all infos.

After that you have to set the params you want to get with the fields param.

In our implementation we get the whole data from this request

https://graph.facebook.com/XXXX/members?fields=email,picture.type(large),link,title,first_name,last_name,department,updated_time,managers{email}&limit=500

Body:
I am having an issue with the Account Management API for Facebook Workplace. All I am trying to do is build a quick and easy employee directory, that grabs all of our active users and spits out their name, title, dept, and photos. The problem is, the data coming back does not seem to match the Facebook Core Schema as seen in the link above. Some of the schema data comes back, but never photos, no matter what I seem to try.

private function getEmployees()
{
    $done = false;
    $current_index = 1;
    $current_page = 1;
    $results = [];

    while(!$done) {

        $res = $this->client->request(
            'GET',
            'https://www.facebook.com/company/XXXXXXXXX/scim/Users?count=100&startIndex=' . $current_index,
            [
                'headers' => ['Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->token
                ]
            ]
        );

        $decoded = json_decode($res->getBody());
        $total = $decoded->totalResults;
        $perPage = $decoded->itemsPerPage;

        if (isset($decoded->Resources)) {
            $results = array_merge($results, $decoded->Resources);

            if (($current_page * $perPage) >= $total) {
                $done = true;
            } else {
                $current_page++;
                $current_index += $perPage;
            }
        } else {
            $done = true;
        }

    }

    return $results;
}

Which gives back:

object(stdClass)[392]
public 'schemas' =>
array (size=3)
  0 => string 'urn:scim:schemas:core:1.0' (length=25)
  1 => string 'urn:scim:schemas:extension:enterprise:1.0' (length=41)
  2 => string 'urn:scim:schemas:extension:facebook:starttermdates:1.0' (length=54)
public 'id' => int 10001156699923
public 'userName' => string 'np@lt.com' (length=21)
public 'name' =>
object(stdClass)[393]
  public 'formatted' => string 'Nick P' (length=11)
public 'title' => string 'Lead PHP Engineer' (length=17)
public 'active' => boolean true
public 'phoneNumbers' =>
array (size=1)
  0 =>
    object(stdClass)[394]
      public 'primary' => boolean true
      public 'type' => string 'work' (length=4)
      public 'value' => string '+1631123456' (length=12)
public 'addresses' =>
array (size=1)
  0 =>
    object(stdClass)[395]
      public 'type' => string 'attributes' (length=10)
      public 'formatted' => string 'Manhattan' (length=9)
      public 'primary' => boolean true
public 'urn:scim:schemas:extension:enterprise:1.0' =>
object(stdClass)[396]
  public 'department' => string 'IT' (length=2)
  public 'manager' =>
    object(stdClass)[397]
      public 'managerId' => int 100011017901494
public 'urn:scim:schemas:extension:facebook:starttermdates:1.0' =>
object(stdClass)[398]
  public 'startDate' => int 0
  public 'termDate' => int 0

So as you can see, it returns other fields that are part of the 'core' schema, but is missing the 'photos' array and others. I thought this might have been because a user didnt have any photos, but almost all have profile pictures, and many have more. I tried getting their user information specifically but encountered the same result, no photos.

Anybody ever try something similar? Any help much appreciated, this has been a bit of a road block for us.

Thanks


问:
Search and connect to wifi in Client side
How can i search for wifi active devices and connect to them in client side and share messages. I want to create a website which will search for wifi devices and connect to them and send and receive data(provide if the user devices like mobiles and computer are having a router). Which framework should i use or any other method without using a framework.

Edit 1
I'm practising on localhost and want to scan for wifi active connections on client side and connect to one of them to share data. How can I achieve this ?

答: I'm surprised to see this question under the PHP and Wordpress tags. Wifi is obviously client side. More, it is on the client's hardware side. Only technologies directly handling the customers' computer hardware can handle this.</p>


问:
Execute Multiple SQL Server Queries for 2 Linked Servers
I have 2 Linked Servers "NewDump" and "OldDump" (Dumps from different dates). I have queries to compare tables from these dumps (like FTM$, FSF$ etc). Each query compares a table between these linked server. Is there a way i can run all these ".SQL" queries (FTM.SQL and FSF.SQL) using a batch file together for automation

eg queries: FTM.SQL

```<code>FROM (
SELECT  *
FROM NewDump...FTM$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FTM$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL
</code>```

eg FSF.SQL Query

```<code>FROM (
SELECT  *
FROM NewDump...FSF$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FSF$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL
</code>```

The Queries FSF.SQL and FTM.SQL are stored in C:\Users\user\Documents\SQL Server Management Studio\Queries

答: You can use SQL Agent to schedule any SQL Statements. It would be neater if you created stored procedures out of the aforementioned queries and scheduled those. </p>

Body:
I have 2 Linked Servers "NewDump" and "OldDump" (Dumps from different dates). I have queries to compare tables from these dumps (like FTM$, FSF$ etc). Each query compares a table between these linked server. Is there a way i can run all these ".SQL" queries (FTM.SQL and FSF.SQL) using a batch file together for automation

eg queries: FTM.SQL

FROM (
SELECT  *
FROM NewDump...FTM$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FTM$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL

eg FSF.SQL Query

FROM (
SELECT  *
FROM NewDump...FSF$) t1

FULL OUTER JOIN (
SELECT *
FROM OldDump...FSF$) t2

ON t1.id = t2.id
WHERE

t1.id IS NULL OR
t2.id IS NULL

The Queries FSF.SQL and FTM.SQL are stored in C:\Users\user\Documents\SQL Server Management Studio\Queries


问:
what is the object type of mean in R?
I am looking for the real object type of some functions in R, for example, I can not find out the object type of mean function.

```<code>> library(pryr)
> otype(mean)
[1] "base"
> ftype(mean)
[1] "s3"      "generic"
</code>```

Sometimes the mean function is S3 and sometimes it is base!

答:
What does ftype tell us?

This function figures out whether the input function is a regular/primitive/internal function, a internal/S3/S4 generic, or a S3/S4/RC method. This is function is slightly simplified as it’s possible for a method from one class to be a generic for another class, but that seems like such a bad idea that hopefully no one has done it.

What does otype give us?

Figure out which object system an object belongs to:

• base: no class attribute

• S3: class attribute, but not S4

• S4: isS4, but not RC

• RC: inherits from "refClass"

For reference:

pryr package documentation

R language objects

Title: what is the object type of mean in R?

Body:
I am looking for the real object type of some functions in R, for example, I can not find out the object type of mean function.

> library(pryr)
> otype(mean)
[1] "base"
> ftype(mean)
[1] "s3"      "generic"

Sometimes the mean function is S3 and sometimes it is base!


问:
Load emacs elisp library only if it is present
I have a standard .emacs file that I want to use on multiple machines. One some of the machines I am not able to load all of my elisp libraries.

Right now, I get this error on machines where, for example, wc-mode-0.2.el is not present:

```<code>Cannot open load file: wc-mode-0.2.el
</code>```

Is there a way that I can make the .emacs file not error out at this point? Either by:

Checking to see if the library exists before I try to load it.

Catching the error condition.

答:
While @yorodm's answer is probably more correct (upvoted!), a form that I've been using for years is:

;; load & configure myfeature if it's available
(cond ((locate-library "myfeature")
       (require 'myfeature)
       (setq myfeature-variable "stuff")
       (do-my-thing))
```

Body:
I have a standard .emacs file that I want to use on multiple machines. One some of the machines I am not able to load all of my elisp libraries.

Right now, I get this error on machines where, for example, wc-mode-0.2.el is not present:

Cannot open load file: wc-mode-0.2.el

Is there a way that I can make the .emacs file not error out at this point? Either by:

Checking to see if the library exists before I try to load it.

Catching the error condition.


问:
Producing EntityManager in a Hybrid Tenancy Context
I have this requirement in which every client must have his data stored individually in a separated database.

I would like to achieve the following structure:

A global microservice handles authentication and also provide information about the database in which the client data is stored.

The others microservices, when requested, query the auth service to know the client database information, only then the entity manager gets produced.

I am struggling to properly manage the state of the EntityManagerFactory instances.

I've tried to store in in a WeakHashMap but some buggy things started to happen. Like a simple findById throwing exceptions.

I am actually using JEE with DeltaSpike data running on a Payara server.

Anyone have ever done that using a similar stack?

答:
If you are using bean managed transaction, then it becomes even easier to use CDI to manage this kind of entity manager factory resource.

First create a datasource context annotation.

```<code>@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, PARAMETER, FIELD, METHOD})
public @interface Datasource {

    /**
     * This may be the database url or whatever.
     */
    @Nonbinding
    String value() default "";

}

@SuppressWarnings("AnnotationAsSuperInterface")
public class DatasourceLiteral extends AnnotationLiteral<Datasource> implements Datasource {

    private static final long serialVersionUID = 7485753390480718735L;

    private final String dbName;

    public DatasourceLiteral(final String dbName) {
        this.dbName = dbName;
    }

    @Override
    public String value() {
        return dbName;
    }

}

@ApplicationScoped
public class EntityManagerFactoryProvider {

    @Produces
    @Datasource
    @ApplicationScoped
    public EntityManagerFactory entityManagerFactory(final InjectionPoint ip) {
        final Annotated annotated = ip.getAnnotated();
        final Datasource datasource = annotated.getAnnotation(Datasource.class);

        /**
         * Add relevant jpa properties
         */
        final Map<String, String> jpaProperties = new HashMap<>();

        /**
         * The main point is here.
         */
        jpaProperties.put("javax.persistence.jdbc.url", datasource.value());

        return Persistence.createEntityManagerFactory("persistence-unit-jpa", jpaProperties);
    }

    public void dispose(@Disposes @Datasource final EntityManagerFactory emf) {
        emf.close();
    }

}

@ApplicationScoped
public class ExampleUserDatasource {

    @Any
    @Inject
    private Instance<EntityManagerFactory> entityManagerFactories;

    public void doSomething(final String user) {
        final UserInfo userInfo = authenticationService.getUser(user);
        final Datasource datasource = new DatasourceLiteral(userInfo.getDatasource());
        final EntityManagerFactory entityManagerFactory = entityManagerFactories.select(datasource).get();

        /**
         * You could also actually inject this.
         * Do whatever you want with it inside a transaction and close it too.
         */
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
    }

}
</code>```

Body:
If you are using bean managed transaction, then it becomes even easier to use CDI to manage this kind of entity manager factory resource.

First create a datasource context annotation.

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, PARAMETER, FIELD, METHOD})
public @interface Datasource {

    /**
     * This may be the database url or whatever.
     */
    @Nonbinding
    String value() default "";

}

@SuppressWarnings("AnnotationAsSuperInterface")
public class DatasourceLiteral extends AnnotationLiteral<Datasource> implements Datasource {

    private static final long serialVersionUID = 7485753390480718735L;

    private final String dbName;

    public DatasourceLiteral(final String dbName) {
        this.dbName = dbName;
    }

    @Override
    public String value() {
        return dbName;
    }

}

@ApplicationScoped
public class EntityManagerFactoryProvider {

    @Produces
    @Datasource
    @ApplicationScoped
    public EntityManagerFactory entityManagerFactory(final InjectionPoint ip) {
        final Annotated annotated = ip.getAnnotated();
        final Datasource datasource = annotated.getAnnotation(Datasource.class);

        /**
         * Add relevant jpa properties
         */
        final Map<String, String> jpaProperties = new HashMap<>();

        /**
         * The main point is here.
         */
        jpaProperties.put("javax.persistence.jdbc.url", datasource.value());

        return Persistence.createEntityManagerFactory("persistence-unit-jpa", jpaProperties);
    }

    public void dispose(@Disposes @Datasource final EntityManagerFactory emf) {
        emf.close();
    }

}

@ApplicationScoped
public class ExampleUserDatasource {

    @Any
    @Inject
    private Instance<EntityManagerFactory> entityManagerFactories;

    public void doSomething(final String user) {
        final UserInfo userInfo = authenticationService.getUser(user);
        final Datasource datasource = new DatasourceLiteral(userInfo.getDatasource());
        final EntityManagerFactory entityManagerFactory = entityManagerFactories.select(datasource).get();

        /**
         * You could also actually inject this.
         * Do whatever you want with it inside a transaction and close it too.
         */
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
    }

}


问:
ShortCut URL Redirect
To get straight to the point.

I have this URL: http://example.com/?open=encyclopedia&letter=s&term=storm and I want this shortcut URL - http://example.com/storm - to redirect to the first URL: http://example.com/?open=encyclopedia&letter=s&term=storm

I have around 1.000 encyclopedic terms and I want this redirection to work for each term entered. For Example: if a visitor enters http://example.com/Storm to automatically be redirected to the page here: http://example.com/?open=encyclopedia&letter=s&term=storm OR http://example.com/Dried_Plant to http://example.com/?open=encyclopedia&letter=d&term=dried+plant

I prefer some htaccess solution to this, if possible.
If not, give what you can give.
I have no example code for this, since I do not know where to start from.

答:
@Croises answer is good if your link looks like following

mysite.com/?open=encyclopedia&letter=s&term=/storm

REQUEST_URI is adding a trailing slash. Your link don't have one:

mysite.com/?open=encyclopedia&letter=s&term=storm

I think this is what you are looking for

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} .(.+)$

RewriteRule ^(.) ?open=encyclopedia&letter=$1&letter=%1 [NC,L]
</code>```

Title: ShortCut URL Redirect

Body:
@Croises answer is good if your link looks like following

mysite.com/?open=encyclopedia&letter=s&term=/storm

REQUEST_URI is adding a trailing slash. Your link don't have one:

mysite.com/?open=encyclopedia&letter=s&term=storm

I think this is what you are looking for

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} .(.+)$

RewriteRule ^(.) ?open=encyclopedia&letter=$1&letter=%1 [NC,L]


问:
Using logical operators with %in% and subset
I have a test dataset that I have split up by quarter:

```<code>> test
   id quarter
1   7      Q1
2   7      Q1
3   5      Q1
4   8      Q1
5   3      Q1
6   6      Q1
7  10      Q1
8   3      Q2
9  10      Q2
10  8      Q2
11  2      Q2
12  7      Q2
13  6      Q2
14  6      Q3
15  9      Q3
16  6      Q3
17  4      Q3
18  9      Q3
19  2      Q3
20  5      Q4
21  8      Q4
22 10      Q4
23  7      Q4
24  1      Q4
25  8      Q4

subsets <-split(test, test$quarter, drop=TRUE)

for (i in 1:length(subsets)) {
  assign(paste0("Q", i), as.data.frame(subsets[[i]]))
}
</code>```

Now my objective is to find out all of the unique ids in Q3 that are not in Q1 or in Q2.  Using the %in% operator I try:

```<code>Q1_ids <- unique(Q1$id)
Q2_ids <- unique(Q2$id)

Q3_ids <- subset(unique(Q3$id), !(unique(Q3$id) %in% Q1_ids | Q2_ids))
</code>```

but then I receive an error that operations are possible only for numeric, logical or complex types.   I can subset by one vector, for example if I only use Q1_ids, but I cannot use a logical operator.  What is the solution to this using the subset() function or another way to approach the problem?

```<code>> dput(test)
structure(list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
"Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
"Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
"Q4")), .Names = c("id", "quarter"), row.names = c(NA, -25L), class = "data.frame", index = structure(integer(0), "`__quarter`" = integer(0)))
</code>```

答:
You can always just write a function that extracts the elements you are looking for, and then call map (or an apply function) to apply the function to each of the quarters.  This particular tidyverse solution would output a named list, containing your desired output for each quarter:</p>

```<code>library(tidyverse)

get_distinct <- function(x, data) {
  distinct_id <- data[data$quarter == x, 1] %>%
      unique()
  setdiff(distinct_id, data[!data$quarter == x, 1]  %>%
      unique())
}

quarters <- unique(test$quarter)

dat <- map(.x = quarters, .f = get_distinct, data = test) %>%
    set_names(quarters)
</code>```

Body:
I have a test dataset that I have split up by quarter:

> test
   id quarter
1   7      Q1
2   7      Q1
3   5      Q1
4   8      Q1
5   3      Q1
6   6      Q1
7  10      Q1
8   3      Q2
9  10      Q2
10  8      Q2
11  2      Q2
12  7      Q2
13  6      Q2
14  6      Q3
15  9      Q3
16  6      Q3
17  4      Q3
18  9      Q3
19  2      Q3
20  5      Q4
21  8      Q4
22 10      Q4
23  7      Q4
24  1      Q4
25  8      Q4

subsets <-split(test, test$quarter, drop=TRUE)

for (i in 1:length(subsets)) {
  assign(paste0("Q", i), as.data.frame(subsets[[i]]))
}

Now my objective is to find out all of the unique ids in Q3 that are not in Q1 or in Q2.  Using the %in% operator I try:

Q1_ids <- unique(Q1$id)
Q2_ids <- unique(Q2$id)

Q3_ids <- subset(unique(Q3$id), !(unique(Q3$id) %in% Q1_ids | Q2_ids))

but then I receive an error that operations are possible only for numeric, logical or complex types.   I can subset by one vector, for example if I only use Q1_ids, but I cannot use a logical operator.  What is the solution to this using the subset() function or another way to approach the problem?

> dput(test)
structure(list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
"Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
"Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
"Q4")), .Names = c("id", "quarter"), row.names = c(NA, -25L), class = "data.frame", index = structure(integer(0), "`__quarter`" = integer(0)))

Body:
You can always just write a function that extracts the elements you are looking for, and then call map (or an apply function) to apply the function to each of the quarters.  This particular tidyverse solution would output a named list, containing your desired output for each quarter:

library(tidyverse)

get_distinct <- function(x, data) {
  distinct_id <- data[data$quarter == x, 1] %>%
      unique()
  setdiff(distinct_id, data[!data$quarter == x, 1]  %>%
      unique())
}

quarters <- unique(test$quarter)

dat <- map(.x = quarters, .f = get_distinct, data = test) %>%
    set_names(quarters)


答:
Since you are using namespace in your class you'll have to use that namespace to properly include User class.

try adding use \infopro\User;:
    `

```<code><?php
    include "User.php";

    use \infopro\User;
    $name = 'talib';
    $age = '29';
    $sex = 'male';
    echo "New user<br>name: " . $name . "<br>" .
        "age: " . $age . "<br>" . "sex: " . $sex."<br>";

    $newuser = new User($name, $age, $sex);
    $newAge = $newuser->getUserage();
    echo $newAge;
?>
</code>```

Title: Can't instantiate class even included

Body:
Since you are using namespace in your class you'll have to use that namespace to properly include User class.

try adding use \infopro\User;:
    `

<?php
    include "User.php";

    use \infopro\User;
    $name = 'talib';
    $age = '29';
    $sex = 'male';
    echo "New user<br>name: " . $name . "<br>" .
        "age: " . $age . "<br>" . "sex: " . $sex."<br>";

    $newuser = new User($name, $age, $sex);
    $newAge = $newuser->getUserage();
    echo $newAge;
?>


问:
incorrect result of fast dct algorithm
I want to implement the Loeffler fast dct algorithm by VHDL. Prior that i checked the algorithm result for a given data such below:

```<code>x=[0 1 2 3 4 5 6 7]
</code>```

then i calculated dct equivalent using this algorithm and result be came:

```<code>y=[28  -8.47  0  -4.6638  0  10.43  0  -5.966 ]
</code>```

but the resut of matlab is this:

y=dct(x)

y =

Columns 1 through 6

```<code>9.8995   -6.4423         0   -0.6735         0   -0.2009
</code>```

Columns 7 through 8

```<code>     0   -0.0507
</code>```

what's my mistake?

thanks

答:
Your implementation calculates the unnormalized DCT-II. You can simply multiply with the following formula to normalize your results:

Your results should now be:

```<code>y = [9.899  -4.235  0  -2.316  0  5.215  0  -2.983]
</code>```

For sure the result isn't equal to matlab, your Loeffler results should be something like this:

```<code>y = [28  -12.8846  0  -1.3469  0  -0.4018  0  -0.1014]
</code>```

Source:
https://help.scilab.org/doc/5.5.2/en_US/dct.html

Title: incorrect result of fast dct algorithm

Body:
I want to implement the Loeffler fast dct algorithm by VHDL. Prior that i checked the algorithm result for a given data such below:

x=[0 1 2 3 4 5 6 7]

then i calculated dct equivalent using this algorithm and result be came:

y=[28  -8.47  0  -4.6638  0  10.43  0  -5.966 ]

but the resut of matlab is this:

y=dct(x)

y =

Columns 1 through 6

9.8995   -6.4423         0   -0.6735         0   -0.2009

Columns 7 through 8

     0   -0.0507

what's my mistake?

thanks

Body:
Your implementation calculates the unnormalized DCT-II. You can simply multiply with the following formula to normalize your results:

Your results should now be:

y = [9.899  -4.235  0  -2.316  0  5.215  0  -2.983]

For sure the result isn't equal to matlab, your Loeffler results should be something like this:

y = [28  -12.8846  0  -1.3469  0  -0.4018  0  -0.1014]

Source:
https://help.scilab.org/doc/5.5.2/en_US/dct.html


问:
How to prevent an action from running if json payload is too large
I want to limit the size of the json payload that is http posted to my action.

How can I limit the size to 1 MB?

If the limit is exceeded, can I return a custom JSON response?

答:
As described in this answer, you can check the Content-Length header:

```<code>request.headers.get(play.api.http.HeaderNames.CONTENT_LENGTH)
</code>```

Check if it's larger than 1 MB and return whatever kind of response you want. Preferably a 413 Payload too large, as pointed out by the other answer.

Body:
As described in this answer, you can check the Content-Length header:

request.headers.get(play.api.http.HeaderNames.CONTENT_LENGTH)

Check if it's larger than 1 MB and return whatever kind of response you want. Preferably a 413 Payload too large, as pointed out by the other answer.


问:
Getting Events per Month using BigQuery within resource limitations
I've got Google Analytics exporting it's data to Big Query. It's now got ca. 14 months of data, containing ca. 430m Events. I want to run a query to get the total number of Events per month (e.g. 201701, 201702, etc.).

I wrote a query, but it will only run on a interval of ca. 4 - 6 days. If I make it larger I get the 'Resources exceeded during query execution.' message. Below is my query. Where did I go wrong in formulating this query? Or should I approach this completely differently (just a beginner...)

The query:

```<code>SELECT
  MonthYear,
  EXACT_COUNT_DISTINCT(combinedVisitorId) AS EventCount,
FROM (
  SELECT
    CONCAT(fullVisitorId,"-",STRING(visitId),"-",STRING(hits.hitNumber)) AS combinedVisitorId,
    hits.eventInfo.eventCategory AS EventCategory,
    CONCAT(CAST(YEAR(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), LPAD(CAST(MONTH(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), 2, '0')) AS MonthYear,
  FROM
    TABLE_DATE_RANGE([XXX:79296192.ga_sessions_], TIMESTAMP("2016-04-01"), TIMESTAMP("2017-05-30"))
  WHERE
    hits.type="EVENT" )
GROUP BY
  MonthYear
ORDER BY
  EventCount DESC
</code>```

答:
It's highly recommended that you use the Standard SQL version in BigQuery. If you want to compute the total events, this might do the trick for you:

```<code>SELECT
  SUM((SELECT COUNTIF(hits.type = 'EVENT') FROM UNNEST(hits) hits)) total_events,
FORMAT_DATE("%B", PARSE_DATE("%Y%m%d", date)) month
FROM `project_id.dataset_id.ga_sessions*`
WHERE
1 = 1
AND CASE WHEN (REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN "20170606" AND "20170606" ) THEN TRUE
  WHEN (NOT REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN "20160605" AND "20170605") THEN TRUE END
GROUP BY month
</code>```

I tested with an entire year here and it processed in around 30 seconds. Notice though that if you use more than a year then data will be grouped in the same month.

Body:
I've got Google Analytics exporting it's data to Big Query. It's now got ca. 14 months of data, containing ca. 430m Events. I want to run a query to get the total number of Events per month (e.g. 201701, 201702, etc.).

I wrote a query, but it will only run on a interval of ca. 4 - 6 days. If I make it larger I get the 'Resources exceeded during query execution.' message. Below is my query. Where did I go wrong in formulating this query? Or should I approach this completely differently (just a beginner...)

The query:

SELECT
  MonthYear,
  EXACT_COUNT_DISTINCT(combinedVisitorId) AS EventCount,
FROM (
  SELECT
    CONCAT(fullVisitorId,"-",STRING(visitId),"-",STRING(hits.hitNumber)) AS combinedVisitorId,
    hits.eventInfo.eventCategory AS EventCategory,
    CONCAT(CAST(YEAR(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), LPAD(CAST(MONTH(SEC_TO_TIMESTAMP(visitStartTime)) AS STRING), 2, '0')) AS MonthYear,
  FROM
    TABLE_DATE_RANGE([XXX:79296192.ga_sessions_], TIMESTAMP("2016-04-01"), TIMESTAMP("2017-05-30"))
  WHERE
    hits.type="EVENT" )
GROUP BY
  MonthYear
ORDER BY
  EventCount DESC

Body:
It's highly recommended that you use the Standard SQL version in BigQuery. If you want to compute the total events, this might do the trick for you:

SELECT
  SUM((SELECT COUNTIF(hits.type = 'EVENT') FROM UNNEST(hits) hits)) total_events,
FORMAT_DATE("%B", PARSE_DATE("%Y%m%d", date)) month
FROM `project_id.dataset_id.ga_sessions*`
WHERE
1 = 1
AND CASE WHEN (REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN "20170606" AND "20170606" ) THEN TRUE
  WHEN (NOT REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN "20160605" AND "20170605") THEN TRUE END
GROUP BY month

I tested with an entire year here and it processed in around 30 seconds. Notice though that if you use more than a year then data will be grouped in the same month.


问:
Very slow performance with DotSpatial shapefile
I'm trying to read all of the feature data from particular shapefile. In this case, I'm using DotSpatial to open the file, and I'm iterating through the features. This particular shapefile is only 9mb in size, and the dbf file is 14mb. There is roughly 75k features to loop through.

Note, this is all programmatically through a console app, so there is no rendering or anything involved.

When loading the shape file, I reproject, then I'm iterating. The loading an reprojecting is super quick. However, as soon as the code reaches my foreach block, it takes nearly 2 full minutes to load the data, and uses roughly 2GB of memory when debugging in VisualStudio. This seems very, very excessive for what's a reasonably small data file.

I've ran the same code outside of Visual Studio, from the command line, however the time is still roughly 2 full minutes, and about 1.3GB of memory for the process.

Is there anyway to speed this up at all?

Below is my code:

```<code>// Load the shape file and project to GDA94
Shapefile indexMapFile = Shapefile.OpenFile(shapeFilePath);
indexMapFile.Reproject(KnownCoordinateSystems.Geographic.Australia.GeocentricDatumofAustralia1994);

// Get's slow here and takes forever to get to the first item
foreach(IFeature feature in indexMapFile.Features)
{
    // Once inside the loop, it's blazingly quick.
}
</code>```

Interestingly, when I use the VS immediate window, it's super super fast, no delay at all...

答:
This has the same problem for very large files (1.2 millions of features), populating .Features collections never ends.

But if you ask for the feature you do not have memory or delay overheads.

```<code>        int lRows = fs.NumRows();
        for (int i = 0; i < lRows; i++)
        {

            // Get the feature
            IFeature pFeat = fs.GetFeature(i);

            StringBuilder sb = new StringBuilder();
            {
                sb.Append(Guid.NewGuid().ToString());
                sb.Append("|");
                sb.Append(pFeat.DataRow["MAPA"]);
                sb.Append("|");
                sb.Append(pFeat.BasicGeometry.ToString());
            }
            pLinesList.Add(sb.ToString());
            lCnt++;

            if (lCnt % 10 == 0)
            {
                pOld = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.Write("\r{0} de {1} ({2}%)", lCnt.ToString(), lRows.ToString(), (100.0 * ((float)lCnt / (float)lRows)).ToString());
                Console.ForegroundColor = pOld;
            }

        }
</code>```

Look for the GetFeature method.

Body:
I'm trying to read all of the feature data from particular shapefile. In this case, I'm using DotSpatial to open the file, and I'm iterating through the features. This particular shapefile is only 9mb in size, and the dbf file is 14mb. There is roughly 75k features to loop through.

Note, this is all programmatically through a console app, so there is no rendering or anything involved.

When loading the shape file, I reproject, then I'm iterating. The loading an reprojecting is super quick. However, as soon as the code reaches my foreach block, it takes nearly 2 full minutes to load the data, and uses roughly 2GB of memory when debugging in VisualStudio. This seems very, very excessive for what's a reasonably small data file.

I've ran the same code outside of Visual Studio, from the command line, however the time is still roughly 2 full minutes, and about 1.3GB of memory for the process.

Is there anyway to speed this up at all?

Below is my code:

// Load the shape file and project to GDA94
Shapefile indexMapFile = Shapefile.OpenFile(shapeFilePath);
indexMapFile.Reproject(KnownCoordinateSystems.Geographic.Australia.GeocentricDatumofAustralia1994);

// Get's slow here and takes forever to get to the first item
foreach(IFeature feature in indexMapFile.Features)
{
    // Once inside the loop, it's blazingly quick.
}

Interestingly, when I use the VS immediate window, it's super super fast, no delay at all...

Body:
This has the same problem for very large files (1.2 millions of features), populating .Features collections never ends.

But if you ask for the feature you do not have memory or delay overheads.

        int lRows = fs.NumRows();
        for (int i = 0; i < lRows; i++)
        {

            // Get the feature
            IFeature pFeat = fs.GetFeature(i);

            StringBuilder sb = new StringBuilder();
            {
                sb.Append(Guid.NewGuid().ToString());
                sb.Append("|");
                sb.Append(pFeat.DataRow["MAPA"]);
                sb.Append("|");
                sb.Append(pFeat.BasicGeometry.ToString());
            }
            pLinesList.Add(sb.ToString());
            lCnt++;

            if (lCnt % 10 == 0)
            {
                pOld = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.Write("\r{0} de {1} ({2}%)", lCnt.ToString(), lRows.ToString(), (100.0 * ((float)lCnt / (float)lRows)).ToString());
                Console.ForegroundColor = pOld;
            }

        }

Look for the GetFeature method.


问:
how to use mapPartitions followed by saveAsTextFiles
I am trying to use mapPartitions and then save the results to HDFS by the following:

```<code>val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
x.mapPartitions(p =>  p.map( r => r+5 ) ).collect().saveAsTextFile("/path/to/folder")
</code>```

:29: error: value saveAsTextFile is not a member of
  Array[Int]
         x.mapPartitions(p =>  p.map( r => r+5 ) ).collect().saveAsTextFile("/path/to/folder")

It seems something is wrong but I failed to figure out what is the correct way.

THanks

答:
Don't use collect:

```<code>x.mapPartitions(p =>  p.map( r => r+5 ) ).saveAsTextFile("/path/to/folder")
</code>```

It collects data to the driver as an Array.

Body:
I am trying to use mapPartitions and then save the results to HDFS by the following:

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
x.mapPartitions(p =>  p.map( r => r+5 ) ).collect().saveAsTextFile("/path/to/folder")

:29: error: value saveAsTextFile is not a member of
  Array[Int]
         x.mapPartitions(p =>  p.map( r => r+5 ) ).collect().saveAsTextFile("/path/to/folder")

It seems something is wrong but I failed to figure out what is the correct way.

THanks

Body:
Don't use collect:

x.mapPartitions(p =>  p.map( r => r+5 ) ).saveAsTextFile("/path/to/folder")

It collects data to the driver as an Array.


问:
Runtime Error 3075 -systax error (missing operand ) in VBA Access
I am getting 3075 error with this statement :

```<code>sql = "UPDATE [qr_code] SET [qr_code].[sequence]=[qs_code].[sequence] FROM [qr_code] RIGHT JOIN [qs_code] ON [qs_code].[sequence_ref]=[qr_code].[sequence_ref]"
DoCmd.RunSQL sql
</code>```

It works in SQL.

答:
Using MS Access' Create / Query Design tool makes me think that the SQL statement should be</p>

```<code>UPDATE [qr_code] RIGHT JOIN [qs_code]
    ON [qr_code].[sequence_ref] = [qs_code].[sequence_ref]
   SET [qr_code].[sequence] = [qs_code].[sequence];
</code>```

Body:
I am getting 3075 error with this statement :

sql = "UPDATE [qr_code] SET [qr_code].[sequence]=[qs_code].[sequence] FROM [qr_code] RIGHT JOIN [qs_code] ON [qs_code].[sequence_ref]=[qr_code].[sequence_ref]"
DoCmd.RunSQL sql

It works in SQL.

Body:
Using MS Access' Create / Query Design tool makes me think that the SQL statement should be

UPDATE [qr_code] RIGHT JOIN [qs_code]
    ON [qr_code].[sequence_ref] = [qs_code].[sequence_ref]
   SET [qr_code].[sequence] = [qs_code].[sequence];


问:
Rendering more than one .vue component
Right now my Vue is rendering the component dnaMoleculeFileInfo. How can I add another component to be rendered with its own props?

```<code>var app = new Vue({
    el: '#app',
    render: h => h(dnaMoleculeFileInfo, {
        props: {
            format: data.dnamoleculefile.format,
            id: data.dnamoleculefile.id,
            name: data.dnamoleculefile.name,
            sequence: data.sequence.bases,
            sequenceLength: data.length
        }
    })
})
</code>```

答:
Something like this.

console.clear()

const dnaMoleculeFileInfo = {
  template:`<h2>I'm a dnaMoleculeFileInfo</h2>`
}

const someOtherComponent = {
  template:`<h2>I'm some other component</h2>`
}

var app = new Vue({
    el: '#app',
    render(h){
      // Add the props you want to these two components
      const dna = h(dnaMoleculeFileInfo)
      const other = h(someOtherComponent)
      // return a container with both of them as children
      return h("div", [dna, other])
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app"></div></code>```

Title: Rendering more than one .vue component

Body:
Right now my Vue is rendering the component dnaMoleculeFileInfo. How can I add another component to be rendered with its own props?

var app = new Vue({
    el: '#app',
    render: h => h(dnaMoleculeFileInfo, {
        props: {
            format: data.dnamoleculefile.format,
            id: data.dnamoleculefile.id,
            name: data.dnamoleculefile.name,
            sequence: data.sequence.bases,
            sequenceLength: data.length
        }
    })
})

Body:
Something like this.

console.clear()

const dnaMoleculeFileInfo = {
  template:`<h2>I'm a dnaMoleculeFileInfo</h2>`
}

const someOtherComponent = {
  template:`<h2>I'm some other component</h2>`
}

var app = new Vue({
    el: '#app',
    render(h){
      // Add the props you want to these two components
      const dna = h(dnaMoleculeFileInfo)
      const other = h(someOtherComponent)
      // return a container with both of them as children
      return h("div", [dna, other])
    }
})

<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app"></div>


问:
Can't get my head around some lambda expressions in Java 8
I have this snippet of code that looks like this without using lambda expressions:

```<code>.map(new Function<List<Post>, List<Post>>() {
    @Override
    public List<Post> apply(List<Post> posts) throws Exception {
        return realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll();
    }
})
.onErrorResumeNext(new Function<Throwable, ObservableSource<? extends List<Post>>>() {
    @Override
    public ObservableSource<? extends List<Post>> apply(Throwable throwable) throws Exception {
        Log.d("rafael", throwable.getMessage());
        return getLocalPostsObservable(userId, page);
    }
})
</code>```

Using lambda expression (converted using Intellij feature) it becomes:

```<code>.map((Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll())
.onErrorResumeNext(throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
})
</code>```

What I don't understand that why the type casting in map() from posts to Function<List<Post>, List<Post>> in

```<code>(Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()
</code>```

Where at the same time there's no type casting in the second expression:

```<code>throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
}
</code>```

答:
What's the return type of findAll()?

I'd bet on a List<Post>, according to the return type of the Function<S, T>.

My guess is that the cast to Function<S, T> is applied to the whole lambda expression, not only to the posts parameter nor its return value.

As for the reason of its presence, it might be to avoid an ambiguous call of map(FunctionLike<S, T>); otherwise, it wouldn't be the first time that a code generation tool adds some useless stuff around.

Body:
I have this snippet of code that looks like this without using lambda expressions:

.map(new Function<List<Post>, List<Post>>() {
    @Override
    public List<Post> apply(List<Post> posts) throws Exception {
        return realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll();
    }
})
.onErrorResumeNext(new Function<Throwable, ObservableSource<? extends List<Post>>>() {
    @Override
    public ObservableSource<? extends List<Post>> apply(Throwable throwable) throws Exception {
        Log.d("rafael", throwable.getMessage());
        return getLocalPostsObservable(userId, page);
    }
})

Using lambda expression (converted using Intellij feature) it becomes:

.map((Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll())
.onErrorResumeNext(throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
})

What I don't understand that why the type casting in map() from posts to Function<List<Post>, List<Post>> in

(Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()

Where at the same time there's no type casting in the second expression:

throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
}