问:
Laravel 6 API RESTful with many to many relationship filtered
I'm developing a Multilanguage API with laravel 6 and I've got this situation in my database:

```<code>Categories
id
other not relevants fields

Languages:
id
name
code

Category_Language
id
language_id
category_id
name --> this is the name of the category in the specific language.
</code>```

Now I've 2 models, the first for Category

```<code>class Category extends Model
{
    public function languages()
    {
        return $this->belongsToMany('App\Models\v1\Language')->withTimestamps()->withPivot('name');
    }
}
</code>```

and the second Model

```<code>class Language extends Model
{
    protected $fillable = ['code', 'name', 'image_id', 'enabled'];

    public function categories() {
        return $this->belongsToMany('App\Models\v1\Category')->withTimestamps()->withPivot('name');
    }
}
</code>```

In my logic (I'm using Service Pattern) I've used this approach on create Category, every time I Pass a JSON object like this:

```<code>{
  "names": [
    {
      "languageId": 1,
      "name": "Hello"
    },
    {
      "languageId": 2,
      "name": "Hola"
    }
  ]
}
</code>```

First of all I create a category (validate if the id of the language is really stored in database) and then with many to many laravel power I attach the language and the name in the category model like this:

```<code> foreach($request->names as $name) {
    $category->languages()->attach($name['languageId'], ['name' => $name['name']]);
 }
</code>```

Now this seems to work perfectly and it's good to retrieve all the category without filtering languages using API Resource like this:

```<code>public function toArray($request)
{
    $category = [];
    $category['id'] = $this->id;
    $category['languages'] = [];

    $category['languages'] = $this->languages->map(function ($language) {
        return [
            'languageId' => $language->id,
            'languageCode' => $language->code,
            'languageName' => $language->name,
            'categoryName' => $language->pivot->name,
        ];
    });

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

and this is the output for 3 categories with 3 languages (faker data):

```<code>array:3 [
  "data" => array:3 [
    0 => array:4 [
      "id" => 1
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "quasi"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "perferendis"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "repudiandae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    1 => array:4 [
      "id" => 2
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "non"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "vitae"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "suscipit"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    2 => array:4 [
      "id" => 3
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "molestiae"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "esse"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "beatae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
  ]
</code>```

now, the problem is when I want to FILTER the categories passing ONLY 1 specific Language, a classical use case when a user use ONLY 1 language during navigations so, If I want ONLY 1 language (and 1 name in pivot relations of category) what kind of operation I need?

I've organized the service with specific filters and ordering for any collections but this kind of need seems to make me crazy!

So this is my final getCategories method that build filter, ordering and include dinamically:

-

imaging so to have a query string like this:

http://localhost:8000/api/v1/categories?orderBy=id:asc&include=language&language.code=EN

and I want a response like this:

```<code>array:3 [
      "data" => array:3 [
        0 => array:4 [
          "id" => 1
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "quasi"
            ]
          ]
        ]
        1 => array:4 [
          "id" => 2
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "non"
            ]
          ]
        ]
        2 => array:4 [
          "id" => 3
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "molestiae"
            ]
          ]
        ]
      ]
</code>```

I need something like this but GENERALLY, because we have others entities that use the same logic for multilanguage system.

To clarify what I want is like a join query like this:

```<code>SELECT *
FROM categories ca INNER JOIN category_language cl ON ca.id =cl.category_id
                 INNER JOIN languages lan ON lan.id = cl.language_id
WHERE lan.code = 'EN';
</code>```

You will retrieve a list of categories only in ENGLISH languages...

Thanks for any suggestion and help!

答:
you can make join in eloquent like:

$language_code=$request->input('language_code');

```<code>    $values=Category::query()->join('category_language','category_language.category_id','=','categories.id')
->join('languages','languages.id','=','category_language.language_id')
->where('languages.code','=',$language_code)
->select('categories.*','languages.code')
    ->orderBy('categories.id')->get();
</code>```

Body:
I'm developing a Multilanguage API with laravel 6 and I've got this situation in my database:

Categories
id
other not relevants fields

Languages:
id
name
code

Category_Language
id
language_id
category_id
name --> this is the name of the category in the specific language.

Now I've 2 models, the first for Category

class Category extends Model
{
    public function languages()
    {
        return $this->belongsToMany('App\Models\v1\Language')->withTimestamps()->withPivot('name');
    }
}

and the second Model

class Language extends Model
{
    protected $fillable = ['code', 'name', 'image_id', 'enabled'];

    public function categories() {
        return $this->belongsToMany('App\Models\v1\Category')->withTimestamps()->withPivot('name');
    }
}

In my logic (I'm using Service Pattern) I've used this approach on create Category, every time I Pass a JSON object like this:

{
  "names": [
    {
      "languageId": 1,
      "name": "Hello"
    },
    {
      "languageId": 2,
      "name": "Hola"
    }
  ]
}

First of all I create a category (validate if the id of the language is really stored in database) and then with many to many laravel power I attach the language and the name in the category model like this:

 foreach($request->names as $name) {
    $category->languages()->attach($name['languageId'], ['name' => $name['name']]);
 }

Now this seems to work perfectly and it's good to retrieve all the category without filtering languages using API Resource like this:

public function toArray($request)
{
    $category = [];
    $category['id'] = $this->id;
    $category['languages'] = [];

    $category['languages'] = $this->languages->map(function ($language) {
        return [
            'languageId' => $language->id,
            'languageCode' => $language->code,
            'languageName' => $language->name,
            'categoryName' => $language->pivot->name,
        ];
    });

    return $category;
}

and this is the output for 3 categories with 3 languages (faker data):

array:3 [
  "data" => array:3 [
    0 => array:4 [
      "id" => 1
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "quasi"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "perferendis"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "repudiandae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    1 => array:4 [
      "id" => 2
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "non"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "vitae"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "suscipit"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    2 => array:4 [
      "id" => 3
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "molestiae"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "esse"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "beatae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
  ]

now, the problem is when I want to FILTER the categories passing ONLY 1 specific Language, a classical use case when a user use ONLY 1 language during navigations so, If I want ONLY 1 language (and 1 name in pivot relations of category) what kind of operation I need?

I've organized the service with specific filters and ordering for any collections but this kind of need seems to make me crazy!

So this is my final getCategories method that build filter, ordering and include dinamically:

-

imaging so to have a query string like this:

http://localhost:8000/api/v1/categories?orderBy=id:asc&include=language&language.code=EN

and I want a response like this:

array:3 [
      "data" => array:3 [
        0 => array:4 [
          "id" => 1
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "quasi"
            ]
          ]
        ]
        1 => array:4 [
          "id" => 2
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "non"
            ]
          ]
        ]
        2 => array:4 [
          "id" => 3
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "molestiae"
            ]
          ]
        ]
      ]

I need something like this but GENERALLY, because we have others entities that use the same logic for multilanguage system.

To clarify what I want is like a join query like this:

SELECT *
FROM categories ca INNER JOIN category_language cl ON ca.id =cl.category_id
                 INNER JOIN languages lan ON lan.id = cl.language_id
WHERE lan.code = 'EN';

You will retrieve a list of categories only in ENGLISH languages...

Thanks for any suggestion and help!

Body:
you can make join in eloquent like:

$language_code=$request->input('language_code');

    $values=Category::query()->join('category_language','category_language.category_id','=','categories.id')
->join('languages','languages.id','=','category_language.language_id')
->where('languages.code','=',$language_code)
->select('categories.*','languages.code')
    ->orderBy('categories.id')->get();


来源: stackexchange

问:
R find intervals in data.table
i want to add a new column with intervals or breakpoints by group. As an an example:

This is my data.table:

```<code>x <- data.table(a = c(1:8,1:8), b = c(rep("A",8),rep("B",8)))
</code>```

I have already the breakpoint or rowindices:

```<code>pos <- data.table(b =  c("A","A","B","B"), bp = c(3,5,2,4))
</code>```

Here i can find the interval for group "A" with:

```<code>findInterval(1:nrow(x[b=="A"]), pos[b=="A"]$bp)
</code>```

How can i do this for each group. In this case "A" and "B"?

答:
An option is to split the datasets by 'b' column, use Map to loop over the corresponding lists, and apply findInterval

```<code>Map(function(u, v) findInterval(seq_len(nrow(u)), v$bp),
      split(x, x$b), split(pos, pos$b))
#$A
#[1] 0 0 1 1 2 2 2 2

#$B
#[1] 0 1 1 2 2 2 2 2
</code>```

or another option is to group by 'b' from 'x', then use findInterval by subsetting the 'bp' from 'pos' by filtering with a logical condition created based on  .BY

```<code>x[, findInterval(seq_len(.N), pos$bp[pos$b==.BY]), b]
#    b V1
# 1: A  0
# 2: A  0
# 3: A  1
# 4: A  1
# 5: A  2
# 6: A  2
# 7: A  2
# 8: A  2
# 9: B  0
#10: B  1
#11: B  1
#12: B  2
#13: B  2
#14: B  2
#15: B  2
#16: B  2
</code>```

ContentLicense: CC BY-SA 4.0

Title: R find intervals in data.table

Body:
i want to add a new column with intervals or breakpoints by group. As an an example:

This is my data.table:

x <- data.table(a = c(1:8,1:8), b = c(rep("A",8),rep("B",8)))

I have already the breakpoint or rowindices:

pos <- data.table(b =  c("A","A","B","B"), bp = c(3,5,2,4))

Here i can find the interval for group "A" with:

findInterval(1:nrow(x[b=="A"]), pos[b=="A"]$bp)

How can i do this for each group. In this case "A" and "B"?

Body:
An option is to split the datasets by 'b' column, use Map to loop over the corresponding lists, and apply findInterval

Map(function(u, v) findInterval(seq_len(nrow(u)), v$bp),
      split(x, x$b), split(pos, pos$b))
#$A
#[1] 0 0 1 1 2 2 2 2

#$B
#[1] 0 1 1 2 2 2 2 2

or another option is to group by 'b' from 'x', then use findInterval by subsetting the 'bp' from 'pos' by filtering with a logical condition created based on  .BY

x[, findInterval(seq_len(.N), pos$bp[pos$b==.BY]), b]
#    b V1
# 1: A  0
# 2: A  0
# 3: A  1
# 4: A  1
# 5: A  2
# 6: A  2
# 7: A  2
# 8: A  2
# 9: B  0
#10: B  1
#11: B  1
#12: B  2
#13: B  2
#14: B  2
#15: B  2
#16: B  2


问:
QAF Reports are not populated in dashboard.htm

Got the latest code here: https://github.com/infostretch/qaf-report.

Extracted dashboard directory & dashboard.htm to the project root directory.

Ran QAF tests.

Opened dashboard.htm during test run & also after test run.

Tried to open dashboard.htm in Google Chrome, Firefox & Safari after giving permissions to access local files. But Dashboard.htm did not load anything. A spinning icon is displayed continously even after several minutes.

Am I missing anything here?

答:
If you are accessing reports locally as file protocol, browser may have restriction to access local files. In such case follow the steps to allow local file access from file for the browser you are using.

Firefox:

```<code>go to about:config
set security.fileuri.strict_origin_policy:false.
</code>```

Safari:

```<code>Click on the Develop menu in the menu bar.
Select Disable Local File Restrictions.
</code>```

If develop menu is not available, Click on the Edit > Preferences > Advanced tab. Check "Show Develop menu in the menu bar.
chrome:

```<code>Close down your Chrome browser (make sure you close all instances if you have multiple windows open)
Go to Run and type the following command: chrome.exe --allow-file-access-from-file.
Hit enter.
</code>```

Reference from local-report-access

Body:
If you are accessing reports locally as file protocol, browser may have restriction to access local files. In such case follow the steps to allow local file access from file for the browser you are using.

Firefox:

go to about:config
set security.fileuri.strict_origin_policy:false.

Safari:

Click on the Develop menu in the menu bar.
Select Disable Local File Restrictions.

If develop menu is not available, Click on the Edit > Preferences > Advanced tab. Check "Show Develop menu in the menu bar.
chrome:

Close down your Chrome browser (make sure you close all instances if you have multiple windows open)
Go to Run and type the following command: chrome.exe --allow-file-access-from-file.
Hit enter.

Reference from local-report-access


问:
Listview.setOnItemclicklistener with Searchview
I've a problem with my ListView onClick. I try to explain u by a particule of my code.

So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?

```<code>
private SearchView sv;

Protected void onCreate........

String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);

sv=findViewById(R.id.searchview);

ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
   if(position == 0){
     Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
  }

  if(position == 1){
     Intent b = new Intent  (getApplicationContext(),AtivityB.class);
startActivity(b)
  }

 if(position == 2){
     Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
  }
}```
```

答:
```<code>    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.//item:
                startActivity(new Intent(this, ActivityA.class));
                return true;
            case R.id.//item:
                startActivity(new Intent(this, ActivityB.class));
                return true;
            case R.id.//item:
                startActivity(new Intent(this, ActivityC.class));
                return true;
             default:
                return super.onOptionsItemSelected(item);
        }
    }
</code>```

Body:
I've a problem with my ListView onClick. I try to explain u by a particule of my code.

So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?

private SearchView sv;

Protected void onCreate........

String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);

sv=findViewById(R.id.searchview);

ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
   if(position == 0){
     Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
  }

  if(position == 1){
     Intent b = new Intent  (getApplicationContext(),AtivityB.class);
startActivity(b)
  }

 if(position == 2){
     Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
  }
}```


问:
What's the canonical way to check for type in Python?
How do I check if an object is of a given type, or if it inherits from a given type?

How do I check if the object o is of type str?

Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.

答:
A simple way to check type is to compare it with something whose type you know.</p>

```<code>>>> a  = 1
>>> type(a) == type(1)
True
>>> b = 'abc'
>>> type(b) == type('')
True
</code>```

OwnerDisplayName: Herge

Body:
A simple way to check type is to compare it with something whose type you know.

>>> a  = 1
>>> type(a) == type(1)
True
>>> b = 'abc'
>>> type(b) == type('')
True


问:
Difference between Google's Query and Place Autocomplete?
Whats the difference between these two services: Google Place Autocomplete https://developers.google.com/places/web-service/autocomplete and Google Query autocomplete https://developers.google.com/places/web-service/query
Except theirs descriptions, which are not clear enough.</p>

答:
The difference between these web services is the following:

The Place autocomplete service will return as suggestions only places from Google database. These place predictions have a place ID, so you can resolve them to position on the map.

The Query autocomplete service will return as suggestions both places from Google database and geographic query predictions. The geographic query predictions are not places entities, they don't have place ID, they are search texts like "pizza near Sydney, New South Wales, Australia" that you probably need to pass further to search engine of your app.


问:
Replace a character in different elements with the same class in JavaScript?
I have several paragraphs in my page. They all have the same class name. I want to replace a character that is in all of them. I tried something like this:

```<code>  var str = $(".foo").html;
  var res = str.split("　").join("");
  $(".foo").html = res;
</code>```

But I get the error: TypeError: str.split is not a function

I noticed that if I target a single paragraph, with its unique Id, everything works fine. I just cannot do it with several paragraphs at the same time, using their class names.

答:
$(".foo") returns a list, therefore, you should iterate over each paragraph and change its content. You can use the each function as follows:

$( ".foo" ).each(function( index, element ) {
     $(element).html( $(element).html().split(" ").join("") );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="foo">hello world</p>
<p class="foo">hello world</p>
<p class="foo">hello world</p></code>```

Body:
I have several paragraphs in my page. They all have the same class name. I want to replace a character that is in all of them. I tried something like this:

  var str = $(".foo").html;
  var res = str.split("　").join("");
  $(".foo").html = res;

But I get the error: TypeError: str.split is not a function

I noticed that if I target a single paragraph, with its unique Id, everything works fine. I just cannot do it with several paragraphs at the same time, using their class names.

Body:
$(".foo") returns a list, therefore, you should iterate over each paragraph and change its content. You can use the each function as follows:

$( ".foo" ).each(function( index, element ) {
     $(element).html( $(element).html().split(" ").join("") );
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="foo">hello world</p>
<p class="foo">hello world</p>
<p class="foo">hello world</p>


问:
new H.data.geojson.Reader giving me an error of undefined. HERE maps
I am new to here maps. I want to render my data using routing API results on the map.
I am using the code from the documentation but I am getting an error H.data is not defined.

Code I am using.

```<code> var reader = new H.data.geojson.Reader('/ajax/pull_map_here.php');
    reader.parse();//Assumption:mapalreadyexists

    map.addLayer(reader.getLayer());
</code>```

I am using these scripts. Do I need to add any other script to resolve this error.

```<code><script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/geojson/0.5.0/geojson.min.js"></script>
</code>```

Initializing the platform object

```<code>var platform = new H.service.Platform({
        'apikey': 'APIKEY_HERE',
        'useHTTPS': true

    });
</code>```

Anyone who can help me out. Much appreciated.

Thanks

答:
```<code><script src="https://js.api.here.com/v3/3.1/mapsjs-data.js" type="text/javascript" charset="utf-8"></script>
</code>```

Provides H.data

Body:
I am new to here maps. I want to render my data using routing API results on the map.
I am using the code from the documentation but I am getting an error H.data is not defined.

Code I am using.

 var reader = new H.data.geojson.Reader('/ajax/pull_map_here.php');
    reader.parse();//Assumption:mapalreadyexists

    map.addLayer(reader.getLayer());

I am using these scripts. Do I need to add any other script to resolve this error.

Initializing the platform object

var platform = new H.service.Platform({
        'apikey': 'APIKEY_HERE',
        'useHTTPS': true

    });

Anyone who can help me out. Much appreciated.

Thanks

Body:
<script src="https://js.api.here.com/v3/3.1/mapsjs-data.js" type="text/javascript" charset="utf-8"></script>

Provides H.data


问:
Applet unable to connect to mysql server
I am developing a java applet which connects to mysql database, the applet works fine on local host but when I uploaded it and tried to run, i get an error as "communications link failure the last packet sent successfully to the server was 0 milliseconds ago.
the driver has not recieved any packets from the server"
i tried it on x10hosting and hostable, please help me if anyone knows the solution...</p>

答:
Are you sure your MySQL server port is really open to the public? E.g., on a publicly-routable IP address and not blocked by your routers/network? Most likely your MySQL instance is not accessible from the outside world...

...which is how it should be. It's very, very, very rarely appropriate to have an applet talk directly to your database server. The usual thing is for the applet to talk to a middle tier on your web server, which in turn talks to the database server. There's a security aspect to that (your middle-tier can defend against various attacks on your database), and there's a practicality aspect: You'll probably want to keep the chatter across the public network to a minimum, and your server can roll up the results of multiple operations into one bundle it then sends to the client.

If your MySQL server really is available to the outside world, is its host the same as the host the applet is loaded from? That's one of the security requirements for (unsigned) applets, that they can only open network connections to the same host they were loaded from. But if that were the issue, I would have expected you to get a security exception (unless Connector/J is hiding it from you).

ContentLicense: CC BY-SA 3.0


问:
MYSQL have update query delete if it updates to a duplicate
I have 3 different tables that look like this

```<code>| appearance |    | goal         |    | card         |
|------------|    |--------------|    |--------------|
| id         |    | appearanceID |    | appearanceID |
| playerName |
</code>```

Now the problem is, I was adding data to this table via a script from two difference sources, and so it duplicated some players names with slightly different spelling. I know I can simply run

```<code>UPDATE appearance
SET playerName = 'xx'
WHERE playername = 'YY';
</code>```

However, that fails because sometimes there was already an entry of player X, and I don't allow duplicate appearances.

Basically I want to be able to write an easy query that says:

"Go change any instance of playerName Y to be X, if it says it already exists then delete the old ones, and also do the same thing for all the appearanceID's that reference player Y."

Is that even possible?

答:
To delete the duplicate rows in appearance, you could do this:

```<code>DELETE a1 FROM appearance a1
INNER JOIN appearance a2
WHERE
    a1.playerName = a2.playerName
    and a1.id > a2.id;
</code>```

This assumes that the older record is the one with a lower id and deletes the newer record(s).

You may also wish to introduce some logic to check for duplicates on insert to prevent them from occurring in the first place.

Body:
I have 3 different tables that look like this

| appearance |    | goal         |    | card         |
|------------|    |--------------|    |--------------|
| id         |    | appearanceID |    | appearanceID |
| playerName |

Now the problem is, I was adding data to this table via a script from two difference sources, and so it duplicated some players names with slightly different spelling. I know I can simply run

UPDATE appearance
SET playerName = 'xx'
WHERE playername = 'YY';

However, that fails because sometimes there was already an entry of player X, and I don't allow duplicate appearances.

Basically I want to be able to write an easy query that says:

"Go change any instance of playerName Y to be X, if it says it already exists then delete the old ones, and also do the same thing for all the appearanceID's that reference player Y."

Is that even possible?

Body:
To delete the duplicate rows in appearance, you could do this:

DELETE a1 FROM appearance a1
INNER JOIN appearance a2
WHERE
    a1.playerName = a2.playerName
    and a1.id > a2.id;

This assumes that the older record is the one with a lower id and deletes the newer record(s).

You may also wish to introduce some logic to check for duplicates on insert to prevent them from occurring in the first place.


问:
Python Tkinter background
```<code>canvas = tk.Canvas(window, width=800, height=600, bg="black") # PEP8: space after comma
canvas.pack()
</code>```

Do anyone know how I could import a image from google to set as a background in canvas?

答:
First, download the image as a .png. If you have the latest version of tkinter, then the following will work.

Write this code:

canvas = tk.Canvas(window, width=800, height=600, bg="black") # PEP8: space after
canvas.pack()
p = tk.PhotoImage(file = "putyourimagenamehere.png")
canvas.create_image(100, 100, image = p)
```

For the above code to work, you need to put the image in the same directory as the .py file.

Hope this helps!

Title: Python Tkinter background

Body:
canvas = tk.Canvas(window, width=800, height=600, bg="black") # PEP8: space after comma
canvas.pack()

Do anyone know how I could import a image from google to set as a background in canvas?

Body:
First, download the image as a .png. If you have the latest version of tkinter, then the following will work.

Write this code:

canvas = tk.Canvas(window, width=800, height=600, bg="black") # PEP8: space after
canvas.pack()
p = tk.PhotoImage(file = "putyourimagenamehere.png")
canvas.create_image(100, 100, image = p)

For the above code to work, you need to put the image in the same directory as the .py file.

Hope this helps!


问:
How to get access to global state from mutation namespace module?
In my state I have two namespace modules: portfolio and stocks like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio
  }
})
```

<p>In <code>stocks</code> I have <code>stocks</code> property and in <code>portfolio</code> I have <code>funds</code> property. I want to commit <code>BUY_STOCK</code> mutation, which needs access to <code>stocks</code> from <code>stocks</code> module and <code>funds</code> from <code>profile</code>. I set it in <code>profile</code> module as follows:</p>

<pre class="lang-js prettyprint-override"><code>"BUY_STOCK"(state, {stockId, quantity, stockPrice}) {
  console.log(state.stocks.stocks, state.portfolio.funds)
}
</code>```

I got undefined. That's because state is just a local module state. How can I get access to global state from this mutation?

答:
It seems like you didn't import the profile module to the store/index.js,
so it would look like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio,
    profile
  }
})

```

<p>And you should probably consider using getters in each module:</p>

<p>portifolio.js</p>

<pre class="lang-js prettyprint-override"><code>export default {
  state: {
    funds: 'Some funds'
  },
  getters: {
    funds(state) {
      return state.funds
    }
  }
}
</code>```

stocks.js

export default {
  state: {
    stocks: 'Some stocks'
  },
  getters: {
    stocks(state) {
      return state.stocks
    }
  }
}
```

<p>Now you can access them from the <code>profile</code> module like so:</p>

<p>profile.js</p>

<pre class="lang-js prettyprint-override"><code>export default {
  actions: {
    BUY_STOCK({ getters }, { stockId, quantity, stockPrice }) {
      console.log(getters.funds, getters.stocks)
    }
  }
}
</code>```

Body:
In my state I have two namespace modules: portfolio and stocks like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio
  }
})

In stocks I have stocks property and in portfolio I have funds property. I want to commit BUY_STOCK mutation, which needs access to stocks from stocks module and funds from profile. I set it in profile module as follows:

"BUY_STOCK"(state, {stockId, quantity, stockPrice}) {
  console.log(state.stocks.stocks, state.portfolio.funds)
}

I got undefined. That's because state is just a local module state. How can I get access to global state from this mutation?

Body:
It seems like you didn't import the profile module to the store/index.js,
so it would look like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio,
    profile
  }
})

And you should probably consider using getters in each module:

portifolio.js

export default {
  state: {
    funds: 'Some funds'
  },
  getters: {
    funds(state) {
      return state.funds
    }
  }
}

stocks.js

export default {
  state: {
    stocks: 'Some stocks'
  },
  getters: {
    stocks(state) {
      return state.stocks
    }
  }
}

Now you can access them from the profile module like so:

profile.js

export default {
  actions: {
    BUY_STOCK({ getters }, { stockId, quantity, stockPrice }) {
      console.log(getters.funds, getters.stocks)
    }
  }
}


问:
Suggestions for deploying AngularJS and NodeJS app
I'm building a basic web app using Angular, NodeJS, Express, and SQLite. The main concern here is pricing for a production environment. I want the cheapest way to deploy/maintain these. I chose SQLite so I don't have to worry about getting a production DB, though originally I wanted to use MongoDB. My question is, should I have my Angular and NodeJS app in the same project, and deploy my Angular app using express? Or should I have my Angular and NodeJS app separate? I originally had it together but was getting all kinds of errors. I did use a MEAN scaffolder which worked fine. But when I replaced MongoDB with TypeORM, I encountered the errors, so maybe my package.json/tsconfig.json was wrong? Regardless, what's the cheapest way to deploy my frontend and backend? I was thinking heroku/firebase, but want to hear some other suggestions</p>

答:
If you are looking for a cheaper and easiest method to host try it with a digital ocean. Don't want to deploy front end in one server backend in another server

Docker is the easiest way to deploy it on the server

Dockerize your project and deploy it with docker or docker-compose


问:
Vue.js cannot understand the problem here
```<code><template>
  <div class="container">
    <ul class="list-group">

      <li class="list-group-item" v-for="p in list" :key="p.id">{{ p.id }}</li>
    </ul>
  </div>
</template>
</code>```

the list is always shown as empty. the console print is

{ob: Observer} data: Array(2) 0: {ob: Observer} 1: {ob:
  Observer} length: 2
  ob: Observer {value: Array(2), dep: Dep, vmCount: 0}
  proto: Array
  ob: Observer {value: {…}, dep: Dep, vmCount: 0} get data: ƒ reactiveGetter() set data: ƒ reactiveSetter(newVal)
  proto: Object

```<code><script>
export default {
  data: function() {
    return {
      list: []
    };
  },
  mounted() {
    this.lp();
  },

  methods: {
    lp: function() {
      console.log("Fetching portfolios...");
      axios
        .get("api/portfolios")

        .then(response => {
          this.list = response.data.data;
          console.log(this.list); //console prints the data
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};
</script>
</code>```

答:
The problem in your code is the part of the arrow function:

```<code>.then(response => {
   this.list = response.data.data;
})
</code>```

in this case the this doesn't refer to the vue object. Instead you should use the function bind() like so:

```<code>.then(function(response) {
   this.list = response.data.data;
}.bind(this))
</code>```

Now the this reference in the function is a reference to the vue object.

Body:
<template>

{{ p.id }}

</template>

the list is always shown as empty. the console print is

{ob: Observer} data: Array(2) 0: {ob: Observer} 1: {ob:
  Observer} length: 2
  ob: Observer {value: Array(2), dep: Dep, vmCount: 0}
  proto: Array
  ob: Observer {value: {…}, dep: Dep, vmCount: 0} get data: ƒ reactiveGetter() set data: ƒ reactiveSetter(newVal)
  proto: Object

Body:
The problem in your code is the part of the arrow function:

.then(response => {
   this.list = response.data.data;
})

in this case the this doesn't refer to the vue object. Instead you should use the function bind() like so:

.then(function(response) {
   this.list = response.data.data;
}.bind(this))

Now the this reference in the function is a reference to the vue object.


问:
How to create a unique string/key form JavaScript object?
I would like to create a unique string/ key/ identifier/ hash from object's values. For example:

```<code>let myObj =
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3',
  key4: 'val4'
};

function getObjectUniqueKey(obj) {
  return (`${ obj.key1 }|${ obj.key2 }|${ obj.key3 }|${ obj.key4 }`);
}
</code>```

The method getObjectUniqueKey() will work fine, however it isn't scale to bigger objects (my objects have more than 10 keys).

Is there any way in JavaScript to create a unique string that will represent an object? something similar to JSON.stringify() but isn't so robust?

(JSON.stringify will also stringify the keys, but all my objects have the same interface - same key's names - so stringifing them isn't needed).

{ key: 'val1' } and { key: 'val2' } should produce different results.

{ key1: 'val' } and { key2: 'val' } should produce different results.

{ a: 1, b: 2 } and { b: 2, a: 1 } should produce the same result.

答:
Here 2 examples without JSON.stringify:

Version1:

var myObj =
{
    key1: 'val2',
    key2: 'val1',
    key4: 'val4',
    key3: 'val3',
};

/**
 * get unique string (Version 1).
 * This is fine if every object has always the same keys.
 */
function getObjectUniqueKey(obj) {
var res = '';
const keys = Object.keys(obj);
keys.sort()
    .forEach((key, i) => {
        res += obj[key]
        if (keys.length != i + 1) {
            res += '|'
        }
    });
return res;
}

console.log(`Version1: ${getObjectUniqueKey(myObj)}`);```
</div>
</div>
</p>

<p><strong>Version2:</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObj =
{
    key1: 'val1',
    key2: 'val2',
    key4: 'val4',
    key3: 'val3',
};

/**
 * This Version can be used when the number of keys are changing.
 * This is based on your example that
 * { key1: 'val' } and { key2: 'val' } should produce different results.
 *
 * Here you have to use a identificator for the key names because otherwise
 * the example objects would create the same result (v1 doesn't care about this).
 */
function getObjectUniqueKeyV2(obj) {
    var res = '';
    const keys = Object.keys(obj);
    keys
        .sort()
        .forEach((key, i) => {
            res += key + ':' + obj[key]
            if (keys.length != i + 1) {
                res += '|'
            }
        });
    return res;
}

console.log(`Version2: ${getObjectUniqueKeyV2(myObj)}`);</code>```

Body:
I would like to create a unique string/ key/ identifier/ hash from object's values. For example:

let myObj =
{
  key1: 'val1',
  key2: 'val2',
  key3: 'val3',
  key4: 'val4'
};

function getObjectUniqueKey(obj) {
  return (`${ obj.key1 }|${ obj.key2 }|${ obj.key3 }|${ obj.key4 }`);
}

The method getObjectUniqueKey() will work fine, however it isn't scale to bigger objects (my objects have more than 10 keys).

Is there any way in JavaScript to create a unique string that will represent an object? something similar to JSON.stringify() but isn't so robust?

(JSON.stringify will also stringify the keys, but all my objects have the same interface - same key's names - so stringifing them isn't needed).

{ key: 'val1' } and { key: 'val2' } should produce different results.

{ key1: 'val' } and { key2: 'val' } should produce different results.

{ a: 1, b: 2 } and { b: 2, a: 1 } should produce the same result.

Body:
Here 2 examples without JSON.stringify:

Version1:

var myObj =
{
    key1: 'val2',
    key2: 'val1',
    key4: 'val4',
    key3: 'val3',
};

/**
 * get unique string (Version 1).
 * This is fine if every object has always the same keys.
 */
function getObjectUniqueKey(obj) {
var res = '';
const keys = Object.keys(obj);
keys.sort()
    .forEach((key, i) => {
        res += obj[key]
        if (keys.length != i + 1) {
            res += '|'
        }
    });
return res;
}

console.log(`Version1: ${getObjectUniqueKey(myObj)}`);

Version2:

var myObj =
{
    key1: 'val1',
    key2: 'val2',
    key4: 'val4',
    key3: 'val3',
};

/**
 * This Version can be used when the number of keys are changing.
 * This is based on your example that
 * { key1: 'val' } and { key2: 'val' } should produce different results.
 *
 * Here you have to use a identificator for the key names because otherwise
 * the example objects would create the same result (v1 doesn't care about this).
 */
function getObjectUniqueKeyV2(obj) {
    var res = '';
    const keys = Object.keys(obj);
    keys
        .sort()
        .forEach((key, i) => {
            res += key + ':' + obj[key]
            if (keys.length != i + 1) {
                res += '|'
            }
        });
    return res;
}

console.log(`Version2: ${getObjectUniqueKeyV2(myObj)}`);


问:
close the total application will closed when we click on home in any activity
close the total application will closed when we click on home in any activity and again start the application from starting onwards (Starting Activity).In my application activities contain back button also.For this Give me some suggestions.

Thanks in advance

答:
Have an activity that extends application, in here you need two flag's.

Declaring Global Variables

```<code>  public class MyApplication extends Application {
         public static boolean flagForHome= false;
         public static boolean flagForChangingActivity= false;

  }
</code>```

Then in onPause and onResume of each activity

Activity Lifecycle

```<code>    public void onResume(){
            if(flagForHome && !flagForChangingActivity){
                finish();
            } else {
                MyApplication.flagForHome= false;
                MyApplication.flagForChangingActivity= false;
            }
    }

    public void onPause(){
            MyApplication.flagForHome= true;
    }
</code>```

Finally when changing activity normally using startActivity(); you will need to set the flagForChangingActivity to true;

Using Intents

```<code>   MyApplication.flagForChangingActivity= true;
   Intent intent = new Intent(this, ActivityTwo.class);
   startActivity(intent);
</code>```

this will stop your app closing when changing activity (as the activity going into the background will hit onPause and the new activity starting up will hit onResume)

Don't forget in your home activity to set the flag back to false. This will stop your app instantly closing itself when you start it the second time!

HomeActivity.class:

```<code>  public void onPause(){
            Application.flagForHome= false;
    }
</code>```

EDIT

Start Activity for Result is just the same procedure:

```<code> MyApplication.flagForChangingActivity= true;
 Intent intent = new Intent(this, ActivityTwo.class);
 startActivityForResult(intent, 0);
</code>```

Body:
Have an activity that extends application, in here you need two flag's.

Declaring Global Variables

  public class MyApplication extends Application {
         public static boolean flagForHome= false;
         public static boolean flagForChangingActivity= false;

  }

Then in onPause and onResume of each activity

Activity Lifecycle

    public void onResume(){
            if(flagForHome && !flagForChangingActivity){
                finish();
            } else {
                MyApplication.flagForHome= false;
                MyApplication.flagForChangingActivity= false;
            }
    }

    public void onPause(){
            MyApplication.flagForHome= true;
    }

Finally when changing activity normally using startActivity(); you will need to set the flagForChangingActivity to true;

Using Intents

   MyApplication.flagForChangingActivity= true;
   Intent intent = new Intent(this, ActivityTwo.class);
   startActivity(intent);

this will stop your app closing when changing activity (as the activity going into the background will hit onPause and the new activity starting up will hit onResume)

Don't forget in your home activity to set the flag back to false. This will stop your app instantly closing itself when you start it the second time!

HomeActivity.class:

  public void onPause(){
            Application.flagForHome= false;
    }

EDIT

Start Activity for Result is just the same procedure:

 MyApplication.flagForChangingActivity= true;
 Intent intent = new Intent(this, ActivityTwo.class);
 startActivityForResult(intent, 0);


问:
Issue retrieving ByteBuddy-generated Spring Bean
I am making my own ORM and I'm at a point where I want to to eliminate the need to create repository classes.  They currently look like this :

```<code>@Repository
public class CustomerDao extends AbstractDao<Customer, Long>
{

}
</code>```

Without going too deep into the inner workings of my ORM, the AbstractDao class uses a bean which is a map containing the entity class as a key and the dao class as a value.  Without bringing ByteBuddy in the mix, the declaration of that bean looks like this :

```<code>@Bean
public Map<Class<?>, AbstractDao<?, ?>> daoMap()
{
    context.getBeansWithAnnotation(Repository.class).forEach((s, c) ->
    {
        if (c instanceof AbstractDao<?, ?>) map.put(ClassUtils.getSuperClassTypeArgument(c.getClass(), 0), (AbstractDao<?, ?>) c);
    });

    return map;
}
</code>```

Again this works great but it's very annoying to have to create these empty classes.  I am trying to use the Reflections and ByteBuddy libraries to generate these classes at runtime and dynamically inject them into the Spring context as repository beans.  Here is my modified method :

```<code>@Bean
public Map<Class<?>, AbstractDao<?, ?>> daoMap() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
    InvocationTargetException, ConstructorMissingException, AnnotationMissingException, NoSuchMethodException, SecurityException
{
    var map = new HashMap<Class<?>, AbstractDao<?, ?>>();

    var byteBuddy = new ByteBuddy();

    for (var entityClass : new Reflections("com.somepackage.entity").getSubTypesOf(Entity.class))
    {
        var daoClass = byteBuddy
            .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, entityClass,
                ReflectionUtils.getIdField(entityClass).getType()).build())
            .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
            .make();

        var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

        ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());
    }

    context.getBeansWithAnnotation(Repository.class).forEach((s, c) ->
    {
        if (c instanceof AbstractDao<?, ?>) map.put(ClassUtils.getSuperClassTypeArgument(c.getClass(), 0), (AbstractDao<?, ?>) c);
    });

    return map;
}
</code>```

The loop that creates the classes and injects them as beans seems to work fine.  It doesn't throw exceptions and affects the right classes.  I am however getting an exception at the getBeansWithAnnotation line :

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mdenis.carbon.carbon_orm.dao.AbstractDao$ByteBuddy$jzMtXq5b': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:278) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansWithAnnotation(DefaultListableBeanFactory.java:672) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeansWithAnnotation(AbstractApplicationContext.java:1264) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.mdenis.carbon.carbon_orm.config.ORMConfig.daoMap(ORMConfig.java:55) ~[classes/:na]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34.CGLIB$daoMap$1(<generated>) ~[classes/:na]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34$$FastClassBySpringCGLIB$$a25eec90.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34.daoMap(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
... 85 common frames omitted
</code>```

This seems to be related to Spring failing to autowire the constructor even though it technically doesn't have to.  Any idea how to resolve this?

答:
Your problem is not related to byte-buddy. The error also occurs if you try to register a preexisting class.

You need to register the new beans in an earlier phase of the context startup. One way of doing that is to use a BeanFactoryPostProcessor. Split your map creation into two sections. The one with the class generation into the BeanFactoryPostProcessor. The one with the Map generation you can keep in the @Bean factory method

e.g.:

```<code>@Configuration
public class RepositoryConfigurationBean implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        try {
            // Replace X1.class with the one from bytebuddy
            // The name should be unique
            configurableListableBeanFactory.registerSingleton("abc", X1.class.getConstructor().newInstance());
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
   }
</code>```

Body:
I am making my own ORM and I'm at a point where I want to to eliminate the need to create repository classes.  They currently look like this :

@Repository
public class CustomerDao extends AbstractDao<Customer, Long>
{

}

Without going too deep into the inner workings of my ORM, the AbstractDao class uses a bean which is a map containing the entity class as a key and the dao class as a value.  Without bringing ByteBuddy in the mix, the declaration of that bean looks like this :

@Bean
public Map<Class<?>, AbstractDao<?, ?>> daoMap()
{
    context.getBeansWithAnnotation(Repository.class).forEach((s, c) ->
    {
        if (c instanceof AbstractDao<?, ?>) map.put(ClassUtils.getSuperClassTypeArgument(c.getClass(), 0), (AbstractDao<?, ?>) c);
    });

    return map;
}

Again this works great but it's very annoying to have to create these empty classes.  I am trying to use the Reflections and ByteBuddy libraries to generate these classes at runtime and dynamically inject them into the Spring context as repository beans.  Here is my modified method :

@Bean
public Map<Class<?>, AbstractDao<?, ?>> daoMap() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
    InvocationTargetException, ConstructorMissingException, AnnotationMissingException, NoSuchMethodException, SecurityException
{
    var map = new HashMap<Class<?>, AbstractDao<?, ?>>();

    var byteBuddy = new ByteBuddy();

    for (var entityClass : new Reflections("com.somepackage.entity").getSubTypesOf(Entity.class))
    {
        var daoClass = byteBuddy
            .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, entityClass,
                ReflectionUtils.getIdField(entityClass).getType()).build())
            .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
            .make();

        var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

        ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());
    }

    context.getBeansWithAnnotation(Repository.class).forEach((s, c) ->
    {
        if (c instanceof AbstractDao<?, ?>) map.put(ClassUtils.getSuperClassTypeArgument(c.getClass(), 0), (AbstractDao<?, ?>) c);
    });

    return map;
}

The loop that creates the classes and injects them as beans seems to work fine.  It doesn't throw exceptions and affects the right classes.  I am however getting an exception at the getBeansWithAnnotation line :

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mdenis.carbon.carbon_orm.dao.AbstractDao$ByteBuddy$jzMtXq5b': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:278) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansWithAnnotation(DefaultListableBeanFactory.java:672) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeansWithAnnotation(AbstractApplicationContext.java:1264) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.mdenis.carbon.carbon_orm.config.ORMConfig.daoMap(ORMConfig.java:55) ~[classes/:na]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34.CGLIB$daoMap$1(<generated>) ~[classes/:na]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34$$FastClassBySpringCGLIB$$a25eec90.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34.daoMap(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
... 85 common frames omitted

This seems to be related to Spring failing to autowire the constructor even though it technically doesn't have to.  Any idea how to resolve this?

Body:
Your problem is not related to byte-buddy. The error also occurs if you try to register a preexisting class.

You need to register the new beans in an earlier phase of the context startup. One way of doing that is to use a BeanFactoryPostProcessor. Split your map creation into two sections. The one with the class generation into the BeanFactoryPostProcessor. The one with the Map generation you can keep in the @Bean factory method

e.g.:

@Configuration
public class RepositoryConfigurationBean implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        try {
            // Replace X1.class with the one from bytebuddy
            // The name should be unique
            configurableListableBeanFactory.registerSingleton("abc", X1.class.getConstructor().newInstance());
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
   }


问:
How do I get the value of href attribute when scraping web in dart?
I am trying to get all the links on the web page with the help of Dart. I've tried web scraper package but I were not able to get the value of the attribute href. Anyone knows the way to do it?</p>

答:
I don't know about the web scraper package and can see it only works for Flutter which I have no experience with. So instead I tried to make something using the packages html and http which seems to work fine and should also work with Flutter:</p>
```<code>import 'package:html/parser.dart' show parse;
import 'package:http/http.dart' as http;

Future<void> main() async {
  final page = await http.get('https://example.com');
  final document = parse(page.body);
  final hrefs = document
      .getElementsByTagName('a')
      .where((e) => e.attributes.containsKey('href'))
      .map((e) => e.attributes['href'])
      .toList();
  print(hrefs); // [https://www.iana.org/domains/example]
}
</code>```

Body:
I don't know about the web scraper package and can see it only works for Flutter which I have no experience with. So instead I tried to make something using the packages html and http which seems to work fine and should also work with Flutter:

import 'package:html/parser.dart' show parse;
import 'package:http/http.dart' as http;

Future<void> main() async {
  final page = await http.get('https://example.com');
  final document = parse(page.body);
  final hrefs = document
      .getElementsByTagName('a')
      .where((e) => e.attributes.containsKey('href'))
      .map((e) => e.attributes['href'])
      .toList();
  print(hrefs); // [https://www.iana.org/domains/example]
}


问:
Doubly linked list - Update list->tail after a merge sort
In an implementation of a doubly linked list I am using the typical structure:

```<code>struct node
{
    void *data;
    struct node *prev;
    struct node *next;
};
</code>```

I will also insert at the end of the list in O(1) time, so I have another struct storing the head and the tail:

```<code>struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
};
</code>```

The program works as expected for all insert and delete operations, but I have a problem with the sort function, I am using the merge-sort algorithm, as I understand it is the most effective or one of the most effective to sort lists, the algorithm works well:

```<code>static struct node *split(struct node *head)
{
    struct node *fast = head;
    struct node *slow = head;

    while ((fast->next != NULL) && (fast->next->next != NULL))
    {
        fast = fast->next->next;
        slow = slow->next;
    }

    struct node *temp = slow->next;

    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, comp);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, comp);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

static struct node *merge_sort(struct node *head, int (*comp)(const void *, const void *))
{
    if ((head == NULL) || (head->next == NULL))
    {
        return head;
    }

    struct node *second = split(head);

    head = merge_sort(head, comp);
    second = merge_sort(second, comp);
    return merge(head, second, comp);
}
</code>```

but I have no idea how to keep the address of list->tail updated:

```<code>void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, comp);
    // list->tail is no longer valid at this point
}
</code>```

Sure I can walk the whole list after ordering and update list->tail by brute force, but I'd like to know if there's a fancier way to do it.

I managed to solve the problem using a circular list, but I would like to avoid changing the structure of the program.

答:
I'm not the best person to provide deep analysis concerning algorithms Big-O notation. Anyways, answering to a question with an already accepted "canonic" answer is great, because there's the possibility to explore alternative solutions without too much pressure.

This it interesting even if, as you will see, the analysed solution is not better than the current solution presented in the question.

The strategy starts by wondering if it is possible keeping track of the candidate tail element without turning the code upside down. The main candidate is the function deciding the order of the nodes in the sorted list: the merge() function.

Now, since after the comparison we decide which node will come first in the sorted list, we will have a "loser" that will be nearer to the tail. So, with a further comparison with the current tail element for each step, in the end we will be able to update the tail element with the "loser of the losers".

The merge function will have the additional struct node **tail parameter (the double pointer is required because we will change the list tail field in place:

```<code>static struct node *merge(struct node *first, struct node *second, struct node **tail, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, tail, comp);

        /* The 'second' node is the "loser". Let's compare current 'tail'
           with it, and in case it loses again, let's update  'tail'.      */
        if( comp(second->data, (*tail)->data) > 0)
            *tail = second;
        /******************************************************************/

        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, tail, comp);

        /* The 'first' node is the "loser". Let's compare current 'tail'
           with it, and in case it loses again, let's update  'tail'.      */
        if( comp(first->data, (*tail)->data) > 0)
            *tail = first;
        /******************************************************************/

        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}
</code>```

There are no more changes required to the code, except those for the "propagation" of the tail double pointer parameter through merge_sort() and linklist_sort() functions:

```<code>static struct node *merge_sort(struct node *head, struct node **tail, int (*comp)(const void *, const void *));

void linklist_sort(List_t *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, &(list->tail), comp);
}
</code>```

The test

In order to test this modification I had to write a basic insert() function, a compare() function designed to obtain a sorted list in descending order, and a printList() utility. Then I wrote a main program to test all the stuff.

I did several tests; here I present just an example, in which I omit the functions presented in the question and above in this answer:

```<code>#include <stdio.h>

typedef struct node
{
    void *data;
    struct node *prev;
    struct node *next;
} Node_t;

typedef struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
} List_t;

void insert(List_t *list, int data)
{
    Node_t * newnode = (Node_t *) malloc(sizeof(Node_t) );
    int * newdata = (int *) malloc(sizeof(int));
    *newdata = data;

    newnode->data = newdata;
    newnode->prev = list->tail;
    newnode->next = NULL;
    if(list->tail)
        list->tail->next = newnode;

    list->tail = newnode;

    if( list->size++ == 0 )
        list->head = newnode;
}

int compare(const void *left, const void *right)
{
    if(!left && !right)
        return 0;

    if(!left && right)
        return 1;
    if(left && !right)
        return -1;

    int lInt = (int)*((int *)left), rInt = (int)*((int *)right);

    return (rInt-lInt);
}

void printList( List_t *l)
{
    for(Node_t *n = l->head; n != NULL; n = n->next )
    {
        printf( " %d ->", *((int*)n->data));
    }
    printf( " NULL (tail=%d)\n", *((int*)l->tail->data));
}

int main(void)
{
  List_t l = { 0 };

  insert( &l, 5 );
  insert( &l, 3 );
  insert( &l, 15 );
  insert( &l, 11 );
  insert( &l, 2 );
  insert( &l, 66 );
  insert( &l, 77 );
  insert( &l, 4 );
  insert( &l, 13 );
  insert( &l, 9 );
  insert( &l, 23 );

  printList( &l );

  linklist_sort( &l, compare );

  printList( &l );

  /* Free-list utilities omitted */

  return 0;
}
</code>```

In this specific test I got the following output:

```<code> 5 -> 3 -> 15 -> 11 -> 2 -> 66 -> 77 -> 4 -> 13 -> 9 -> 23 -> NULL (tail=23)
 77 -> 66 -> 23 -> 15 -> 13 -> 11 -> 9 -> 5 -> 4 -> 3 -> 2 -> NULL (tail=2)
</code>```

Conclusions

The good news is that theoretically speaking we still have an algorithm that, in the worst case, will have O(N log(N)) time complexity.

The bad news is that, to avoid a linear search in  a linked list (N "simple steps"), we have to do N*logN comparisons, involving a call to a function. This makes the linear search still a better option.

Body:
In an implementation of a doubly linked list I am using the typical structure:

struct node
{
    void *data;
    struct node *prev;
    struct node *next;
};

I will also insert at the end of the list in O(1) time, so I have another struct storing the head and the tail:

struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
};

The program works as expected for all insert and delete operations, but I have a problem with the sort function, I am using the merge-sort algorithm, as I understand it is the most effective or one of the most effective to sort lists, the algorithm works well:

static struct node *split(struct node *head)
{
    struct node *fast = head;
    struct node *slow = head;

    while ((fast->next != NULL) && (fast->next->next != NULL))
    {
        fast = fast->next->next;
        slow = slow->next;
    }

    struct node *temp = slow->next;

    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, comp);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, comp);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

static struct node *merge_sort(struct node *head, int (*comp)(const void *, const void *))
{
    if ((head == NULL) || (head->next == NULL))
    {
        return head;
    }

    struct node *second = split(head);

    head = merge_sort(head, comp);
    second = merge_sort(second, comp);
    return merge(head, second, comp);
}

but I have no idea how to keep the address of list->tail updated:

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, comp);
    // list->tail is no longer valid at this point
}

Sure I can walk the whole list after ordering and update list->tail by brute force, but I'd like to know if there's a fancier way to do it.

I managed to solve the problem using a circular list, but I would like to avoid changing the structure of the program.

Body:
I'm not the best person to provide deep analysis concerning algorithms Big-O notation. Anyways, answering to a question with an already accepted "canonic" answer is great, because there's the possibility to explore alternative solutions without too much pressure.

This it interesting even if, as you will see, the analysed solution is not better than the current solution presented in the question.

The strategy starts by wondering if it is possible keeping track of the candidate tail element without turning the code upside down. The main candidate is the function deciding the order of the nodes in the sorted list: the merge() function.

Now, since after the comparison we decide which node will come first in the sorted list, we will have a "loser" that will be nearer to the tail. So, with a further comparison with the current tail element for each step, in the end we will be able to update the tail element with the "loser of the losers".

The merge function will have the additional struct node **tail parameter (the double pointer is required because we will change the list tail field in place:

static struct node *merge(struct node *first, struct node *second, struct node **tail, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, tail, comp);

        /* The 'second' node is the "loser". Let's compare current 'tail'
           with it, and in case it loses again, let's update  'tail'.      */
        if( comp(second->data, (*tail)->data) > 0)
            *tail = second;
        /******************************************************************/

        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, tail, comp);

        /* The 'first' node is the "loser". Let's compare current 'tail'
           with it, and in case it loses again, let's update  'tail'.      */
        if( comp(first->data, (*tail)->data) > 0)
            *tail = first;
        /******************************************************************/

        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

There are no more changes required to the code, except those for the "propagation" of the tail double pointer parameter through merge_sort() and linklist_sort() functions:

static struct node *merge_sort(struct node *head, struct node **tail, int (*comp)(const void *, const void *));

void linklist_sort(List_t *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, &(list->tail), comp);
}

The test

In order to test this modification I had to write a basic insert() function, a compare() function designed to obtain a sorted list in descending order, and a printList() utility. Then I wrote a main program to test all the stuff.

I did several tests; here I present just an example, in which I omit the functions presented in the question and above in this answer:

#include <stdio.h>

typedef struct node
{
    void *data;
    struct node *prev;
    struct node *next;
} Node_t;

typedef struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
} List_t;

void insert(List_t *list, int data)
{
    Node_t * newnode = (Node_t *) malloc(sizeof(Node_t) );
    int * newdata = (int *) malloc(sizeof(int));
    *newdata = data;

    newnode->data = newdata;
    newnode->prev = list->tail;
    newnode->next = NULL;
    if(list->tail)
        list->tail->next = newnode;

    list->tail = newnode;

    if( list->size++ == 0 )
        list->head = newnode;
}

int compare(const void *left, const void *right)
{
    if(!left && !right)
        return 0;

    if(!left && right)
        return 1;
    if(left && !right)
        return -1;

    int lInt = (int)*((int *)left), rInt = (int)*((int *)right);

    return (rInt-lInt);
}

void printList( List_t *l)
{
    for(Node_t *n = l->head; n != NULL; n = n->next )
    {
        printf( " %d ->", *((int*)n->data));
    }
    printf( " NULL (tail=%d)\n", *((int*)l->tail->data));
}

int main(void)
{
  List_t l = { 0 };

  insert( &l, 5 );
  insert( &l, 3 );
  insert( &l, 15 );
  insert( &l, 11 );
  insert( &l, 2 );
  insert( &l, 66 );
  insert( &l, 77 );
  insert( &l, 4 );
  insert( &l, 13 );
  insert( &l, 9 );
  insert( &l, 23 );

  printList( &l );

  linklist_sort( &l, compare );

  printList( &l );

  /* Free-list utilities omitted */

  return 0;
}

In this specific test I got the following output:

 5 -> 3 -> 15 -> 11 -> 2 -> 66 -> 77 -> 4 -> 13 -> 9 -> 23 -> NULL (tail=23)
 77 -> 66 -> 23 -> 15 -> 13 -> 11 -> 9 -> 5 -> 4 -> 3 -> 2 -> NULL (tail=2)

Conclusions

The good news is that theoretically speaking we still have an algorithm that, in the worst case, will have O(N log(N)) time complexity.

The bad news is that, to avoid a linear search in  a linked list (N "simple steps"), we have to do N*logN comparisons, involving a call to a function. This makes the linear search still a better option.


问:
Number of months between two dates for each year in r
I'm working with data that looks like this:

```<code>name       start_date        end_date
 A         1993-06-25       1993-11-04
 B         2003-12-12       2004-07-20
 C         1997-06-11       2000-11-27
 D         1990-06-29       1992-07-02
</code>```

I want to count up the number of months in each year that the names span.

So that the data looks like this:

```<code>name  year number_months
A     1993    5
B     2003    1
B     2004    7
C     1997    6
C     1998   12
C     1999   12
C     2000   11
D     1990    6
D     1991   12
D     1992    7
</code>```

Here is a reproducible example:

```<code>name <- c("A", "B", "C", "D")
start_date <- as.Date(c("1993-06-25", "2003-12-12", "1997-06-11", "1990-06-29"))
end_date <- as.Date(c("1993-11-04", "2004-07-20", "2000-11-27", "1992-07-02"))

df <- data.frame(name, start_date, end_date)

</code>```

答:
An option in tidyverse

```<code>library(dplyr)
library(tidyr)
library(purrr)
library(tibble)
library(lubridate)
df %>%
   transmute(name,  out = map2(start_date, end_date,
     ~ seq(.x, .y, by = 'months') %>%
           year %>%
           table %>%
           enframe(name = 'year', value = 'number_months'))) %>%
   unnest(c(out))
</code>```

Or another option with interval

```<code>df %>%
     transmute(name,  out = map2(start_date, end_date,
          ~ tibble(date = seq(.x, .y, by = 'months'), year = year(date)) %>%
               group_by(year) %>%
               summarise(number_months = interval(floor_date(first(date), 'month'),
                   ceiling_date(last(date), 'month')) %/% months(1)) )) %>%
     unnest(c(out))
</code>```

Or in base R (extending @rawr's solution)

```<code>do.call(rbind, Map(function(x, y, z)
 cbind(name = z, stack(table(format(seq(x, y, by = 'months'),
  '%Y')))), df$start_date, df$end_date, df$name))
</code>```

Or as @rawr commented, replacing the stack with data.frame can be used as well

```<code>do.call(rbind, Map(function(x, y, z)
     cbind(name = z, data.frame(table(format(seq(x, y, by = 'months'),
       '%Y')))), df$start_date, df$end_date, df$name))
</code>```

Body:
I'm working with data that looks like this:

name       start_date        end_date
 A         1993-06-25       1993-11-04
 B         2003-12-12       2004-07-20
 C         1997-06-11       2000-11-27
 D         1990-06-29       1992-07-02

I want to count up the number of months in each year that the names span.

So that the data looks like this:

name  year number_months
A     1993    5
B     2003    1
B     2004    7
C     1997    6
C     1998   12
C     1999   12
C     2000   11
D     1990    6
D     1991   12
D     1992    7

Here is a reproducible example:

name <- c("A", "B", "C", "D")
start_date <- as.Date(c("1993-06-25", "2003-12-12", "1997-06-11", "1990-06-29"))
end_date <- as.Date(c("1993-11-04", "2004-07-20", "2000-11-27", "1992-07-02"))

df <- data.frame(name, start_date, end_date)

Body:
An option in tidyverse

library(dplyr)
library(tidyr)
library(purrr)
library(tibble)
library(lubridate)
df %>%
   transmute(name,  out = map2(start_date, end_date,
     ~ seq(.x, .y, by = 'months') %>%
           year %>%
           table %>%
           enframe(name = 'year', value = 'number_months'))) %>%
   unnest(c(out))

Or another option with interval

df %>%
     transmute(name,  out = map2(start_date, end_date,
          ~ tibble(date = seq(.x, .y, by = 'months'), year = year(date)) %>%
               group_by(year) %>%
               summarise(number_months = interval(floor_date(first(date), 'month'),
                   ceiling_date(last(date), 'month')) %/% months(1)) )) %>%
     unnest(c(out))

Or in base R (extending @rawr's solution)

do.call(rbind, Map(function(x, y, z)
 cbind(name = z, stack(table(format(seq(x, y, by = 'months'),
  '%Y')))), df$start_date, df$end_date, df$name))

Or as @rawr commented, replacing the stack with data.frame can be used as well

do.call(rbind, Map(function(x, y, z)
     cbind(name = z, data.frame(table(format(seq(x, y, by = 'months'),
       '%Y')))), df$start_date, df$end_date, df$name))


问:
How do I expire a PHP session after 30 minutes?
I need to keep a session alive for 30 minutes and then destroy it. </p>

答:
How PHP handles sessions is quite confusing for beginners to understand. This might help them by giving an overview of how sessions work:
how sessions work(custom-session-handlers) </p>

OwnerDisplayName: Tom


问:
How do I make two dependent POST calls in Angular?
I have one HTTP POST call to create a moratorium. The second post call will try to use a moratoriumID (returned from the first call) to insert a series of moratorium locations. I've been searching around and the answer seems to be in service use switchMap() within .pipe() . Is this correct?
If so, why am I getting the following error:

```<code>Argument of type '(dataFromSvc1: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput<any>'.
  Type 'void' is not assignable to type 'ObservableInput<any>'.ts(2345)
</code>```

See code and image below.

```<code>PostMoratorium(moratoriumtopost: Moratorium,moratoriumLocationstopostarray: MoratoriumLocation[]): Observable<number> {
const PostMoratoriumUrl = `${this.moratoriumUrl}`;

return this.apiService.postWithLocalErrorHandling(PostMoratoriumUrl, moratoriumtopost)
  .pipe(
     //I get the error here with dataFromSvc1 underlined !
    switchMap(dataFromSvc1 => {
      const PostMoratoriumLocationsUrl = `${this.moratoriumUrl}/moratorium/${dataFromSvc1}/location`;
      moratoriumLocationstopostarray.forEach(giveMoratoriumId);

      function giveMoratoriumId(item) {
        const moratoriumlocationtopost = {
          county:item.county ,
          city:item.city,
          zip:item.zipCode,
          moratoriumId:dataFromSvc1,
        } as MoratoriumLocation;
        return this.apiService.postWithLocalErrorHandling(PostMoratoriumLocationsUrl,moratoriumlocationtopost);
      }
    }
    )//switchMap
  );//pipe
</code>```

}

答:
You should use concatMap for requests that need to be made in order and depend on the previous value. You can read more about it here

```<code>PostMoratorium(moratoriumtopost: Moratorium,moratoriumLocationstopostarray: MoratoriumLocation[]): Observable<number> {

   const PostMoratoriumUrl = `${this.moratoriumUrl}`;
   return this.apiService.postWithLocalErrorHandling(PostMoratoriumUrl, moratoriumtopost)
      .pipe(concatMap(dataFromSvc1 => {
          const PostMoratoriumLocationsUrl = `${this.moratoriumUrl}/moratorium/${dataFromSvc1}/location`;
          moratoriumLocationstopostarray.forEach(giveMoratoriumId);
          const moratoriumlocationtopost = {
             county: item.county,
             city: item.city,
             zip: item.zipCode,
             moratoriumId: dataFromSvc1
          } as MoratoriumLocation;

          return this.apiService.postWithLocalErrorHandling(PostMoratoriumLocationsUrl,moratoriumlocationtopost);
      }
    }
    )
  );
</code>```

Let me explain what's happening here:

this.apiService.postpostWithLocalErrorHandling(PostMoratoriumUrl, moratoriumtopost) gets called and will return a value.

This value is made available in the callback function of .concatMap as dataFromSvc1.

We now use this data to do some further processing

And we return this.apiService.postWithLocalErrorHandling(PostMoratoriumLocationsUrl,moratoriumlocationtopost); since the callback of concatMap (just like switchMap) expects an observable. This Http call is now made.

Always use concatMap for chains of observables that depend on previous input and require an order of execution.

Hope this helps

Body:
I have one HTTP POST call to create a moratorium. The second post call will try to use a moratoriumID (returned from the first call) to insert a series of moratorium locations. I've been searching around and the answer seems to be in service use switchMap() within .pipe() . Is this correct?
If so, why am I getting the following error:

Argument of type '(dataFromSvc1: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput<any>'.
  Type 'void' is not assignable to type 'ObservableInput<any>'.ts(2345)

See code and image below.

PostMoratorium(moratoriumtopost: Moratorium,moratoriumLocationstopostarray: MoratoriumLocation[]): Observable<number> {
const PostMoratoriumUrl = `${this.moratoriumUrl}`;

return this.apiService.postWithLocalErrorHandling(PostMoratoriumUrl, moratoriumtopost)
  .pipe(
     //I get the error here with dataFromSvc1 underlined !
    switchMap(dataFromSvc1 => {
      const PostMoratoriumLocationsUrl = `${this.moratoriumUrl}/moratorium/${dataFromSvc1}/location`;
      moratoriumLocationstopostarray.forEach(giveMoratoriumId);

      function giveMoratoriumId(item) {
        const moratoriumlocationtopost = {
          county:item.county ,
          city:item.city,
          zip:item.zipCode,
          moratoriumId:dataFromSvc1,
        } as MoratoriumLocation;
        return this.apiService.postWithLocalErrorHandling(PostMoratoriumLocationsUrl,moratoriumlocationtopost);
      }
    }
    )//switchMap
  );//pipe

}

Body:
You should use concatMap for requests that need to be made in order and depend on the previous value. You can read more about it here

PostMoratorium(moratoriumtopost: Moratorium,moratoriumLocationstopostarray: MoratoriumLocation[]): Observable<number> {

   const PostMoratoriumUrl = `${this.moratoriumUrl}`;
   return this.apiService.postWithLocalErrorHandling(PostMoratoriumUrl, moratoriumtopost)
      .pipe(concatMap(dataFromSvc1 => {
          const PostMoratoriumLocationsUrl = `${this.moratoriumUrl}/moratorium/${dataFromSvc1}/location`;
          moratoriumLocationstopostarray.forEach(giveMoratoriumId);
          const moratoriumlocationtopost = {
             county: item.county,
             city: item.city,
             zip: item.zipCode,
             moratoriumId: dataFromSvc1
          } as MoratoriumLocation;

          return this.apiService.postWithLocalErrorHandling(PostMoratoriumLocationsUrl,moratoriumlocationtopost);
      }
    }
    )
  );

Let me explain what's happening here:

this.apiService.postpostWithLocalErrorHandling(PostMoratoriumUrl, moratoriumtopost) gets called and will return a value.

This value is made available in the callback function of .concatMap as dataFromSvc1.

We now use this data to do some further processing

And we return this.apiService.postWithLocalErrorHandling(PostMoratoriumLocationsUrl,moratoriumlocationtopost); since the callback of concatMap (just like switchMap) expects an observable. This Http call is now made.

Always use concatMap for chains of observables that depend on previous input and require an order of execution.

Hope this helps


问:
CORS : No 'Access-Control-Allow-Origin' header is present on the requested resource
I am working on a D3 - grunt-cli application in which I am facing a CORS issue when sending post requests to a Fuseki Server.

```<code>function saveToFusekiFunc() {
    document.getElementById('fileid').click();
    document.getElementById('fileid').value = null;

    d3.select("#fileid").on("change", function() {
      var contents;
      var file = d3.select("#fileid").property("files")[0];
      console.log(file);
      var reader = new FileReader();
      reader.onload = function(e) {
      contents = e.target.result;
      console.log(contents);

    let xhr = new XMLHttpRequest();
    let url = "http://localhost:3030/Test/";

    xhr.open(
      "POST",
       url ,
      true
    );

    //xhr.setRequestHeader('Data-Type', 'jsonp');
    xhr.setRequestHeader('Content-Type', 'text/turtle;charset=utf-8');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
    xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:8000/');
    xhr.setRequestHeader('Access-Control-Max-Age', '86400');

    xhr.onreadystatechange = function()
    {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
    }
    xhr.send(contents);
    };
    reader.readAsText(file);

    })

  }
</code>```

Above is my code with which I try to make the request. This only works if I enable the CORS plugin in my browser extension.

I have also tried to include the access by making changes to the gruntfile.js middlewares. But it did not help. From which I am almost sure that this is some issue at the server end.

My dependenices are as shown below:

```<code>"dependencies": {
    "d3": "^3.5.6",
    "grunt-cli": "^1.3.2",
    "lodash": "^4.1.0"
  }
</code>```

Have tried most of the solutions found online but nothing has worked other than directly blocking the CORS check in the browser. I am trying to make a request from 'http://localhost:8000/' to the Fuseki Server 'http://localhost:3030/'.

The error I am getting is:

```<code>Access to XMLHttpRequest at 'http://localhost:3030/Test/' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

Request headers:

Also checked the web.xml file of the Fuseki configuration which seems to have the CORS settings:

```<code><!-- CORS -->
  <filter>
    <filter-name>cross-origin</filter-name>
    <!-- Ported and standalone version of org.eclipse.jetty.servlets.CrossOriginFilter -->
    <filter-class>org.apache.jena.fuseki.servlets.CrossOriginFilter</filter-class>
    <!-- Defaults may be fine -->
    <init-param>
      <param-name>allowedOrigins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>allowedMethods</param-name>
      <param-value>GET,POST,DELETE,PUT,HEAD,OPTIONS,PATCH</param-value>
    </init-param>
    <init-param>
      <param-name>allowedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization</param-value>
    </init-param>
    <init-param>
      <param-name>exposedHeaders</param-name>
      <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
  </filter>
</code>```

答:
A CORS request used the Origin header and the response will be the headers such as Access-Control-Allow-Origin.

The code sets response headers in the request with headers and does not have an "Origin".

Body:
I am working on a D3 - grunt-cli application in which I am facing a CORS issue when sending post requests to a Fuseki Server.

function saveToFusekiFunc() {
    document.getElementById('fileid').click();
    document.getElementById('fileid').value = null;

    d3.select("#fileid").on("change", function() {
      var contents;
      var file = d3.select("#fileid").property("files")[0];
      console.log(file);
      var reader = new FileReader();
      reader.onload = function(e) {
      contents = e.target.result;
      console.log(contents);

    let xhr = new XMLHttpRequest();
    let url = "http://localhost:3030/Test/";

    xhr.open(
      "POST",
       url ,
      true
    );

    //xhr.setRequestHeader('Data-Type', 'jsonp');
    xhr.setRequestHeader('Content-Type', 'text/turtle;charset=utf-8');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
    xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:8000/');
    xhr.setRequestHeader('Access-Control-Max-Age', '86400');

    xhr.onreadystatechange = function()
    {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
    }
    xhr.send(contents);
    };
    reader.readAsText(file);

    })

  }

Above is my code with which I try to make the request. This only works if I enable the CORS plugin in my browser extension.

I have also tried to include the access by making changes to the gruntfile.js middlewares. But it did not help. From which I am almost sure that this is some issue at the server end.

My dependenices are as shown below:

"dependencies": {
    "d3": "^3.5.6",
    "grunt-cli": "^1.3.2",
    "lodash": "^4.1.0"
  }

Have tried most of the solutions found online but nothing has worked other than directly blocking the CORS check in the browser. I am trying to make a request from 'http://localhost:8000/' to the Fuseki Server 'http://localhost:3030/'.

The error I am getting is:

Access to XMLHttpRequest at 'http://localhost:3030/Test/' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Request headers:

Also checked the web.xml file of the Fuseki configuration which seems to have the CORS settings:

  <filter>
    <filter-name>cross-origin</filter-name>

    <filter-class>org.apache.jena.fuseki.servlets.CrossOriginFilter</filter-class>

    <init-param>
      <param-name>allowedOrigins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>allowedMethods</param-name>
      <param-value>GET,POST,DELETE,PUT,HEAD,OPTIONS,PATCH</param-value>
    </init-param>
    <init-param>
      <param-name>allowedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization</param-value>
    </init-param>
    <init-param>
      <param-name>exposedHeaders</param-name>
      <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
  </filter>


问:
Converting to Serializable object
this may be a stupid question but I wanted to convert a 2 dimensional string array into a serializable object in java. What is the best way to do this?</p>

答:
```<code>        ObjectOutputStream stream = null;
    try {
        stream = new ObjectOutputStream(out);
        String strings[][] = {
                {"a", "b", "c"},
                {"1", "2", "3"},
        };
        stream.writeObject(strings);
    } catch (IOException e) {
        e.printStackTrace();  //$REVIEW$ To change body of catch statement use File | Settings | File Templates.
    }
</code>```

Here goes the answer. Arrays are by default serializable. Just write it to ObjectOutputStream like another serializable object

Title: Converting to Serializable object

Body:
        ObjectOutputStream stream = null;
    try {
        stream = new ObjectOutputStream(out);
        String strings[][] = {
                {"a", "b", "c"},
                {"1", "2", "3"},
        };
        stream.writeObject(strings);
    } catch (IOException e) {
        e.printStackTrace();  //$REVIEW$ To change body of catch statement use File | Settings | File Templates.
    }

Here goes the answer. Arrays are by default serializable. Just write it to ObjectOutputStream like another serializable object