问:
why my navigation bar is completely white in iOS 13?

I want to make my large title navigation bar to be back to the default nav bar like the image above, the image above is when I run the app on iOS 12, there is a separator line and the color is little bit grey.

but when I run the app in iOS 13 is like the image below, the navigation bar is completely white and it seems there is no dark grey separator

I want to make my nav bar in iOS 13 is exactly the same as iOS 12, which is little grey and it has separator line

and here is the code I run in viewWillAppear :

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.largeTitleDisplayMode =  .always
}
</code>```

I am using storyboard, and here is the setting I use. even from storyboard, as you can see, it seems the nav bar is already completely white and no separator

答:
The behavior you are seeing is normal and correct in iOS 13. In iOS 13, a navigation bar with a large title is, by default, transparent. That means the white of the main view behind it shows through and it has no shadow (what you call the "separator"). You surely must have noticed this by now on your phone; iOS 13 has been around for almost a year! Apple's own apps generally look this way.

If that isn't what you want, configure the navigation bar's scrollEdgeAppearance to be what you do want.

Body:
I want to make my large title navigation bar to be back to the default nav bar like the image above, the image above is when I run the app on iOS 12, there is a separator line and the color is little bit grey.

but when I run the app in iOS 13 is like the image below, the navigation bar is completely white and it seems there is no dark grey separator

I want to make my nav bar in iOS 13 is exactly the same as iOS 12, which is little grey and it has separator line

and here is the code I run in viewWillAppear :

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.largeTitleDisplayMode =  .always
}

I am using storyboard, and here is the setting I use. even from storyboard, as you can see, it seems the nav bar is already completely white and no separator


来源: stackexchange

问:
How to pass route with {id} to Datatable blade. To view specific user details
This is my route

```<code>Route::get('/view/{id}', [
    'uses' => 'ClientController@view',
    'as' => 'view'
]);
</code>```

This is my Client controller

```<code>public function view($id){
     $client = Client::where('id',$id)->first();
     return view('view',compact('client'));
}
</code>```

This is my datatable

```<code>@extends('layouts.datatables_master')

@section('content')
    <table class="table table-bordered" id="clients-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Company Name</th>
                <th>Name</th>
                <th>Surname</th>
                <th>ID Number</th>
                <th>Created</th>
                <th>Last Updated</th>
                <th>Actions</th>
            </tr>
        </thead>
    </table>
@stop

@push('scripts')
<script>
$(function() {
    $('#clients-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{!! route('business.list') !!}',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'companyname', name: 'companyname' },
            { data: 'name', name: 'name' },
            { data: 'surname', name: 'surname' },
            { data: 'idnumber', name: 'idnumber' },
            { data: 'created_at', name: 'created_at' },
            { data: 'updated_at', name: 'updated_at' },
            { data: "actions",
                      "render": function(data, type, row) {
                        return '<a href="{{route('view',1)}}" class="btn btn-xs btn-info"><i class="fa fa-search" title="View"></i></a>                                               <a href="#" class="btn btn-xs btn-primary"><i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i></a>    <a href="#" class="btn btn-xs btn-danger"><i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i></a>'

                               ;}
            }

        ]
    });
});
</script>
@endpush
</code>```

Problem

My Main issue is passing an ID for all users. If you check my render function on my DataTable I said return route(view,1) where it's 1. I want to pass $id but it says undefined variable. Please help.

答:
the value of data should be an 'id', and use url() instead of route() :</p>

```<code>{ data: "id",
    "render": function(data, type, row) {
       return '<a href="{{ url("view") }}/"'+ data +'>View</a>';
        }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my route

Route::get('/view/{id}', [
    'uses' => 'ClientController@view',
    'as' => 'view'
]);

This is my Client controller

public function view($id){
     $client = Client::where('id',$id)->first();
     return view('view',compact('client'));
}

This is my datatable

@extends('layouts.datatables_master')

@section('content')

                ID
                Company Name
                Name
                Surname
                ID Number
                Created
                Last Updated
                Actions

@stop

@push('scripts')

@endpush

Problem

My Main issue is passing an ID for all users. If you check my render function on my DataTable I said return route(view,1) where it's 1. I want to pass $id but it says undefined variable. Please help.

Body:
the value of data should be an 'id', and use url() instead of route() :

{ data: "id",
    "render": function(data, type, row) {
       return '<a href="{{ url("view") }}/"'+ data +'>View</a>';
        }
}

ContentLicense: CC BY-SA 4.0


问:
MyISAM table index file keep crashing on regular basis!
Table keep Crashing
ERROR 126 (HY000): Incorrect key file for table './DB/Table.MYI'; try to repair it

It does get fixed by repair table but the problem is reoccurring!! and it's 5G table takes ~45mins to repair.

答:
Check your slow query log for a long running query on table.
Make sure other process like "backup" isn't interrupting it!!</p>

ContentLicense: CC BY-SA 2.5


问:
Converting strings to boolean gives only False value
Trying to convert data (string format from a csv file) to boolean (in a dataframe), I have 'lost' information on their original value, so now all the values are boolean False.

The columns that I am trying to change into boolean are the following:

```<code>df['Col1'] =df['Col1'].astype('bool')
df['Col2'] =df['Col2'].astype('bool')
</code>```

I have also tried with

```<code>df.Col1 = np.where(df.Col1.eq('true'), True, False)
df. Col2 = np.where(df.Col2.eq('true') | df.Col2.eq('tbc'), True, False)
</code>```

The unique values for each column, Col1 and Col2 are:

```<code>Col1: array([true, false, nan], dtype=object)

Col2: array(['true', 'false', 'tbc', nan], dtype=object)
</code>```

My original dataset has the following values.

```<code>Col1      Col2
true      true
true      true
false     false
nan       false
false     true
true      tbc
</code>```

Though they were converted into boolean, all the values are False:

```<code>Col1      Col2
False     False
False     False
False     False
False     False
False     False
False     False
</code>```

I would like to treat TBC as True. Why am I getting only False values? Any idea on how I could fix it?

Sample of original dataset and code:

```<code>Date                 Checked             Verified
2018-05-23           FALSE                TRUE
2018-05-24           TRUE                 TBC
2018-05-26           FALSE                TBC
2018-05-31            nan                 nan
2019-12-01           TRUE                 TRUE
2019-12-05           TRUE                 TBC
2019-12-15           TRUE                 FALSE
2019-12-23           FALSE                nan
</code>```

Code

Read the file csv:

```<code>df=pd.read_csv(path, sep=';', engine='python')
</code>```

Transform to lower case

```<code>df= df.apply(lambda x: x.astype(str).str.lower())
</code>```

Transform string to boolean

```<code>df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)
</code>```

Then I test how many rows have value Checked = True:

```<code>len(df[df['Checked']=='true'])
</code>```

output: 153

Convert to boolean Checked:

```<code>df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
len(df[df['Checked']==True])
</code>```

output: 153

Convert Verified to boolean:

```<code>df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

len(df[df['Verified']==True])
</code>```

output: 0 (expected 60)

答:
For me, this works perfectly. Since you haven't given the exact csv format, I assumed it would be like this:

```<code>Date;Checked;Verified
2018-05-23;FALSE;TRUE
2018-05-24;TRUE;TBC
2018-05-26;FALSE;TBC
2018-05-31;nan;nan
2019-12-01;TRUE;TRUE
2019-12-05;TRUE;TBC
2019-12-15;TRUE;FALSE
2019-12-23;FALSE;nan
</code>```

Then I called the code, like you did:

```<code>df=pd.read_csv(path, sep=';', engine='python')
df=df.apply(lambda x: x.astype(str).str.lower())
df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)
</code>```

The resulting dataframe looks like this:

```<code>         Date  Checked  Verified
0  2018-05-23    False      True
1  2018-05-24     True      True
2  2018-05-26    False      True
3  2018-05-31    False     False
4  2019-12-01     True      True
5  2019-12-05     True      True
6  2019-12-15     True     False
7  2019-12-23    False     False
</code>```

Which python and pandas version do you use?
I tested this with Python 3.6.1 and Pandas 1.04

Body:
Trying to convert data (string format from a csv file) to boolean (in a dataframe), I have 'lost' information on their original value, so now all the values are boolean False.

The columns that I am trying to change into boolean are the following:

df['Col1'] =df['Col1'].astype('bool')
df['Col2'] =df['Col2'].astype('bool')

I have also tried with

df.Col1 = np.where(df.Col1.eq('true'), True, False)
df. Col2 = np.where(df.Col2.eq('true') | df.Col2.eq('tbc'), True, False)

The unique values for each column, Col1 and Col2 are:

Col1: array([true, false, nan], dtype=object)

Col2: array(['true', 'false', 'tbc', nan], dtype=object)

My original dataset has the following values.

Col1      Col2
true      true
true      true
false     false
nan       false
false     true
true      tbc

Though they were converted into boolean, all the values are False:

Col1      Col2
False     False
False     False
False     False
False     False
False     False
False     False

I would like to treat TBC as True. Why am I getting only False values? Any idea on how I could fix it?

Sample of original dataset and code:

Date                 Checked             Verified
2018-05-23           FALSE                TRUE
2018-05-24           TRUE                 TBC
2018-05-26           FALSE                TBC
2018-05-31            nan                 nan
2019-12-01           TRUE                 TRUE
2019-12-05           TRUE                 TBC
2019-12-15           TRUE                 FALSE
2019-12-23           FALSE                nan

Code

Read the file csv:

df=pd.read_csv(path, sep=';', engine='python')

Transform to lower case

df= df.apply(lambda x: x.astype(str).str.lower())

Transform string to boolean

df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

Then I test how many rows have value Checked = True:

len(df[df['Checked']=='true'])

output: 153

Convert to boolean Checked:

df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
len(df[df['Checked']==True])

output: 153

Convert Verified to boolean:

df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

len(df[df['Verified']==True])

output: 0 (expected 60)

Body:
For me, this works perfectly. Since you haven't given the exact csv format, I assumed it would be like this:

Date;Checked;Verified
2018-05-23;FALSE;TRUE
2018-05-24;TRUE;TBC
2018-05-26;FALSE;TBC
2018-05-31;nan;nan
2019-12-01;TRUE;TRUE
2019-12-05;TRUE;TBC
2019-12-15;TRUE;FALSE
2019-12-23;FALSE;nan

Then I called the code, like you did:

df=pd.read_csv(path, sep=';', engine='python')
df=df.apply(lambda x: x.astype(str).str.lower())
df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

The resulting dataframe looks like this:

         Date  Checked  Verified
0  2018-05-23    False      True
1  2018-05-24     True      True
2  2018-05-26    False      True
3  2018-05-31    False     False
4  2019-12-01     True      True
5  2019-12-05     True      True
6  2019-12-15     True     False
7  2019-12-23    False     False

Which python and pandas version do you use?
I tested this with Python 3.6.1 and Pandas 1.04


问:
converting list inside tuple and adding on to the tuple
```<code>[('Username', 'INFO', 'ERROR'), ('ac', [2, 2]), ('hello', [4,3])]
</code>```

how can I get: [('Username', 'INFO', 'ERROR'), ('ac', 2, 2), ('hello', 4,3)]

so basically how to get rid of the list inside tuple!!!!

or:

How to convert this to {'ac': [2, 2], 'hello': [4, 3]} or {'ac': (2, 2), 'hello': (4, 3)}

to: [('ac', 2, 2), ('hello', 4,3)]

答:
For the dictionary

*v will unpack values

y = {'ac': [2, 2], 'hello': [4, 3]}

[(k, *v) for k, v in y.items()]

>>> [('ac', 2, 2), ('hello', 4, 3)]
```

<h2>For the list of tuples</h2>

<pre class="lang-py prettyprint-override"><code>z = [('Username', 'INFO', 'ERROR'), ('ac', [2, 2]), ('hello', [4,3])]

xx = list()
for x in z:
    tt = tuple()
    for y in x:
        if not type(y) == list:
            tt += (y,)
        else:
            tt += (*y,)
    xx.append(tt)

xx = [('Username', 'INFO', 'ERROR'), ('ac', 2, 2), ('hello', 4, 3)]
</code>```

Body:
[('Username', 'INFO', 'ERROR'), ('ac', [2, 2]), ('hello', [4,3])]

how can I get: [('Username', 'INFO', 'ERROR'), ('ac', 2, 2), ('hello', 4,3)]

so basically how to get rid of the list inside tuple!!!!

or:

How to convert this to {'ac': [2, 2], 'hello': [4, 3]} or {'ac': (2, 2), 'hello': (4, 3)}

to: [('ac', 2, 2), ('hello', 4,3)]

Body:
For the dictionary

*v will unpack values

y = {'ac': [2, 2], 'hello': [4, 3]}

[(k, *v) for k, v in y.items()]

>>> [('ac', 2, 2), ('hello', 4, 3)]

For the list of tuples

z = [('Username', 'INFO', 'ERROR'), ('ac', [2, 2]), ('hello', [4,3])]

xx = list()
for x in z:
    tt = tuple()
    for y in x:
        if not type(y) == list:
            tt += (y,)
        else:
            tt += (*y,)
    xx.append(tt)

xx = [('Username', 'INFO', 'ERROR'), ('ac', 2, 2), ('hello', 4, 3)]


问:
How to wait for ajax response?
I am so confused about getting response from server with ajax. I use jquery already, so I'd like to stick with it, as it usually simplifies code. Unless there is much better way, please suggest.

Basically I validate signup form with JS, one of the steps is checking if username is already taken.
I dont know how to wait for response before proceeding. I dont want to use async:false.

Here is code. Right now, checkUsername always returns validate().

```<code>// check in DB if username is already taken
function isUsernameTaken(username) {
  $.ajax({
    type: "POST",
    url: "/checkUsername/",
    data: {
      username: username,
    },
    success: function (response) {
      if (response.type == "taken") {
        return true;
      } else {
        return false;
      }
    },
    error: function (xhr, errmsg, err) {
      console.log(xhr.status + ": " + xhr.responseText);
      return false;
    },
  });
}

// run checks
function checkUsername() {
  const input = usernameInput;
  const inputVal = input.val().trim();

  if (isUsernameTaken(inputVal)) {
    console.log("Username taken");
    invalidate(input, "Username taken");
    return;
  } else {
    console.log("validate");
    validate(input);
  }
}
</code>```

答:
The issue is that once you start using asynchronous functions, you have to use them all the way through the call stack.

jQuery's $.ajax method (and aliases) all return a deferred object which is also a promise-like object so the idea is to return that so other code can use it to wait.

For example

function isUsernameTaken(username) {
  return $.post("/checkUsername/", { username })
    .then(({ type }) => type === 'taken', (jqXHR, textStatus, errorThrown) => {
      console.error(textStatus, errorThrown)
      return false
    })
}
```

<p>This returns a promise that resolves with a Boolean value. You would then use this like so</p>

<pre class="lang-js prettyprint-override"><code>isUsernameTaken(inputVal).then(isTaken => {
  if (isTaken) {
    console.log("Username taken")
    invalidate(input, "Username taken")
  } else {
    console.log("validate")
    validate(input)
  }
})
</code>```

Title: How to wait for ajax response?

Body:
I am so confused about getting response from server with ajax. I use jquery already, so I'd like to stick with it, as it usually simplifies code. Unless there is much better way, please suggest.

Basically I validate signup form with JS, one of the steps is checking if username is already taken.
I dont know how to wait for response before proceeding. I dont want to use async:false.

Here is code. Right now, checkUsername always returns validate().

// check in DB if username is already taken
function isUsernameTaken(username) {
  $.ajax({
    type: "POST",
    url: "/checkUsername/",
    data: {
      username: username,
    },
    success: function (response) {
      if (response.type == "taken") {
        return true;
      } else {
        return false;
      }
    },
    error: function (xhr, errmsg, err) {
      console.log(xhr.status + ": " + xhr.responseText);
      return false;
    },
  });
}

// run checks
function checkUsername() {
  const input = usernameInput;
  const inputVal = input.val().trim();

  if (isUsernameTaken(inputVal)) {
    console.log("Username taken");
    invalidate(input, "Username taken");
    return;
  } else {
    console.log("validate");
    validate(input);
  }
}

Body:
The issue is that once you start using asynchronous functions, you have to use them all the way through the call stack.

jQuery's $.ajax method (and aliases) all return a deferred object which is also a promise-like object so the idea is to return that so other code can use it to wait.

For example

function isUsernameTaken(username) {
  return $.post("/checkUsername/", { username })
    .then(({ type }) => type === 'taken', (jqXHR, textStatus, errorThrown) => {
      console.error(textStatus, errorThrown)
      return false
    })
}

This returns a promise that resolves with a Boolean value. You would then use this like so

isUsernameTaken(inputVal).then(isTaken => {
  if (isTaken) {
    console.log("Username taken")
    invalidate(input, "Username taken")
  } else {
    console.log("validate")
    validate(input)
  }
})


问:
NULL pointer with boost::shared_ptr?
What's the equivalent to the following:

```<code>std::vector<Foo*> vec;
vec.push_back(NULL);
</code>```

when dealing with boost::shared_ptr? Is it the following code?

```<code>std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());
</code>```

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

```<code>boost::shared_ptr<Foo> nullPtr;
</code>```

答:
You could declare a global nullPtr for shared_ptr<Foo>. But if you pollute the global namespace, what would you call the global nullPtr for shared_ptr<Bar>?

Typically I declare the null ptr as a static in the class of the pointer.

```<code>#include <boost\shared_ptr.hpp>

class Foo; // forward decl
typedef boost::shared_ptr<Foo> FooPtr;
class Foo
{
public:
    static FooPtr Null;
}
...
// define static in cpp file
FooPtr Foo::Null;
...
// use Foo Null
vec.push_back(Foo::Null);
</code>```

That way each class has a static Null.

OwnerDisplayName: Frank

Title: NULL pointer with boost::shared_ptr?

Body:
What's the equivalent to the following:

std::vector<Foo*> vec;
vec.push_back(NULL);

when dealing with boost::shared_ptr? Is it the following code?

std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

boost::shared_ptr<Foo> nullPtr;

Body:
You could declare a global nullPtr for shared_ptr<Foo>. But if you pollute the global namespace, what would you call the global nullPtr for shared_ptr<Bar>?

Typically I declare the null ptr as a static in the class of the pointer.

#include <boost\shared_ptr.hpp>

class Foo; // forward decl
typedef boost::shared_ptr<Foo> FooPtr;
class Foo
{
public:
    static FooPtr Null;
}
...
// define static in cpp file
FooPtr Foo::Null;
...
// use Foo Null
vec.push_back(Foo::Null);

That way each class has a static Null.

OwnerDisplayName: m-sharp

LastEditorDisplayName: m-sharp


问:
How can I select the next div using jQuery?
I am quite a noob when it comes to jQuery and I'm trying to select the next element using the next() selector but having a little trouble in getting it to work!

What I'm trying to do is to activate slideDown() once the user has finished making their selection on a ui slider. Here is my code:

$('.slider').slider({
   stop: function(event, ui) {
       $(this).nextAll('.secondq:first').slideDown('slow')
   }
});

Trouble is, this doesn't work at all. It will only work if I put the 'secondq' question inside the parent div of the ui slider. Here is my HTML:

```<code><div class="option">
                            <h2 align="left">How high is your ceiling from the floor?</h2>
                            <input type="text" align="right" name="bonus" class="value" disabled="disabled"  />
                            <div class="slidewrap">
                                <div class="sliderFt slider"></div>
                            </div>
                        </div>
                        <!-- End Option -->
                        <div class="option">
                            <h2 align="left">How many windows do you have?</h2>
                            <input type="text" align="right" name="bonus" class="value" disabled="disabled"  />
                            <div class="slidewrap">
                                <div class="sliderWinDoor slider"></div>
                            </div>
                            <div class="secondq" style="display:none;">
                                <h2>What type of material are your windows made of?</h2>
                                <div class="radiocont">
                                    <label>Wood</label>
                                    <input type="radio" class="styled" value="wood" name="windowtype" />
                                </div>
                                <div class="radiocont">
                                    <label>Metal</label>
                                    <input type="radio" class="styled" value="metal" name="windowtype" />
                                </div>
                                <div class="radiocont">
                                    <label>PVC</label>
                                    <input type="radio" class="styled" value="pvc" name="windowtype" />
                                </div>
                            </div>
                        </div>
</code>```

答:
nextAll only gets siblings. Based on your HTML structure, you could do:

```<code>$(this).parent().next()
</code>```

To make it more independent from the structure, you could also do:

```<code>$(this).closest('.slidewrap').nextAll('.secondq:first')
</code>```

Body:
I am quite a noob when it comes to jQuery and I'm trying to select the next element using the next() selector but having a little trouble in getting it to work!

What I'm trying to do is to activate slideDown() once the user has finished making their selection on a ui slider. Here is my code:

$('.slider').slider({
   stop: function(event, ui) {
       $(this).nextAll('.secondq:first').slideDown('slow')
   }
});

Trouble is, this doesn't work at all. It will only work if I put the 'secondq' question inside the parent div of the ui slider. Here is my HTML:

How high is your ceiling from the floor?

                            <input type="text" align="right" name="bonus" class="value" disabled="disabled"  />

How many windows do you have?

                            <input type="text" align="right" name="bonus" class="value" disabled="disabled"  />

What type of material are your windows made of?

                                    Wood
                                    <input type="radio" class="styled" value="wood" name="windowtype" />

                                    Metal
                                    <input type="radio" class="styled" value="metal" name="windowtype" />

                                    PVC
                                    <input type="radio" class="styled" value="pvc" name="windowtype" />

Body:
nextAll only gets siblings. Based on your HTML structure, you could do:

$(this).parent().next()

To make it more independent from the structure, you could also do:

$(this).closest('.slidewrap').nextAll('.secondq:first')


问:
Get file size of an URL without download
To get the file size of an URL without download, I wrote:

```<code>public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && evt.getLength() > 0) {
                cr.kill();
            }
        });
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }
</code>```

It seems to work on Simulator, Android and iOS with a testing URL of my Spring Boot server.

Anyway, I consider this code as a workaround, as I couldn't find an API that directly gives me the file size without starting the download first. Starting the download and then killing it works, but maybe there may be a better way to get the same result. By the way, the condition && evt.getLength() > 0 may never be satisfied in some cases (depending on the headers received), so it would be better to read only the headers, in which "Content-Length" may be present or absent.

So, my question is if, with Codename One, there is a way to download only the response headers, without starting the download. Thank you.

答:
Using the HTTP head request should give you the content length header that you can then use to get the size of the file without triggering a download. Your code might not follow through on the download but it does physically happen so a head request would be superior.

Unfortunately while there's a nice wrapper to head in Rest. This wrapper isn't very useful since there's no API to query response headers. That would make sense as an enhancement. You would need to derive ConnectionRequest and read the server response headers to get the content length.

Body:
To get the file size of an URL without download, I wrote:

public static long getFileSizeWithoutDownload(String url) {
        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && evt.getLength() > 0) {
                cr.kill();
            }
        });
        NetworkManager.getInstance().addToQueueAndWait(cr);
        return cr.getContentLength();
    }

It seems to work on Simulator, Android and iOS with a testing URL of my Spring Boot server.

Anyway, I consider this code as a workaround, as I couldn't find an API that directly gives me the file size without starting the download first. Starting the download and then killing it works, but maybe there may be a better way to get the same result. By the way, the condition && evt.getLength() > 0 may never be satisfied in some cases (depending on the headers received), so it would be better to read only the headers, in which "Content-Length" may be present or absent.

So, my question is if, with Codename One, there is a way to download only the response headers, without starting the download. Thank you.


问:
Is it possible to define variables in a task for a role?
I need to include a role in my own role, which relies on variables being set. Can I include them in a task and will they be applied to that included role?

Something like this:

```<code>- name: Configure firewall ports
  include_role:
    name: ipr-cnrs.nftables
  vars:
    - nft_define:
        input tcp accepted:
          name: in_tcp_accept
          value: '{ 22, 23 }'
</code>```

答:
Q: "Can I include the variables in a task and will they be applied to that included role?"

A: Yes. It's possible. Correct syntax is

- name: Configure firewall ports
  include_role:
    name: ipr_cnrs_nftables
  vars:
    nft_define:
      input tcp accepted:
        name: in_tcp_accept
        value: '{ 22, 23 }'
```

<p>For example, the task</p>

<pre class="lang-yaml prettyprint-override"><code>shell> cat roles/ipr_cnrs_nftables/tasks/main.yml
- debug:
    var: nft_define
</code>```

gives

```<code>    "nft_define": {
        "input tcp accepted": null,
        "name": "in_tcp_accept",
        "value": "{ 22, 23 }"
    }
</code>```

Notes:

Quoting from Role Names

"Role names are limited to lowercase word characters (i.e., a-z, 0-9) and ‘_’. No special characters are allowed, including ‘.’, ‘-‘, and space. During import, any ‘.’ and ‘-‘ characters contained in the repository name or role_name will be replaced with ‘_’."

The attribute value shall be a list of ports. It's a string in the example. Change it

    value: [22, 23 ]
```

In a playbook, the variable will be available when the flow-control reaches the include statement. See Including and Importing.

Body:
I need to include a role in my own role, which relies on variables being set. Can I include them in a task and will they be applied to that included role?

Something like this:

- name: Configure firewall ports
  include_role:
    name: ipr-cnrs.nftables
  vars:
    - nft_define:
        input tcp accepted:
          name: in_tcp_accept
          value: '{ 22, 23 }'

Body:
Q: "Can I include the variables in a task and will they be applied to that included role?"

A: Yes. It's possible. Correct syntax is

- name: Configure firewall ports
  include_role:
    name: ipr_cnrs_nftables
  vars:
    nft_define:
      input tcp accepted:
        name: in_tcp_accept
        value: '{ 22, 23 }'

For example, the task

shell> cat roles/ipr_cnrs_nftables/tasks/main.yml
- debug:
    var: nft_define

gives

    "nft_define": {
        "input tcp accepted": null,
        "name": "in_tcp_accept",
        "value": "{ 22, 23 }"
    }

Notes:

Quoting from Role Names

"Role names are limited to lowercase word characters (i.e., a-z, 0-9) and ‘_’. No special characters are allowed, including ‘.’, ‘-‘, and space. During import, any ‘.’ and ‘-‘ characters contained in the repository name or role_name will be replaced with ‘_’."

The attribute value shall be a list of ports. It's a string in the example. Change it

    value: [22, 23 ]

In a playbook, the variable will be available when the flow-control reaches the include statement. See Including and Importing.


问:
Reading rows from Google sheets but the returning array is null
I would like to read data from google sheets and then write cell values to input type text fields. Firefox returns an error "TypeError: conteudo is null" when I try to access an array returning data from GSheets.
This is the link to my google sheets example.

Sample data

```
Nome: Name
Data_Nascimento: 20/07/1950
CPF: 12345678
```

See below my code.

File: code.gs

```<code>function doGet(request) {
    setPage('index');
    return HtmlService
    .createTemplateFromFile('index')
    .evaluate()
    .addMetaTag('viewport', 'width=device-width, initial-scale=1')
    .setTitle("teste");
  }

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

var urlss = "https://docs.google.com/spreadsheets/d/1q8kz2L2q4u99dvR0zeDuCghSgtlNKMpbmZgCRHC3hn0/edit?usp=sharing";

function setPage(page) {
  var ps=PropertiesService.getUserProperties();
  ps.setProperty('PageTitle', page);
  return ps.getProperty('PageTitle');
}

function getConsultaPacientes() {

  var ss = SpreadsheetApp.openByUrl(urlss);
  var ws = ss.getSheetByName("lista");
  var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getValues();

  var listaNomePaciente = dadosPaciente.map(function(param) { return param[0];});
  var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1];});
  var listaCPFPaciente = dadosPaciente.map(function(param) { return param[2];});

  pacienteEncontrado = [listaNomePaciente,listaCPFPaciente,listaDtNascPaciente];
  return pacienteEncontrado;
 }
</code>```

File: page_js

```<code><script>

document.getElementById("btconsultaPaciente").addEventListener("click",objConsultaPaciente);

function objConsultaPaciente(){
   google.script.run.withSuccessHandler(populateDadosPacientes).getConsultaPacientes();
}

function populateDadosPacientes(conteudo) {
   document.getElementById("idnome").value=conteudo[0];
   document.getElementById("idcpf").value=conteudo[1];
   document.getElementById("iddtnascimento").value=conteudo[2];
   M.updateTextFields();

   }

</script>
</code>```

File: index.html

```<code><!DOCTYPE html>
  <html>
    <head>
      <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
      <!-- <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0"> -->
    </head>

    <body>
         <div class="container">

               <div class="row">
                  <div class="input-field col s12 m2 l2">
                     <button id="btconsultaPaciente" class="btn tooltipped" data-position="bottom" data-tooltip="Consultar Paciente">Populate</button>
                  </div>
               </div> <!-- CLOSE ROW -->

               <div class="divider"></div>

               <br>

               <div class="row">
                  <div class="input-field col s12 m4 l4">
                     <input type="text" id="idnome" class="validate">
                     <label class="active" for="idnome">Nome</label>
                  </div>
                  <div class="input-field col s12 m4 l4">
                     <input type="text" id="iddtnascimento" class="datepicker">
                     <label>Data de Nascimento</label>
                  </div>
                  <div class="input-field col s12 m4 l4">
                     <input type="text" id="idcpf" class="validate">
                     <label for="idcpf">CPF</label>
                  </div>
               </div> <!-- CLOSE ROW -->

               <div class="row">
                  <div class="col">

                  </div>
               </div> <!-- CLOSE ROW -->

         </div> <!-- CLOSE CONTAINER -->

      <!-- Compiled and minified JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
      <?!= include('index_js'); ?>
    </body>
</html>
</code>```

Body:
I would like to read data from google sheets and then write cell values to input type text fields. Firefox returns an error "TypeError: conteudo is null" when I try to access an array returning data from GSheets.
This is the link to my google sheets example.

Sample data

Nome: Name
Data_Nascimento: 20/07/1950
CPF: 12345678

See below my code.

File: code.gs

function doGet(request) {
    setPage('index');
    return HtmlService
    .createTemplateFromFile('index')
    .evaluate()
    .addMetaTag('viewport', 'width=device-width, initial-scale=1')
    .setTitle("teste");
  }

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

var urlss = "https://docs.google.com/spreadsheets/d/1q8kz2L2q4u99dvR0zeDuCghSgtlNKMpbmZgCRHC3hn0/edit?usp=sharing";

function setPage(page) {
  var ps=PropertiesService.getUserProperties();
  ps.setProperty('PageTitle', page);
  return ps.getProperty('PageTitle');
}

function getConsultaPacientes() {

  var ss = SpreadsheetApp.openByUrl(urlss);
  var ws = ss.getSheetByName("lista");
  var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getValues();

  var listaNomePaciente = dadosPaciente.map(function(param) { return param[0];});
  var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1];});
  var listaCPFPaciente = dadosPaciente.map(function(param) { return param[2];});

  pacienteEncontrado = [listaNomePaciente,listaCPFPaciente,listaDtNascPaciente];
  return pacienteEncontrado;
 }

File: page_js

File: index.html

<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

                     <button id="btconsultaPaciente" class="btn tooltipped" data-position="bottom" data-tooltip="Consultar Paciente">Populate</button>

                     <input type="text" id="idnome" class="validate">
                     Nome

                     <input type="text" id="iddtnascimento" class="datepicker">
                     Data de Nascimento

                     <input type="text" id="idcpf" class="validate">
                     CPF

      <?!= include('index_js'); ?>

Body:
Try this:

function getConsultaPacientes(input) {
  var input=input||10;//default for testing
  var ss=SpreadsheetApp.getActive();//changed for testing
  var ws=ss.getSheetByName("Sheet1");//changed sheet name
  var vA=ws.getRange(2,1,ws.getLastRow()-1,13).getValues();
  var list1=vA.map(function(param){return param[12];});
  var list2=vA.map(function(param){return param[0];});
  var list3=vA.map(function(param){return param[1];});
  var pos=list1.indexOf(input);
  if(pos>-1) {
    var pac=[list2[pos],list3[pos]];
    return pac;
  } else {
    return 'Indisponível';
  }
}

My Test Data:

COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10,COL11,COL12,COL13,COL14,COL15
8,2,3,7,3,10,7,11,9,0,9,10,7,4,7
3,0,5,4,1,7,11,10,11,11,0,5,10,5,6
7,10,11,5,8,8,11,6,10,7,6,4,4,2,11
10,0,2,1,7,7,9,9,10,8,5,8,9,8,6
0,10,1,9,0,9,9,0,6,7,9,3,8,11,10
6,6,1,3,5,5,3,4,6,0,5,6,0,0,2
0,11,6,1,7,3,9,1,6,9,4,9,3,9,8
6,7,5,9,11,7,5,9,8,10,11,9,6,2,10
1,4,8,7,7,5,7,9,10,8,5,6,2,7,1
3,5,0,2,1,1,1,1,7,1,11,8,7,11,10
6,3,2,7,2,3,0,5,11,0,8,3,7,11,3
11,6,1,11,2,7,5,10,6,1,11,0,3,3,10


问:
ASP.NET Core 3.1 cannot process Axios request until ApiController attribute is added
I have the following issue. Whenever I send something to my Api endpoint, ASP.NET Core 3.1 is not able to process the request. However, when I add the ApiController attribute it works perfectly fine.

My code is correct but only works when I add this attribute. How is that so?

For reference, here's my code

API

```<code>[ApiController] //Remove this and the code breaks
[Route("api/SomeApi")]
public class ApiController : Controller {

    private readonly IService service;

    public ApiController(IService service)
    {
        this.service = service;
    }

    [HttpPost]
    [Route("Add")]
    public SomeClass Add(SomeClass foo)
    {
        var userId = service.GetCurrentUserId(User);
        foo.Id = Guid.NewGuid();
        foo.UserId = userId;
        service.Add(foo);
        return foo;
    }
}
</code>```

JS

```<code>axios.post('/api/SomeApi/Add', {
   foo: this.foo,

}).then(function (response: any) {
   this.Id = response.Id;
});
</code>```

FYI, I have other methods on my ApiController using GET/POST. The GET ones work perfectly fine but the POST methods only work when I use query parameters. In this case, I didn't use query parameters because I have more data to send to my Api than actually given in the example.

I've already tried to get my response using [FromBody]. It did not work. I instead got null. foo was not even instantiated.

答:
I had the same problem and solved it using qs library for stringifying the JSON Object.

```<code>axios.post('/controller/action', Qs.stringify({Id: 1, Name: 'Test'}))
    .then(function (response) {
        console.log(response);
    })
    .catch(function (response) {
        console.log(response);
    });
</code>```

Another way that worked for plain objects is using URLSearchParams.

```<code>var requestData = {Id: 1, Name: 'Test'}
var params = new URLSearchParams();

for(key in requestData)
params.append(key, requestData[key]);

axios.post('/controller/action', params)
.then(function (response) {
    console.log(response);
})
.catch(function (response) {
    console.log(response);
});
</code>```

Body:
I have the following issue. Whenever I send something to my Api endpoint, ASP.NET Core 3.1 is not able to process the request. However, when I add the ApiController attribute it works perfectly fine.

My code is correct but only works when I add this attribute. How is that so?

For reference, here's my code

API

[ApiController] //Remove this and the code breaks
[Route("api/SomeApi")]
public class ApiController : Controller {

    private readonly IService service;

    public ApiController(IService service)
    {
        this.service = service;
    }

    [HttpPost]
    [Route("Add")]
    public SomeClass Add(SomeClass foo)
    {
        var userId = service.GetCurrentUserId(User);
        foo.Id = Guid.NewGuid();
        foo.UserId = userId;
        service.Add(foo);
        return foo;
    }
}

JS

axios.post('/api/SomeApi/Add', {
   foo: this.foo,

}).then(function (response: any) {
   this.Id = response.Id;
});

FYI, I have other methods on my ApiController using GET/POST. The GET ones work perfectly fine but the POST methods only work when I use query parameters. In this case, I didn't use query parameters because I have more data to send to my Api than actually given in the example.

I've already tried to get my response using [FromBody]. It did not work. I instead got null. foo was not even instantiated.

Body:
I had the same problem and solved it using qs library for stringifying the JSON Object.

axios.post('/controller/action', Qs.stringify({Id: 1, Name: 'Test'}))
    .then(function (response) {
        console.log(response);
    })
    .catch(function (response) {
        console.log(response);
    });

Another way that worked for plain objects is using URLSearchParams.

var requestData = {Id: 1, Name: 'Test'}
var params = new URLSearchParams();

for(key in requestData)
params.append(key, requestData[key]);

axios.post('/controller/action', params)
.then(function (response) {
    console.log(response);
})
.catch(function (response) {
    console.log(response);
});


问:
In python, when does pass by reference occur?
I have a code as below,

```<code>attractions = [[] for i in range(5)]

def add_attraction(attraction):
  attractions_for_destination = attractions[2]
  attractions_for_destination.append(attraction)
  return
</code>```

pass by reference occurs in 3rd line "attractions_for_destination = attractions[2]". The general idea of pass by reference that I have is that it happens between actual parameter and formal parameter. But the above line is a simple assignment code. Can pass by reference happen in a simple assignment code?

If so, if I write

```<code>attractions_for_destination = attractions[2] + ": best attraction site"
</code>```

will altering the value force the newly made variable to use a new memory space?

答:
Saying pass by reference or pass by value isn't really applicable to python. For example consider Java. Everything in Java is pass by value, everything. However the value of an object is the reference to the object. So it is, in a way, pass by reference since mutating the object will be reflected to the calling context. Calling it "pass by value" is a bit confusing since for people used to C-family (where this distinction is more straightforward) assume that pass by value means you won't modify the underlying argument passed.

So saying Java is "pass by value" is true but possibly confusing. It is a more relevant statement at much lower levels of the language (like when talking about how the compiler handles passing arguments but not at the level of application programmer).

Python is similar. The confusion about the Java example actually lead Python to not say if it is pass by value/reference. http://stupidpythonideas.blogspot.com/2013/11/does-python-pass-by-value-or-by.html

So for programming, it is save to assume that any object is "passed by reference" (technically no but essentially yes). It is more complicated than that but that link explains it in more depth.

Body:
I have a code as below,

attractions = [[] for i in range(5)]

def add_attraction(attraction):
  attractions_for_destination = attractions[2]
  attractions_for_destination.append(attraction)
  return

pass by reference occurs in 3rd line "attractions_for_destination = attractions[2]". The general idea of pass by reference that I have is that it happens between actual parameter and formal parameter. But the above line is a simple assignment code. Can pass by reference happen in a simple assignment code?

If so, if I write

attractions_for_destination = attractions[2] + ": best attraction site"

will altering the value force the newly made variable to use a new memory space?


问:
Assistance needed with join query
I have two very simple tables in Oracle 9G:

Customer

```<code>userid | firstName | lastName | email
-------+-----------+----------+---------------------
  1      user1       User1      user1@mail.in
  2      user2       User2      user2@mail.in
</code>```

Order

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1          1          0         12/12/2009    1
2          1          1         13/12/2009    2
3          1          1         14/12/2009    3
4          2          0         12/12/2009    4
5          2          1         16/12/2009    2
6          1          0         14/12/2009    5
7          2          1         17/12/2009    4
8          2          0         10/12/2010    2
</code>```

I want to select all users which have orders of type 0

```<code>select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'
</code>```

The result is:

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1          1          0         12/12/2009    1
4          2          0         12/12/2009    4
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2
</code>```

Now I need to modify this query to bring only last purchase date for each user id and get the result like this:

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2
</code>```

How should I modify my query to get this result?

答:
```<code>SELECT *
FROM Order o
INNER JOIN
(SELECT MAX(o.id) AS maxid
FROM Customer c
INNER JOIN Order o ON c.userid = o.userid
WHERE o.orderType ='0'
GROUP BY c.userid) x ON x.maxid = o.id
</code>```

Title: Assistance needed with join query

Body:
I have two very simple tables in Oracle 9G:

Customer

userid | firstName | lastName | email
-------+-----------+----------+---------------------
  1      user1       User1      user1@mail.in
  2      user2       User2      user2@mail.in

Order

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1          1          0         12/12/2009    1
2          1          1         13/12/2009    2
3          1          1         14/12/2009    3
4          2          0         12/12/2009    4
5          2          1         16/12/2009    2
6          1          0         14/12/2009    5
7          2          1         17/12/2009    4
8          2          0         10/12/2010    2

I want to select all users which have orders of type 0

select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'

The result is:

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1          1          0         12/12/2009    1
4          2          0         12/12/2009    4
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2

Now I need to modify this query to bring only last purchase date for each user id and get the result like this:

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2

How should I modify my query to get this result?


问:
How to publish website but prevent visitors?
I would like to publish my asp.net core to my own domain that is hosted on a shared hosting.
However, after publishing I would like to spend a few hours live testing it (yeah, I have yet to learn auto testing using selenium).

While doing so, I want to prevent visitors from knowing that the site is published so that they won't use it; some strangers know that I will be publishing some time soon and they may have set up auto monitoring.

How can that be achieved?

答:
You can setup a gateway for you website.

You can set IP whitelist in the server hosting provider, or you can use a reverse proxy like Nginx to set IP whitelist or HTTP auth before the requests arrive your website.

If the domain doesn't matters, you can use subdomain as Jacob suggests


问:
Azure - How to execute UDF from external data source in select statement
I have an external data source created in DB1 and its pointing to DB2 database in Azure.

I want to query a UDF defined in DB2 from DB1.

Following syntax works, from DB1:

EXEC sp_execute_remote

    N'Ext_DB2',

    N'SELECT  Result'

But I want to use following syntax:

select C1, C2, < function_in_DB2 >
from t1

I tried searching web, this format is not mentioned anywhere, is it not supported? Any pointers will help.

Thanks !

答:
Just per my experience, I think Azure SQL database doesn't support it. As we know, we can't do cross database query directly.

Since none document talk about this, I would suggest you ask Azure SQL support to get more support, ref: How to create an Azure support request.

Hope this helps.


问:
Problem with maven and spring boot: null returned by binding at org.eclipse.sisu.wire.LocatorWiring
I'm trying to run maven commands on spring boot project but all the time I'm getting a lot of errors like this:

```<code>22) null returned by binding at org.eclipse.sisu.wire.LocatorWiring
 but parameter 0 of org.eclipse.aether.internal.impl.DefaultMetadataResolver.<init>() is not @Nullable
  while locating org.eclipse.aether.impl.RepositoryEventDispatcher
    for parameter 0 at org.eclipse.aether.internal.impl.DefaultMetadataResolver.<init>(DefaultMetadataResolver.java:103)
  while locating org.eclipse.aether.internal.impl.DefaultMetadataResolver
  while locating java.lang.Object annotated with *
  at org.eclipse.sisu.wire.LocatorWiring
  while locating org.eclipse.aether.impl.MetadataResolver
    for parameter 0 at org.apache.maven.repository.internal.DefaultVersionResolver.<init>(DefaultVersionResolver.java:111)
  while locating org.apache.maven.repository.internal.DefaultVersionResolver
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.eclipse.aether.impl.VersionResolver
    for parameter 1 at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.<init>(DefaultArtifactDescriptorReader.java:116)
  while locating org.apache.maven.repository.internal.DefaultArtifactDescriptorReader
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.eclipse.aether.impl.ArtifactDescriptorReader
    for parameter 1 at org.eclipse.aether.internal.impl.DefaultDependencyCollector.<init>(DefaultDependencyCollector.java:92)
  while locating org.eclipse.aether.internal.impl.DefaultDependencyCollector
  while locating java.lang.Object annotated with *
  at org.eclipse.sisu.wire.LocatorWiring
  while locating org.eclipse.aether.impl.DependencyCollector
    for parameter 5 at org.eclipse.aether.internal.impl.DefaultRepositorySystem.<init>(DefaultRepositorySystem.java:121)
  while locating org.eclipse.aether.internal.impl.DefaultRepositorySystem
  while locating java.lang.Object annotated with *
  while locating org.apache.maven.artifact.resolver.DefaultArtifactResolver
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.artifact.resolver.ArtifactResolver
  while locating org.apache.maven.repository.legacy.LegacyRepositorySystem
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.repository.RepositorySystem
  while locating org.apache.maven.project.DefaultProjectBuildingHelper
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.project.ProjectBuildingHelper
  while locating org.apache.maven.project.DefaultProjectBuilder
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.project.ProjectBuilder
  while locating org.apache.maven.DefaultMaven
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.Maven

</code>```

While running in Intellij on Windows there is no problem. The problem is when I'm trying to run it from command line on linux. On the both devices is the same version of maven.

Pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.tatara</groupId>
    <artifactId>Euress</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Euress</name>
    <description>Euress application</description>

    <properties>
        <java.version>1.8</java.version>
        <groovy.version>2.1.5</groovy.version>
        <gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
        <spock-spring.version>1.1-groovy-2.4</spock-spring.version>
        <cglib-nodep.version>3.2.7</cglib-nodep.version>
        <groovy-all.version>2.4.4</groovy-all.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>${groovy-all.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib-nodep.version}</version>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-spring</artifactId>
            <version>${spock-spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.gmavenplus</groupId>
                <artifactId>gmavenplus-plugin</artifactId>
                <version>${gmavenplus-plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compileTests</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sources>
                        <source>
                            <directory>${project.basedir}/src/main/java/groovy</directory>
                            <includes>
                                <include>**/*.groovy</include>
                            </includes>
                        </source>
                    </sources>
                    <testSources>
                        <testSource>
                            <directory>${project.basedir}/src/test/groovy</directory>
                            <includes>
                                <include>**/*.groovy</include>
                            </includes>
                        </testSource>
                    </testSources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Maybe someone could help me to find any solution for that problem ? I think it could be something with spock and maven versions.

答:
I cannot build your project and see the same error because I only have a POM. But I can look at your POM and see

<groovy.version>2.1.5</groovy.version>
<groovy-all.version>2.4.4</groovy-all.version>
```

<p>You do not use <code>groovy.version</code> directly, but probably in one of the dependency POMs this property is used because when I look at the effective POM via <code>mvn help:effective-pom</code>, I see this:</p>

<pre class="lang-xml prettyprint-override"><code><!-- (...) -->

    <groovy-all.version>2.4.4</groovy-all.version>
    <groovy.version>2.1.5</groovy.version>

<!-- (...) -->

      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy</artifactId>
        <version>2.1.5</version>
      </dependency>
      <dependency>2.
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-ant</artifactId>
        <version>2.1.5</version>
      </dependency>
      <!-- and many more modules like these -->
</code>```

Then I see that Spock-Spring 1.1-groovy-2.4 actually prefers Groovy 2.4.9, so we are dealing with yet another version here, we already have

2.1.5 - definitely too old, why would you use Groovy 2.1 for a Spock version designed for Groovy 2.4?

2.4.4

2.4.9

Then in your effective POM there also is a transitive dependency

      <dependency>
        <groupId>org.awaitility</groupId>
        <artifactId>awaitility-groovy</artifactId>
        <version>4.0.1</version>
      </dependency>
```

<p>which again references the property you are overriding and a newer Spock and Groovy version:</p>

<pre class="lang-xml prettyprint-override"><code>    <properties>
        <groovy.version>2.5.7</groovy.version>
        <spock.version>1.3-groovy-2.5</spock.version>
    </properties>

<!-- (...) -->

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>${groovy.version}</version>
        </dependency>
</code>```

And this is where your version conflict comes from. I suggest you define which Groovy and Spock versions you want in your own POM (or parent POM) in a dependencyManagement section, later only importing the actual dependencies without version numbers in the dependencies section. And while you are at it, you could also upgrade to Spock 1.3-groovy-2.5 and a Groovy 2.5 version. Shall we?

Besides, you are not even directly referencing Spock Core, it is only a transitive dependency of Spock Spring. Maybe you want to include the direct dependency too because it is kind of important for your testing, is it not?

I am keeping your Groovy-All import, but you might consider just to import the Groovy modules you really need for testing, minimally just org.codehaus.groovy:groovy.

See if this works for you:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/>
  </parent>

  <groupId>com.tatara</groupId>
  <artifactId>Euress</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>Euress</name>
  <description>Euress application</description>

  <properties>
    <java.version>1.8</java.version>
    <groovy.version>2.5.8</groovy.version>
    <gmavenplus-plugin.version>1.8.1</gmavenplus-plugin.version>
    <spock.version>1.3-groovy-2.5</spock.version>
    <cglib-nodep.version>3.2.7</cglib-nodep.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy</artifactId>
        <version>${groovy.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>${cglib-nodep.version}</version>
      </dependency>
      <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-core</artifactId>
        <version>${spock.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-spring</artifactId>
        <version>${spock.version}</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>${groovy.version}</version>
      <type>pom</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
    </dependency>
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-spring</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-neo4j</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.codehaus.gmavenplus</groupId>
        <artifactId>gmavenplus-plugin</artifactId>
        <version>${gmavenplus-plugin.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compileTests</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <sources>
            <source>
              <directory>${project.basedir}/src/main/java/groovy</directory>
              <includes>
                <include>**/*.groovy</include>
              </includes>
            </source>
          </sources>
          <testSources>
            <testSource>
              <directory>${project.basedir}/src/test/groovy</directory>
              <includes>
                <include>**/*.groovy</include>
              </includes>
            </testSource>
          </testSources>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>
```

Body:
I'm trying to run maven commands on spring boot project but all the time I'm getting a lot of errors like this:

22) null returned by binding at org.eclipse.sisu.wire.LocatorWiring
 but parameter 0 of org.eclipse.aether.internal.impl.DefaultMetadataResolver.<init>() is not @Nullable
  while locating org.eclipse.aether.impl.RepositoryEventDispatcher
    for parameter 0 at org.eclipse.aether.internal.impl.DefaultMetadataResolver.<init>(DefaultMetadataResolver.java:103)
  while locating org.eclipse.aether.internal.impl.DefaultMetadataResolver
  while locating java.lang.Object annotated with *
  at org.eclipse.sisu.wire.LocatorWiring
  while locating org.eclipse.aether.impl.MetadataResolver
    for parameter 0 at org.apache.maven.repository.internal.DefaultVersionResolver.<init>(DefaultVersionResolver.java:111)
  while locating org.apache.maven.repository.internal.DefaultVersionResolver
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.eclipse.aether.impl.VersionResolver
    for parameter 1 at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.<init>(DefaultArtifactDescriptorReader.java:116)
  while locating org.apache.maven.repository.internal.DefaultArtifactDescriptorReader
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.eclipse.aether.impl.ArtifactDescriptorReader
    for parameter 1 at org.eclipse.aether.internal.impl.DefaultDependencyCollector.<init>(DefaultDependencyCollector.java:92)
  while locating org.eclipse.aether.internal.impl.DefaultDependencyCollector
  while locating java.lang.Object annotated with *
  at org.eclipse.sisu.wire.LocatorWiring
  while locating org.eclipse.aether.impl.DependencyCollector
    for parameter 5 at org.eclipse.aether.internal.impl.DefaultRepositorySystem.<init>(DefaultRepositorySystem.java:121)
  while locating org.eclipse.aether.internal.impl.DefaultRepositorySystem
  while locating java.lang.Object annotated with *
  while locating org.apache.maven.artifact.resolver.DefaultArtifactResolver
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.artifact.resolver.ArtifactResolver
  while locating org.apache.maven.repository.legacy.LegacyRepositorySystem
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.repository.RepositorySystem
  while locating org.apache.maven.project.DefaultProjectBuildingHelper
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.project.ProjectBuildingHelper
  while locating org.apache.maven.project.DefaultProjectBuilder
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.project.ProjectBuilder
  while locating org.apache.maven.DefaultMaven
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
  while locating org.apache.maven.Maven

While running in Intellij on Windows there is no problem. The problem is when I'm trying to run it from command line on linux. On the both devices is the same version of maven.

Pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.tatara</groupId>
    <artifactId>Euress</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Euress</name>
    <description>Euress application</description>

    <properties>
        <java.version>1.8</java.version>
        <groovy.version>2.1.5</groovy.version>
        <gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
        <spock-spring.version>1.1-groovy-2.4</spock-spring.version>
        <cglib-nodep.version>3.2.7</cglib-nodep.version>
        <groovy-all.version>2.4.4</groovy-all.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>${groovy-all.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib-nodep.version}</version>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-spring</artifactId>
            <version>${spock-spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.gmavenplus</groupId>
                <artifactId>gmavenplus-plugin</artifactId>
                <version>${gmavenplus-plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compileTests</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sources>
                        <source>
                            <directory>${project.basedir}/src/main/java/groovy</directory>
                            <includes>
                                <include>**/*.groovy</include>
                            </includes>
                        </source>
                    </sources>
                    <testSources>
                        <testSource>
                            <directory>${project.basedir}/src/test/groovy</directory>
                            <includes>
                                <include>**/*.groovy</include>
                            </includes>
                        </testSource>
                    </testSources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Maybe someone could help me to find any solution for that problem ? I think it could be something with spock and maven versions.

Body:
I cannot build your project and see the same error because I only have a POM. But I can look at your POM and see

<groovy.version>2.1.5</groovy.version>
<groovy-all.version>2.4.4</groovy-all.version>

You do not use groovy.version directly, but probably in one of the dependency POMs this property is used because when I look at the effective POM via mvn help:effective-pom, I see this:

<!-- (...) -->

    <groovy-all.version>2.4.4</groovy-all.version>
    <groovy.version>2.1.5</groovy.version>

<!-- (...) -->

      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy</artifactId>
        <version>2.1.5</version>
      </dependency>
      <dependency>2.
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-ant</artifactId>
        <version>2.1.5</version>
      </dependency>
      <!-- and many more modules like these -->

Then I see that Spock-Spring 1.1-groovy-2.4 actually prefers Groovy 2.4.9, so we are dealing with yet another version here, we already have

2.1.5 - definitely too old, why would you use Groovy 2.1 for a Spock version designed for Groovy 2.4?

2.4.4

2.4.9

Then in your effective POM there also is a transitive dependency

      <dependency>
        <groupId>org.awaitility</groupId>
        <artifactId>awaitility-groovy</artifactId>
        <version>4.0.1</version>
      </dependency>

which again references the property you are overriding and a newer Spock and Groovy version:

    <properties>
        <groovy.version>2.5.7</groovy.version>
        <spock.version>1.3-groovy-2.5</spock.version>
    </properties>

<!-- (...) -->

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>${groovy.version}</version>
        </dependency>

And this is where your version conflict comes from. I suggest you define which Groovy and Spock versions you want in your own POM (or parent POM) in a dependencyManagement section, later only importing the actual dependencies without version numbers in the dependencies section. And while you are at it, you could also upgrade to Spock 1.3-groovy-2.5 and a Groovy 2.5 version. Shall we?

Besides, you are not even directly referencing Spock Core, it is only a transitive dependency of Spock Spring. Maybe you want to include the direct dependency too because it is kind of important for your testing, is it not?

I am keeping your Groovy-All import, but you might consider just to import the Groovy modules you really need for testing, minimally just org.codehaus.groovy:groovy.

See if this works for you:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/>
  </parent>

  <groupId>com.tatara</groupId>
  <artifactId>Euress</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>Euress</name>
  <description>Euress application</description>

  <properties>
    <java.version>1.8</java.version>
    <groovy.version>2.5.8</groovy.version>
    <gmavenplus-plugin.version>1.8.1</gmavenplus-plugin.version>
    <spock.version>1.3-groovy-2.5</spock.version>
    <cglib-nodep.version>3.2.7</cglib-nodep.version>
  </properties>

  <!-- Manage your versions here, i.e. fixing them for your project, even if your imported POMs disagree -->
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy</artifactId>
        <version>${groovy.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>${cglib-nodep.version}</version>
      </dependency>
      <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-core</artifactId>
        <version>${spock.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.spockframework</groupId>
        <artifactId>spock-spring</artifactId>
        <version>${spock.version}</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <!-- Import the dependencies you need here, the versions and default scopes have already be managed above -->
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>${groovy.version}</version>
      <type>pom</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
    </dependency>
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.spockframework</groupId>
      <artifactId>spock-spring</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-neo4j</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.codehaus.gmavenplus</groupId>
        <artifactId>gmavenplus-plugin</artifactId>
        <version>${gmavenplus-plugin.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compileTests</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <sources>
            <source>
              <directory>${project.basedir}/src/main/java/groovy</directory>
              <includes>
                <include>**/*.groovy</include>
              </includes>
            </source>
          </sources>
          <testSources>
            <testSource>
              <directory>${project.basedir}/src/test/groovy</directory>
              <includes>
                <include>**/*.groovy</include>
              </includes>
            </testSource>
          </testSources>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


问:
express js enforcing request body types
is it possible to declare the types for the request body? I want to return bad request if the body contains other properties than the declared ones    </p>

```<code>import express from 'express'

const app = express()

app.use(express.json())

interface CustomRequest extends express.Request{
    body:{
        name:string
    }
}

app.post('/t', (req: CustomRequest, res: express.Response) => {
    res.send("hello world")
})

app.listen(5000, () => {
    console.log("app listening on 5000")
})
</code>```

答:
I suggest you to take a look at @hapi/joi package web site. https://hapi.dev/module/joi/

It's easy to use and very powerful!

You can implement a middleware to validate the request (body, params, query) and also response objects! You can do it using the express-joi-validator package.

First you must import the modules:

```<code>const Joi = require('@hapi/joi');
const joiValidator = require('express-joi-validation')
  .createValidator();
</code>```

Then define your schema (expected object structure)

```<code>const loginSchema = Joi.object({
    user: Joi.string().required(),
    password: Joi.string().required(),
});
</code>```

Finally implement your middleware:

```<code>app.post('/login', joiValidator.body(loginSchema), (req, res) => {
    // Your logic here...
    res.send({status: 'ok'}); // Just an example
});
</code>```

If validation fails it will send back to client a 400 (Bad Request) response!

Let me know if you have any question about it!

Hope it helps!

Title: express js enforcing request body types

Body:
is it possible to declare the types for the request body? I want to return bad request if the body contains other properties than the declared ones

import express from 'express'

const app = express()

app.use(express.json())

interface CustomRequest extends express.Request{
    body:{
        name:string
    }
}

app.post('/t', (req: CustomRequest, res: express.Response) => {
    res.send("hello world")
})

app.listen(5000, () => {
    console.log("app listening on 5000")
})

Body:
I suggest you to take a look at @hapi/joi package web site. https://hapi.dev/module/joi/

It's easy to use and very powerful!

You can implement a middleware to validate the request (body, params, query) and also response objects! You can do it using the express-joi-validator package.

First you must import the modules:

const Joi = require('@hapi/joi');
const joiValidator = require('express-joi-validation')
  .createValidator();

Then define your schema (expected object structure)

const loginSchema = Joi.object({
    user: Joi.string().required(),
    password: Joi.string().required(),
});

Finally implement your middleware:

app.post('/login', joiValidator.body(loginSchema), (req, res) => {
    // Your logic here...
    res.send({status: 'ok'}); // Just an example
});

If validation fails it will send back to client a 400 (Bad Request) response!

Let me know if you have any question about it!

Hope it helps!


问:
how to combine two tables in django
There are two tables

Hookahs and tobacco for example

and for the basket model, you need to combine these two models, help

For example:

```<code>class Hookah(model.Model):
    name = models.Charfield()
    description = .....
    price = .......

class Tabacco(model.Model):
    name = models.Charfield()
    description = .....
    price = .......
</code>```

and OrderItem model:

```<code>class OrderItem(model.Model):
</code>```

and here I need to pass the top two models, as a product, how to do it?
i.e. combine Hookah and Tabacoo into one

please help me

答:
I think in this case, you should probably look at building a single product model and have a type attribute separate the product types. That way you can FK to a single product model with your order item model.

Something like this:

models.py

```<code>class Type(models.Model):
    ...
    name = models.CharField(max_length=50)
    ...

class Product(models.Model)
    name = models.CharField(max_length=150)
    description = models.TextField()
    type = models.ForeignKey(Type, on_delete=models.DO_NOTHING)

class Order(models.Model):
    ...
    product = models.ForeignKey(Product, on_delete=models.DO_NOTHING)
    ....
</code>```

Title: how to combine two tables in django

Body:
There are two tables

Hookahs and tobacco for example

and for the basket model, you need to combine these two models, help

For example:

class Hookah(model.Model):
    name = models.Charfield()
    description = .....
    price = .......

class Tabacco(model.Model):
    name = models.Charfield()
    description = .....
    price = .......

and OrderItem model:

class OrderItem(model.Model):

and here I need to pass the top two models, as a product, how to do it?
i.e. combine Hookah and Tabacoo into one

please help me

Body:
I think in this case, you should probably look at building a single product model and have a type attribute separate the product types. That way you can FK to a single product model with your order item model.

Something like this:

models.py

class Type(models.Model):
    ...
    name = models.CharField(max_length=50)
    ...

class Product(models.Model)
    name = models.CharField(max_length=150)
    description = models.TextField()
    type = models.ForeignKey(Type, on_delete=models.DO_NOTHING)

class Order(models.Model):
    ...
    product = models.ForeignKey(Product, on_delete=models.DO_NOTHING)
    ....


问:
Pretty Git branch graphs
I've seen some books and articles have some really pretty looking graphs of Git branches and commits. How can I make high-quality printable images of Git history?</p>

答:
There's a funky Git commit graph as one of the demos of the Raphael web graphics library.

The demo is static, but it should be easy enough to take the code and swap out their static data for a live set of data -- I think it's just Git commit data in JSON format.

The demo is here: http://dmitrybaranovskiy.github.io/raphael/github/impact.html

Title: Pretty Git branch graphs


问:
Python - NaN return (pandas - resample function)
I'm doing a finance study based on the youtube link below and I would like to understand why I got the NaN return instead of the expected calculation. What do I need to do in this script to reach the expected value?

YouTube case: https://www.youtube.com/watch?v=UpbpvP0m5d8

```<code>import investpy as env
import numpy as np
import pandas as pd

lt = ['ABEV3','CEAB3','ENBR3','FLRY3','IRBR3','ITSA4','JHSF3','STBP3']
prices = pd.DataFrame()
for i in lt:
    df = env.get_stock_historical_data(stock=i, from_date='01/01/2020', to_date='29/05/2020',  country='brazil')
    df['Ativo'] = i
    prices = pd.concat([prices, df], sort=True)

pivoted = prices.pivot(columns='Ativo', values='Close')

e_r = pivoted.resample('Y').last().pct_change().mean()
e_r
</code>```

Return:

```<code>Ativo
ABEV3   NaN
CEAB3   NaN
ENBR3   NaN
FLRY3   NaN
IRBR3   NaN
ITSA4   NaN
JHSF3   NaN
STBP3   NaN
dtype: float64
</code>```

答:
You need to change the 'from_date' to have more than one year of data.

You current script returns one row and .pct_change() on one row of data returns NaN, because there is no previous row to compare against.

When I changed from_date to '01/01/2018'

```<code>import investpy as env
import numpy as np
import pandas as pd

lt = ['ABEV3','CEAB3','ENBR3','FLRY3','IRBR3','ITSA4','JHSF3','STBP3']
prices = pd.DataFrame()
for i in lt:
    df = env.get_stock_historical_data(stock=i, from_date='01/01/2018', to_date='29/05/2020',  country='brazil')
    df['Ativo'] = i
    prices = pd.concat([prices, df], sort=True)

pivoted = prices.pivot(columns='Ativo', values='Close')

e_r = pivoted.resample('Y').last().pct_change().mean()
e_r
</code>```

I get the following output:

```<code>Ativo
ABEV3   -0.043025
CEAB3   -0.464669
ENBR3    0.180655
FLRY3    0.191976
IRBR3   -0.175084
ITSA4   -0.035767
JHSF3    1.283291
STBP3    0.223627
dtype: float64
</code>```

Body:
I'm doing a finance study based on the youtube link below and I would like to understand why I got the NaN return instead of the expected calculation. What do I need to do in this script to reach the expected value?

YouTube case: https://www.youtube.com/watch?v=UpbpvP0m5d8

import investpy as env
import numpy as np
import pandas as pd

lt = ['ABEV3','CEAB3','ENBR3','FLRY3','IRBR3','ITSA4','JHSF3','STBP3']
prices = pd.DataFrame()
for i in lt:
    df = env.get_stock_historical_data(stock=i, from_date='01/01/2020', to_date='29/05/2020',  country='brazil')
    df['Ativo'] = i
    prices = pd.concat([prices, df], sort=True)

pivoted = prices.pivot(columns='Ativo', values='Close')

e_r = pivoted.resample('Y').last().pct_change().mean()
e_r

Return:

Ativo
ABEV3   NaN
CEAB3   NaN
ENBR3   NaN
FLRY3   NaN
IRBR3   NaN
ITSA4   NaN
JHSF3   NaN
STBP3   NaN
dtype: float64

Body:
You need to change the 'from_date' to have more than one year of data.

You current script returns one row and .pct_change() on one row of data returns NaN, because there is no previous row to compare against.

When I changed from_date to '01/01/2018'

import investpy as env
import numpy as np
import pandas as pd

lt = ['ABEV3','CEAB3','ENBR3','FLRY3','IRBR3','ITSA4','JHSF3','STBP3']
prices = pd.DataFrame()
for i in lt:
    df = env.get_stock_historical_data(stock=i, from_date='01/01/2018', to_date='29/05/2020',  country='brazil')
    df['Ativo'] = i
    prices = pd.concat([prices, df], sort=True)

pivoted = prices.pivot(columns='Ativo', values='Close')

e_r = pivoted.resample('Y').last().pct_change().mean()
e_r

I get the following output:

Ativo
ABEV3   -0.043025
CEAB3   -0.464669
ENBR3    0.180655
FLRY3    0.191976
IRBR3   -0.175084
ITSA4   -0.035767
JHSF3    1.283291
STBP3    0.223627
dtype: float64


问:
datalist how to tell if selected input in dropdown
```<code> <label>Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onchange="castvote()"  /></label>
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>

function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    console.log("Chrome" in datalist);
    }
</code>```

when i select Chrome or any other options and check to see if it is one of the options i wanted (one of the drop down options) the console is returning false. How do I make it return true (detect that one of the options I selected is indeed the dropdown options)? If possible no Jquery please

答:
since you gave the options in the , you can't get something different to the  options, and taking this in account, in the logic you described all the time the result will be true, if you want to get the selected value you can use the event object from the event listener. Here is an example of that.

As an extra note, is better if you add the listeners with "addEventListener" because you will get more control of the events, and add more than one event per element.

const browsersDataList = document.getElementById("browser-choice");

browsersDataList.addEventListener("change", castvote);

function castvote(event) {
  console.log(event.target.value)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#browser-choice {
  width: 400px;
}</code>```

Choose a browser from this list:
<input list="browsers" id="browser-choice" name="browser-choice" />
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>```

Body:
 Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser"
      style="width: 400px;" onchange="castvote()"  />
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>

function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    console.log("Chrome" in datalist);
    }

when i select Chrome or any other options and check to see if it is one of the options i wanted (one of the drop down options) the console is returning false. How do I make it return true (detect that one of the options I selected is indeed the dropdown options)? If possible no Jquery please

Body:
since you gave the options in the , you can't get something different to the  options, and taking this in account, in the logic you described all the time the result will be true, if you want to get the selected value you can use the event object from the event listener. Here is an example of that.

As an extra note, is better if you add the listeners with "addEventListener" because you will get more control of the events, and add more than one event per element.

const browsersDataList = document.getElementById("browser-choice");

browsersDataList.addEventListener("change", castvote);

function castvote(event) {
  console.log(event.target.value)
}

#browser-choice {
  width: 400px;
}

<label for="browser-choice">Choose a browser from this list:</label>
<input list="browsers" id="browser-choice" name="browser-choice" />
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>