问:
On ubuntu how to install python3.5 next to an existent python3.6 (or newer) install?
Well I currently have as main version python 3.6. I still wish to use this version as main python3 version. However next to it I wish to be able to use python 3.5 (for development of scripts used on synology, which has as newest version python 3.5).

I tried installing python 3.5 from apt:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libpython3.5-stdlib' for regex 'python3.5'
Note, selecting 'libpython3.5-minimal' for regex 'python3.5'
0 upgraded, 0 newly installed, 0 to remove and 13 not upgraded.
</code>```

However after this python3.5 --version still returns

```<code>Command 'python3.5' not found, did you mean:
  command 'python3.6' from deb python3.6-minimal
  command 'python3.7' from deb python3.7-minimal
</code>```

I also cannot find any trace in /usr/bin of said installation (or previous version). If I search my computer for python3.5 I do find a lot of folders, though mostly under /snap/core/ I also know that I did have python3.5 installed at one point, and upgraded it later.

答:
It's much easier to switch between different python environments and packages using conda or virtualenv. I personally use miniconda to create minimal environments.

After installation just create a new environment with your desired python version:

```<code>$ conda create --name EnvName python=3.5
</code>```

And switch to that environment with $ conda activate EnvName

Body:
Well I currently have as main version python 3.6. I still wish to use this version as main python3 version. However next to it I wish to be able to use python 3.5 (for development of scripts used on synology, which has as newest version python 3.5).

I tried installing python 3.5 from apt:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libpython3.5-stdlib' for regex 'python3.5'
Note, selecting 'libpython3.5-minimal' for regex 'python3.5'
0 upgraded, 0 newly installed, 0 to remove and 13 not upgraded.

However after this python3.5 --version still returns

Command 'python3.5' not found, did you mean:
  command 'python3.6' from deb python3.6-minimal
  command 'python3.7' from deb python3.7-minimal

I also cannot find any trace in /usr/bin of said installation (or previous version). If I search my computer for python3.5 I do find a lot of folders, though mostly under /snap/core/ I also know that I did have python3.5 installed at one point, and upgraded it later.

Body:
It's much easier to switch between different python environments and packages using conda or virtualenv. I personally use miniconda to create minimal environments.

After installation just create a new environment with your desired python version:

$ conda create --name EnvName python=3.5

And switch to that environment with $ conda activate EnvName


来源: stackexchange

问:
Using adb to check the screen lock type on Marshmallow
I've seens topics for checking if screen is locked using adb but not the type of specific way which can be "none", "swipe", "pattern" etc. Is there a way to check it?

答:
I did some digging, and it turns out that you are not the first person to try this. The short answeris that there is no answer.

Read this...

Unfortunately, the answer that it gives is not what you want to hear, but if you can give us some additional context, we may be able to help you find a workaround.

ContentLicense: CC BY-SA 4.0


问:
Yii 2 gii is generating view files on different directory
I am new to yii framework. On yii version:2.0.1 I have created a module in which I tried to generate a CRUD model using the gii functionality.
 After putting the model class, controller class and view path when I clicked on generate gii showed all the files has been created successfully.
 But when I tried to view, below message has been shown to me,

The view file does not exist :

```<code>C:\xampp\htdocs\advanced\backend\modules\settings\views\companies\index.php
</code>```

I found the view files in web directory not in the path I entered. Hence the error.

Here is my inputs to gii,

Model Class:

```<code>backend\modules\settings\models\Companies
</code>```

Search Model Class:

```<code>backend\modules\settings\models\CompaniesSearch
</code>```

Controller Class:

```<code>backend\modules\settings\controllers\CompaniesController
</code>```

View Path:

```<code>backend\modules\settings\views\companies
</code>```

When I click generate I have given below message :

Generating code using template "C:\xampp\htdocs\advanced\vendor\yiisoft\yii2-gii\generators\crud/default"...

generated modules\settings\controllers\CompaniesController.php

generated modules\settings\models\CompaniesSearch.php

generated backend\modules\settings\views\companies\_form.php

generated backend\modules\settings\views\companies\_search.php

generated backend\modules\settings\views\companies\create.php

generated backend\modules\settings\views\companies\index.php

generated backend\modules\settings\views\companies\update.php

generated backend\modules\settings\views\companies\view.php

done!

Does anybody have any idea why is it happening.

Thanks in advance.

答:
Previously I put a model into the incorrect directory when wanting to achieve an absolute path (address it absolutely as it seems to be more often functional) -

app/backend/modules/settings .

Notice the 'app' in the beginning (the /app is the main directory in Yii starter kit) which I thought would avoid the relative path but must NOT be there nor @mail sign, but on the contrary, it did the opposite - it appended it relatively with its absolute length to the /document root directory, basically duplicated it,

"app/myproject.com/app/backend/modules/settings"

So it unwinds from the model location,  the causes of Gii complaints about incorrect paths or put also controllers the incorrect way.

Also strangely enough for views in contrast to models, it had to be put the upper mentioned different way with the @  relative reference sign annotation (which was not allowed to be used for controllers or models at the time of writing)

@backend/modules/settings/views/companies, otherwise it appended the directory tree into the document root, again concatenated - the web directory of backend backend/web (backend/modules/settings/views/companies)

ContentLicense: CC BY-SA 3.0

Body:
I am new to yii framework. On yii version:2.0.1 I have created a module in which I tried to generate a CRUD model using the gii functionality.
 After putting the model class, controller class and view path when I clicked on generate gii showed all the files has been created successfully.
 But when I tried to view, below message has been shown to me,

The view file does not exist :

C:\xampp\htdocs\advanced\backend\modules\settings\views\companies\index.php

I found the view files in web directory not in the path I entered. Hence the error.

Here is my inputs to gii,

Model Class:

backend\modules\settings\models\Companies

Search Model Class:

backend\modules\settings\models\CompaniesSearch

Controller Class:

backend\modules\settings\controllers\CompaniesController

View Path:

backend\modules\settings\views\companies

When I click generate I have given below message :

Generating code using template "C:\xampp\htdocs\advanced\vendor\yiisoft\yii2-gii\generators\crud/default"...

generated modules\settings\controllers\CompaniesController.php

generated modules\settings\models\CompaniesSearch.php

generated backend\modules\settings\views\companies\_form.php

generated backend\modules\settings\views\companies\_search.php

generated backend\modules\settings\views\companies\create.php

generated backend\modules\settings\views\companies\index.php

generated backend\modules\settings\views\companies\update.php

generated backend\modules\settings\views\companies\view.php

done!

Does anybody have any idea why is it happening.

Thanks in advance.


问:
Unspecified Margin Problem?
On this page, the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this:

```<code>.post h2 {
margin:0;
text-align: left;
font-size: 18px;
overflow:hidden;
font-weight:normal;
}
</code>```

I'm trying to decrease the top and bottom margins around the title.

Here's a screenshot of the problem:

答:
As i can see there no problem in your class=titleand your h2 have this:

```<code>h2 {
    color: #000000;
    font-family: HarabaraHandItalic;
    font-size: 30px;
    padding: 0 0 0 15px;
}
</code>```

and

```<code>.title {
      background: url("images/title.jpg") no-repeat scroll 0 0 transparent;
        margin: 0 0 0 0;
        padding: 0;
}
</code>```

the url is not working and you can add margin in your h2 instead.

Title: Unspecified Margin Problem?

Body:
On this page, the title says it has a margin top & bottom of 25px (when I use inspect element in Chrome 10) - but the CSS looks like this:

.post h2 {
margin:0;
text-align: left;
font-size: 18px;
overflow:hidden;
font-weight:normal;
}

I'm trying to decrease the top and bottom margins around the title.

Here's a screenshot of the problem:

Body:
As i can see there no problem in your class=titleand your h2 have this:

h2 {
    color: #000000;
    font-family: HarabaraHandItalic;
    font-size: 30px;
    padding: 0 0 0 15px;
}

and

.title {
      background: url("images/title.jpg") no-repeat scroll 0 0 transparent;
        margin: 0 0 0 0;
        padding: 0;
}

the url is not working and you can add margin in your h2 instead.


问:
Grabbing a list of dates from a column and formatting them to MM/dd/yyyy
I'm trying to write a program that will only apply to the rows whose dates match the current day. I know how to format the current date in MM/dd/yyyy but I'm having trouble looping through my list and formatting the dates to the list that I will use for comparing. Any advice helps, thank you!</p>

```<code>function date() {
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "M/dd/yyyy")
  console.log(curDate)

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); // get the sheet
  var columnF = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1); // get all the rows

  var fValues = columnF.getValues(); // get the values
  console.log('fvalues are; ', fValues)
  var format = []
  var datecolumn = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1)

  for (var i = 2; i < 4; i++) {
    var datecolumn = sheet.getRange(i, 5).getValue();
    format.push(datecolumn)
  };
  console.log('date array is: ', format)

  var format2 = []
  for (var i = 0; i < fValues.length; i++) {

    var fmtcell = Utilities.formatDate(fValues, "GMT-5", "MM/dd/yyyy")

    format2.push(fmtcell)
  }
}
</code>```

答:
If I understand you correctly, you want to compare a group of dates, located in column E from Sheet1, with current date, as well as format these dates to a certain format.

If that's the case, you can do the following (check inline comments):

function dateCompare() {
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yyyy");
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  // Retrieve list of dates in column E (formatted as current date):
  var firstRow = 2;
  var column = 5;
  var numRows = sheet.getLastRow() - firstRow + 1;
  var dates = sheet.getRange(firstRow, column, numRows).getValues().map(function(date) {
    return Utilities.formatDate(new Date(date[0]), "GMT+1", "MM/dd/yyyy");
  });
  dates.forEach(function(date, i) { // Iterate through each date in column E
    if (date === curDate) { // Compare each date in column E to current date
      // Do something to the row:
      var row = sheet.getRange(firstRow + i, 1, 1, sheet.getLastColumn());
    }
  });
}
```

Please consider that getValues() returns a 2D dimensional array. You can transform this 2D into a one-dimensional array and format the dates in the array at the same time with map.

Reference:

Utilities.formatDate(date, timeZone, format)

Range.getValues()

Array.prototype.map()

Body:
I'm trying to write a program that will only apply to the rows whose dates match the current day. I know how to format the current date in MM/dd/yyyy but I'm having trouble looping through my list and formatting the dates to the list that I will use for comparing. Any advice helps, thank you!

function date() {
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "M/dd/yyyy")
  console.log(curDate)

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); // get the sheet
  var columnF = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1); // get all the rows

  var fValues = columnF.getValues(); // get the values
  console.log('fvalues are; ', fValues)
  var format = []
  var datecolumn = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1)

  for (var i = 2; i < 4; i++) {
    var datecolumn = sheet.getRange(i, 5).getValue();
    format.push(datecolumn)
  };
  console.log('date array is: ', format)

  var format2 = []
  for (var i = 0; i < fValues.length; i++) {

    var fmtcell = Utilities.formatDate(fValues, "GMT-5", "MM/dd/yyyy")

    format2.push(fmtcell)
  }
}

Body:
If I understand you correctly, you want to compare a group of dates, located in column E from Sheet1, with current date, as well as format these dates to a certain format.

If that's the case, you can do the following (check inline comments):

function dateCompare() {
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yyyy");
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  // Retrieve list of dates in column E (formatted as current date):
  var firstRow = 2;
  var column = 5;
  var numRows = sheet.getLastRow() - firstRow + 1;
  var dates = sheet.getRange(firstRow, column, numRows).getValues().map(function(date) {
    return Utilities.formatDate(new Date(date[0]), "GMT+1", "MM/dd/yyyy");
  });
  dates.forEach(function(date, i) { // Iterate through each date in column E
    if (date === curDate) { // Compare each date in column E to current date
      // Do something to the row:
      var row = sheet.getRange(firstRow + i, 1, 1, sheet.getLastColumn());
    }
  });
}

Please consider that getValues() returns a 2D dimensional array. You can transform this 2D into a one-dimensional array and format the dates in the array at the same time with map.

Reference:

Utilities.formatDate(date, timeZone, format)

Range.getValues()

Array.prototype.map()


问:
How to set the time period for django model
I want to keep the time period in Django model.

like 60 sec, 10 min.

so I choose TimeField class for this purpose

```<code> my_period = models.TimeField()
</code>```

Is it correct practice???

Because when I try to edit this value in admin page, there shows am or pm.

I think I should just ignore it though....

Thanks to the comment!

I updated the code as below.

```<code>import datetime
class GlobalParam(models.Model):

    my_period = models.DurationField()
    #my_period = datetime.timedelta(days=20, hours=10) ＃where should I put...??

    def __str__(self):
        return my_period
</code>```

However it shows error...

```<code> File "/Users/whitebear/anaconda3/lib/python3.7/site-packages/django/utils/duration.py", line 44, in duration_microseconds
    return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
</code>```

答:
For your case, DurationField is better.</p>

```<code>model.my_period = datetime.timedelta(days=20, hours=10)
</code>```

Body:
I want to keep the time period in Django model.

like 60 sec, 10 min.

so I choose TimeField class for this purpose

 my_period = models.TimeField()

Is it correct practice???

Because when I try to edit this value in admin page, there shows am or pm.

I think I should just ignore it though....

Thanks to the comment!

I updated the code as below.

import datetime
class GlobalParam(models.Model):

    my_period = models.DurationField()
    #my_period = datetime.timedelta(days=20, hours=10) ＃where should I put...??

    def __str__(self):
        return my_period

However it shows error...

 File "/Users/whitebear/anaconda3/lib/python3.7/site-packages/django/utils/duration.py", line 44, in duration_microseconds
    return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds

Body:
For your case, DurationField is better.

model.my_period = datetime.timedelta(days=20, hours=10)


问:
Flutter : Not able to edit pubspec.yml file, It displays "File is read-only" popup warning while trying to edit pubspec.yml file
I am new to Flutter. I am trying to create one hybrid app using Flutter/Dart. I was able to edit pubspec.yml so far, but suddenly it says "File is read-only" when try to type anything in this file. Could anyone please help how can i make it editable again.

I have attached the screenshot for reference. Screenshot is captured when "File is read-only" warning is displayed on keyboard key press.

Screenshot

Thanks,
Davinder

答:
If you are a Mac user you have to "Change permissions",  you could do so:

Assign permissions to users and groups

On your Mac, select a disk, folder, or file, then choose File > Get
Info.

If the information in Sharing & Permissions isn’t visible,
    click the disclosure triangle.

Click the lock icon  to unlock it.

Enter an administrator name and password.

Click a user or group in the Name column, then choose a privilege setting from   the pop-up menu.

Read & Write: Allows a user to open the item and change it.

Read Only: Allows a user to open the item, but not change its
contents.

Write Only: Makes a folder into a drop box. Users can copy
items to the drop box, but can’t open it. Only the owner of the drop
box can open it.

No Access: Blocks all access to the item.

Learn more


问:
hide one part of JSplitPane in Applet
Here is my situation, i want to implement a sidebar on the right side of a JFrame. The sidebar is hidden in default, appear if i click a button.

In order to hide the sidebar, I set the divider location of the JSplitPane with a very large value, say 10000. It works properly in normal java application. Also, i set the setResizeWeight of the JSplitPane to 1.0.

However, if i run it in a applet, the sidebar appear a little bit on the right when i resize the JFrame.

How can i hide the sidebar even when i resize the JFrame? Any idea would be welcome.
ps. i need it done in java 1.4

答: Have you tried making the JSplitPane wider than the parent by the thickness of the split bar? The JSplitPane should be clipped by the parent container so you don't see the split bar until you want to at which time you can size the pane equal to the parent size and position the split bar position.</p>

ContentLicense: CC BY-SA 2.5

Title: hide one part of JSplitPane in Applet


问:
Could not load file or assembly 'RestSharp, Version=105.2.3.0
I am having some trouble understanding this issue.

I have a local project with Twilio added via Nuget. But when I export the project to my IIS server, it cannot use Twilio, even if i have added all the DLL files for Twilio.

I think I am missing something with the include or something..

This is the errormessage i get:

```<code>Exception information:
    Exception type: FileNotFoundException
    Exception message: Could not load file or assembly 'RestSharp, Version=105.2.3.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at Twilio.TwilioClient..ctor(String accountSid, String authToken, String accountResourceSid, String apiVersion, String baseUrl)
   at Twilio.TwilioRestClient..ctor(String accountSid, String authToken, String accountResourceSid) in C:\projects\twilio-csharp\src\Twilio.Api\Core.cs:line 182
   at Modules.Messaging.TwilioClient.Send()
</code>```

答:
Remove all references  form Restsharp.

Clean Solution (Clean solution option)

Add RestSharpSigned.105.2.3  (find by name RestSharpSigned).

it's work.

Body:
I am having some trouble understanding this issue.

I have a local project with Twilio added via Nuget. But when I export the project to my IIS server, it cannot use Twilio, even if i have added all the DLL files for Twilio.

I think I am missing something with the include or something..

This is the errormessage i get:

Exception information:
    Exception type: FileNotFoundException
    Exception message: Could not load file or assembly 'RestSharp, Version=105.2.3.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at Twilio.TwilioClient..ctor(String accountSid, String authToken, String accountResourceSid, String apiVersion, String baseUrl)
   at Twilio.TwilioRestClient..ctor(String accountSid, String authToken, String accountResourceSid) in C:\projects\twilio-csharp\src\Twilio.Api\Core.cs:line 182
   at Modules.Messaging.TwilioClient.Send()


问:
How to create a new column in a dataframe, with either 1 or 0 based on percentage of results in previous columns?
I have a data frame with 144 rows and 48 columns. It contains results from various prediction models as either 1 or 0. I want to go through a row, find the percentage of 1's in that row and add a new column with either 1 if the percentage is greater than 80, else 0.

I know how to do this in excel with if and countif/count%, but here I don't really know how to do it. I hope I provided enough info, I am sorry if I did not. Thank you very much for any advice.

答:
You can use .sum and cast to int in you prefer it over boolean. To set the value of the column lots_of_ones to 1 if the percentage of 1s on the other columns is bigger than a threshold you can do:

```<code>import pandas as pd

threshold = 0.8
df = pd.DataFrame([[0,0,0,0],[0,1,1,1], [1,1,1,1]])
df["lots_of_ones"] = (df.sum(axis=1) / df.columns.shape[0] > threshold).astype(int)
</code>```

Result

```<code>>>> df
   0  1  2  3  lots_of_ones
0  0  0  0  0             0
1  0  1  1  1             0
2  1  1  1  1             1
</code>```

Body:
You can use .sum and cast to int in you prefer it over boolean. To set the value of the column lots_of_ones to 1 if the percentage of 1s on the other columns is bigger than a threshold you can do:

import pandas as pd

threshold = 0.8
df = pd.DataFrame([[0,0,0,0],[0,1,1,1], [1,1,1,1]])
df["lots_of_ones"] = (df.sum(axis=1) / df.columns.shape[0] > threshold).astype(int)

Result

>>> df
   0  1  2  3  lots_of_ones
0  0  0  0  0             0
1  0  1  1  1             0
2  1  1  1  1             1


问:
remove double quotes from a string in c++
I am stripping off double quotes from a string, but I keep getting this error from the following function. What is the problem here?

```<code>void readCSVCell(stringstream& lineStream, string& s) {
    std::getline(lineStream,s,',');
    s.erase(remove( s.begin(), s.end(), '\"' ), s.end());
}
</code>```

[ERROR]

c.cpp: In function void readCSVCell(std::stringstream&, std::string&):

c.cpp:11: error: cannot convert __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > to const char* for argument 1 to int remove(const char*)

答:
You can use below code to remove double quotes from string in C++.</p>

```<code>stringVariable.erase(
    std::remove(stringVariable.begin(), stringVariable.end(), '\"'),
    stringVariable.end());
</code>```

Body:
I am stripping off double quotes from a string, but I keep getting this error from the following function. What is the problem here?

void readCSVCell(stringstream& lineStream, string& s) {
    std::getline(lineStream,s,',');
    s.erase(remove( s.begin(), s.end(), '\"' ), s.end());
}

[ERROR]

c.cpp: In function void readCSVCell(std::stringstream&, std::string&):

c.cpp:11: error: cannot convert __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > to const char* for argument 1 to int remove(const char*)

Body:
You can use below code to remove double quotes from string in C++.

stringVariable.erase(
    std::remove(stringVariable.begin(), stringVariable.end(), '\"'),
    stringVariable.end());


问:
Laravel - Package can't recognise Auth functions?
I made a package which is counting the visitors on a webpage. Currently I have a single route, controller and view which don't do very much other than display a simple string. I have a separate Laravel application where this package is specifically build for. In this separate application I have a layout file called backend.

layouts/layouts/backend.blade.php.

My package view is extending this template like so: (backend.blade.php does not exists in the package but in the separate laravel application of-course)

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

@section('content')
    <div class="container-fluid pt-5 ">
        <div class="row">
            <div class="col-md-6">
                <h3>{{ __('Visitors') }}</h3>
            </div>
        </div>
    </div>
@endsection
</code>```

The package successfully extends this layout but it can't find functions such as Auth::user()->token and it will say

```<code>Trying to get property 'token' of non-object (View: /Users/rainierlaan/Sites/rainierlaan/resources/views/layouts/layouts/backend.blade.php)
</code>```

Why does this happen?

This is my packages service provider

```<code> public function register()
    {
        // Controllers
        $this->app->make('Rainieren\Visitors\Http\Controllers\VisitorController');
        // Views
        $this->loadViewsFrom(__DIR__.'/resources/views', 'visitors');
        $this->publishes([
            __DIR__.'/resources/views' => resource_path('views/visitors'),
        ]);
        // Migrations
        $this->loadMigrationsFrom(__DIR__.'/database/migrations');
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        include __DIR__ . '/routes/routes.php';
    }
</code>```

When I do vendor:publish the view successfully publishes to the right folder but somehow can't recognise functions such as Auth::user()->token or Auth::user()->unreadNotifications->count())

This is my package route:

```<code><?php

Route::get('dashboard/visitors', '\Rainieren\Visitors\Http\Controllers\VisitorController@index')->name('visitors');

</code>```

And this is the controller

```<code>public function index()
    {
        return view('visitors::index');
    }
</code>```

答:
I have seen in all of my active packages that they don't use Auth class at all in the views.

Their workaround is using this in the controller and pass it to the view:

```<code>$user = auth()->user();

return view('folder.view' ,['user'=>$user]);
</code>```

And then in the view:

```<code>{{$user->token}} <!-- OR --!> {{$user->unreadNotifications->count()}}
</code>```

Obviously as @N69S has stated only if a user is authenticated this is going to work.

Hope this works!!

EDIT:(Sorry didn't understand well the first time)

The error is in your service provider class yo have to do all the logic on the boot function, not in the register, because if you do in the register function, you load all before the laravel framework (To say something)
https://laravel.com/docs/5.7/providers#the-register-method

Your serviceprovider should end like this:

```<code>    public function register()
    {
        //Nothing
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        // Controllers
        $this->app->make('Rainieren\Visitors\Http\Controllers\VisitorController');
        // Views
        $this->loadViewsFrom(__DIR__.'/resources/views', 'visitors');
        $this->publishes([
            __DIR__.'/resources/views' => resource_path('views/visitors'),
        ]);
        // Migrations
        $this->loadMigrationsFrom(__DIR__.'/database/migrations');
        include __DIR__ . '/routes/routes.php';
    }
</code>```

Hope this finally works!

Body:
I made a package which is counting the visitors on a webpage. Currently I have a single route, controller and view which don't do very much other than display a simple string. I have a separate Laravel application where this package is specifically build for. In this separate application I have a layout file called backend.

layouts/layouts/backend.blade.php.

My package view is extending this template like so: (backend.blade.php does not exists in the package but in the separate laravel application of-course)

@extends('layouts.layouts.backend')

@section('content')

{{ __('Visitors') }}

@endsection

The package successfully extends this layout but it can't find functions such as Auth::user()->token and it will say

Trying to get property 'token' of non-object (View: /Users/rainierlaan/Sites/rainierlaan/resources/views/layouts/layouts/backend.blade.php)

Why does this happen?

This is my packages service provider

 public function register()
    {
        // Controllers
        $this->app->make('Rainieren\Visitors\Http\Controllers\VisitorController');
        // Views
        $this->loadViewsFrom(__DIR__.'/resources/views', 'visitors');
        $this->publishes([
            __DIR__.'/resources/views' => resource_path('views/visitors'),
        ]);
        // Migrations
        $this->loadMigrationsFrom(__DIR__.'/database/migrations');
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        include __DIR__ . '/routes/routes.php';
    }

When I do vendor:publish the view successfully publishes to the right folder but somehow can't recognise functions such as Auth::user()->token or Auth::user()->unreadNotifications->count())

This is my package route:

<?php

Route::get('dashboard/visitors', '\Rainieren\Visitors\Http\Controllers\VisitorController@index')->name('visitors');

And this is the controller

public function index()
    {
        return view('visitors::index');
    }

Body:
I have seen in all of my active packages that they don't use Auth class at all in the views.

Their workaround is using this in the controller and pass it to the view:

$user = auth()->user();

return view('folder.view' ,['user'=>$user]);

And then in the view:

{{$user->token}} <!-- OR --!> {{$user->unreadNotifications->count()}}

Obviously as @N69S has stated only if a user is authenticated this is going to work.

Hope this works!!

EDIT:(Sorry didn't understand well the first time)

The error is in your service provider class yo have to do all the logic on the boot function, not in the register, because if you do in the register function, you load all before the laravel framework (To say something)
https://laravel.com/docs/5.7/providers#the-register-method

Your serviceprovider should end like this:

    public function register()
    {
        //Nothing
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        // Controllers
        $this->app->make('Rainieren\Visitors\Http\Controllers\VisitorController');
        // Views
        $this->loadViewsFrom(__DIR__.'/resources/views', 'visitors');
        $this->publishes([
            __DIR__.'/resources/views' => resource_path('views/visitors'),
        ]);
        // Migrations
        $this->loadMigrationsFrom(__DIR__.'/database/migrations');
        include __DIR__ . '/routes/routes.php';
    }

Hope this finally works!


问:
Laravel and Arabic slugs
When creating a slug from a name, the slug is in English letters.

Example:

name = مقالة جديدة

slug = mk-l-gdyd

It should be: مقالة-جديدة

Any idea how to solve this issue? I'm using this package.

Model

class Post extends Model
{
    use HasSlug;

    protected $primarykey = 'id';

    protected $fillable = [
        'title', 'slug', 'body',
    ];

    protected $dates = [
        'created_at', 'updated_at'
    ];

    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('title')
            ->saveSlugsTo('slug');
    }
}
```

答:
The spatie/laravel-sluggable package uses the Laravel Str::slug() helper to generate the slug, which can take a third parameter for language if a character has a different transliterations depending on the original language used.  To use this with the Spatie package, add usingLanguage('ar') to your method chain.

To set the language used by Str::slug you may call usingLanguage

public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('title')
        ->saveSlugsTo('slug')
        ->usingLanguage('ar');
}
```

However please note that the entire purpose of this method is to produce "SEO-friendly" slugs by transliterating into ASCII (i.e. Western alphabet only), and will not preserve any non-ASCII characters.

As a side note, even Yoast SEO isn't sure what to do with non-ASCII slugs.  In the meantime, the simplest approach would be to use preg_replace() to strip punctuation and convert whitespace to hyphens.

Title: Laravel and Arabic slugs

Body:
The spatie/laravel-sluggable package uses the Laravel Str::slug() helper to generate the slug, which can take a third parameter for language if a character has a different transliterations depending on the original language used.  To use this with the Spatie package, add usingLanguage('ar') to your method chain.

To set the language used by Str::slug you may call usingLanguage

public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('title')
        ->saveSlugsTo('slug')
        ->usingLanguage('ar');
}

However please note that the entire purpose of this method is to produce "SEO-friendly" slugs by transliterating into ASCII (i.e. Western alphabet only), and will not preserve any non-ASCII characters.

As a side note, even Yoast SEO isn't sure what to do with non-ASCII slugs.  In the meantime, the simplest approach would be to use preg_replace() to strip punctuation and convert whitespace to hyphens.


问:
Readonly database MDF file. Windows app
can someone help me.

I've tried moving the MDF file around to different locations but I'm still unable to update the database. I'm using Windows 7.

Here's my code:

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestDatabase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        System.Data.SqlClient.SqlConnection con;
        DataSet ds1;
        System.Data.SqlClient.SqlDataAdapter da;

        int MaxRows = 0;
        int inc = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new System.Data.SqlClient.SqlConnection();
            ds1 = new DataSet();
            con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\rebdog\\AppData\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            con.Open();

            string sql = "SELECT * From tblWorkers";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, con);

            MessageBox.Show("database Open");

            da.Fill(ds1, "Workers");
            NavigateRecords();
            MaxRows = ds1.Tables["Workers"].Rows.Count;

            con.Close();

            MessageBox.Show("database closed");
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            System.Data.SqlClient.SqlCommandBuilder cb;

            cb = new System.Data.SqlClient.SqlCommandBuilder(da);

            DataRow dRow = ds1.Tables["Workers"].NewRow();

            dRow[1] = textBox1.Text;
            dRow[2] = textBox2.Text;
            dRow[3] = textBox3.Text;

            ds1.Tables["Workers"].Rows.Add(dRow);

            MaxRows = MaxRows + 1;
            inc = MaxRows - 1;

            da.Update(ds1,"Workers");
        }
    }
}
</code>```

The code is from a tutorial, I need to get this working before I add a database to my project.

Thank you guys.

答:
According to your code (in the connection string) the mdf file should be in

```<code>C:\Users\rebdog\AppData\MyWorkers.mdf
</code>```

The connection is set up to use integrated security, meaning that it uses your windows login to access that database. So if you have problems accessing the database, it might be because it requires another user account, or because your user doesn't have read/write access to that folder.

Title: Readonly database MDF file. Windows app

Body:
can someone help me.

I've tried moving the MDF file around to different locations but I'm still unable to update the database. I'm using Windows 7.

Here's my code:

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestDatabase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        System.Data.SqlClient.SqlConnection con;
        DataSet ds1;
        System.Data.SqlClient.SqlDataAdapter da;

        int MaxRows = 0;
        int inc = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new System.Data.SqlClient.SqlConnection();
            ds1 = new DataSet();
            con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\rebdog\\AppData\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            con.Open();

            string sql = "SELECT * From tblWorkers";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, con);

            MessageBox.Show("database Open");

            da.Fill(ds1, "Workers");
            NavigateRecords();
            MaxRows = ds1.Tables["Workers"].Rows.Count;

            con.Close();

            MessageBox.Show("database closed");
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            System.Data.SqlClient.SqlCommandBuilder cb;

            cb = new System.Data.SqlClient.SqlCommandBuilder(da);

            DataRow dRow = ds1.Tables["Workers"].NewRow();

            dRow[1] = textBox1.Text;
            dRow[2] = textBox2.Text;
            dRow[3] = textBox3.Text;

            ds1.Tables["Workers"].Rows.Add(dRow);

            MaxRows = MaxRows + 1;
            inc = MaxRows - 1;

            da.Update(ds1,"Workers");
        }
    }
}

The code is from a tutorial, I need to get this working before I add a database to my project.

Thank you guys.

Body:
According to your code (in the connection string) the mdf file should be in

C:\Users\rebdog\AppData\MyWorkers.mdf

The connection is set up to use integrated security, meaning that it uses your windows login to access that database. So if you have problems accessing the database, it might be because it requires another user account, or because your user doesn't have read/write access to that folder.


问:
Will Python Daemon thread be blocked by busy parent thread given there is GIL?
I know Python daemon thread will auto exit if parent thread exit. The reason I ask if because my main thread is sometime working on CPU heavy calculation which blocks the heart beat message. Other module thinks this service is dead and planning for funeral.

I want to use some kind of daemon thread(or process?) that is the child of main thread, to send heart beat message.

My question is if my main thread is blocking, for example:

```<code>while True:
   a = a + 1
</code>```

Will my daemon child thread be blocked as well? any example or evidence? What role does GIL (Global Interpreter Lock) play here?

Edit

To @ShadowRanger's point, the following example shows, waiter can log out the the message, given the worker thread is blocking (taking 220% CPU resource)

```<code>import time
from threading import Thread

class worker(Thread):
    def run(self):
        t = 10
        x = 10
        while True:
            x = t + 1

class waiter(Thread):
    def run(self):
        for x in xrange(100,150):
            print x
            time.sleep(0.5)

def run():
    worker().start()
    waiter().start()

run()
</code>```

答: For safety reasons I'd go with multiprocessing here. Your heartbeat response could be a separate process released from chains of GIL. Otherwise you'll depend on indeterministic code flow and you may get random errors in least expected moments.

Body:
I know Python daemon thread will auto exit if parent thread exit. The reason I ask if because my main thread is sometime working on CPU heavy calculation which blocks the heart beat message. Other module thinks this service is dead and planning for funeral.

I want to use some kind of daemon thread(or process?) that is the child of main thread, to send heart beat message.

My question is if my main thread is blocking, for example:

while True:
   a = a + 1

Will my daemon child thread be blocked as well? any example or evidence? What role does GIL (Global Interpreter Lock) play here?

Edit

To @ShadowRanger's point, the following example shows, waiter can log out the the message, given the worker thread is blocking (taking 220% CPU resource)

import time
from threading import Thread

class worker(Thread):
    def run(self):
        t = 10
        x = 10
        while True:
            x = t + 1

class waiter(Thread):
    def run(self):
        for x in xrange(100,150):
            print x
            time.sleep(0.5)

def run():
    worker().start()
    waiter().start()

run()


问:
Parallax page with color changing text
I want to make a page with a big text across the screen and if you scroll, the background colors change (it could be done with images aswell)

I've tried a lot but i cant get it working...

code:

```<code><!DOCTYPE html>
<head>
    <title>testhtml</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        html, body{
            height: 100%;
        }
        .parallax{

            background-image: url(../assets/img/img1.jpg);
            min-height: 100%;
            height: 100%;
            position: fixed;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            -webkit-background-clip: text;
        }
        .title {
            overflow:hidden;
            display:inline-block;
            padding:10px;
            font-weight:bold;
            font-family:arial;
            color:transparent;
            font-size:200px;
        }span {
            -webkit-text-fill-color: transparent;
            -webkit-background-clip: text;
            display:block;
        }

    </style>
</head>
<body>

    <div class="parallax">
                <h1 class="title"><span>Test</span></h1>

    </div>
</body>
</code>```

it shows the text with image as background, but when you scroll the images stays, because its fixed i think.

But it should be the image staying and the background scrolling

答:
To make the text somewhere constant on the page,you need fixed position which will force the element to stay always in a certain position

This fixed class always will force the text in the center.

```<code>.fixed {
    position:fixed;
      top:40%;
    left:50%;
    transform:translate(-50%,-50%);
    text-align: center;
}
</code>```

Here you can see my solution : https://codepen.io/Cicek96/pen/qBdNVBO

Title: Parallax page with color changing text

Body:
I want to make a page with a big text across the screen and if you scroll, the background colors change (it could be done with images aswell)

I've tried a lot but i cant get it working...

code:

<!DOCTYPE html>

    <title>testhtml</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Test

it shows the text with image as background, but when you scroll the images stays, because its fixed i think.

But it should be the image staying and the background scrolling

Body:
To make the text somewhere constant on the page,you need fixed position which will force the element to stay always in a certain position

This fixed class always will force the text in the center.

.fixed {
    position:fixed;
      top:40%;
    left:50%;
    transform:translate(-50%,-50%);
    text-align: center;
}

Here you can see my solution : https://codepen.io/Cicek96/pen/qBdNVBO


问:
Why I Cannot subscript a value of type '[String : [String]]' with an argument of type 'String.SubSequence' (aka 'Substring')?
I have an array that I want to convert to a dictionary and I declared a function to do so but I get this error each time I compile
"Cannot subscript a value of type '[String : [String]]' with an argument of type 'String.SubSequence' (aka 'Substring')"

my code is

```<code>let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
   var animalsDict = [String: [String]]()
    var animalSectionTitles = [String]()

 func createAnimalDict() {
        for animal in animals {
            let secondLetterIndex = animal.index(animal.startIndex, offsetBy: 1)
            let animalKey = animal[..<secondLetterIndex]
            if var animalValues = animalsDict[animalKey] {
                animalValues.append(animal)
                animalsDict[animalKey] = animalValues
            }else {
                animalsDict[animalKey] = [animal]
            }
        }
        animalSectionTitles = [String](animalsDict.keys)
        animalSectionTitles = animalSectionTitles.sorted(by: { $0 < $1 })
    }
</code>```

I expect to get this dictionary after converting to fill a tableview with this dictionary which its key refer to section title and its values refer to the rows' titles

```<code>let animals: [String: [String]] = ["B" : ["Bear", "Black Swan", "Buffalo"],

"C" : ["Camel", "Cockatoo"],

"D" : ["Dog", "Donkey"],

"E" : ["Emu"],

"G" : ["Giraffe", "Greater Rhea"],

"H" : ["Hippopotamus", "Horse"],

"K" : ["Koala"],

"L" : ["Lion", "Llama"],

"M" : ["Manatus", "Meerkat"],

"P" : ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"],

"R" : ["Rhinoceros"],

"S" : ["Seagull"],

"T" : ["Tasmania Devil"],

"W" : ["Whale", "Whale Shark", "Wombat"]]
</code>```

答:
You can simply use Dictionary's init(grouping:by:) initializer like so,

```<code>var animalsDict = Dictionary(grouping: animals) { String($0.first!) }

var animalSectionTitles = animalsDict.keys.sorted()
</code>```

Output:

```<code>print(animalsDict) //["G": ["Giraffe", "Greater Rhea"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], "E": ["Emu"], "H": ["Hippopotamus", "Horse"], "K": ["Koala"], "L": ["Lion", "Llama"], "R": ["Rhinoceros"], "D": ["Dog", "Donkey"], "B": ["Bear", "Black Swan", "Buffalo"], "M": ["Manatus", "Meerkat"], "W": ["Whale", "Whale Shark", "Wombat"], "S": ["Seagull"], "T": ["Tasmania Devil"], "C": ["Camel", "Cockatoo"]]

print(animalSectionTitles) //["B", "C", "D", "E", "G", "H", "K", "L", "M", "P", "R", "S", "T", "W"]
</code>```

Body:
I have an array that I want to convert to a dictionary and I declared a function to do so but I get this error each time I compile
"Cannot subscript a value of type '[String : [String]]' with an argument of type 'String.SubSequence' (aka 'Substring')"

my code is

let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
   var animalsDict = [String: [String]]()
    var animalSectionTitles = [String]()

 func createAnimalDict() {
        for animal in animals {
            let secondLetterIndex = animal.index(animal.startIndex, offsetBy: 1)
            let animalKey = animal[..<secondLetterIndex]
            if var animalValues = animalsDict[animalKey] {
                animalValues.append(animal)
                animalsDict[animalKey] = animalValues
            }else {
                animalsDict[animalKey] = [animal]
            }
        }
        animalSectionTitles = [String](animalsDict.keys)
        animalSectionTitles = animalSectionTitles.sorted(by: { $0 < $1 })
    }

I expect to get this dictionary after converting to fill a tableview with this dictionary which its key refer to section title and its values refer to the rows' titles

let animals: [String: [String]] = ["B" : ["Bear", "Black Swan", "Buffalo"],

"C" : ["Camel", "Cockatoo"],

"D" : ["Dog", "Donkey"],

"E" : ["Emu"],

"G" : ["Giraffe", "Greater Rhea"],

"H" : ["Hippopotamus", "Horse"],

"K" : ["Koala"],

"L" : ["Lion", "Llama"],

"M" : ["Manatus", "Meerkat"],

"P" : ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"],

"R" : ["Rhinoceros"],

"S" : ["Seagull"],

"T" : ["Tasmania Devil"],

"W" : ["Whale", "Whale Shark", "Wombat"]]

Body:
You can simply use Dictionary's init(grouping:by:) initializer like so,

var animalsDict = Dictionary(grouping: animals) { String($0.first!) }

var animalSectionTitles = animalsDict.keys.sorted()

Output:

print(animalsDict) //["G": ["Giraffe", "Greater Rhea"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], "E": ["Emu"], "H": ["Hippopotamus", "Horse"], "K": ["Koala"], "L": ["Lion", "Llama"], "R": ["Rhinoceros"], "D": ["Dog", "Donkey"], "B": ["Bear", "Black Swan", "Buffalo"], "M": ["Manatus", "Meerkat"], "W": ["Whale", "Whale Shark", "Wombat"], "S": ["Seagull"], "T": ["Tasmania Devil"], "C": ["Camel", "Cockatoo"]]

print(animalSectionTitles) //["B", "C", "D", "E", "G", "H", "K", "L", "M", "P", "R", "S", "T", "W"]


答:
All you need to do is convert the Substring, namely animalKey to a String and your code works just as expected.

```<code>let animalKey = String(animal[..<secondLetterIndex])
</code>```

Title: Why I Cannot subscript a value of type '[String : [String]]' with an argument of type 'String.SubSequence' (aka 'Substring')?

Body:
All you need to do is convert the Substring, namely animalKey to a String and your code works just as expected.

let animalKey = String(animal[..<secondLetterIndex])


问:
How to show fragment dialog in button.setOnClickListener from Adapter class in Kotlin-MVP?
I'm developing one Android application using this Kotlin-MVP structure. I have one activity and it contains TabLayout of 4 fragments. All fragment has one button in RecyclerView. I need to show one "Fragment Dialog" on that button click listener. Can you please let me know how can I show fragment dialog on button click listener from adapter class? Please review screenshot.

I'm accessing button on click listener event from Adapter class which is below itemView.btn_accept.setOnClickListener:

```<code>class InApprovalAdapter(private val jobListItems: MutableList<JobItem>) : RecyclerView.Adapter<InApprovalAdapter.JobViewHolder>() {

private var _ProfileId: Long? = null;

fun getProfileId(): Long? {
    return _ProfileId
}

fun setProfileId(s: Long) {
    _ProfileId = s
}

private var _UserToken : String? = null;

fun getUserToken(): String? {
    return _UserToken
}

fun setUserToken(s: String) {
    _UserToken = s
}

private var _UserTypeId : Long? = null;
fun getUserTypeId(): Long? {
    return _UserTypeId
}

fun setUserTypeId(s: Long) {
    _UserTypeId = s
}

override fun getItemCount() = this.jobListItems.size

override fun onBindViewHolder(holder: JobViewHolder, position: Int) = holder.let {
    it.clear()
    it.onBind(position)
}

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int) = JobViewHolder(LayoutInflater.from(parent?.context)
        .inflate(R.layout.item_inapproval_list, parent, false))

internal fun addJobsToList(jobs: List<JobItem>, profileId: Long?, userToken: String?, userTypeId: Long?) {
    this.jobListItems.addAll(jobs)
    setProfileId(profileId!!.toLong())
    setUserToken(userToken!!)
    setUserTypeId(userTypeId!!)
    notifyDataSetChanged()
}

inner class JobViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    fun clear() {
        itemView.tv_job_id.text = "";
        itemView.tv_job_title.text= "";
        //itemView.tv_job_description.text ="";
        itemView.tv_job_category.text ="";
        itemView.tv_date_created.text ="";
    }

    fun onBind(position: Int) {

        val (jobId, name, description, serviceId, serviceName,
                address, engineerIds, engineerNames, startDateTimeUtc,
                startDateTimeLocal, endDateTimeUtc, endDateTimeLocal,
                customerId, customerName, customerMobile, customerAltMobile,
                priorityTypeId, priorityTypeName, statusTypeId, statusTypeName,
                isDeleted, isStatusTypeActive, createdBy, createdByName,
                dateCreatedPretty, modifiedBy, modifiedByName ,hasJobMedia,
                jobMedias, hasJobFeedback, jobDetailsImage, dateCreatedUtc, dateModifiedUtc) = jobListItems[position]

        inflateData(jobId, name,
                description,
                serviceId,
                serviceName,
                address,
                engineerIds,
                engineerNames,
                startDateTimeUtc,
                startDateTimeLocal,
                endDateTimeUtc,
                endDateTimeLocal,
                customerId,
                customerName,
                customerMobile,
                customerAltMobile,
                priorityTypeId,priorityTypeName,
                statusTypeId,
                statusTypeName,
                isDeleted,
                isStatusTypeActive,
                createdBy,
                createdByName,
                dateCreatedPretty,
                modifiedBy,
                modifiedByName ,
                hasJobMedia,
                jobMedias, hasJobFeedback, jobDetailsImage, dateCreatedUtc, dateModifiedUtc)
        setItemClickListener(jobId)
    }

    private fun setItemClickListener(jobId: Long?) {
        itemView.setOnClickListener {
            jobId?.let {
                try {
                    val intent = Intent(itemView.context, ServiceDetailActivity::class.java)
                    intent.putExtra("JobId", jobId)
                    itemView.context.startActivity(intent)
                } catch (e: Exception) {
                    Toast.makeText(itemView.context, e.message, Toast.LENGTH_LONG).show()
                }
            }
        }

        itemView.btn_accept.setOnClickListener {

        }

        itemView.btn_reject.setOnClickListener{

        }
    }
    private fun inflateData(jobId: Long?, name: String?, description: String?, serviceId: Long?, serviceName: String?, address: String?, engineerIds: String?,
                            engineerNames: String?, startDateTimeUtc: String?, startDateTimeLocal: String?, endDateTimeUtc: String?,
                            endDateTimeLocal: String?, customerId: Long?, customerName: String?, customerMobile:String?, customerAltMobile: String?,
                            priorityTypeId: Long?, priorityTypeName: String?, statusTypeId: Long?, statusTypeName: String?, isDeleted: Boolean?, isStatusTypeActive: Boolean?,
                            createdBy: Long?, createdByName: String?, dateCreatedPretty: String?, modifiedBy: Long?, modifiedByName: String?, hasJobMedia: Boolean?,
                            jobMedias: List<JobDetailsImage>?, hasJobFeedback: Boolean?, jobDetailsImage:  List<JobDetailsImage>?, dateCreatedUtc: String?, dateModifiedUtc: String?) {
        name.let {
            itemView.tv_job_title.text = it;
        }
        jobId.let {
            itemView.tv_job_id.text = "Job\n#" + it
        }
        /*description.let {
            itemView.tv_job_description.text = it
        }*/
        serviceName.let {
            itemView.tv_job_category.text = it
        }
        dateCreatedPretty.let {
            itemView.tv_date_created.text = it
        }

        if(getUserTypeId() == AppConstants.UserType.Administrator.type ||
                getUserTypeId() == AppConstants.UserType.Admin.type)
        {
            itemView.btn_reject.text = "Reject";
        }
        else
        {
            itemView.btn_reject.text = "Delete";
            itemView.btn_accept.visibility = View.GONE
        }
    }

    private fun callJobStatusChangeApi(jobId: Long?, statusTypeId: Long?)
    {
        val androidId = Settings.Secure.getString(itemView.context.contentResolver, Settings.Secure.ANDROID_ID)

        Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_JOB_CHANGEJOBSTATUS)
                .addHeaders("Authorization", "bearer " + getUserToken())
                .addQueryParameter("profileId",  getProfileId().toString())
                .addQueryParameter("jobId", jobId.toString())
                .addQueryParameter("statusTypeId", statusTypeId.toString())
                .addQueryParameter("DeviceId", androidId.toString())
                .build()
                .getAsObject(BaseResponse::class.java, object : ParsedRequestListener<BaseResponse> {

                    override fun onResponse(baseResponse: BaseResponse) {
                        // do anything with response
                        println("succeeded : " + baseResponse.succeeded)
                        println("message : " + baseResponse.message)

                        if(baseResponse.succeeded)
                        {
                            val inApprovalFragment : InApprovalFragment = InApprovalFragment()
                            inApprovalFragment.showStatusSubmissionSuccessMessage(itemView.context, baseResponse.message);
                            notifyDataSetChanged();
                        }
                    }

                    override fun onError(anError: ANError) {
                        // handle error
                        println(anError.message);
                    }

                })
    }

}

}
</code>```

答:
I does same thing , shown custom dialog from adapter which is called from fragment.Not need to make dialog fragment,it will do same thing.

Pass activity from fragment while setting adapter

in ListFragment:-

```<code>rvAdapter = Listadapter( listnotes,activity!!)
</code>```

in Listadapter class :-

```<code>class Listadapter( val DataList: ArrayList<String>?,val parentActivity: Activity) : RecyclerView.Adapter<Listadapter.ViewHolder>() {}
</code>```

in onBindViewHolder method:-

```<code>view.notes.setOnClickListener {
        DialogNOTES(parentActivity,DataList[position])
    }
</code>```

make method to show custom dailog in Listadapter class:-

```<code>private fun DialogNOTES(parentActivity: Activity,notes:String) {
    val dialog = Dialog(parentActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(true)
    dialog.setContentView(R.layout.notes_dilog)//custom dialog layout
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    dialog.show()

    dialog.dilog_notes.setText(notes)

}
</code>```

Body:
I'm developing one Android application using this Kotlin-MVP structure. I have one activity and it contains TabLayout of 4 fragments. All fragment has one button in RecyclerView. I need to show one "Fragment Dialog" on that button click listener. Can you please let me know how can I show fragment dialog on button click listener from adapter class? Please review screenshot.

I'm accessing button on click listener event from Adapter class which is below itemView.btn_accept.setOnClickListener:

class InApprovalAdapter(private val jobListItems: MutableList<JobItem>) : RecyclerView.Adapter<InApprovalAdapter.JobViewHolder>() {

private var _ProfileId: Long? = null;

fun getProfileId(): Long? {
    return _ProfileId
}

fun setProfileId(s: Long) {
    _ProfileId = s
}

private var _UserToken : String? = null;

fun getUserToken(): String? {
    return _UserToken
}

fun setUserToken(s: String) {
    _UserToken = s
}

private var _UserTypeId : Long? = null;
fun getUserTypeId(): Long? {
    return _UserTypeId
}

fun setUserTypeId(s: Long) {
    _UserTypeId = s
}

override fun getItemCount() = this.jobListItems.size

override fun onBindViewHolder(holder: JobViewHolder, position: Int) = holder.let {
    it.clear()
    it.onBind(position)
}

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int) = JobViewHolder(LayoutInflater.from(parent?.context)
        .inflate(R.layout.item_inapproval_list, parent, false))

internal fun addJobsToList(jobs: List<JobItem>, profileId: Long?, userToken: String?, userTypeId: Long?) {
    this.jobListItems.addAll(jobs)
    setProfileId(profileId!!.toLong())
    setUserToken(userToken!!)
    setUserTypeId(userTypeId!!)
    notifyDataSetChanged()
}

inner class JobViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    fun clear() {
        itemView.tv_job_id.text = "";
        itemView.tv_job_title.text= "";
        //itemView.tv_job_description.text ="";
        itemView.tv_job_category.text ="";
        itemView.tv_date_created.text ="";
    }

    fun onBind(position: Int) {

        val (jobId, name, description, serviceId, serviceName,
                address, engineerIds, engineerNames, startDateTimeUtc,
                startDateTimeLocal, endDateTimeUtc, endDateTimeLocal,
                customerId, customerName, customerMobile, customerAltMobile,
                priorityTypeId, priorityTypeName, statusTypeId, statusTypeName,
                isDeleted, isStatusTypeActive, createdBy, createdByName,
                dateCreatedPretty, modifiedBy, modifiedByName ,hasJobMedia,
                jobMedias, hasJobFeedback, jobDetailsImage, dateCreatedUtc, dateModifiedUtc) = jobListItems[position]

        inflateData(jobId, name,
                description,
                serviceId,
                serviceName,
                address,
                engineerIds,
                engineerNames,
                startDateTimeUtc,
                startDateTimeLocal,
                endDateTimeUtc,
                endDateTimeLocal,
                customerId,
                customerName,
                customerMobile,
                customerAltMobile,
                priorityTypeId,priorityTypeName,
                statusTypeId,
                statusTypeName,
                isDeleted,
                isStatusTypeActive,
                createdBy,
                createdByName,
                dateCreatedPretty,
                modifiedBy,
                modifiedByName ,
                hasJobMedia,
                jobMedias, hasJobFeedback, jobDetailsImage, dateCreatedUtc, dateModifiedUtc)
        setItemClickListener(jobId)
    }

    private fun setItemClickListener(jobId: Long?) {
        itemView.setOnClickListener {
            jobId?.let {
                try {
                    val intent = Intent(itemView.context, ServiceDetailActivity::class.java)
                    intent.putExtra("JobId", jobId)
                    itemView.context.startActivity(intent)
                } catch (e: Exception) {
                    Toast.makeText(itemView.context, e.message, Toast.LENGTH_LONG).show()
                }
            }
        }

        itemView.btn_accept.setOnClickListener {

        }

        itemView.btn_reject.setOnClickListener{

        }
    }
    private fun inflateData(jobId: Long?, name: String?, description: String?, serviceId: Long?, serviceName: String?, address: String?, engineerIds: String?,
                            engineerNames: String?, startDateTimeUtc: String?, startDateTimeLocal: String?, endDateTimeUtc: String?,
                            endDateTimeLocal: String?, customerId: Long?, customerName: String?, customerMobile:String?, customerAltMobile: String?,
                            priorityTypeId: Long?, priorityTypeName: String?, statusTypeId: Long?, statusTypeName: String?, isDeleted: Boolean?, isStatusTypeActive: Boolean?,
                            createdBy: Long?, createdByName: String?, dateCreatedPretty: String?, modifiedBy: Long?, modifiedByName: String?, hasJobMedia: Boolean?,
                            jobMedias: List<JobDetailsImage>?, hasJobFeedback: Boolean?, jobDetailsImage:  List<JobDetailsImage>?, dateCreatedUtc: String?, dateModifiedUtc: String?) {
        name.let {
            itemView.tv_job_title.text = it;
        }
        jobId.let {
            itemView.tv_job_id.text = "Job\n#" + it
        }
        /*description.let {
            itemView.tv_job_description.text = it
        }*/
        serviceName.let {
            itemView.tv_job_category.text = it
        }
        dateCreatedPretty.let {
            itemView.tv_date_created.text = it
        }

        if(getUserTypeId() == AppConstants.UserType.Administrator.type ||
                getUserTypeId() == AppConstants.UserType.Admin.type)
        {
            itemView.btn_reject.text = "Reject";
        }
        else
        {
            itemView.btn_reject.text = "Delete";
            itemView.btn_accept.visibility = View.GONE
        }
    }

    private fun callJobStatusChangeApi(jobId: Long?, statusTypeId: Long?)
    {
        val androidId = Settings.Secure.getString(itemView.context.contentResolver, Settings.Secure.ANDROID_ID)

        Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_JOB_CHANGEJOBSTATUS)
                .addHeaders("Authorization", "bearer " + getUserToken())
                .addQueryParameter("profileId",  getProfileId().toString())
                .addQueryParameter("jobId", jobId.toString())
                .addQueryParameter("statusTypeId", statusTypeId.toString())
                .addQueryParameter("DeviceId", androidId.toString())
                .build()
                .getAsObject(BaseResponse::class.java, object : ParsedRequestListener<BaseResponse> {

                    override fun onResponse(baseResponse: BaseResponse) {
                        // do anything with response
                        println("succeeded : " + baseResponse.succeeded)
                        println("message : " + baseResponse.message)

                        if(baseResponse.succeeded)
                        {
                            val inApprovalFragment : InApprovalFragment = InApprovalFragment()
                            inApprovalFragment.showStatusSubmissionSuccessMessage(itemView.context, baseResponse.message);
                            notifyDataSetChanged();
                        }
                    }

                    override fun onError(anError: ANError) {
                        // handle error
                        println(anError.message);
                    }

                })
    }

}

}

Body:
I does same thing , shown custom dialog from adapter which is called from fragment.Not need to make dialog fragment,it will do same thing.

Pass activity from fragment while setting adapter

in ListFragment:-

rvAdapter = Listadapter( listnotes,activity!!)

in Listadapter class :-

class Listadapter( val DataList: ArrayList<String>?,val parentActivity: Activity) : RecyclerView.Adapter<Listadapter.ViewHolder>() {}

in onBindViewHolder method:-

view.notes.setOnClickListener {
        DialogNOTES(parentActivity,DataList[position])
    }

make method to show custom dailog in Listadapter class:-

private fun DialogNOTES(parentActivity: Activity,notes:String) {
    val dialog = Dialog(parentActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(true)
    dialog.setContentView(R.layout.notes_dilog)//custom dialog layout
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    dialog.show()

    dialog.dilog_notes.setText(notes)

}


问:
SwiftUI how to set image for NavigationBar titleView like in UIKit?
I want to set an image in the titleView of NavigationBar in SwiftUI, as we do in UIKit

```<code>navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))
</code>```

this is how we do it in UIKit.

anyone know how to do it?

答:
Here's how to do it:

Add SwiftUIX to your project.

Set your custom title view via View.navigationBarTitleView(_:displayMode:)

Example code:

struct ContentView: View {
    public var body: some View {
        NavigationView {
            Text("Hello World")
                .navigationBarTitleView(MyView())
        }
    }
}
```

Body:
I want to set an image in the titleView of NavigationBar in SwiftUI, as we do in UIKit

navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))

this is how we do it in UIKit.

anyone know how to do it?


问:
what better? Use the Provider of asp.net or not use?
what best practice?
If i will not use the provider I will need to make table of Session, roles, my tables and other....

if the provider better, how can I build custom register with connection to another tables(foreign keys)? how can i get the current user in registration(with sessionid?)

Thanks.

答:
It depends on your requirements.

The following articles could be helpfull:

Introduction to Membership

How To: Use Membership in ASP.NET 2.0

MembershipProvider Class

[How Do I:] Create a Custom Membership Provider? (Video)


问:
Angular Material Dialog closes immediately
I try to open a Angular Material dialog from my component. But the dialog closes immediately after it opens.

I know there are some similar questions on Stackoverflow, but their answers don't seem to work for me. Not sure if calling the dialog function out of the complete part of the subscription is the problem.

ExampleDialogComponent.ts

```<code>export class ExampleDialogComponent implements OnInit {

  inputVal1: string;
  inputVal2: string;

  constructor(public dialogRef: MatDialogRef<ExampleDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any, private formBuilder: FormBuilder) {
    this.inputVal1 = data.inputVal1;
    this.inputVal2 = data.inputVal2;
  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }

  onCloseConfirm() {
    setTimeout(() => {
      this.dialogRef.close({
      message: 'Confirm',
      outputVal1: this.inputVal1,
      outputVal2: this.inputVal2,
      });
    }, 0);
  }
}
</code>```

ExampleDialogComponent.html

```<code><mat-step>
      <ng-template matStepLabel>last step</ng-template>
      <mat-dialog-actions>
        <button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>
        <button mat-button mat-dialog-close>close</button>
      </mat-dialog-actions>
</mat-step>
</code>```

MainCompontent.ts

```<code>openModal() {
    this.inputs = [];
    this.http.getInputs().subscribe(
      data => {
        data.forEach(element => this.inputs.push(element));
      },
      (err) => {
        console.log(err);
      },
      () => {
        this.openAddDialog();
      });
  }

  openAddDialog() {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      inputValue1: 'test 1',
      inputValue2: 'test 2',
    };

    const dialogRef = this.dialog.open(ExampleDialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      console.log('Dialog was closed');
      console.log('result: ' + result);

      this.http.createResultinDB(result);
        .subscribe(subData => console.log(subData), error => console.log(error));
    });
  }

  getDeliveryPackageList(): Observable<any> {
    return this.http.get(`${this.baseUrl}`);
  }
</code>```

Thanks a lot for your help.

答:
The problem is that you have to add to your app.module.ts the entryComponents array with the name of your Dialog component as follow:

```<code>@NgModule({
  entryComponents: [
    ExampleDialogComponent
  ],
  declarations: [...],
.
.
.
})
</code>```

Body:
I try to open a Angular Material dialog from my component. But the dialog closes immediately after it opens.

I know there are some similar questions on Stackoverflow, but their answers don't seem to work for me. Not sure if calling the dialog function out of the complete part of the subscription is the problem.

ExampleDialogComponent.ts

export class ExampleDialogComponent implements OnInit {

  inputVal1: string;
  inputVal2: string;

  constructor(public dialogRef: MatDialogRef<ExampleDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any, private formBuilder: FormBuilder) {
    this.inputVal1 = data.inputVal1;
    this.inputVal2 = data.inputVal2;
  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }

  onCloseConfirm() {
    setTimeout(() => {
      this.dialogRef.close({
      message: 'Confirm',
      outputVal1: this.inputVal1,
      outputVal2: this.inputVal2,
      });
    }, 0);
  }
}

ExampleDialogComponent.html

<mat-step>
      <ng-template matStepLabel>last step</ng-template>
      <mat-dialog-actions>
        <button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>
        <button mat-button mat-dialog-close>close</button>
      </mat-dialog-actions>
</mat-step>

MainCompontent.ts

openModal() {
    this.inputs = [];
    this.http.getInputs().subscribe(
      data => {
        data.forEach(element => this.inputs.push(element));
      },
      (err) => {
        console.log(err);
      },
      () => {
        this.openAddDialog();
      });
  }

  openAddDialog() {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      inputValue1: 'test 1',
      inputValue2: 'test 2',
    };

    const dialogRef = this.dialog.open(ExampleDialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      console.log('Dialog was closed');
      console.log('result: ' + result);

      this.http.createResultinDB(result);
        .subscribe(subData => console.log(subData), error => console.log(error));
    });
  }

  getDeliveryPackageList(): Observable<any> {
    return this.http.get(`${this.baseUrl}`);
  }

Thanks a lot for your help.

Body:
The problem is that you have to add to your app.module.ts the entryComponents array with the name of your Dialog component as follow:

@NgModule({
  entryComponents: [
    ExampleDialogComponent
  ],
  declarations: [...],
.
.
.
})


问:
Send customer on-hold order notification once order is placed in Woocommerce 3.3
I have this issue. I using Woocommerce 3.3.3 in this moment in my site and noticed one weird issue. After customer placed order, their order is stuck on "On Hold" into Woocommerce orders.

and customer dont get any order confirmation mail. When go to order and move status on order from "On Hold" to "Processing" customer is getting Order Confirmation mail, that should be automatically. Searched, and found this "fix":

```<code>add_filter( ‘woocommerce_defer_transactional_emails’, ‘__return_false’ );
</code>```

to be placed into functions.php, but seems that dont changed nothing. Anyone with similar issue?

答:
Just to point out:

The solution @LoicTheAztec mentioned works:

```<code>add_action('woocommerce_new_order', 'new_order_on_hold_notification', 30, 1 );
function new_order_on_hold_notification( $order_id ) {
    $order = wc_get_order( $order_id );

    // Only for on hold new orders
    if( ! $order->has_status('on-hold') )
        return; // Exit

    // Send Customer On-Hold Order notification
    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
}
</code>```

However there's an issue with this solution, at the time woocommerce_new_orderhook is called the order hasn't been fully created yet, so as result in the email notification the order items are not displayed. Use the following hook instead:

```<code>    add_action('woocommerce_checkout_order_processed', 'new_order_on_hold_notification');
    function new_order_on_hold_notification( $order_id ) {
                    $order = wc_get_order( $order_id );

                    // Only for on hold new orders
                    if( ! $order->has_status('on-hold') )
                        return; // Exit

                    // Send Customer On-Hold Order notification
                    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
     }
</code>```

At the time woocommerce_checkout_order_processed is called the order items are already available for your email.

Body:
I have this issue. I using Woocommerce 3.3.3 in this moment in my site and noticed one weird issue. After customer placed order, their order is stuck on "On Hold" into Woocommerce orders.

and customer dont get any order confirmation mail. When go to order and move status on order from "On Hold" to "Processing" customer is getting Order Confirmation mail, that should be automatically. Searched, and found this "fix":

add_filter( ‘woocommerce_defer_transactional_emails’, ‘__return_false’ );

to be placed into functions.php, but seems that dont changed nothing. Anyone with similar issue?

Body:
Just to point out:

The solution @LoicTheAztec mentioned works:

add_action('woocommerce_new_order', 'new_order_on_hold_notification', 30, 1 );
function new_order_on_hold_notification( $order_id ) {
    $order = wc_get_order( $order_id );

    // Only for on hold new orders
    if( ! $order->has_status('on-hold') )
        return; // Exit

    // Send Customer On-Hold Order notification
    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
}

However there's an issue with this solution, at the time woocommerce_new_orderhook is called the order hasn't been fully created yet, so as result in the email notification the order items are not displayed. Use the following hook instead:

    add_action('woocommerce_checkout_order_processed', 'new_order_on_hold_notification');
    function new_order_on_hold_notification( $order_id ) {
                    $order = wc_get_order( $order_id );

                    // Only for on hold new orders
                    if( ! $order->has_status('on-hold') )
                        return; // Exit

                    // Send Customer On-Hold Order notification
                    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
     }

At the time woocommerce_checkout_order_processed is called the order items are already available for your email.


问:
router subscribe calls multiple time
With this code

ngOnInit() {
  this.router.events.subscribe((val) => {
    if (this.router.url.indexOf('page') > -1) {
      let id = this.activedRoute.snapshot.params['Id']
      this.busy = this.httpCall.get('/pub/page/GetPageById/' + id)
        .subscribe(data => {
          this.pages = <Page[]>data
        })

      console.log(id)
    }
  })
}
```

when I navigate to domain.com/#/en/page/13 it logs 13 as expected.

But when I navigate to the page which id is 27 it logs: 13 13 27.

When I navigate back to 13 log has: 27 27 13.

Why is it?

答:
This happens when you write "this.router.events" on ngOnInit or Constructor, For fixing this issue you should write it on other function like that:

```<code>onRouteChange () {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        if (this.router.url.indexOf('page') > -1) {
            let Id = this.activedRoute.snapshot.params['Id'];
            this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
                .subscribe(
                data => {
                    this.pages = <Page[]>data;
                });

            console.log(Id);
        }
      }
    })
  }
</code>```

but there is another issue in this which you should consider when you use "this.router.events.subscribe", everything you wrote down in this function happens when you navigate in pages so it better to use this line to prevent run it on every path changes:

```<code>import {Router, NavigationStart} from '@angular/router';

onRouteChange () {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        // this line
        if(event.url == 'your_page_path')
        if (this.router.url.indexOf('page') > -1) {
            let Id = this.activedRoute.snapshot.params['Id'];
            this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
                .subscribe(
                data => {
                    this.pages = <Page[]>data;
                });

            console.log(Id);
        }
      }
    })
  }
</code>```

Title: router subscribe calls multiple time

Body:
With this code

ngOnInit() {
  this.router.events.subscribe((val) => {
    if (this.router.url.indexOf('page') > -1) {
      let id = this.activedRoute.snapshot.params['Id']
      this.busy = this.httpCall.get('/pub/page/GetPageById/' + id)
        .subscribe(data => {
          this.pages = <Page[]>data
        })

      console.log(id)
    }
  })
}

when I navigate to domain.com/#/en/page/13 it logs 13 as expected.

But when I navigate to the page which id is 27 it logs: 13 13 27.

When I navigate back to 13 log has: 27 27 13.

Why is it?

Body:
This happens when you write "this.router.events" on ngOnInit or Constructor, For fixing this issue you should write it on other function like that:

onRouteChange () {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        if (this.router.url.indexOf('page') > -1) {
            let Id = this.activedRoute.snapshot.params['Id'];
            this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
                .subscribe(
                data => {
                    this.pages = <Page[]>data;
                });

            console.log(Id);
        }
      }
    })
  }

but there is another issue in this which you should consider when you use "this.router.events.subscribe", everything you wrote down in this function happens when you navigate in pages so it better to use this line to prevent run it on every path changes:

import {Router, NavigationStart} from '@angular/router';

onRouteChange () {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        // this line
        if(event.url == 'your_page_path')
        if (this.router.url.indexOf('page') > -1) {
            let Id = this.activedRoute.snapshot.params['Id'];
            this.busy = this.httpCall.get('/pub/page/GetPageById/' + Id)
                .subscribe(
                data => {
                    this.pages = <Page[]>data;
                });

            console.log(Id);
        }
      }
    })
  }


问:
How to proxy_pass to a sub path
I have a host with two containers:

nginx

check_mk

the check_mk interface is accessible by http://172.17.0.2:5000/cmk
I have proxy_pass rule set up in nginx:

```<code>server {
    listen 80;
    server_name cmk.domain.com;
    location / {
        proxy_pass         http://172.17.0.2:5000;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }
}
</code>```

When I hit the nginx on port 80 with cmk.domain.com/cmk it works.

What I want is that when hitting the server_name cmk.domain.com, the /cmk would be added automatically.
I tried doing  proxy_pass  http://172.17.0.2:5000/cmk; but then I get a page not found error.
What am I missing here?

答:
Try this</p>

```<code>server {
    listen 80;
    server_name cmk.domain.com;

    location /cmk {
        proxy_pass         http://172.17.0.2:5000;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }

    location / {
        return 301 http://cmk.domain.com/cmk$request_uri;
    }
}
</code>```

Title: How to proxy_pass to a sub path

Body:
I have a host with two containers:

nginx

check_mk

the check_mk interface is accessible by http://172.17.0.2:5000/cmk
I have proxy_pass rule set up in nginx:

server {
    listen 80;
    server_name cmk.domain.com;
    location / {
        proxy_pass         http://172.17.0.2:5000;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }
}

When I hit the nginx on port 80 with cmk.domain.com/cmk it works.

What I want is that when hitting the server_name cmk.domain.com, the /cmk would be added automatically.
I tried doing  proxy_pass  http://172.17.0.2:5000/cmk; but then I get a page not found error.
What am I missing here?

Body:
Try this

server {
    listen 80;
    server_name cmk.domain.com;

    location /cmk {
        proxy_pass         http://172.17.0.2:5000;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }

    location / {
        return 301 http://cmk.domain.com/cmk$request_uri;
    }
}


答:
You may try the following

```<code>dump($stringParts = array_values(array_filter(explode(" ", 'مقالة جديدة'))));

$slug = '';
foreach ($stringParts as $key =>  $string) {
    $hyphen = ($key < sizeof($stringParts) - 1) ? '-' : '';
    $slug .= $string . $hyphen;
}

dd($slug);
// "مقالة-جديدة"
</code>```

Check Working Demo

Title: Laravel and Arabic slugs

Body:
When creating a slug from a name, the slug is in English letters.

Example:

name = مقالة جديدة

slug = mk-l-gdyd

It should be: مقالة-جديدة

Any idea how to solve this issue? I'm using this package.

Model

class Post extends Model
{
    use HasSlug;

    protected $primarykey = 'id';

    protected $fillable = [
        'title', 'slug', 'body',
    ];

    protected $dates = [
        'created_at', 'updated_at'
    ];

    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('title')
            ->saveSlugsTo('slug');
    }
}

Body:
You may try the following

dump($stringParts = array_values(array_filter(explode(" ", 'مقالة جديدة'))));

$slug = '';
foreach ($stringParts as $key =>  $string) {
    $hyphen = ($key < sizeof($stringParts) - 1) ? '-' : '';
    $slug .= $string . $hyphen;
}

dd($slug);
// "مقالة-جديدة"

Check Working Demo


问:
How can I create a 3D surface plot in R where 3 variables are used for the coordinates and a 4th variable is used for coloring?
This is easy to do if you are trying to do a 3D scatter plot. Code below:

```<code>library(plotly)
library(tidyverse)

df = iris

plot_ly(df,
            x=df$Sepal.Length,
            y=df$Sepal.Width,
            z=df$Petal.Length,
            type="scatter3d",
            mode="markers",
            color=df$Petal.Width)
</code>```

The resulting output is:

I would like to make this a surface plot, but when I change the type to "surface", the image does not render and I get the following warning:

```<code>'surface' objects don't have these attributes: 'mode', 'marker'
</code>```

答:
For plotting a surface, plot_ly expects z to be a matrix. You can specify color with a surfacecolor matrix. plotly::schema()$traces$surface$meta$description has some useful information:

The data the describes the coordinates of the surface is set in z.
  Data in z should be a {2D array}. Coordinates in x and y can
  either be 1D {arrays} or {2D arrays} (e.g. to graph parametric
  surfaces). If not provided in x and y, the x and y coordinates are
  assumed to be linear starting at 0 with a unit step. The color scale
  corresponds to the z values by default. For custom color scales, use
  surfacecolor which should be a {2D array}, where its bounds can be
  controlled using cmin and cmax.

Body:
This is easy to do if you are trying to do a 3D scatter plot. Code below:

library(plotly)
library(tidyverse)

df = iris

plot_ly(df,
            x=df$Sepal.Length,
            y=df$Sepal.Width,
            z=df$Petal.Length,
            type="scatter3d",
            mode="markers",
            color=df$Petal.Width)

The resulting output is:

I would like to make this a surface plot, but when I change the type to "surface", the image does not render and I get the following warning:

'surface' objects don't have these attributes: 'mode', 'marker'