问:
user id and username not inserting with relationship
```<code>class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}
</code>```

This is Country Model

```<code>class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id','id');
    }
    public function history()
    {
        return $this->hasOne(UserHistory::class,'user_id','id');
    }
}
</code>```

This is User Model

```<code>class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $users = \App\User::with(['roles','profile'])->get();
        return view('dashboard.users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $roles = \App\Role::all();
        $countries = \App\Country::all();
        return view('dashboard.users.create',compact('countries','roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $user = [
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ];
        $user = \App\User::create($user);
               $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
        if ($request->hasFile('photo'))
         $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
     else
        $filename = "profiles/dummy.jpg";
    if ($user) {
        $profile = new \App\UserProfile([
            'user_id' => $user->id,
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);
        $user->profile()->save($profile);
        $user->roles()->attach($request->roles);
        return redirect()->route('users.index');
    }

}
</code>```

This is Controller

```<code>class UserProfile extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}
</code>```

This is UserProfile Model

```<code>@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf
    <div class="form-row align-item-center">
        <div class="col-md-12">
            <label for="inputUsername"> Name</label>
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">
        </div>
        <div class="col-md-12">
            <label for="inputName">Full Name</label>
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">
        </div>
        <div class="col-md-12">
            <label for="inputUserEmail">Email</label>
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">
        </div>
        <div class="col-md-12">
            <label for="inputPassword">Password</label>
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">
        </div>
        <div class="col-md-12">
            <label for="inputPhone">Phone</label>
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">
        </div>
        <div class="col-md-12">
            <label for="selectCountry">Select Country</label>
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 mt-3">
            <label for="inputCity">City</label>
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">
        </div>
        <div class="col-md-12">
            <label for="selectRoles">Select Roles</label>
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 my-3">
            <label for="inputFileName">Profile Image</label>
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">
        </div>
        <div class="col-md-12">
        <button type="submit" class="btn btn-primary mb-2">Add New User</button>
    </div>
</div>
</form>
@endsection
</code>```

This is create view

I have used this code with relationships when i create user and getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into user_profiles (user_id, city, country_id, photo, phone, updated_at, created_at) values (?, Karachi, 1, profiles/thumbnail_385.jpg, +923148790984, 2020-02-20 04:49:17, 2020-02-20 04:49:17))

答:
Try this:

```<code>    public function store(Request $request)
    {

        $filename = sprintf('thumbnail_%s.jpg', random_int(1, 1000));

        if ($request->hasFile('photo'))
            $filename = $request->file('photo')->storeAs('profiles', $filename, 'public');
        else
            $filename = "profiles/dummy.jpg";

        $user = \App\User::create([
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ])->profile()->create([
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);

        if ($user) {
            $user->roles()->attach($request->roles);
            return redirect()->route('users.index');
        } else {
            //redirect to error page
        }
    }
</code>```

Body:
class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}

This is Country Model

class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id','id');
    }
    public function history()
    {
        return $this->hasOne(UserHistory::class,'user_id','id');
    }
}

This is User Model

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $users = \App\User::with(['roles','profile'])->get();
        return view('dashboard.users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $roles = \App\Role::all();
        $countries = \App\Country::all();
        return view('dashboard.users.create',compact('countries','roles'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $user = [
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ];
        $user = \App\User::create($user);
               $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
        if ($request->hasFile('photo'))
         $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
     else
        $filename = "profiles/dummy.jpg";
    if ($user) {
        $profile = new \App\UserProfile([
            'user_id' => $user->id,
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);
        $user->profile()->save($profile);
        $user->roles()->attach($request->roles);
        return redirect()->route('users.index');
    }

}

This is Controller

class UserProfile extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}

This is UserProfile Model

@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf

             Name
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">

            Full Name
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">

            Email
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">

            Password
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">

            Phone
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">

            Select Country
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>

            City
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">

            Select Roles
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>

            Profile Image
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">

        <button type="submit" class="btn btn-primary mb-2">Add New User</button>

</form>
@endsection

This is create view

I have used this code with relationships when i create user and getting this error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into user_profiles (user_id, city, country_id, photo, phone, updated_at, created_at) values (?, Karachi, 1, profiles/thumbnail_385.jpg, +923148790984, 2020-02-20 04:49:17, 2020-02-20 04:49:17))

Body:
Try this:

    public function store(Request $request)
    {

        $filename = sprintf('thumbnail_%s.jpg', random_int(1, 1000));

        if ($request->hasFile('photo'))
            $filename = $request->file('photo')->storeAs('profiles', $filename, 'public');
        else
            $filename = "profiles/dummy.jpg";

        $user = \App\User::create([
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ])->profile()->create([
            'city' => $request->city,
            'country_id' => $request->country,
            'photo' => $filename,
            'phone' => $request->phone,
        ]);

        if ($user) {
            $user->roles()->attach($request->roles);
            return redirect()->route('users.index');
        } else {
            //redirect to error page
        }
    }


来源: stackexchange

问:
How to merge several csv file during a loop by joining columns on columns
here 's my problem. I have 100 files, they all have two columns: 'time_slope' and 'slope'. I would like to create a single file with everything in it. Here is an example:

```<code>-----file 1----
2001.1     10
2001.2     20
2001.3     12
2001.4      4
2001.5      1
2001.6     13

-----file 2----
2001.3     20
2001.4     15
2001.5     6

-----file 3----
2001.6     15
2001.7     15
2001.8     15
2001.9     20
2002.0     23

**The expected result is:**
------- output file ---------
date    file1 file2 file3
2001.1    10   NAN  NAN
2001.2    20   NAN  NAN
2001.3    12   NAN  NAN
2001.4     4    15  NAN
2001.5     1     6  NAN
2001.6    13   NAN   15
2001.7   NAN   NAN   15
2001.8   NAN   NAN   15
2001.9   NAN   NAN   20
2002.0   NAN   NAN   23
</code>```

Here is what I tried:

```<code>import pandas as pd
import os, glob
import numpy as np

filename_list = []

file_path = r"C:\Users\Path"
for file in glob.glob(path + "/*.csv"):
    filename_list.append(file)

from numpy import genfromtxt
df_ini = pd.read_csv('output.csv')         #IN FILE OUTPUT THERE ARE ALREADY TWO COLUMNS WITH VALUES
df_ini.columns=['time_slopes','slope']
for filename in filename_list:
    with open(filename, 'r') as f:
    # convert numpy array into DataFrame
    numpyarray = genfromtxt(f, delimiter=',')
    df = pd.DataFrame({'time_slopes':numpyarray[:, 0],'slope':numpyarray[:, 1]})
    # remove NaN values:
    df = df.dropna(how='all')
    # re-index file:
    df.reset_index(drop=True, inplace=True)
    # merge file:
    dfmerge = df_ini.merge(df,on='time_slopes',how='left')
    dfmerge.to_csv("output.csv", sep=',', index=False)
</code>```

This piece of code return only two columns the first one (from df_ini) and the last one (from file number 100)...during each iteration the last column is rewrited instead of behind added.
date    file1 file100
2001.1    10    NAN

Does anybody know how to solve this?
Thanks!

ContentLicense: CC BY-SA 4.0

Body:
here 's my problem. I have 100 files, they all have two columns: 'time_slope' and 'slope'. I would like to create a single file with everything in it. Here is an example:

-----file 1----
2001.1     10
2001.2     20
2001.3     12
2001.4      4
2001.5      1
2001.6     13

-----file 2----
2001.3     20
2001.4     15
2001.5     6

-----file 3----
2001.6     15
2001.7     15
2001.8     15
2001.9     20
2002.0     23

**The expected result is:**
------- output file ---------
date    file1 file2 file3
2001.1    10   NAN  NAN
2001.2    20   NAN  NAN
2001.3    12   NAN  NAN
2001.4     4    15  NAN
2001.5     1     6  NAN
2001.6    13   NAN   15
2001.7   NAN   NAN   15
2001.8   NAN   NAN   15
2001.9   NAN   NAN   20
2002.0   NAN   NAN   23

Here is what I tried:

import pandas as pd
import os, glob
import numpy as np

filename_list = []

file_path = r"C:\Users\Path"
for file in glob.glob(path + "/*.csv"):
    filename_list.append(file)

from numpy import genfromtxt
df_ini = pd.read_csv('output.csv')         #IN FILE OUTPUT THERE ARE ALREADY TWO COLUMNS WITH VALUES
df_ini.columns=['time_slopes','slope']
for filename in filename_list:
    with open(filename, 'r') as f:
    # convert numpy array into DataFrame
    numpyarray = genfromtxt(f, delimiter=',')
    df = pd.DataFrame({'time_slopes':numpyarray[:, 0],'slope':numpyarray[:, 1]})
    # remove NaN values:
    df = df.dropna(how='all')
    # re-index file:
    df.reset_index(drop=True, inplace=True)
    # merge file:
    dfmerge = df_ini.merge(df,on='time_slopes',how='left')
    dfmerge.to_csv("output.csv", sep=',', index=False)

This piece of code return only two columns the first one (from df_ini) and the last one (from file number 100)...during each iteration the last column is rewrited instead of behind added.
date    file1 file100
2001.1    10    NAN

Does anybody know how to solve this?
Thanks!

Body:
This may help you.

file_1 = pd.DataFrame({'date': [2001.1, 2001.2, 2001.3], 'slope': [10, 20, 12]})
file_2 = pd.DataFrame({'date': [2001.4, 2001.5, 2001.6], 'slope': [20, 15, 6]})
file_3 = pd.DataFrame({'date': [2001.6, 2001.7, 2001.8], 'slope': [30, 40, 90]})

df_list = [file_1, file_2, file_3]
for df in df_list:
    df.index = df['date']
    df.drop(['date'], axis=1, inplace=True)

final_df = pd.concat(df_list, axis=1, ignore_index=True)
final_df = final_df.reset_index()

print(final_df)

Output:

     date     0     1     2
0  2001.1  10.0   NaN   NaN
1  2001.2  20.0   NaN   NaN
2  2001.3  12.0   NaN   NaN
3  2001.4   NaN  20.0   NaN
4  2001.5   NaN  15.0   NaN
5  2001.6   NaN   6.0  30.0
6  2001.7   NaN   NaN  40.0
7  2001.8   NaN   NaN  90.0


问:
Android searchView with voice icon
In an android app, I want to implement a searchView like this

There are some requirements:

the SearchIcon and the text("搜索")are in the middle of the searchView

a voiceIcon is inside the right side of the searchview.

3.the searchView is expanded by default.

I try to use the android searchView component, but i can't move the searchIcon to the middle of the searchView and I dont konw how to add an voiceIcon.

How can I do this,Thanks.

答:
you can also replace the mic icon with your custom icon
 by adding this to ur search_view in xml

app:voiceIcon="@drawable/ic_mic

ContentLicense: CC BY-SA 3.0

Title: Android searchView with voice icon


问:
How do I insert a new TR into the MIDDLE of a HTML table using JQuery?
I know how to append a new row to a table using JQuery:

```<code>var newRow = $("<tr>..."</tr>");
$("#mytable tbody").append(newRow);
</code>```

The question is how do I create a new row that precedes some existing row.

答:
```<code>var newRow = $("<tr>...</tr>");
$("#idOfRowToInsertAfter").after(newRow);
</code>```

The key is knowing the id of the row you want to insert the new row after, or at least coming up with some selector syntax that will get you that row.

jQuery docs on after()

OwnerDisplayName: Decker

ContentLicense: CC BY-SA 2.5

Body:
I know how to append a new row to a table using JQuery:

var newRow = $("
..."
");
$("#mytable tbody").append(newRow);

The question is how do I create a new row that precedes some existing row.

Body:
var newRow = $("<tr>...</tr>");
$("#idOfRowToInsertAfter").after(newRow);

The key is knowing the id of the row you want to insert the new row after, or at least coming up with some selector syntax that will get you that row.

jQuery docs on after()

OwnerDisplayName: matt b


问:
Sendkeys("{BACKSPACE}") inserts "B" characters instead of backspacing
I have a TextBox declared in a Silverlight project with contents “123456” and then use the following code in a Coded UI test.  First it searches and clicks the TextBox to set focus, and then tries to delete characters.

```<code>currencyPage.ClickEditByAutomationId("textBox");
Keyboard.SendKeys("{END}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
</code>```

This is the resulting text in my TextBox: 123456BBBBB

What am I doing wrong?  XAML of the textbox:

答:
Try</p>

```<code>Keyboard.SendKeys("{BACK}");
</code>```

Body:
I have a TextBox declared in a Silverlight project with contents “123456” and then use the following code in a Coded UI test.  First it searches and clicks the TextBox to set focus, and then tries to delete characters.

currencyPage.ClickEditByAutomationId("textBox");
Keyboard.SendKeys("{END}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");
Keyboard.SendKeys("{BACKSPACE}");

This is the resulting text in my TextBox: 123456BBBBB

What am I doing wrong?  XAML of the textbox:

Body:
Try

Keyboard.SendKeys("{BACK}");


问:
How to get UITableViewCell object from indexPath in Swift?
I'm trying to get UITableViewCell object programmatically using Swift, so I wrote this code:

```<code>let cell:UITableViewCell = (UITableViewCell) UITableView.cellForRowAtIndexPath(indexPath.row)
</code>```

but getting compile error as:

Cannot convert value of type '(UITableViewCell).Type' to specified type 'UITableViewCell'

  Consecutive statements on a line must be separated by ';'

  Instance member 'cellForRowAtIndexPath' cannot be used on type 'UITableView'; did you mean to use a value of this type instead?

答:
Swift 5 Easy solution

```<code>//MARK:- Collection View
let cell = yourcollectionview.cellForItem(at: indexPath) as! YourCollectionViewCell
</code>```

Table View

```<code>let cell = tableView.cellForRow(at: indexPath) as! YourTableViewCell
</code>```

Usage

```<code>let tempImage = cell.yourImageView.image!
</code>```

Body:
I'm trying to get UITableViewCell object programmatically using Swift, so I wrote this code:

let cell:UITableViewCell = (UITableViewCell) UITableView.cellForRowAtIndexPath(indexPath.row)

but getting compile error as:

Cannot convert value of type '(UITableViewCell).Type' to specified type 'UITableViewCell'

  Consecutive statements on a line must be separated by ';'

  Instance member 'cellForRowAtIndexPath' cannot be used on type 'UITableView'; did you mean to use a value of this type instead?

Body:
Swift 5 Easy solution

//MARK:- Collection View
let cell = yourcollectionview.cellForItem(at: indexPath) as! YourCollectionViewCell

Table View

let cell = tableView.cellForRow(at: indexPath) as! YourTableViewCell

Usage

let tempImage = cell.yourImageView.image!


问:
list operations in python to combine
I have a scenario where I have two lists l1 & l2 as mentioned below:

```<code>l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]

l2 = [{'app_id': 9833, 'name': ABC}, {'app_id': 1036, 'name': CDE}, {'app_id': 1039, 'name': XYZ},{'app_id': 1030, 'name': JKL}]
</code>```

I am trying to check in this two list whether the app_id is common in both the lists if common then add the name value as well in the third list, so the desired output should be something like this.

```<code>l3 = [{'app_id': 9833, 'name': ABC, 'state': 0}, {'app_id': 1036, 'name': CDE, 'state': 1}, {'app_id': 1039, 'name': XYZ, 'state': 0},{'app_id': 1030, 'name': JKL, 'state': 0}]
</code>```

This is what I have tried and looks like the approach is wrong.

```<code>for key in l1:
    temp=key['app_id']
    for keynd in l2:
        if keynd[app_id]==temp:
            l3.append(keynd['name'])
</code>```

Can someone help me here on how to achieve this ?

答:
I have assumed that the names are also strings.
This should work:</p>

```<code>l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]
l2 = [{'app_id': 9833, 'name': 'ABC'}, {'app_id': 1036, 'name': 'CDE'}, {'app_id': 1039, 'name': 'XYZ'}, {'app_id': 1030, 'name': 'JKL'}]
l3 = []

for i in range(len(l1)):
    if l1[i]['app_id'] == l2[i]['app_id']:
        l3.append({'app_id': l1[i]['app_id'], 'name': l2[i]['name'], 'state': l1[i]['state']})

print(l3)
</code>```

Title: list operations in python to combine

Body:
I have a scenario where I have two lists l1 & l2 as mentioned below:

l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]

l2 = [{'app_id': 9833, 'name': ABC}, {'app_id': 1036, 'name': CDE}, {'app_id': 1039, 'name': XYZ},{'app_id': 1030, 'name': JKL}]

I am trying to check in this two list whether the app_id is common in both the lists if common then add the name value as well in the third list, so the desired output should be something like this.

l3 = [{'app_id': 9833, 'name': ABC, 'state': 0}, {'app_id': 1036, 'name': CDE, 'state': 1}, {'app_id': 1039, 'name': XYZ, 'state': 0},{'app_id': 1030, 'name': JKL, 'state': 0}]

This is what I have tried and looks like the approach is wrong.

for key in l1:
    temp=key['app_id']
    for keynd in l2:
        if keynd[app_id]==temp:
            l3.append(keynd['name'])

Can someone help me here on how to achieve this ?

Body:
I have assumed that the names are also strings.
This should work:

l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]
l2 = [{'app_id': 9833, 'name': 'ABC'}, {'app_id': 1036, 'name': 'CDE'}, {'app_id': 1039, 'name': 'XYZ'}, {'app_id': 1030, 'name': 'JKL'}]
l3 = []

for i in range(len(l1)):
    if l1[i]['app_id'] == l2[i]['app_id']:
        l3.append({'app_id': l1[i]['app_id'], 'name': l2[i]['name'], 'state': l1[i]['state']})

print(l3)


问:
What are the ways to protect javascript code
Is there any way to prevent a web app from being stored and operated from local file system.

The app has proprietary front end work-space, built with JS & many other libraries, which must be available for usage only if the user is logged in over the domain with active internet.

If any user attempt to save the page and relevant files to local file system and try opening the workspace, it must be prevented.

Is there any possibility to achieve this

答:
If someone really wants to look at the code that's being run, there's no way to prevent it, because it's running on their machine, and they can do anything they want with their machine, including examining network requests (such as from their browser, or from their OS).

If there is information that the client should not be able to access under any circumstances, the only solution is to not send that information to the client in the first place.

Now, there are methods to check whether a script is being run from a webpage or a file, eg:

```<code>if (window.location.href.startsWith('file:')) {
  throw new Error();
}
</code>```

But the user may still examine the script and tamper with it if they desire.

Body:
If someone really wants to look at the code that's being run, there's no way to prevent it, because it's running on their machine, and they can do anything they want with their machine, including examining network requests (such as from their browser, or from their OS).

If there is information that the client should not be able to access under any circumstances, the only solution is to not send that information to the client in the first place.

Now, there are methods to check whether a script is being run from a webpage or a file, eg:

if (window.location.href.startsWith('file:')) {
  throw new Error();
}

But the user may still examine the script and tamper with it if they desire.


问:
How to get short URL link in android using Firebase Dynamic Links?
I'm trying to share a link which would redirect a user to YouTube link if clicked on a desktop browser and redirect to the app if clicked on Android.The links are working fine but I'm getting the deep link instead of short link

```<code>Uri uri = getIntent().getData();
String path = uri.getPath();
</code>```

Is there a way to get the short link in android ?

答:
I have just found a workaround this problem passing params in my deep link.
For e.g.

```<code>https://www.youtube.com/watch?v=y0brSA1cyzw&deeplinkparam=somevalue
</code>```

So, the deep link in above url is

```<code>https://www.youtube.com/watch?v=y0brSA1cyzw
</code>```

and the param that I want to pass is appended by &deeplinkparam=somevalue

Body:
I'm trying to share a link which would redirect a user to YouTube link if clicked on a desktop browser and redirect to the app if clicked on Android.The links are working fine but I'm getting the deep link instead of short link

Uri uri = getIntent().getData();
String path = uri.getPath();

Is there a way to get the short link in android ?

Body:
I have just found a workaround this problem passing params in my deep link.
For e.g.

https://www.youtube.com/watch?v=y0brSA1cyzw&deeplinkparam=somevalue

So, the deep link in above url is

https://www.youtube.com/watch?v=y0brSA1cyzw

and the param that I want to pass is appended by &deeplinkparam=somevalue


问:
Close Navigation Drawer on Back Button Pressed in Flutter
I have a material designed Navigation Drawer in my very first flutter app. This work's fine but I did't find any way to close the Navigation Drawer on Back Button Press if it's open when use WillPopScope to show AlertDialog. The application just show AlertDialog instead of close the Drawer when back press. I want Drawer should close if already open and show AlertDialog otherwise.

```<code>@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: onBackPressed,
    child: Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      drawer: Drawer(
      ),
      body: Center(
        child: Text("Home"),
      ),
    ),
  );
}
</code>```

onBackPressed shows dialog to close the app.

```<code>Future<bool> onBackPressed() {
  return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) => AlertDialog(
            title: Text("Do you want to exit?"),
            actions: <Widget>[
              FlatButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text("No")),
              FlatButton(
                  onPressed: () => Navigator.pop(context, true),
                  child: Text("Yes"))
            ],
          ));
}
</code>```

Can anybody guide me how can I achieve this?

答:
You can copy paste run full code below

Step 1: You need Scaffold key to controll Drawer so you need GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

Step 2: In onWillPop You can check isDrawerOpen and do Navigator.pop

code snippet

```<code> GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_key.currentState.isDrawerOpen) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Scaffold(
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("My App Page");
        //return false;
      },
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: "test",),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;
  GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_key.currentState.isDrawerOpen) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Scaffold(
        key: _key,
        appBar: AppBar(title: Text(title)),
        body: Center(child: Text('My Page!')),
        drawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Drawer Header'),
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
              ),
              ListTile(
                title: Text('page 2'),
                onTap: () {
                  Navigator.push(
                      context, new MaterialPageRoute(builder: (context) => Page2()));
                },
              ),
              ListTile(
                title: Text('Item 2'),
                onTap: () {
                  // Update the state of the app
                  // ...
                  // Then close the drawer
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("Page2");
        _popNavigationWithResult(context, 'from_back');
        return false;
      },
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _popNavigationWithResult(context, 'from_button');
          },
        ),
        body: Container(
          child: Center(
            child: Text('Page 2',
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold)),
          ),
        ),
      ),
    );
  }

  void _popNavigationWithResult(BuildContext context, dynamic result) {
    Navigator.pop(context, result);
  }
}
</code>```

Body:
I have a material designed Navigation Drawer in my very first flutter app. This work's fine but I did't find any way to close the Navigation Drawer on Back Button Press if it's open when use WillPopScope to show AlertDialog. The application just show AlertDialog instead of close the Drawer when back press. I want Drawer should close if already open and show AlertDialog otherwise.

@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: onBackPressed,
    child: Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      drawer: Drawer(
      ),
      body: Center(
        child: Text("Home"),
      ),
    ),
  );
}

onBackPressed shows dialog to close the app.

Future<bool> onBackPressed() {
  return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) => AlertDialog(
            title: Text("Do you want to exit?"),
            actions: <Widget>[
              FlatButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text("No")),
              FlatButton(
                  onPressed: () => Navigator.pop(context, true),
                  child: Text("Yes"))
            ],
          ));
}

Can anybody guide me how can I achieve this?

Body:
You can copy paste run full code below

Step 1: You need Scaffold key to controll Drawer so you need GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

Step 2: In onWillPop You can check isDrawerOpen and do Navigator.pop

code snippet

 GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_key.currentState.isDrawerOpen) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Scaffold(

working demo

full code

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("My App Page");
        //return false;
      },
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: "test",),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;
  GlobalKey<ScaffoldState> _key = new GlobalKey<ScaffoldState>();

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_key.currentState.isDrawerOpen) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Scaffold(
        key: _key,
        appBar: AppBar(title: Text(title)),
        body: Center(child: Text('My Page!')),
        drawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Drawer Header'),
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
              ),
              ListTile(
                title: Text('page 2'),
                onTap: () {
                  Navigator.push(
                      context, new MaterialPageRoute(builder: (context) => Page2()));
                },
              ),
              ListTile(
                title: Text('Item 2'),
                onTap: () {
                  // Update the state of the app
                  // ...
                  // Then close the drawer
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        print("Page2");
        _popNavigationWithResult(context, 'from_back');
        return false;
      },
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _popNavigationWithResult(context, 'from_button');
          },
        ),
        body: Container(
          child: Center(
            child: Text('Page 2',
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold)),
          ),
        ),
      ),
    );
  }

  void _popNavigationWithResult(BuildContext context, dynamic result) {
    Navigator.pop(context, result);
  }
}


问:
How to sort a Vector of Vectors?
In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

```<code> Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);
</code>```

Then sort the variables in one of the columns e.g. Column2.

Thank you

答: Vectors are maybe not the best representation of your table. Have a look at Glazed Lists.</p>

Title: How to sort a Vector of Vectors?

Body:
In Java I am wondering how to sort vectors of vectors on a particular column where one vector is used as a row and one vector is used to hold all the row vectors e.g.

 Vector row = new Vector();
    Vector main = new Vector();

    row.add("Column1");
    row.add("Column2");
    row.add("Column3");

    main.add(row);

Then sort the variables in one of the columns e.g. Column2.

Thank you


问:
Avoid using persitence layer on model for aggregate children

Problem

Suppose the following DDD model.

```<code>class Building {
    Room[] rooms

    addRoom(String name)  {
        room = new Room(name) // Model
        db.create(room)       // Persistence!!!
        rooms.add(room)       // Model
    }
}

class Room {
    String name
}
</code>```

We can see that Building is the AR and is responsible for creating its aggregate Room. My problem is when I try to Create Room in the database following the CRUD model. At some moment, one can create a room, so my model will call Building and it will create the Room. However, my model shouldn't use the persistence layer.

Note that you can add rooms, which means that you can have a Building in the database inconsistent with the actual model. So I would have to update my Building too.

If I move the Creation of Room for the database outside the model, then, when I update my Building in the database, the Room must already exist in the database. But Room is an aggregate child of Building and shouldn't be accessed by classes other than Building.

Question

How do I Create the Room in the database outside the model keeping the Room as aggregate child?

答:
In your scenario, if I didn't get it wrong, Building is the aggregate root that holds a collection of Room entities (remember that aggregate itself is an entity too).

A repository that looks something like the following should be responsible for persistence operations (e.g. create, find, update, etc.) of your aggregate root, that is Building.

public interface Repositoy<Building> {

    Building findById(String buildingId);

    void store(Building building);
}
```

<p>You have correctly pointed out that domain operations (e.g. add room in your case) must happen through the aggregate root. However, the aggregate root (or any other entity) <em>must not take up persistence responsibilities</em> (as you purported: <code>db.create(room)</code>).</p>

<p>Client interacts with the domain through a <em>domain service</em> or an <em>application service</em>. Those, in turn, retrieves an aggregate root through its repository, makes necessary modification, and stores the <em>entire aggregate</em> in a single transaction. Consequently, upon each successful transaction, you always have a <em>consistent aggregate</em> with its children in database, nothing to worry about missing parent, child, etc.</p>

<pre class="lang-java prettyprint-override"><code>public class SomeDomainOrApplicationService {

    private Repositoy<Building> repository;

    public void createRoomServiceMethod(String buildingId) {

        // retrieve aggregate root
        Building building = repository.findById(buildingId);

        // modify aggregate
        String roomName; // assign room name
        building.addRoom(roomName);

        // store aggregate
        repository.store(building);
    }
}
</code>```

Body:
Problem

Suppose the following DDD model.

class Building {
    Room[] rooms

    addRoom(String name)  {
        room = new Room(name) // Model
        db.create(room)       // Persistence!!!
        rooms.add(room)       // Model
    }
}

class Room {
    String name
}

We can see that Building is the AR and is responsible for creating its aggregate Room. My problem is when I try to Create Room in the database following the CRUD model. At some moment, one can create a room, so my model will call Building and it will create the Room. However, my model shouldn't use the persistence layer.

Note that you can add rooms, which means that you can have a Building in the database inconsistent with the actual model. So I would have to update my Building too.

If I move the Creation of Room for the database outside the model, then, when I update my Building in the database, the Room must already exist in the database. But Room is an aggregate child of Building and shouldn't be accessed by classes other than Building.

Question

How do I Create the Room in the database outside the model keeping the Room as aggregate child?

Body:
In your scenario, if I didn't get it wrong, Building is the aggregate root that holds a collection of Room entities (remember that aggregate itself is an entity too).

A repository that looks something like the following should be responsible for persistence operations (e.g. create, find, update, etc.) of your aggregate root, that is Building.

public interface Repositoy<Building> {

    Building findById(String buildingId);

    void store(Building building);
}

You have correctly pointed out that domain operations (e.g. add room in your case) must happen through the aggregate root. However, the aggregate root (or any other entity) must not take up persistence responsibilities (as you purported: db.create(room)).

Client interacts with the domain through a domain service or an application service. Those, in turn, retrieves an aggregate root through its repository, makes necessary modification, and stores the entire aggregate in a single transaction. Consequently, upon each successful transaction, you always have a consistent aggregate with its children in database, nothing to worry about missing parent, child, etc.

public class SomeDomainOrApplicationService {

    private Repositoy<Building> repository;

    public void createRoomServiceMethod(String buildingId) {

        // retrieve aggregate root
        Building building = repository.findById(buildingId);

        // modify aggregate
        String roomName; // assign room name
        building.addRoom(roomName);

        // store aggregate
        repository.store(building);
    }
}


问:
How to add button tint programmatically
In the new AppCompat library, we can tint the button this way:

```<code><Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />
</code>```

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

答:
If you are using Kotlin and Material Design, you can change color of your MaterialButton like this:

```<code>myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))
</code>```

You can improve it even better by creating an extension function for your MaterialButton in order to make you code more readable and your coding little more convenient:

```<code>fun MaterialButton.changeColor(color: Int) {
    this.background.setTintList(ContextCompat.getColorStateList(context, color))
}
</code>```

Then, you can use your function everywhere like this:

```<code>myButton.changeColor(R.color.myColor)
</code>```

Title: How to add button tint programmatically

Body:
In the new AppCompat library, we can tint the button this way:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

Body:
If you are using Kotlin and Material Design, you can change color of your MaterialButton like this:

myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))

You can improve it even better by creating an extension function for your MaterialButton in order to make you code more readable and your coding little more convenient:

fun MaterialButton.changeColor(color: Int) {
    this.background.setTintList(ContextCompat.getColorStateList(context, color))
}

Then, you can use your function everywhere like this:

myButton.changeColor(R.color.myColor)


问:
Play one video at a time on html page
I have a html page.
I have used a video tag for playing video online
I have used two video tags,
But when I play both videos, then
both videos play at same time

I want a solution that, if I play one video and then click on the second one then the first one should be paused and the second one starts playing.
Any help would be appreciated.

答:
Add

```<code>onplay="stopOtherMedia(this)"
</code>```

on all audio and video tags

```<code>function stopOtherMedia(element) {
    $("audio").not(element).each(function(index, audio) {
        audio.pause();
    });

    $("video").not(element).each(function(index, video) {
        video.pause();
    });

}
</code>```

Title: Play one video at a time on html page

Body:
Add

onplay="stopOtherMedia(this)"

on all audio and video tags

function stopOtherMedia(element) {
    $("audio").not(element).each(function(index, audio) {
        audio.pause();
    });

    $("video").not(element).each(function(index, video) {
        video.pause();
    });

}


问:
Extract the user-defined Error message from exception
Inside my stored procedure, i just checked a particular condition and i'll throw Exception if that condition fails. like below,

```<code>Raise Exception '%', 'Hello world';
</code>```

It is working fine, But the error message Hello world also comes with some other error code like stuffs like below in my front end,

```<code>DA00014:ERROR: P0001: Hello world
|___________________|
        |
      I really dont want this part to get displayed in the front end.
</code>```

Is there any proper way available to filter out/Extract the right message from thrown exception.?

[Note: Please don't suggest me to do some string manipulations.]

```<code>DBMS      : POSTGRESQL 9.0.3
Driver    : Npgsql 1.0
Front End : VB.net
</code>```

答:
This should work:</p>

```<code>Catch ex As Exception

    lblMsg.Text = ex.Message.Replace("ERROR: P0001: ", "")

End Try
</code>```

Body:
Inside my stored procedure, i just checked a particular condition and i'll throw Exception if that condition fails. like below,

Raise Exception '%', 'Hello world';

It is working fine, But the error message Hello world also comes with some other error code like stuffs like below in my front end,

DA00014:ERROR: P0001: Hello world
|___________________|
        |
      I really dont want this part to get displayed in the front end.

Is there any proper way available to filter out/Extract the right message from thrown exception.?

[Note: Please don't suggest me to do some string manipulations.]

DBMS      : POSTGRESQL 9.0.3
Driver    : Npgsql 1.0
Front End : VB.net

Body:
This should work:

Catch ex As Exception

    lblMsg.Text = ex.Message.Replace("ERROR: P0001: ", "")

End Try


问:
isolated scope data not displaying in directive template
I am building a custom Angular directive to display pagination across my application.

I'm using isolated scope to pass totalNoOfRecords but it's not getting displayed. Any help will be appreciated

Here's my code what I tried so far

Template where I'm calling the directive:

<pagination totalData="111"></pagination>
```

<p>Directive.js</p>

```function pagination() {
    return {
        restrict: 'EA',
        templateUrl: 'template/directives/pagination.html',
        scope: {
            totalData: '@',
        },
        link: dirPaginationControlsLinkFn
    };
}
```

<p>Directive Template</p>

```
   of {{totalData}}

```

答:
In AngularJS, the scope bindings should be in camelCase in JS and in kebab-case in HTML.

You have to change your HTML from

```<code><pagination totalData="111"></pagination>
</code>```

to

```<code><pagination total-data="111"></pagination>
</code>```

Body:
I am building a custom Angular directive to display pagination across my application.

I'm using isolated scope to pass totalNoOfRecords but it's not getting displayed. Any help will be appreciated

Here's my code what I tried so far

Template where I'm calling the directive:

<pagination totalData="111"></pagination>

Directive.js

function pagination() {
    return {
        restrict: 'EA',
        templateUrl: 'template/directives/pagination.html',
        scope: {
            totalData: '@',
        },
        link: dirPaginationControlsLinkFn
    };
}

Directive Template

   of {{totalData}}

Body:
In AngularJS, the scope bindings should be in camelCase in JS and in kebab-case in HTML.

You have to change your HTML from

<pagination totalData="111"></pagination>

to

<pagination total-data="111"></pagination>


问:
add scrollbar to popup window in IE after opening window
i want to add scrollbar to popup window after opening it.
In FireFox there is a property 'window.scrollbars', but IE doesn't have such property,
how can i add scrollbar in IE using javascript?
Thanks.</p>

答:
Use css overflow:scroll; property.

To access it by JavaScript, use:

```<code>document.body.style.overflow = 'scroll';
</code>```

Body:
Use css overflow:scroll; property.

To access it by JavaScript, use:

document.body.style.overflow = 'scroll';


问:
How does Translate To and/or the Coordinate System work in Xamarin Forms
When images are clicked, a dropdown window comes and the user can click on one of the many options of where to put the image. However, the second image appears to be off by about 35 and the third image seems about 70 lower. I am using the Image.TranslateTo. How does the coordinate system work in Xamarin Forms and is there a better way to put images in a specific place on the coordinate system?</p>

答:
About Translation method , there are three parameters inside it .

```<code>image.TranslateTo (TranslationX, TranslationY, millisecond);
</code>```

TranslationX : Gets or sets the X translation delta of the element.

TranslationY : Gets or sets the Y translation delta of the element.

millisecond : how much time need to finish animation (milliseconds).

That means parameter TranslationX and TranslationY just indicate the Offset of View, not the coordinate .

If I have the xaml code as follow :

```<code><Image Source="icon.png" BackgroundColor="Accent" HorizontalOptions="Center" VerticalOptions="Center">
    <Image.GestureRecognizers>
        <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" NumberOfTapsRequired="1"/>
    </Image.GestureRecognizers>
</Image>
<Image x:Name="imageone" Source="imageone.png" BackgroundColor="Aqua" HorizontalOptions="Center" WidthRequest="50" HeightRequest="50"/>
<Image x:Name="imagetwo" Source="imagetwo.png" BackgroundColor="Beige" HeightRequest="50" />
<Image x:Name="imagethree" Source="imagethree.png" BackgroundColor="BurlyWood" HeightRequest="50" />
</code>```

The screen shows :(For better to explain, I set the HeightRequest and BackgroundColor for Image.)

You wiil see from above code , height of imageone/imagetwo/imagethree all is 50 . And I will get the X of imageone first after running . It's 180 .Then I will write code for TapGestureRecognizer_Tapped method as follow to translate imageone and imagetwo.

```<code>private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
    Console.WriteLine("Tap" + imageone.X +"---"+ imageone.Y);
    imageone.TranslateTo(-180, 0, 1000);
    imagetwo.TranslateTo(0, 100, 1000);
}
</code>```

The effect as follow :

And the printed logs of Console is :

```<code>14:34:36.621 I/mono-stdout( 4499): Tap180---290.714285714286
14:34:41.171 I/mono-stdout( 4499): Tap180---290.714285714286
</code>```

Then you will found there are two conclusions :

First , TranslationX and TranslationY just indicate the Offset of View .

Second , Translation method will not modify the coordinate of View .

Body:
About Translation method , there are three parameters inside it .

image.TranslateTo (TranslationX, TranslationY, millisecond);

TranslationX : Gets or sets the X translation delta of the element.

TranslationY : Gets or sets the Y translation delta of the element.

millisecond : how much time need to finish animation (milliseconds).

That means parameter TranslationX and TranslationY just indicate the Offset of View, not the coordinate .

If I have the xaml code as follow :

<Image Source="icon.png" BackgroundColor="Accent" HorizontalOptions="Center" VerticalOptions="Center">
    <Image.GestureRecognizers>
        <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" NumberOfTapsRequired="1"/>
    </Image.GestureRecognizers>
</Image>
<Image x:Name="imageone" Source="imageone.png" BackgroundColor="Aqua" HorizontalOptions="Center" WidthRequest="50" HeightRequest="50"/>
<Image x:Name="imagetwo" Source="imagetwo.png" BackgroundColor="Beige" HeightRequest="50" />
<Image x:Name="imagethree" Source="imagethree.png" BackgroundColor="BurlyWood" HeightRequest="50" />

The screen shows :(For better to explain, I set the HeightRequest and BackgroundColor for Image.)

You wiil see from above code , height of imageone/imagetwo/imagethree all is 50 . And I will get the X of imageone first after running . It's 180 .Then I will write code for TapGestureRecognizer_Tapped method as follow to translate imageone and imagetwo.

private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
    Console.WriteLine("Tap" + imageone.X +"---"+ imageone.Y);
    imageone.TranslateTo(-180, 0, 1000);
    imagetwo.TranslateTo(0, 100, 1000);
}

The effect as follow :

And the printed logs of Console is :

14:34:36.621 I/mono-stdout( 4499): Tap180---290.714285714286
14:34:41.171 I/mono-stdout( 4499): Tap180---290.714285714286

Then you will found there are two conclusions :

First , TranslationX and TranslationY just indicate the Offset of View .

Second , Translation method will not modify the coordinate of View .


问:
jquery to validate phone number
I want to validate phone numbers like (123) 456-7890 or 1234567890
 How should be the 'matches' condition be written in the following code?</p>

```<code>form.validate({

    rules: {

       phoneNumber: {matches:"[0-9]+",minlength:10, maxlength:10}
</code>```

Title: jquery to validate phone number

Body:
I want to validate phone numbers like (123) 456-7890 or 1234567890
 How should be the 'matches' condition be written in the following code?

form.validate({

    rules: {

       phoneNumber: {matches:"[0-9]+",minlength:10, maxlength:10}

Body:
I tried the below solution and it work fine for me.

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

Tried below phone format:

+(123) 456 7899

(123) 456 7899

(123).456.7899

(123)-456-7899

123-456-7899

123 456 7899

1234567899


问:
In Java8, when will the merge function be triggered in Collectors.toMap?
I want to transform a Hashmap<String,Long> to a Treemap, in order to sort its key by string.length (I can't simply use treemap.addAll because I have may other logic when insert and I want to use java8)

The code is below. But when keys with same length exist in the initial Hashmap, it will trigger the merge function which throws Exception(I intent to do it because there won't be same string in my case). I wonder why the merge function be triggered since the JavaDoc of toMap() says "If the mapped keys contains duplicates (according to Object#equals(Object)), the value mapping function is applied to each equal element, and results are merged using the provided merging function."  I think that in my code the  "mapped keys" should be the entry in hashMap mapped by Entry::getKey but not string.length() in the TreeMap comparator. i.e. "abc" != "def". So it shouldn't trigger the merge. But?? What the hell?

```<code>public class TestToMap {

    public static Map<String, Long> map1 = new HashMap<String, Long>() {
        {
            put("abc", 123L);
            put("def", 456L);
        }
    };

    public static void main(String[] args) {
        Map<String, Long> priceThresholdMap = map1.entrySet().stream()
            .collect(Collectors.toMap(Entry::getKey,
                                      Entry::getValue,
                                      throwingMerger(),
                                      () -> new TreeMap<String, Long>(
                                          (a, b) -> {
                                              return a.length() - b.length();
                                          }))); // this will trigger merge function, why?
        //() -> new TreeMap<String, Long>(Comparator.comparingInt(String::length).thenComparing(String::compareTo))));  // but this won't trigger merge function

    }

    private static <T> BinaryOperator<T> throwingMerger() {
        return (u, v) -> {
            throw new IllegalStateException(String.format("priceThresholdMap has duplicate v1 %s,v2 %s", u, v));
        };
    }
}
</code>```

答:
Of course it should trigger a merge. The merge function is used to merge values having identical keys in the output Map, which in your case is a TreeMap.

In a TreeMap, keys are identical if the Comparator's compare method returns 0, so two keys having the same length are deemed identical, and their corresponding values should be merged.

Note that your Comparator causes the output TreeMap not to implement the Map interface correctly, since the ordering it defines is not consistent with equals():

Note that the ordering maintained by a tree map, like any sorted map, and
  whether or not an explicit comparator is provided, must be consistent
  with equals if this sorted map is to correctly implement the
  Map interface

(From TreeMap Javadoc)

If you want to sort the String's by length, you can still be consistent with equals:

Instead of

```<code>return a.length() - b.length()
</code>```

use

```<code>return a.length() == b.length() ? a.compareTo(b) : Integer.compare(a.length(),b.length())
</code>```

Now unequal Strings having the same length will be ordered lexicographically, while String having different length will be ordered by length.

Body:
I want to transform a Hashmap<String,Long> to a Treemap, in order to sort its key by string.length (I can't simply use treemap.addAll because I have may other logic when insert and I want to use java8)

The code is below. But when keys with same length exist in the initial Hashmap, it will trigger the merge function which throws Exception(I intent to do it because there won't be same string in my case). I wonder why the merge function be triggered since the JavaDoc of toMap() says "If the mapped keys contains duplicates (according to Object#equals(Object)), the value mapping function is applied to each equal element, and results are merged using the provided merging function."  I think that in my code the  "mapped keys" should be the entry in hashMap mapped by Entry::getKey but not string.length() in the TreeMap comparator. i.e. "abc" != "def". So it shouldn't trigger the merge. But?? What the hell?

public class TestToMap {

    public static Map<String, Long> map1 = new HashMap<String, Long>() {
        {
            put("abc", 123L);
            put("def", 456L);
        }
    };

    public static void main(String[] args) {
        Map<String, Long> priceThresholdMap = map1.entrySet().stream()
            .collect(Collectors.toMap(Entry::getKey,
                                      Entry::getValue,
                                      throwingMerger(),
                                      () -> new TreeMap<String, Long>(
                                          (a, b) -> {
                                              return a.length() - b.length();
                                          }))); // this will trigger merge function, why?
        //() -> new TreeMap<String, Long>(Comparator.comparingInt(String::length).thenComparing(String::compareTo))));  // but this won't trigger merge function

    }

    private static <T> BinaryOperator<T> throwingMerger() {
        return (u, v) -> {
            throw new IllegalStateException(String.format("priceThresholdMap has duplicate v1 %s,v2 %s", u, v));
        };
    }
}

Body:
Of course it should trigger a merge. The merge function is used to merge values having identical keys in the output Map, which in your case is a TreeMap.

In a TreeMap, keys are identical if the Comparator's compare method returns 0, so two keys having the same length are deemed identical, and their corresponding values should be merged.

Note that your Comparator causes the output TreeMap not to implement the Map interface correctly, since the ordering it defines is not consistent with equals():

Note that the ordering maintained by a tree map, like any sorted map, and
  whether or not an explicit comparator is provided, must be consistent
  with equals if this sorted map is to correctly implement the
  Map interface

(From TreeMap Javadoc)

If you want to sort the String's by length, you can still be consistent with equals:

Instead of

return a.length() - b.length()

use

return a.length() == b.length() ? a.compareTo(b) : Integer.compare(a.length(),b.length())

Now unequal Strings having the same length will be ordered lexicographically, while String having different length will be ordered by length.


问:
What is the best way to request input from user
I want to request info from user. See example below:

```<code>Your Name: |_________|
      Age: |_________|
  Address: |_________|
</code>```

What is the best way to code the above in HTML?

It is best to implement it in div. Have left and right div for label and input

It is best to implement it in table

答:
Form styling via CSS is clean and practical, and has the added benefit of using HTML markup in the way it was intended.

Your form HTML can be written like this:

```<code><form>
    <label>Your Name:</label>
    <input type="text" name="your_name" /><br />
    <label>Age:</label>
    <input type="text" name="age" /><br />
    <label>Address:</label>
    <input type="text" name="address" /><br />
</form>
</code>```

Your CSS will look like this:

```<code><style type="text/css">
    form label {
      float: left;
      width: 100px;
      text-align: right;
      }

    form input {
      float: left;
      width: 335px;
      text-align: left;
      }
    form br {
      clear: both;
    }
</style>
</code>```

Tables are designed for tabular data. If you would expect to see your data in a spreadsheet, you can use it in an HTML table. Otherwise, CSS should be used to style your layout.

Body:
I want to request info from user. See example below:

Your Name: |_________|
      Age: |_________|
  Address: |_________|

What is the best way to code the above in HTML?

It is best to implement it in div. Have left and right div for label and input

It is best to implement it in table

Body:
Form styling via CSS is clean and practical, and has the added benefit of using HTML markup in the way it was intended.

Your form HTML can be written like this:

<form>
    <label>Your Name:</label>
    <input type="text" name="your_name" /><br />
    <label>Age:</label>
    <input type="text" name="age" /><br />
    <label>Address:</label>
    <input type="text" name="address" /><br />
</form>

Your CSS will look like this:

<style type="text/css">
    form label {
      float: left;
      width: 100px;
      text-align: right;
      }

    form input {
      float: left;
      width: 335px;
      text-align: left;
      }
    form br {
      clear: both;
    }
</style>

Tables are designed for tabular data. If you would expect to see your data in a spreadsheet, you can use it in an HTML table. Otherwise, CSS should be used to style your layout.


问:
EMF2DOMAdapterImpl_ERROR_0 Websphere Application Server WAS (V8.5) DeploymentDescriptorLoadException: WEB-INF/web.xml
Websphere Application Server V 8.5 fails to startup with certain web.xml structure.

Current DOCTYPE uses http://java.sun.com/dtd/web-app_2_3.dtd .

答:
This error mainly occurs when there is a problem with the web.xml deployment descriptor.
This problem is caused because of invalid tag in the web.xml which can be due to multiple different things such as:

There should be no duplicate tages for

session-config

welcome-file-list

jsp-config

login-config

locale-encoding-mapping-list

Web.xml is not supposed to have multiple url-pattern under one servlet-mapping tag in deployment descriptor. If you have around 3 - 4 url-patterns under one servlet-mapping, move this to multiple servlet mapping containing one url-patterns.

For more debug information you can check the logs in AppServer\profiles\AppSrv01\logs\server1\SystemErr


问:
PHP can't display Chinese character
I just migrated my codebase to a new server. Previously, the user saves Chinese characters to the MariaDB database. In the database it saves as below:

This is the text when I copy the content from database: å¹¿å·žå‡Œè¿è´§è¿ä»£ç†æœåŠ¡æœ‰é™å…¬å

My old server using Ubuntu, PHP 5.5.9-1 & Apache, it shows the character correctly in frontend:

In the new server, I am using Centos, PHP 7.2.27 with Apache & Nginx it shows:

I have tried many things but still cannot fix. I am not sure if it PHP issue or server issue. Anyone can help. Thank you.

答:
uses utf-8 charset, include below lines at top of php page</p>

```<code><?php
header('Content-type: text/html; charset=utf-8');
?>
</code>```

Title: PHP can't display Chinese character

Body:
uses utf-8 charset, include below lines at top of php page

<?php
header('Content-type: text/html; charset=utf-8');
?>


问:
What is the algorithm used in sort method in dart?
I found out that dart language has a built-in sort method in List class and I would like to know what is the algorithm they used in this method and what is the Big O notation of it?</p>

答:
I found out that dart language has a built-in sort method in List class and I would like to know what is the algorithm they used in this method and what is the Big O notation of it?

If we take a look inside the SDK we can find the following implementation of the sort method on List:

```<code>  void sort([int compare(E a, E b)]) {
    Sort.sort(this, compare ?? _compareAny);
  }
</code>```

https://github.com/dart-lang/sdk/blob/b86c6e0ce93e635e3434935e31fac402bb094705/sdk/lib/collection/list.dart#L340-L342

Which just forward the sorting to the following internal helper class:

https://github.com/dart-lang/sdk/blob/a75ffc89566a1353fb1a0f0c30eb805cc2e8d34c/sdk/lib/internal/sort.dart

Which has the following comment about the sorting algorithm:

/**
 * Dual-Pivot Quicksort algorithm.
 *
 * This class implements the dual-pivot quicksort algorithm as presented in
 * Vladimir Yaroslavskiy's paper.
 *
 * Some improvements have been copied from Android's implementation.
 */
```

<p>This sorting algorithm is actually the same used in Java (at least Java 7):</p>

<p>http://www.docjar.com/html/api/java/util/DualPivotQuicksort.java.html</p>

<p>Here we can see that the O-notation is mostly <code>O(n log(n))</code>:</p>

<pre class="lang-none prettyprint-override"><code>    * This class implements the Dual-Pivot Quicksort algorithm by
    * Vladimir Yaroslavskiy, Jon Bentley, and Josh Bloch. The algorithm
    * offers O(n log(n)) performance on many data sets that cause other
    * quicksorts to degrade to quadratic performance, and is typically
    * faster than traditional (one-pivot) Quicksort implementations.
</code>```

For more details you can read the paper by the designer of the Dual-Pivot Quicksort algorithm:

https://web.archive.org/web/20151002230717/http://iaroslavski.narod.ru/quicksort/DualPivotQuicksort.pdf

But, also please note that Dart also has the following constant:

```<code>  // When a list has less then [:_INSERTION_SORT_THRESHOLD:] elements it will
  // be sorted by an insertion sort.
  static const int _INSERTION_SORT_THRESHOLD = 32;
...
  static void _doSort<E>(
      List<E> a, int left, int right, int compare(E a, E b)) {
    if ((right - left) <= _INSERTION_SORT_THRESHOLD) {
      _insertionSort(a, left, right, compare);
    } else {
      _dualPivotQuicksort(a, left, right, compare);
    }
  }
</code>```

So for small lists, it makes more sense to use the traditional insertion sort algorithm which has a worst case big O of О(n^2). But since the input are very small, it is properly faster than the Dual-Pivot Quicksort algorithm.

Body:
I found out that dart language has a built-in sort method in List class and I would like to know what is the algorithm they used in this method and what is the Big O notation of it?

If we take a look inside the SDK we can find the following implementation of the sort method on List:

  void sort([int compare(E a, E b)]) {
    Sort.sort(this, compare ?? _compareAny);
  }

https://github.com/dart-lang/sdk/blob/b86c6e0ce93e635e3434935e31fac402bb094705/sdk/lib/collection/list.dart#L340-L342

Which just forward the sorting to the following internal helper class:

https://github.com/dart-lang/sdk/blob/a75ffc89566a1353fb1a0f0c30eb805cc2e8d34c/sdk/lib/internal/sort.dart

Which has the following comment about the sorting algorithm:

/**
 * Dual-Pivot Quicksort algorithm.
 *
 * This class implements the dual-pivot quicksort algorithm as presented in
 * Vladimir Yaroslavskiy's paper.
 *
 * Some improvements have been copied from Android's implementation.
 */

This sorting algorithm is actually the same used in Java (at least Java 7):

http://www.docjar.com/html/api/java/util/DualPivotQuicksort.java.html

Here we can see that the O-notation is mostly O(n log(n)):

    * This class implements the Dual-Pivot Quicksort algorithm by
    * Vladimir Yaroslavskiy, Jon Bentley, and Josh Bloch. The algorithm
    * offers O(n log(n)) performance on many data sets that cause other
    * quicksorts to degrade to quadratic performance, and is typically
    * faster than traditional (one-pivot) Quicksort implementations.

For more details you can read the paper by the designer of the Dual-Pivot Quicksort algorithm:

https://web.archive.org/web/20151002230717/http://iaroslavski.narod.ru/quicksort/DualPivotQuicksort.pdf

But, also please note that Dart also has the following constant:

  // When a list has less then [:_INSERTION_SORT_THRESHOLD:] elements it will
  // be sorted by an insertion sort.
  static const int _INSERTION_SORT_THRESHOLD = 32;
...
  static void _doSort<E>(
      List<E> a, int left, int right, int compare(E a, E b)) {
    if ((right - left) <= _INSERTION_SORT_THRESHOLD) {
      _insertionSort(a, left, right, compare);
    } else {
      _dualPivotQuicksort(a, left, right, compare);
    }
  }

So for small lists, it makes more sense to use the traditional insertion sort algorithm which has a worst case big O of О(n^2). But since the input are very small, it is properly faster than the Dual-Pivot Quicksort algorithm.


问:
Blurry path edges in IE & Edge when SVG is preceded by an element not sized in pixels
I am trying to draw a sharp rectangle using SVG <path>.

I have a problem that the top and bottom edge of the shape have an unexpected antialiasing when rendered in IE and Edge. The problem happens only if the <path> element is preceded by another element that has dimensions expressed in different unit than px.

The problem does not appear to
 or SVG <rect> elements. Only SVG <path> seem to be affected.

I appreciate any help, how do I make the <path> render crisply without changeing the surrounding
s?

I can simulate the same problem with a simple SVG object and:

a native button: https://jsfiddle.net/7btjcy18/

a font sized with REM units: https://jsfiddle.net/ptzs71ba/

The following screenshot shows the problem. Chrome on the left, Edge on the right. On a zoom, you can see the blurry borders highlighted with the arrows.

#div1 {
  font-size: 1.2rem;
  margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1">REM font size</div>

<svg xmlns="http://www.w3.org/2000/svg">
  <path d="M 0 0 L 300 0 L 300 100 L 0 100" />
</svg></code>```

答:
The issue is related with svg being in coordinates like 31.2 (not exactly on pixel line). I also found a similar thread. According to the accepted answer, you should design the svg to let its shapes are on pixel boundaries(especially the horizontal and vertical parts of the shapes).

Any time your shape passes through the middle of pixels, you will get grey pixels due to the anti-aliasing that 2D renderers use.

I think it's the not integer value 1.2rem which leads to the svg's coordinates not being on pixel line. I try with integer value and the issue is gone in IE and Edge:

#div1 {
  font-size: 2rem;
  margin-bottom: 20px;
}

#div2 {
  width: 300px;
  height: 100px;
  background: black;
  margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1">REM font size</div>

<div id="div2"></div>
<svg xmlns="http://www.w3.org/2000/svg">
   <path d="M 0 0 L 300 0 L 300 100 L 0 100" />
</svg></code>```

Body:
I am trying to draw a sharp rectangle using SVG <path>.

I have a problem that the top and bottom edge of the shape have an unexpected antialiasing when rendered in IE and Edge. The problem happens only if the <path> element is preceded by another element that has dimensions expressed in different unit than px.

The problem does not appear to
 or SVG <rect> elements. Only SVG <path> seem to be affected.

I appreciate any help, how do I make the <path> render crisply without changeing the surrounding
s?

I can simulate the same problem with a simple SVG object and:

a native button: https://jsfiddle.net/7btjcy18/

a font sized with REM units: https://jsfiddle.net/ptzs71ba/

The following screenshot shows the problem. Chrome on the left, Edge on the right. On a zoom, you can see the blurry borders highlighted with the arrows.

#div1 {
  font-size: 1.2rem;
  margin-bottom: 20px;
}

REM font size

<svg xmlns="http://www.w3.org/2000/svg">
  <path d="M 0 0 L 300 0 L 300 100 L 0 100" />
</svg>

Body:
The issue is related with svg being in coordinates like 31.2 (not exactly on pixel line). I also found a similar thread. According to the accepted answer, you should design the svg to let its shapes are on pixel boundaries(especially the horizontal and vertical parts of the shapes).

Any time your shape passes through the middle of pixels, you will get grey pixels due to the anti-aliasing that 2D renderers use.

I think it's the not integer value 1.2rem which leads to the svg's coordinates not being on pixel line. I try with integer value and the issue is gone in IE and Edge:

#div1 {
  font-size: 2rem;
  margin-bottom: 20px;
}

#div2 {
  width: 300px;
  height: 100px;
  background: black;
  margin-bottom: 20px;
}

<div id="div1">REM font size</div>

<div id="div2"></div>
<svg xmlns="http://www.w3.org/2000/svg">
   <path d="M 0 0 L 300 0 L 300 100 L 0 100" />
</svg>


问:
list operations in python to combine
I have a scenario where I have two lists l1 & l2 as mentioned below:

```<code>l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]

l2 = [{'app_id': 9833, 'name': ABC}, {'app_id': 1036, 'name': CDE}, {'app_id': 1039, 'name': XYZ},{'app_id': 1030, 'name': JKL}]
</code>```

I am trying to check in this two list whether the app_id is common in both the lists if common then add the name value as well in the third list, so the desired output should be something like this.

```<code>l3 = [{'app_id': 9833, 'name': ABC, 'state': 0}, {'app_id': 1036, 'name': CDE, 'state': 1}, {'app_id': 1039, 'name': XYZ, 'state': 0},{'app_id': 1030, 'name': JKL, 'state': 0}]
</code>```

This is what I have tried and looks like the approach is wrong.

```<code>for key in l1:
    temp=key['app_id']
    for keynd in l2:
        if keynd[app_id]==temp:
            l3.append(keynd['name'])
</code>```

Can someone help me here on how to achieve this ?

答:
Alternate solution: merging them using dataframe:

```<code>import pandas as pd
l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]
l2 = [{'app_id': 9833, 'name': 'ABC'}, {'app_id': 1036, 'name': 'CDE'}, {'app_id': 1039, 'name': 'XYZ'},{'app_id': 1030, 'name': 'JKL'}]
L1 = pd.DataFrame(l1)
L2 = pd.DataFrame(l2)
print(pd.merge(L1, L2, on = 'app_id').to_dict(orient = 'records'))
</code>```

output:

```<code>[{'app_id': 9833, 'name': 'ABC', 'state': 0},
 {'app_id': 1036, 'name': 'CDE', 'state': 1},
 {'app_id': 1039, 'name': 'XYZ', 'state': 0},
 {'app_id': 1030, 'name': 'JKL', 'state': 0}]
</code>```

Title: list operations in python to combine

Body:
I have a scenario where I have two lists l1 & l2 as mentioned below:

l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]

l2 = [{'app_id': 9833, 'name': ABC}, {'app_id': 1036, 'name': CDE}, {'app_id': 1039, 'name': XYZ},{'app_id': 1030, 'name': JKL}]

I am trying to check in this two list whether the app_id is common in both the lists if common then add the name value as well in the third list, so the desired output should be something like this.

l3 = [{'app_id': 9833, 'name': ABC, 'state': 0}, {'app_id': 1036, 'name': CDE, 'state': 1}, {'app_id': 1039, 'name': XYZ, 'state': 0},{'app_id': 1030, 'name': JKL, 'state': 0}]

This is what I have tried and looks like the approach is wrong.

for key in l1:
    temp=key['app_id']
    for keynd in l2:
        if keynd[app_id]==temp:
            l3.append(keynd['name'])

Can someone help me here on how to achieve this ?

Body:
Alternate solution: merging them using dataframe:

import pandas as pd
l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]
l2 = [{'app_id': 9833, 'name': 'ABC'}, {'app_id': 1036, 'name': 'CDE'}, {'app_id': 1039, 'name': 'XYZ'},{'app_id': 1030, 'name': 'JKL'}]
L1 = pd.DataFrame(l1)
L2 = pd.DataFrame(l2)
print(pd.merge(L1, L2, on = 'app_id').to_dict(orient = 'records'))

output:

[{'app_id': 9833, 'name': 'ABC', 'state': 0},
 {'app_id': 1036, 'name': 'CDE', 'state': 1},
 {'app_id': 1039, 'name': 'XYZ', 'state': 0},
 {'app_id': 1030, 'name': 'JKL', 'state': 0}]


问:
Keycloak - Add/Remove Realm role from a user using APIcalls
passing userRepresentation.id
to  keycloakServerURL + "/auth/admin/realms/XXXX/users/"+userId+"/role-mappings/realm"
I get these roles for a certain user...

```<code>[
    {
        "id": "xxxxxxx-1faf-4604-832a-fa7ab7eb4344",
        "name": "uma_authorization",
        "description": "${role_uma_authorization}",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    },
    {
        "id": "xxxxxxx-ad9f-444e-adf4-be11ab7a3d98",
        "name": "member_paid",
        "description": "Membership Paid",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    },
    {
        "id": "xxxxx-2d73-48a8-844d-a953cb570270",
        "name": "offline_access",
        "description": "${role_offline-access}",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    }
]
</code>```

I cannot figure out which API I am supposed to use to add/remove a role from/to the User.

Please can you advise what is the API I need to use

The best I can find is this one below but I don't know what the params (Path and request property should be)...

```<code>public void removeRole(JsonObject userToken, String clientId, String role) throws IOException {

    /auth/admin/realms/XXXX/groups/" + role + "/role-mappings/clients/" + clientId);

    ...
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");

    con.setRequestProperty("id", clientId);
    con.setRequestProperty("name", role);
    ....
</code>```

答:
Endpoints are

Get Role Mappings:

GET /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Add Role Mappings:

POST /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Delete Role Mappings:

DELETE /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Example Add Role

You have a role e.g. named testrole with the id dc5572a5-b7e0-4c4b-b841-dc88108df70f (you see it in the url when you have opened the keycloak admin GUI, or you fetch it with some other RestAPI Request)

Now we have a Request of Type POST to the endpoint /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm with a body of type application/json and the following body-value

```<code>[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]
</code>```

After successful execution you get a response with HTTP-Code 204 => The testrole - role mapping is applied to this user

Example Curl Request

```<code>curl --request POST \
  --url http://localhost/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm \
  --header 'authorization: Bearer eyJh......h3RLw' \
  --header 'content-type: application/json' \
  --data '[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]'
</code>```

If you want to delete it again, just send the same request (same body) but with the HTTP-method DELETE instead of POST

Please let me now if this solved your issue

Body:
passing userRepresentation.id
to  keycloakServerURL + "/auth/admin/realms/XXXX/users/"+userId+"/role-mappings/realm"
I get these roles for a certain user...

[
    {
        "id": "xxxxxxx-1faf-4604-832a-fa7ab7eb4344",
        "name": "uma_authorization",
        "description": "${role_uma_authorization}",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    },
    {
        "id": "xxxxxxx-ad9f-444e-adf4-be11ab7a3d98",
        "name": "member_paid",
        "description": "Membership Paid",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    },
    {
        "id": "xxxxx-2d73-48a8-844d-a953cb570270",
        "name": "offline_access",
        "description": "${role_offline-access}",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    }
]

I cannot figure out which API I am supposed to use to add/remove a role from/to the User.

Please can you advise what is the API I need to use

The best I can find is this one below but I don't know what the params (Path and request property should be)...

public void removeRole(JsonObject userToken, String clientId, String role) throws IOException {

    /auth/admin/realms/XXXX/groups/" + role + "/role-mappings/clients/" + clientId);

    ...
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");

    con.setRequestProperty("id", clientId);
    con.setRequestProperty("name", role);
    ....

Body:
Endpoints are

Get Role Mappings:

GET /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Add Role Mappings:

POST /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Delete Role Mappings:

DELETE /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Example Add Role

You have a role e.g. named testrole with the id dc5572a5-b7e0-4c4b-b841-dc88108df70f (you see it in the url when you have opened the keycloak admin GUI, or you fetch it with some other RestAPI Request)

Now we have a Request of Type POST to the endpoint /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm with a body of type application/json and the following body-value

[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]

After successful execution you get a response with HTTP-Code 204 => The testrole - role mapping is applied to this user

Example Curl Request

curl --request POST \
  --url http://localhost/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm \
  --header 'authorization: Bearer eyJh......h3RLw' \
  --header 'content-type: application/json' \
  --data '[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]'

If you want to delete it again, just send the same request (same body) but with the HTTP-method DELETE instead of POST

Please let me now if this solved your issue


问:
How to access input value in multiple component?
I have 2 components :  headerComponent and searchPageComponent.

    Whatever the value we enter on header component search bar, the search page component should get the value.

header.component.html

```<code><form class="form-inline md-form form-sm">
          <input class="form-control form-control-sm mr-3 w-75" id="searchString" type="text"
             placeholder="Search" [(ngModel)]="searchValue" name="searchString" (ngModelChange)="onChange($event)">
          <button class="headerSearchbarBtn" id="btnSearch" routerLink="/searchResult">
              <span class="headerSearchbarIcon"></span>
           </button>
       </form>
</code>```

header.component.ts

```<code>export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
          this.searchValue = $event;
         }
       }
</code>```

Search.component.ts

```<code>export class SearchComponent implements  OnInit {
        ngOnInit() {
          console.log(this.searchValue); // 'this.searchValue' => value should come from header.compomnent.ts
        }
      }
</code>```

There is no parent child relation here, I want to know how the data is passed from one component to other,
    and Why cant we directly access the input field box value in different components in Angular?

答:
You need to use BehaviorSubject for without parent and child relation components.
This link will help to you: https://stackblitz.com/edit/angular-behaviorsubject-example?file=src%2Fapp%2Fone%2Fone.component.html</p>

Body:
I have 2 components :  headerComponent and searchPageComponent.

    Whatever the value we enter on header component search bar, the search page component should get the value.

header.component.html

<form class="form-inline md-form form-sm">
          <input class="form-control form-control-sm mr-3 w-75" id="searchString" type="text"
             placeholder="Search" [(ngModel)]="searchValue" name="searchString" (ngModelChange)="onChange($event)">
          <button class="headerSearchbarBtn" id="btnSearch" routerLink="/searchResult">

           </button>
       </form>

header.component.ts

export class HeaderComponent implements OnInit {
        searchValue: string;
        constructor(private router: Router) { }
        ngOnInit() {
         }
         onChange($event) {
          this.searchValue = $event;
         }
       }

Search.component.ts

export class SearchComponent implements  OnInit {
        ngOnInit() {
          console.log(this.searchValue); // 'this.searchValue' => value should come from header.compomnent.ts
        }
      }

There is no parent child relation here, I want to know how the data is passed from one component to other,
    and Why cant we directly access the input field box value in different components in Angular?


问:
Best practices for fetching and displaying many amount of data
As the title said, I'm implementing a webpage which display many chart and table with .net

(note: i dont have prior experience with .net, but i do have experience with other language. so its not that hard for me to do the implementation. The thing is I want to know whether what I'm doing is "correct" or not)

So, this page suppose to display bunch of chart and table which have different set of data. Currently I'm implementing it with MVC where the controller fetch all the data at once, and then return the view with an object that saving all those data.

it goes something like this:

Model:

```<code>public class AViewModel
{
    Public List<ClassofData1> DataForTable1 { get; set; }
    Public List<ClassofData2> DataForTable2 { get; set; }
    Public List<ClassofData3> DataForChart1 { get; set; }
    Public List<ClassofData4> DataForChart2 { get; set; }
    ... //repeat for dozen of time :)
}
</code>```

controller:

```<code>public class AController : Controller
{
    public ActionResult Index()
    {
        AViewModel DataforView = mew AViewModel();

        DataforView.DataForTable1 = Fetch1(); //im oversimplifying here, but it basically goes like this
        DataforView.DataForTable2 = Fetch2();
        DataforView.DataForChart1 = Fetch3();
        DataforView.DataForChart2 = Fetch4();
        ... //repeat for another dozen of time :)

        return View("Index", DataforView);
    }
}
</code>```

And then display everything on a HTML page.

Is it okay to implement it like that? loading all those data into a single viewmodel and "dump" it all on the HTML page.

Or should i make bunch of API which the HTML page call one by one to fetch those data, instead of loading everything at once in the index controller just like i did?

答:
You need A piginating. Here is an example https://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/

In short, you should execute Sorted requests (By default by ID as example).

Your action should see like this:

```<code>ActionResult Search(string query, int startIndex, int pageSize) {...}
</code>```

Your response shoud be like this:

```<code>public interface IPagedList<T> : IList<T>
{
    int PageCount { get; }
    int TotalItemCount { get; }
    int PageIndex { get; }
    int PageNumber { get; }
    int PageSize { get; }
    bool HasPreviousPage { get; }
    bool HasNextPage { get; }
    bool IsFirstPage { get; }
    bool IsLastPage { get; }
}
</code>```

So, by PageNumber and PageSize you can calculate start and end index of elements. To select like this please use

```<code>var page = source.Skip(startIndex).Take(pageSize);
</code>```

Body:
As the title said, I'm implementing a webpage which display many chart and table with .net

(note: i dont have prior experience with .net, but i do have experience with other language. so its not that hard for me to do the implementation. The thing is I want to know whether what I'm doing is "correct" or not)

So, this page suppose to display bunch of chart and table which have different set of data. Currently I'm implementing it with MVC where the controller fetch all the data at once, and then return the view with an object that saving all those data.

it goes something like this:

Model:

public class AViewModel
{
    Public List<ClassofData1> DataForTable1 { get; set; }
    Public List<ClassofData2> DataForTable2 { get; set; }
    Public List<ClassofData3> DataForChart1 { get; set; }
    Public List<ClassofData4> DataForChart2 { get; set; }
    ... //repeat for dozen of time :)
}

controller:

public class AController : Controller
{
    public ActionResult Index()
    {
        AViewModel DataforView = mew AViewModel();

        DataforView.DataForTable1 = Fetch1(); //im oversimplifying here, but it basically goes like this
        DataforView.DataForTable2 = Fetch2();
        DataforView.DataForChart1 = Fetch3();
        DataforView.DataForChart2 = Fetch4();
        ... //repeat for another dozen of time :)

        return View("Index", DataforView);
    }
}

And then display everything on a HTML page.

Is it okay to implement it like that? loading all those data into a single viewmodel and "dump" it all on the HTML page.

Or should i make bunch of API which the HTML page call one by one to fetch those data, instead of loading everything at once in the index controller just like i did?

Body:
You need A piginating. Here is an example https://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/

In short, you should execute Sorted requests (By default by ID as example).

Your action should see like this:

ActionResult Search(string query, int startIndex, int pageSize) {...}

Your response shoud be like this:

public interface IPagedList<T> : IList<T>
{
    int PageCount { get; }
    int TotalItemCount { get; }
    int PageIndex { get; }
    int PageNumber { get; }
    int PageSize { get; }
    bool HasPreviousPage { get; }
    bool HasNextPage { get; }
    bool IsFirstPage { get; }
    bool IsLastPage { get; }
}

So, by PageNumber and PageSize you can calculate start and end index of elements. To select like this please use

var page = source.Skip(startIndex).Take(pageSize);