问:
Slow performance in populating DataGridView with large data
I am using a BindingSource control (reference here) to populate my DataGridView control. There are around 1000+ records populating on it. I am using threading to do so. The DataGridView performs very slow in this case.

I tried to set DoubleBuffered property to true, RowHeadersWidthSizeMode to disabled, AutoSizeColumnsMode to none. But still the same behavior.

How can I improve the performance of the Grid?

答:
I had to disable auto-sizing in a few places to see the greatest improvement in performance. In my case, I had auto-size modes enabled for AutoSizeRowsMode, AutoSizeColumnsMode, and ColumnHeadersHeightSizeMode. So I had to disable each of these before binding the data to the DataGridView:

```<code>dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

// ... Bind the data here ...

// Set the DataGridView auto-size modes back to their original settings.
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
</code>```

Body:
I had to disable auto-sizing in a few places to see the greatest improvement in performance. In my case, I had auto-size modes enabled for AutoSizeRowsMode, AutoSizeColumnsMode, and ColumnHeadersHeightSizeMode. So I had to disable each of these before binding the data to the DataGridView:

dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

// ... Bind the data here ...

// Set the DataGridView auto-size modes back to their original settings.
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;


来源: stackexchange

问:
Androidx and exoplayer
i try add exoplayer and AndroidX in may project  and got this error.

error

Program type already present:
  android.support.v4.media.MediaBrowserCompat$CustomActionCallback

Message{kind=ERROR, text=Program type already present:
  android.support.v4.media.MediaBrowserCompat$CustomActionCallback,
  sources=[Unknown source file], tool name=Optional.of(D8)}

gradle.properties

```<code>android.useAndroidX=true
android.enableJetifier=true
</code>```

build.gradle

```<code>dependencies {
//support library
implementation 'com.google.android.material:material:1.0.0-rc01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0-rc01'
implementation 'androidx.appcompat:appcompat:1.0.0-rc01'
implementation 'androidx.cardview:cardview:1.0.0-rc01'
implementation 'androidx.appcompat:appcompat:1.0.0-rc01'
implementation 'androidx.recyclerview:recyclerview:1.0.0-rc01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
//android architector componet
implementation "androidx.room:room-runtime:2.0.0-rc01"
kapt "androidx.room:room-compiler:2.0.0-rc01"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0-rc01"

//exo player
implementation 'com.google.android.exoplayer:exoplayer:2.8.4'
....
}
</code>```

答: AndroidX is supported 'natively' since ExoPlayer 2.10.* (without using android.useAndroidX=true and android.enableJetifier=true)</p>

ContentLicense: CC BY-SA 4.0

Title: Androidx and exoplayer

Body:
i try add exoplayer and AndroidX in may project  and got this error.

error

Program type already present:
  android.support.v4.media.MediaBrowserCompat$CustomActionCallback

Message{kind=ERROR, text=Program type already present:
  android.support.v4.media.MediaBrowserCompat$CustomActionCallback,
  sources=[Unknown source file], tool name=Optional.of(D8)}

gradle.properties

android.useAndroidX=true
android.enableJetifier=true

build.gradle

dependencies {
//support library
implementation 'com.google.android.material:material:1.0.0-rc01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0-rc01'
implementation 'androidx.appcompat:appcompat:1.0.0-rc01'
implementation 'androidx.cardview:cardview:1.0.0-rc01'
implementation 'androidx.appcompat:appcompat:1.0.0-rc01'
implementation 'androidx.recyclerview:recyclerview:1.0.0-rc01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
//android architector componet
implementation "androidx.room:room-runtime:2.0.0-rc01"
kapt "androidx.room:room-compiler:2.0.0-rc01"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0-rc01"

//exo player
implementation 'com.google.android.exoplayer:exoplayer:2.8.4'
....
}


问:
how to handle xml data in javascript
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

```<code>$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

the returned xml data looks like:

```<code><DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...
</code>```

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

```<code>success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}
</code>```

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

答:
You can use the jquery xml parsing.

http://api.jquery.com/jQuery.parseXML/

So in your Success function.

```<code>success: function(data) {
    //xmlDoc = $.parseXML( data);
    $xml = $( data);
    $userName = $xml.find('USERNAME');
    var uName = $userName.text();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to handle xml data in javascript

Body:
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

the returned xml data looks like:

<DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

Body:
You can use the jquery xml parsing.

http://api.jquery.com/jQuery.parseXML/

So in your Success function.

success: function(data) {
    //xmlDoc = $.parseXML( data);
    $xml = $( data);
    $userName = $xml.find('USERNAME');
    var uName = $userName.text();
}


问:
Differences between SeriesCollection and FullSeriesCollection
I am trying to clean some auto generated code and I am rather new with the series functionality in excel. So in many websites/forums I found people using a lot more SeriesCollection instead of my generated code using FullSeriesCollection.

My code is filtering some stuff and then it is setting the x axis values of a chart so it is doing that:

.ChartObjects("Voltage").Chart.FullSeriesCollection(1).XValues = "=Parametric_Sheet!D:D"

I'm trying to know if this code is ok or not or if I can clean it.

答:
Sure someone else will give more info.

At least one difference is seriesCollection is backwards compatible across Excel version.

Your code is fine for newer Excel versions but if you want to ensure compatibility across then use seriesCollection instead.


问:
What's the correct way to handle removing a potentially busy file in NodeJS?
I have a NodeJS server managing some files. It's going to watch for a known filename from an external process and, once received, read it and then delete it. However, sometimes it's attempted to be read/deleted before the file has "unlocked" from previous use so likely will fail occasionally. What I'd like to do is retry this file asap, either as soon as it's finished or continuously at a fast pace.

I'd rather avoid a long sleep where possible, because this needs to be handled ASAP and every second counts.

```<code>fs.watchFile(intput_json_file, {interval: 10}, function(current_stats, previous_stats) {

                var json_data = "";
                try {
                    var file_cont = fs.readFileSync(input_json_file); // < TODO: async this
                    json_data = JSON.parse(file_cont.toString());
                    fs.unlink(input_json_file);
                } catch (error) {
                    console.log("The JSON in the could not be parsed. File will continue to be watched.");
                    console.log(error);
                    return;
                }

                // Else, this has loaded properly.
                fs.unwatchFile(input_json_file);

                // ... do other things with the file's data.

}

// set a timeout for the file watching, just in case
setTimeout(fs.unwatchFile, CLEANUP_TIMEOUT, input_json_file);
</code>```

I  expect "EBUSY: resource busy or locked" to turn up occasionally, but fs.watchFile isn't always called when the file is unlocked.

I thought of creating a function and then calling it with a delay of 1-10ms, where it could call itself if that fails too, but that feels like a fast route to a... cough stack overflow.

I'd also like to steer clear of synchronous methods so that this scales nicely, but being relatively new to NodeJS all the callbacks are starting to turn into a maze.

答: May be it will be over for this story, but you can create own fs with full control. In this case other programs will write data directly to your program. Just search by word fuse and fuse-binding

Body:
I have a NodeJS server managing some files. It's going to watch for a known filename from an external process and, once received, read it and then delete it. However, sometimes it's attempted to be read/deleted before the file has "unlocked" from previous use so likely will fail occasionally. What I'd like to do is retry this file asap, either as soon as it's finished or continuously at a fast pace.

I'd rather avoid a long sleep where possible, because this needs to be handled ASAP and every second counts.

fs.watchFile(intput_json_file, {interval: 10}, function(current_stats, previous_stats) {

                var json_data = "";
                try {
                    var file_cont = fs.readFileSync(input_json_file); // < TODO: async this
                    json_data = JSON.parse(file_cont.toString());
                    fs.unlink(input_json_file);
                } catch (error) {
                    console.log("The JSON in the could not be parsed. File will continue to be watched.");
                    console.log(error);
                    return;
                }

                // Else, this has loaded properly.
                fs.unwatchFile(input_json_file);

                // ... do other things with the file's data.

}

// set a timeout for the file watching, just in case
setTimeout(fs.unwatchFile, CLEANUP_TIMEOUT, input_json_file);

I  expect "EBUSY: resource busy or locked" to turn up occasionally, but fs.watchFile isn't always called when the file is unlocked.

I thought of creating a function and then calling it with a delay of 1-10ms, where it could call itself if that fails too, but that feels like a fast route to a... cough stack overflow.

I'd also like to steer clear of synchronous methods so that this scales nicely, but being relatively new to NodeJS all the callbacks are starting to turn into a maze.


问:
Cordova In app browser App Transport Security
I am trying to load content in an In App Browser from my local server ( using httpd plugin ). the web page is coming from a https, while the local server is loading of course a http.

I am testing on an Iphone x IOS 12. Using adobe Build

Tried:

```<code><access origin='*' allows-arbitrary-loads-in-media='true' allows-arbitrary-loads-in-web-content='true' allows-local-networking='true' />

<edit-config target="NSAllowsArbitraryLoads" file="*-Info.plist" mode="merge">

<true />

</edit-config>

<plugin name="cordova-plugin-transport-security" source="npm" />
</code>```

Error:

```<code>[blocked] The page at https://somewebpage was not allowed to run insecure content from http://127.0.0.1:8080/javascripts/somejsfile.js.
</code>```

none of these worked. anyone have a suggestion?

答:
Another solution for android that doesn't change the security settings of the browser, is to use "https://cdvfile/assets/www/cordova.js" instead of "cdvfile://localhost/assets/www/cordova.js", and add the following line to the remapUri method in FileUtils.java (in the cordova file plugin):

```<code>uri = Uri.parse(uri.toString().replace("https://cdvfile/", "cdvfile://localhost/"));
</code>```

This will load the file as usual and not cause the webview to block the request.

See PR https://github.com/apache/cordova-plugin-file/pull/322

Body:
I am trying to load content in an In App Browser from my local server ( using httpd plugin ). the web page is coming from a https, while the local server is loading of course a http.

I am testing on an Iphone x IOS 12. Using adobe Build

Tried:

<access origin='*' allows-arbitrary-loads-in-media='true' allows-arbitrary-loads-in-web-content='true' allows-local-networking='true' />

<edit-config target="NSAllowsArbitraryLoads" file="*-Info.plist" mode="merge">

<true />

</edit-config>

<plugin name="cordova-plugin-transport-security" source="npm" />

Error:

[blocked] The page at https://somewebpage was not allowed to run insecure content from http://127.0.0.1:8080/javascripts/somejsfile.js.

none of these worked. anyone have a suggestion?

Body:
Another solution for android that doesn't change the security settings of the browser, is to use "https://cdvfile/assets/www/cordova.js" instead of "cdvfile://localhost/assets/www/cordova.js", and add the following line to the remapUri method in FileUtils.java (in the cordova file plugin):

uri = Uri.parse(uri.toString().replace("https://cdvfile/", "cdvfile://localhost/"));

This will load the file as usual and not cause the webview to block the request.

See PR https://github.com/apache/cordova-plugin-file/pull/322


问:
Efficient way to search inside list of json based on its key containment
I have some variables and JSON from api, let say

```<code>var airlines = "Airasia";
var hotel = "Hyatt";
var tourType = "holiday";
var result = JSON.parse(data);
</code>```

the json structure is following:

```<code>    [ { id: 1,
        departure_month: 'September - November 2019',
        program: '9 Days',
        package_name: 'Example package 1',
        tour_type: 'holiday',
        airlines: 'Lion',
        hotel: 'Hyatt'
      },
      { id: 2,
        departure_month: 'September - November 2019',
        program: '15 Days',
        package_name: 'Example package 2',
        tour_type: 'pilgrimage',
        airlines: 'Saudia',
        hotel: 'pullman'
       },
      { id: 3,
        departure_month: 'September - November 2019',
        program: '10 Days',
        package_name: 'Example package 3',
        tour_type: 'holiday',
        airlines: 'Airasia',
        hotel: 'Hyatt'
       }
    ]
</code>```

I want to efficiently search if one or more of the parameters (ex: airline, hotel, tourType) are exist or not and the code will return the json that match with those keys

so for example if alirlines = "Saudia" and hotel = "pullman" and the rest is empty, then the code will only return corresponding parameters

```<code>{ id: 2,
    departure_month: 'September - November 2019',
    program: '15 Days',
    package_name: 'Example package 2',
    tour_type: 'pilgrimage',
    airlines: 'Saudia',
    hotel: 'pullman'
   }
</code>```

答:
I think you just want the built in ES6 operator find which lets you specify your search parameters and will return the first element it matches in the array.

See here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Example:

```<code>result.find(item => item.airlines === 'Saudia' && item.hotel === 'pullman');
</code>```

If you want to find ALL matches then you would use result.filter instead of find.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Body:
I have some variables and JSON from api, let say

var airlines = "Airasia";
var hotel = "Hyatt";
var tourType = "holiday";
var result = JSON.parse(data);

the json structure is following:

    [ { id: 1,
        departure_month: 'September - November 2019',
        program: '9 Days',
        package_name: 'Example package 1',
        tour_type: 'holiday',
        airlines: 'Lion',
        hotel: 'Hyatt'
      },
      { id: 2,
        departure_month: 'September - November 2019',
        program: '15 Days',
        package_name: 'Example package 2',
        tour_type: 'pilgrimage',
        airlines: 'Saudia',
        hotel: 'pullman'
       },
      { id: 3,
        departure_month: 'September - November 2019',
        program: '10 Days',
        package_name: 'Example package 3',
        tour_type: 'holiday',
        airlines: 'Airasia',
        hotel: 'Hyatt'
       }
    ]

I want to efficiently search if one or more of the parameters (ex: airline, hotel, tourType) are exist or not and the code will return the json that match with those keys

so for example if alirlines = "Saudia" and hotel = "pullman" and the rest is empty, then the code will only return corresponding parameters

{ id: 2,
    departure_month: 'September - November 2019',
    program: '15 Days',
    package_name: 'Example package 2',
    tour_type: 'pilgrimage',
    airlines: 'Saudia',
    hotel: 'pullman'
   }

Body:
I think you just want the built in ES6 operator find which lets you specify your search parameters and will return the first element it matches in the array.

See here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Example:

result.find(item => item.airlines === 'Saudia' && item.hotel === 'pullman');

If you want to find ALL matches then you would use result.filter instead of find.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


问:
How to merge dynamic range of cells in one specific column?
For e.g. I have three values (numbers) in cells B1, B2 and B3. These explain how many cells I should merge in column A.
For example B1 = 6, B2 =3 and B3 = 2  then I want to merge cell range A16 to A22 (16+6), then A23 to A26 should be a new merged range and the last merged range should be A27 to A29.</p>

答:
Could you show the code that you have already written?

I think you have to use the function Merge in your range.

The code below works great for me :

```<code>Sub merge()
    Dim i As Integer
    Dim i2 As Integer
    Dim i3 As Integer
    i = Range("B1")
    i2 = Range("B2")
    i3 = Range("B3")
    Range("A1:A" & i).merge
    Range("A" & (i + 1) & ":A" & (i + i2)).merge
    Range("A" & (i + i2 + 1) & ":A" & (i + i2 + i3)).merge
End Sub
</code>```

Body:
Could you show the code that you have already written?

I think you have to use the function Merge in your range.

The code below works great for me :

Sub merge()
    Dim i As Integer
    Dim i2 As Integer
    Dim i3 As Integer
    i = Range("B1")
    i2 = Range("B2")
    i3 = Range("B3")
    Range("A1:A" & i).merge
    Range("A" & (i + 1) & ":A" & (i + i2)).merge
    Range("A" & (i + i2 + 1) & ":A" & (i + i2 + i3)).merge
End Sub


问:
Filter users after the role
I am very beginner in Laravel.

I have this code:

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

        public static $roles = [];

        protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

        protected $hidden = [
            'password', 'remember_token',
        ];

        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }

        public function mainRole()
        {
            return $this->hasOne('App\Role');
        }

        public function hasRole(array $roles)
        {

            foreach($roles as $role)
            {

                if(isset(self::$roles[$role]))
                {
                    if(self::$roles[$role])  return true;

                }
                else
                {
                    self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                    if(self::$roles[$role]) return true;
                }

            }
            return false;
        }

    }
Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });
</code>```

and seed:

```<code>public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

    }
</code>```

I would like to display a list of users who have the ADMIN role.

I have this code:

```<code>public function showAdminList(string $query, string $sortColumn, string $sortMethod) {

    return User::where('email', 'LIKE', '%' . $query . '%')->orWhere('id', 'LIKE', '%' . $query . '%')->orWhere('name', 'LIKE', '%' . $query . '%')->orWhere('surname', 'LIKE', '%' . $query . '%')->orderBy($sortColumn, $sortMethod)->paginate(25);

}
</code>```

The above code shows me all the users I have in the database. How can I display only those users who have the ADMIN role?

答:
Check out querying relations in Laravel for "Querying Relationship Existence".

In your case, your User model has many-to-many roles relationship. If you want to select only those users who has certain role, you can query users like this:

```<code>$role = 'receptionist';
$receptionists = User::whereHas('roles', function ($query) use ($role) {
    $query->where('name', $role);
})->get();
</code>```

So just add this whereHas() call to your query and read $role value from your request.

Title: Filter users after the role

Body:
I am very beginner in Laravel.

I have this code:

    class User extends Authenticatable implements MustVerifyEmail
    {
        use Notifiable;

        public static $roles = [];

        protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];

        protected $hidden = [
            'password', 'remember_token',
        ];

        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }

        public function mainRole()
        {
            return $this->hasOne('App\Role');
        }

        public function hasRole(array $roles)
        {

            foreach($roles as $role)
            {

                if(isset(self::$roles[$role]))
                {
                    if(self::$roles[$role])  return true;

                }
                else
                {
                    self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                    if(self::$roles[$role]) return true;
                }

            }
            return false;
        }

    }
Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

and seed:

public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

    }

I would like to display a list of users who have the ADMIN role.

I have this code:

public function showAdminList(string $query, string $sortColumn, string $sortMethod) {

    return User::where('email', 'LIKE', '%' . $query . '%')->orWhere('id', 'LIKE', '%' . $query . '%')->orWhere('name', 'LIKE', '%' . $query . '%')->orWhere('surname', 'LIKE', '%' . $query . '%')->orderBy($sortColumn, $sortMethod)->paginate(25);

}

The above code shows me all the users I have in the database. How can I display only those users who have the ADMIN role?

Body:
Check out querying relations in Laravel for "Querying Relationship Existence".

In your case, your User model has many-to-many roles relationship. If you want to select only those users who has certain role, you can query users like this:

$role = 'receptionist';
$receptionists = User::whereHas('roles', function ($query) use ($role) {
    $query->where('name', $role);
})->get();

So just add this whereHas() call to your query and read $role value from your request.


问:
how to reduce the size of a dataframe?
I'm trying to read multiple csv files from a directory by the following code, but it changes the size of each dataframe from 150000 to 150001, which causes problem when I test it with my trained dataset output which is of 150000 size. any body can fix this? since I'm a complete beginner to ML multiple suggestions and (explanation) would be appreciated... Note that dataFrame.iloc() did not worked in this scenario.</p>

```<code># indir = ".//test"
# os.chdir(indir)
fileList = glb.glob("*.csv")
# dfList = []
for filenames in fileList:
  print(filenames)
  df = pd.read_csv(filenames, header=None`
  df[0][0] = 0
  df.iloc[0:]
  print(df.size)
#   dfList.append(df)
</code>```

答:
Why will you put header = None. If you already know that the first row of the csv file is the column names, then put header = 0 which will tell pandas to read the first row as the header and not a row. This will result in correct size.

Also with your code, you are not dropping the first row, hence it is wrong. To drop the first row, you have to use df = df.iloc[1:]

Title: how to reduce the size of a dataframe?

Body:
I'm trying to read multiple csv files from a directory by the following code, but it changes the size of each dataframe from 150000 to 150001, which causes problem when I test it with my trained dataset output which is of 150000 size. any body can fix this? since I'm a complete beginner to ML multiple suggestions and (explanation) would be appreciated... Note that dataFrame.iloc() did not worked in this scenario.

# indir = ".//test"
# os.chdir(indir)
fileList = glb.glob("*.csv")
# dfList = []
for filenames in fileList:
  print(filenames)
  df = pd.read_csv(filenames, header=None`
  df[0][0] = 0
  df.iloc[0:]
  print(df.size)
#   dfList.append(df)


问:
Specify deploy keys for git repo hosted within Azure Devops
I'm unable to find any documentation relating to deploy keys on specific repositories within Azure DevOps.

Is this a possibility with the ADO platform?  This is widely supported feature in all other git SCM providers, so I assume ADO has a way of managing this as well?

答:
Currently I don't think there is any concept of a "Deploy only" SSH key in Azure DevOps, and don't even get me started on how trying to clone multiple repositories via SSH leads to using keys without a passphrase and requires uploading the key into Secure Files and pulling it down in a special task that requires a bunch of manual steps locally to configure.

https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/install-ssh-key?view=azure-devops


问:
Access Views inside a DataTemplate at runtime in Xamarin.Forms
I would like to know if there is a way to obtain a reference to a view inside a DataTemplate in a ListView in Xamarin.Forms.
Supposing I have this xaml:

```<code><ListView x:Name="ProductList" ItemsSource="{Binding Products}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout BackgroundColor="#eee" x:Name="ProductStackLayout"
                                     Orientation="Vertical" Padding="5" Tapped="ListItemTapped">
                            <Label Text="{Binding Name}"
                                   Style="{DynamicResource ProductPropertiesStyle}"/>
                            <Label Text="{Binding Notes}" IsVisible="{Binding HasNotes}"
                                    Style="{DynamicResource NotesStyle}"
                                />
                            <Label Text="{Binding Date}"
                                   Style="{DynamicResource DateStyle}"
                            />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

I would like to be able to grab a reference to the StackLayout named "ProductStackLayout" in every row of the ListView. I need to do this when the page is appearing, to dynamically manipulate it's content (for something than can't be achieved with data binding), so I can't take advantage of view references passed in event handlers originating from elements in the DataTemplate itself like ItemTapped or similar.

For what I know, in WPF or UWP something like that could be achieved with the help of the VisualTreeHelper class, but I don't believe there is an equivalent of this class in Xamarin.Forms.

答:
You can also cast like this:

```<code>    ITemplatedItemsView<Cell> templatedItemsView = listView as ITemplatedItemsView<Cell>;
    ViewCell firstCell = templatedItemsView.TemplatedItems[0] as ViewCell;
    StackLayout stackLayout = firstCell.View as StackLayout;
</code>```

Which will give you reference to the views

But you probably want to react based on the change of the binding context since you otherwise will have to manually change the content of the view.

Using BindingContextChanged I suspect would make you render the content twice - first the change causes a render like normal - afterwards you render it again. So if for instance a change in a string occurs - a label will rerender - afterwards you get the value in BindingContextChanged and preform the render that you actually wanted.

You can subclass ListView which i think would prevent it:

```<code>public class CustomListView : ListView
{
    protected override void SetupContent(Cell content, int index)
    {
        // render differently depending on content.BindingContext
        base.SetupContent(content, index);
    }
}
</code>```

Body:
I would like to know if there is a way to obtain a reference to a view inside a DataTemplate in a ListView in Xamarin.Forms.
Supposing I have this xaml:

<ListView x:Name="ProductList" ItemsSource="{Binding Products}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout BackgroundColor="#eee" x:Name="ProductStackLayout"
                                     Orientation="Vertical" Padding="5" Tapped="ListItemTapped">

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

I would like to be able to grab a reference to the StackLayout named "ProductStackLayout" in every row of the ListView. I need to do this when the page is appearing, to dynamically manipulate it's content (for something than can't be achieved with data binding), so I can't take advantage of view references passed in event handlers originating from elements in the DataTemplate itself like ItemTapped or similar.

For what I know, in WPF or UWP something like that could be achieved with the help of the VisualTreeHelper class, but I don't believe there is an equivalent of this class in Xamarin.Forms.

Body:
You can also cast like this:

    ITemplatedItemsView<Cell> templatedItemsView = listView as ITemplatedItemsView<Cell>;
    ViewCell firstCell = templatedItemsView.TemplatedItems[0] as ViewCell;
    StackLayout stackLayout = firstCell.View as StackLayout;

Which will give you reference to the views

But you probably want to react based on the change of the binding context since you otherwise will have to manually change the content of the view.

Using BindingContextChanged I suspect would make you render the content twice - first the change causes a render like normal - afterwards you render it again. So if for instance a change in a string occurs - a label will rerender - afterwards you get the value in BindingContextChanged and preform the render that you actually wanted.

You can subclass ListView which i think would prevent it:

public class CustomListView : ListView
{
    protected override void SetupContent(Cell content, int index)
    {
        // render differently depending on content.BindingContext
        base.SetupContent(content, index);
    }
}


问:
replace conditional to polymorphism when using typescript model class
I have built a game of life simulation and now I am trying to clean the code and make it more Object Orientated. Despite several days of search, I am having a hard time replacing conditionals with polymorphism.

So I have a component.ts a game model and a cell model. The cell model contains property status: boolean amongst other things. which can be dead or alive. Then I have given the user the ability to toggle a cell status on start. So I have tried for the status to create an abstract class and then two subclasses with dead or alive but I am not sure if that is the right way to go.

this is the cell.model

```<code>import { Coordinates } from './coordinates.model';

export class Cell {
  private coordinates: Coordinates;
  public status: string;

  constructor(coordinates) {
    this.coordinates = coordinates;
    this.status = new Alive().status;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    console.log(this.status)
  }

}

export abstract class Status {
  status: string;
  abstract setStatus(): string;
}

export class Alive extends Status {
  status = 'alive';
  setStatus(): string {
    return this.status = 'dead';
  }
}

export class Dead extends Status {
  status = 'dead';
  setStatus(): string {
    return this.status = 'alive';
  }
}
</code>```

In the game model as u can see below, I used conditionals to change the status

```<code>toggleCell(cellIndex: number) {
  const cell: Cell = this.cells[cellIndex];
  // if (this.cells[cellIndex].status === 'dead') {
  //     this.cells[cellIndex].status = 'alive';
  //     this.addToLivingCells(cellIndex);

  // } else {
  //     this.cells[cellIndex].status = 'dead';
  //     this.removeFromLivingCells(cellIndex);
  // }

  cell.toggleCell()
}
</code>```

so what I want to do is remove the conditionals and use polymorphism to toggle the status from the dead to alive and back depending on the current status.

Let me know if the rest of the code is needed.

Thanks in advance

答:
The example here does seem too simple to bother with polymorphism... that would probably only be worth it if you find yourself doing a lot of switch (this.status) or the like.  But here's how I might go about it:

First, I would make Status an interface instead of an abstract class, unless you actually have some common functionality:

```<code>interface Status {
  readonly status: "alive" | "dead";
  getOtherStatus(): Status;  // instead of setStatus()
  otherFunctionalityThatChangesDependingOnStatus(): void; // etc
}
</code>```

Then, if you do have two classes Alive and Dead, you absolutely do not want to mutate the status string inside setStatus(), since that breaks your model entirely.  Because Alive and Dead are two different classes, an instance of one cannot become an instance of the other (well, it technically can, but you shouldn't try to do that).  And since an Alive instance must always be an Alive instance, it makes little sense to change this.status to "dead".  In your original implementation, const a = new Alive() is alive, then a.setStatus() makes it a "dead Alive", and then a.setStatus() will keep it a "dead Alive", because of the implementation of Alive.setStatus().

Instead, you should treat Alive and Dead instances as immutable, at least as far as their status is concerned.  Instead of mutating this.status via setStatus(), you should return a Status object corresponding to the other status via getOtherStatus().  If Alive and Dead are immutable, there's no real reason to carry around more than one instance of each class (since const a = new Alive() and const b = new Alive() would make two distinct objects which act exactly the same in all circumstances).  So you can do something like this:

```<code>class Alive implements Status {
  static readonly instance = new Alive(); // the one instance of Alive
  private constructor() {}
  readonly status = "alive";
  getOtherStatus() {
    return Dead.instance;
  }
  otherFunctionalityThatChangesDependingOnStatus() {
    console.log("It's good to be alive!");
  }
}

class Dead implements Status {
  static readonly instance = new Dead(); // the one instance of Dead
  private constuctor() {}
  readonly status = "dead";
  getOtherStatus() {
    return Alive.instance;
  }
  otherFunctionalityThatChangesDependingOnStatus() {
    console.log("I'm out of here!")
  }
}
</code>```

So you never call new Alive() or new Dead(); instead you can grab Alive.instance or Dead.instance.  Finally you can make Cell depend on Status. The status property of Cell should be a Status instance, not a string.  That's how you can get the object-oriented behavior of Alive and Dead.  You initialize status to Alive.instance, and you toggleCell() by setting this.status to this.status.getOtherStatus():

```<code>class Cell {
  private coordinates: Coordinates;
  public status: Status;

  constructor(coordinates: Coordinates) {
    this.coordinates = coordinates;
    this.status = Alive.instance;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    this.status = this.status.getOtherStatus();
    console.log(this.status);
  }
}
</code>```

And let's test it:

```<code>const c = new Cell(null!);
c.status.otherFunctionalityThatChangesDependingOnStatus(); // It's good to be alive!
c.toggleCell();
c.status.otherFunctionalityThatChangesDependingOnStatus(); // I'm out of here!
c.toggleCell();
c.status.otherFunctionalityThatChangesDependingOnStatus(); // It's good to be alive!
</code>```

Looks good.  Okay, hope this helps.  Good luck!

Link to code

Body:
I have built a game of life simulation and now I am trying to clean the code and make it more Object Orientated. Despite several days of search, I am having a hard time replacing conditionals with polymorphism.

So I have a component.ts a game model and a cell model. The cell model contains property status: boolean amongst other things. which can be dead or alive. Then I have given the user the ability to toggle a cell status on start. So I have tried for the status to create an abstract class and then two subclasses with dead or alive but I am not sure if that is the right way to go.

this is the cell.model

import { Coordinates } from './coordinates.model';

export class Cell {
  private coordinates: Coordinates;
  public status: string;

  constructor(coordinates) {
    this.coordinates = coordinates;
    this.status = new Alive().status;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    console.log(this.status)
  }

}

export abstract class Status {
  status: string;
  abstract setStatus(): string;
}

export class Alive extends Status {
  status = 'alive';
  setStatus(): string {
    return this.status = 'dead';
  }
}

export class Dead extends Status {
  status = 'dead';
  setStatus(): string {
    return this.status = 'alive';
  }
}

In the game model as u can see below, I used conditionals to change the status

toggleCell(cellIndex: number) {
  const cell: Cell = this.cells[cellIndex];
  // if (this.cells[cellIndex].status === 'dead') {
  //     this.cells[cellIndex].status = 'alive';
  //     this.addToLivingCells(cellIndex);

  // } else {
  //     this.cells[cellIndex].status = 'dead';
  //     this.removeFromLivingCells(cellIndex);
  // }

  cell.toggleCell()
}

so what I want to do is remove the conditionals and use polymorphism to toggle the status from the dead to alive and back depending on the current status.

Let me know if the rest of the code is needed.

Thanks in advance

Body:
The example here does seem too simple to bother with polymorphism... that would probably only be worth it if you find yourself doing a lot of switch (this.status) or the like.  But here's how I might go about it:

First, I would make Status an interface instead of an abstract class, unless you actually have some common functionality:

interface Status {
  readonly status: "alive" | "dead";
  getOtherStatus(): Status;  // instead of setStatus()
  otherFunctionalityThatChangesDependingOnStatus(): void; // etc
}

Then, if you do have two classes Alive and Dead, you absolutely do not want to mutate the status string inside setStatus(), since that breaks your model entirely.  Because Alive and Dead are two different classes, an instance of one cannot become an instance of the other (well, it technically can, but you shouldn't try to do that).  And since an Alive instance must always be an Alive instance, it makes little sense to change this.status to "dead".  In your original implementation, const a = new Alive() is alive, then a.setStatus() makes it a "dead Alive", and then a.setStatus() will keep it a "dead Alive", because of the implementation of Alive.setStatus().

Instead, you should treat Alive and Dead instances as immutable, at least as far as their status is concerned.  Instead of mutating this.status via setStatus(), you should return a Status object corresponding to the other status via getOtherStatus().  If Alive and Dead are immutable, there's no real reason to carry around more than one instance of each class (since const a = new Alive() and const b = new Alive() would make two distinct objects which act exactly the same in all circumstances).  So you can do something like this:

class Alive implements Status {
  static readonly instance = new Alive(); // the one instance of Alive
  private constructor() {}
  readonly status = "alive";
  getOtherStatus() {
    return Dead.instance;
  }
  otherFunctionalityThatChangesDependingOnStatus() {
    console.log("It's good to be alive!");
  }
}

class Dead implements Status {
  static readonly instance = new Dead(); // the one instance of Dead
  private constuctor() {}
  readonly status = "dead";
  getOtherStatus() {
    return Alive.instance;
  }
  otherFunctionalityThatChangesDependingOnStatus() {
    console.log("I'm out of here!")
  }
}

So you never call new Alive() or new Dead(); instead you can grab Alive.instance or Dead.instance.  Finally you can make Cell depend on Status. The status property of Cell should be a Status instance, not a string.  That's how you can get the object-oriented behavior of Alive and Dead.  You initialize status to Alive.instance, and you toggleCell() by setting this.status to this.status.getOtherStatus():

class Cell {
  private coordinates: Coordinates;
  public status: Status;

  constructor(coordinates: Coordinates) {
    this.coordinates = coordinates;
    this.status = Alive.instance;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    this.status = this.status.getOtherStatus();
    console.log(this.status);
  }
}

And let's test it:

const c = new Cell(null!);
c.status.otherFunctionalityThatChangesDependingOnStatus(); // It's good to be alive!
c.toggleCell();
c.status.otherFunctionalityThatChangesDependingOnStatus(); // I'm out of here!
c.toggleCell();
c.status.otherFunctionalityThatChangesDependingOnStatus(); // It's good to be alive!

Looks good.  Okay, hope this helps.  Good luck!

<a href="https://typescript-play.js.org/#code/JYOwLgpgTgZghgYwgAgMpjmArgZ2QbwChlkoI4ATAexABsBPZHDbHALmQCI5bgA3CJ2QAfLhXIVOAbmLIA5hDAB5MAAto6TLgAUASg6bWMklTXQAYlhAIwwGj2Bh6AFVWYAwm5AKcAEQgADhAgFKBySiCGOvrIfFTAFDIAvoSECLRwOHgAgrwCyMAAtgG0EIXBYHhReEQkzJjACKQSNAwFIPXWKAC8yCAQAO7IufwQesbIAVD8mCgINMxQWDZUUHoEKSRklK2M9azIvdx5ghMKymZQ1eu1JM3YUCDI-pQAdKCdSBObyKbqUJZrLZ7LwnK4PF4fP4giEwhFrroCLISPMOlRSq9aFQ5NpOABJMAAcjwcioVAoyDAVGQACMUA4BABCTi6b6EFJpDJZZ4SArFUrlcBVFi4JF1FiNZo7OiMD4YLqHPqDHmUcayKYzSDIVHMZZUtaI-A-bbUGVMEV4I7iSjSWTnFT-BFiu5kB5PEYCd4deVfWQ-P4WKw2OwgBxgtxgTxwbwQPyBYKhbzwi03ZHahboiCY7G4vGEwq-LBgX4wZD-CDM1l+9mpdKZPDuCC0WjOjV8Wbp1aJ2bsZDuMlQbuQHATAJYGm8Jr7XAGC0yWQ6sBLFZreZd0A9jj99eh4eGtNqYA4V5rwcb4eK09D2MTEiH4-Ty3DE5ez4QNl2xTbs+72N6LcDteNRpq6WCPJSqhHiegHnje1ayFSchyKUjbNv+sTxBStx3pBD4Woq96vI+rz2pcCK3umaIYliOKEY+VYkCkHKLtqir9EMqG0NoIBYM2jJVggREWq8AYAkGwKhqCLgRlGMZxjCibhJEKassgAD0anIASxLyGSFJUrS9InIyaSvIhyEQJxaqCcRomAsGIKONJELRlC8awkmylaDg4zqZpeYFlQRYlmW0AVqZ5koU2XECUJ3kiZc9kSWGzmRpCsbQgmcJeawvkaVpRIknplLUnSyAMuFQA" rel="nofollow noreferrer">Link to code


问:
Implementing FBSessionDelegate protocol in xcode
I am trying to implement Facebook connect with an app I am create for iOS devices. I've followed all the directions to they key, and the SDK works, I get one warning though. It says I do not implement the FBSessionDelegate protocol. During the debugging in simulator it takes me into safari to signin to FB instead of doing it in the app itself. Is the FBSessionDelegate responsible for this? If so, how do I get it so it does it all within the app.</p>

答:
The FBSessionDelegate is not responsible for this issue. The iOS SDK has a fallback to Safari if it can't launch the FB App.
In Facebook.m in this method:

```<code>- (void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth
                    safariAuth:(BOOL)trySafariAuth
</code>```

...there is this comment:

```<code>  // If the device is running a version of iOS that supports multitasking,
  // try to obtain the access token from the Facebook app installed
  // on the device.
  // If the Facebook app isn't installed or it doesn't support
  // the fbauth:// URL scheme, fall back on Safari for obtaining the access token.
  // This minimizes the chance that the user will have to enter his or
  // her credentials in order to authorize the application.
</code>```

This comment explains the reasons why Safari would be used instead of the FB App.

Is your simulator a device that
supports multitasking?

Does your simulator have the FB App
installed?

Is the FB App the latest version?
(to make sure it supports the
fbauth:// scheme)

The FBSessionDelegate, as dfrdmn explained, implements 3 methods that would all be called after the redirection to FB or Safari has already occurred and therefore isn't contributing to your issue.

To get rid of that warning there are a few things you need to make sure you do.

-- In your .h file make sure you implement the FBSessionDelegate.

```<code>@interface AppDelegate : NSObject <FBSessionDelegate>
</code>```

-- In your .h file make sure you #import "Facebook.h". Using @class Facebook will not work.

ContentLicense: CC BY-SA 2.5

Body:
The FBSessionDelegate is not responsible for this issue. The iOS SDK has a fallback to Safari if it can't launch the FB App.
In Facebook.m in this method:

- (void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth
                    safariAuth:(BOOL)trySafariAuth

...there is this comment:

  // If the device is running a version of iOS that supports multitasking,
  // try to obtain the access token from the Facebook app installed
  // on the device.
  // If the Facebook app isn't installed or it doesn't support
  // the fbauth:// URL scheme, fall back on Safari for obtaining the access token.
  // This minimizes the chance that the user will have to enter his or
  // her credentials in order to authorize the application.

This comment explains the reasons why Safari would be used instead of the FB App.

Is your simulator a device that
supports multitasking?

Does your simulator have the FB App
installed?

Is the FB App the latest version?
(to make sure it supports the
fbauth:// scheme)

The FBSessionDelegate, as dfrdmn explained, implements 3 methods that would all be called after the redirection to FB or Safari has already occurred and therefore isn't contributing to your issue.

To get rid of that warning there are a few things you need to make sure you do.

-- In your .h file make sure you implement the FBSessionDelegate.

@interface AppDelegate : NSObject <FBSessionDelegate>

-- In your .h file make sure you #import "Facebook.h". Using @class Facebook will not work.


问:
SQL Check if value in Table is in range of 2 columns in another Table
I'm trying to check whether a value in TABLE_1 is in a range based on 2 columns in TABLE_2. I am able to accomplish based on the answer provided in question SQL: Checking if a number within range of multiple ranges however when I used this method with a large dataset (~40K rows in both tables) it is maxing out CPU on my SQL server and the query takes an excess of 3 minutes. Is there a way to optimize this query and to limit the CPU that the query uses? If not, is there an alternate query that might be more efficient.

TABLE_1:

```<code>mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)
</code>```

TABLE_2:

```<code>mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+
</code>```

Query:

```<code>SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);
</code>```

Output:

```<code>+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)
</code>```

答:
This is your query:

```<code>SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT AND
                        TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);
</code>```

For performance, start with an index on TABLE_2(FRUIT, START_RANGE, END_RANGE).

Body:
I'm trying to check whether a value in TABLE_1 is in a range based on 2 columns in TABLE_2. I am able to accomplish based on the answer provided in question SQL: Checking if a number within range of multiple ranges however when I used this method with a large dataset (~40K rows in both tables) it is maxing out CPU on my SQL server and the query takes an excess of 3 minutes. Is there a way to optimize this query and to limit the CPU that the query uses? If not, is there an alternate query that might be more efficient.

TABLE_1:

mysql> SELECT * FROM TABLE_1;
+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  1 | Apples  |  2314 |
|  2 | Oranges |  3412 |
|  3 | Oranges |  1296 |
|  4 | Apples  |  2230 |
|  5 | Apples  |  5293 |
|  6 | Oranges |  1994 |
+----+---------+-------+
6 rows in set (0.00 sec)

TABLE_2:

mysql> SELECT * FROM TABLE_2;
+----+---------+-------------+-----------+
| ID | FRUIT   | START_RANGE | END_RANGE |
+----+---------+-------------+-----------+
|  1 | Apples  |        2300 |      2400 |
|  2 | Apples  |        7000 |      8000 |
|  3 | Oranges |        1296 |      1296 |
|  4 | Apples  |        5000 |      6000 |
|  5 | Oranges |        9000 |      9999 |
|  6 | Oranges |        8000 |      9000 |
+----+---------+-------------+-----------+

Query:

SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT
                  AND TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);

Output:

+----+---------+-------+
| ID | FRUIT   | COUNT |
+----+---------+-------+
|  2 | Oranges |  3412 |
|  4 | Apples  |  2230 |
|  6 | Oranges |  1994 |
+----+---------+-------+
3 rows in set (0.00 sec)

Body:
This is your query:

SELECT *
FROM TABLE_1
WHERE NOT EXISTS (SELECT 1 FROM TABLE_2
                  WHERE TABLE_1.FRUIT = TABLE_2.FRUIT AND
                        TABLE_1.COUNT BETWEEN TABLE_2.START_RANGE AND TABLE_2.END_RANGE);

For performance, start with an index on TABLE_2(FRUIT, START_RANGE, END_RANGE).


问:
Asp.net MVC 4 Jquery validator not hitting InvalidHandler
I'm struggling on this problem...
I've override my master page to change invalid hightlight and Unhightlight classes and to modify the InvalidHandler like below:

```<code><script type="text/javascript">

    $.validator.setDefaults({
        ignore: [],
        invalidHandler: function (event, validator) {
            $(".tab-content").find("div.tab-pane:hidden:has(div.has-error)").each(function (index, tab) {
                var id = $(tab).attr("id");
                alert(id);
                $('a[href="#' + id + '"]').tab('show');
            });
        },
        highlight: function (element, errorClass, validClass) {
            if (element.type === 'radio') {
                this.findByName(element.name).addClass("bad").removeClass("good");
            } else {
                $(element).addClass("bad").removeClass("good");
                $(element).closest('.form-group').removeClass('good').addClass('bad');
            }
        },
        unhighlight: function (element, errorClass, validClass) {
            if (element.type === 'radio') {
                this.findByName(element.name).removeClass("bad").addClass("good");
            } else {
                $(element).removeClass("bad").addClass(validClass);
                $(element).closest('.form-group').removeClass('bad').addClass('good');
            }
        }
    });
</code>```

The Hightlight and Unhightlight has been hited, but  InvalidHandler doesn't...
Could somebody help me?
Thanks in advance!

答:
If you're using jQuery Unobtrusive Validation, it doesn't necessarily respect the default, and I haven't been able to get invalidHandler working either.

You can subscribe to an event that is thrown:

```<code>`$('form').on('invalid-form', function (...) { });`
</code>```

Or I've also found in the jQuery unobtrusive source that they try pull options out of jQuery.validator.unobstrusive.options so you can do this:

```<code>jQuery.validator.unobtrusive.options =
jQuery.validator.unobtrusive.options || {};
jQuery.validator.unobtrusive.options.invalidHandler = function (...) { };
</code>```

Either way, for me I'm getting it called twice, which is painful too.

Body:
If you're using jQuery Unobtrusive Validation, it doesn't necessarily respect the default, and I haven't been able to get invalidHandler working either.

You can subscribe to an event that is thrown:

`$('form').on('invalid-form', function (...) { });`

Or I've also found in the jQuery unobtrusive source that they try pull options out of jQuery.validator.unobstrusive.options so you can do this:

jQuery.validator.unobtrusive.options =
jQuery.validator.unobtrusive.options || {};
jQuery.validator.unobtrusive.options.invalidHandler = function (...) { };

Either way, for me I'm getting it called twice, which is painful too.


问:
Cypress JS and ability to upload and append an image
So I'm working on uploading a file in Cypress. Now I have an issue of appending the image to the page. I'm trying to upload/append the image under the following:

```<code><label for="upload-137" class="field-upload>
 <div class="layout justify-center">
  <span class="v-btn">
   <div class="v-btn__content">
    <i class="v-icon">add</i>
   </div>
  </span>
 </div>
 <input id="upload-137" name="upload" type="file" accept=".jpg,.jpeg,.png" class="file-input">
</label>
</code>```

Specifically I'm looking to append it after layout as a sibling after the span.

So my thought would be:

```<code>   cy.fixture('/driver/jack.jpg', 'base64').then(fileContent => {
    const jack = cy.get('input[type="file"]').upload({
      fileContent,
      fileName: 'jack.jpg',
      mimeType: 'image/jpg'
    }, {
      subjectType: 'input'
    }, );
    cy.get('.field-upload > .layout').then(($div) => {
      function words(){
        var image = document.createElement("img");
        image.setAttribute("src", jack);
        var location = document.getElementsByClassName("layout");
        location.appendChild(image);
      }
      $div.append(words)
    })
  })
</code>```

My thinking was to use cypress upload package to pull in the file to assign it to the input field and upload. Then get the location, create the img, set the source including in the fixture that's been uploaded. Then append it to the location (based on class name).

I end up getting

TypeError: location.appendChild is not a function

Is there a way to append an image that was uploaded?

答:
The method document.getElementsByClassName returns you an array of elements. Where as appendChild is a method of an element. Hence you are getting the error.

To resolve this, there are 2 ways,

Assign ID

Assign an ID to your HTML element which makes it unique and get this element via document.getElementById. After that you can append your other element to it.

```<code><label for="upload-137" class="field-upload>
 <div class="layout justify-center" id="layoutContainer">
  <span class="v-btn">
   <div class="v-btn__content">
    <i class="v-icon">add</i>
   </div>
  </span>
 </div>
 <input id="upload-137" name="upload" type="file" accept=".jpg,.jpeg,.png" class="file-input">
</label>
</code>```

And in your JavaScript:

```<code>var image = document.createElement("img");
image.setAttribute("src", jack);
var location = document.getElementById("layoutContainer");
location.appendChild(image);
</code>```

2. Get element from array

If you do not ant to assign an ID, you can get the element from the array via index. Although in this case, you need to be sure that there is only one HTML tag with the class layout.

```<code>var image = document.createElement("img");
image.setAttribute("src", jack);
var location = document.getElementsByClassName("layout")[0];
location.appendChild(image);
</code>```

Body:
So I'm working on uploading a file in Cypress. Now I have an issue of appending the image to the page. I'm trying to upload/append the image under the following:

    add

 <input id="upload-137" name="upload" type="file" accept=".jpg,.jpeg,.png" class="file-input">

Specifically I'm looking to append it after layout as a sibling after the span.

So my thought would be:

   cy.fixture('/driver/jack.jpg', 'base64').then(fileContent => {
    const jack = cy.get('input[type="file"]').upload({
      fileContent,
      fileName: 'jack.jpg',
      mimeType: 'image/jpg'
    }, {
      subjectType: 'input'
    }, );
    cy.get('.field-upload > .layout').then(($div) => {
      function words(){
        var image = document.createElement("img");
        image.setAttribute("src", jack);
        var location = document.getElementsByClassName("layout");
        location.appendChild(image);
      }
      $div.append(words)
    })
  })

My thinking was to use cypress upload package to pull in the file to assign it to the input field and upload. Then get the location, create the img, set the source including in the fixture that's been uploaded. Then append it to the location (based on class name).

I end up getting

TypeError: location.appendChild is not a function

Is there a way to append an image that was uploaded?

Body:
The method document.getElementsByClassName returns you an array of elements. Where as appendChild is a method of an element. Hence you are getting the error.

To resolve this, there are 2 ways,

Assign ID

Assign an ID to your HTML element which makes it unique and get this element via document.getElementById. After that you can append your other element to it.

<label for="upload-137" class="field-upload>
 <div class="layout justify-center" id="layoutContainer">
  <span class="v-btn">
   <div class="v-btn__content">
    <i class="v-icon">add</i>
   </div>
  </span>
 </div>
 <input id="upload-137" name="upload" type="file" accept=".jpg,.jpeg,.png" class="file-input">
</label>

And in your JavaScript:

var image = document.createElement("img");
image.setAttribute("src", jack);
var location = document.getElementById("layoutContainer");
location.appendChild(image);

2. Get element from array

If you do not ant to assign an ID, you can get the element from the array via index. Although in this case, you need to be sure that there is only one HTML tag with the class layout.

var image = document.createElement("img");
image.setAttribute("src", jack);
var location = document.getElementsByClassName("layout")[0];
location.appendChild(image);


问:
Approaches to Extend ng2-pdf-viewer to support drawing on top of pdf?
I am making use of ng2-pdf-viewer as a PDF Viewer Component in my application, now I want to extend the component to support drawing on top of pdf, in summary adding a pencil or something that will help me to draw shapes etc on the pdf.

What could be the possible approaches to achieve the same? Like a layer of canvas or something? or do we have some package in npm that has high level support for text, drawing and images.

Even I tried looking for npm packages, for supporting drawing on pdf, or pdf packages itself like ngx-extended-pdf-viewer, simple-pdf-viewer but unfortunately didn't found any solution.

For instance an example of what I mean by drawing is attached as follows by leveraging acrobat reader drawing capabilities.

答:
After receiving no answers to the Question, I ended up solving the problem my-self, I have written my own layer of canvas over the ng2-pdf-viewer, and extended the functionality of the layer to change the stroke size, width, color using color-picker, and even retaining the canvas pixels on ng2-pdf-viewer after zooming in/out pdf in ng2-pdf-viewer.

Soon, I will create a fiddle for same, as script is long.


问:
regex to match white space and one
I am a beginner when it comes to writing a regular expression, I want o write regex which can match the following lines

```<code> 0 x0_0                            1                 -228900  Result - true
 0 x2_0                            0                 -228900  Result - false
 0 x3_0                            0                 -128900  Result - false
</code>```

Actually I want regex to return true if it has

```<code>x<AnyDigit>_<AnyDigit> <WhiteSpace>  1
</code>```

I have written below expression

```<code>x(\d+)_(\d+)[\s1]
</code>```

but it is returning true in below case as well

```<code>0 x3_0                           0                 -128900
</code>```

答:
In  your pattern you use a character class [\s1] which will match either a whitespace char (which will also match a newline) or a 1.

If you want a match only, you can omit the capturing groups. Note that \d+ matches 1+ digits.

You could update your pattern to:

```<code>\bx\d+_\d+[ \t]+1\b
</code>```

Explanation

\bx\d+ Match word boundary to prevent x being part of a larger word, then 1+ digits

_\d+ Match underscore followed by 1+ digits

[ \t]+ Match 1+ times a space or tab

1\b Match 1 follower by a word boundary

Regex demo

Title: regex to match white space and one

Body:
I am a beginner when it comes to writing a regular expression, I want o write regex which can match the following lines

 0 x0_0                            1                 -228900  Result - true
 0 x2_0                            0                 -228900  Result - false
 0 x3_0                            0                 -128900  Result - false

Actually I want regex to return true if it has

x<AnyDigit>_<AnyDigit> <WhiteSpace>  1

I have written below expression

x(\d+)_(\d+)[\s1]

but it is returning true in below case as well

0 x3_0                           0                 -128900

Body:
In  your pattern you use a character class [\s1] which will match either a whitespace char (which will also match a newline) or a 1.

If you want a match only, you can omit the capturing groups. Note that \d+ matches 1+ digits.

You could update your pattern to:

\bx\d+_\d+[ \t]+1\b

Explanation

\bx\d+ Match word boundary to prevent x being part of a larger word, then 1+ digits

_\d+ Match underscore followed by 1+ digits

[ \t]+ Match 1+ times a space or tab

1\b Match 1 follower by a word boundary

Regex demo


问:
Examine two columns and delete lowest number of the id of column named contentid
Data comes from:

```<code>SELECT
    CONTENTID, t1.TITLE, t1.PAGEID, COUNT, SPACENAME, CREATIONDATE, LASTMODDATE, VERSION
FROM
    (SELECT
         SPACEID, TITLE, PAGEID, COUNT(*) AS COUNT
     FROM
         CONTENT
     WHERE
         CONTENTTYPE = 'ATTACHMENT'
     GROUP BY
         TITLE, PAGEID, SPACEID
     HAVING
         COUNT(TITLE) > 1 AND COUNT(PAGEID) > 1) t1
JOIN
    (SELECT
         CONTENTID, CREATIONDATE, LASTMODDATE, VERSION, TITLE, PAGEID
     FROM
         CONTENT
     WHERE
         VERSION = 1) t4 ON t4.PAGEID = t1.PAGEID
JOIN
    (SELECT
         SPACEID, SPACENAME
     FROM
         SPACES) t2 ON t1.SPACEID = t2.SPACEID
ORDER BY
    t1.PAGEID,t1.TITLE, CREATIONDATE, LASTMODDATE
</code>```

Output (removed some of the columns because it is just the first two needed to make the decision on what to remove and it is easier to display here):

```<code>CONTENTID   TITLE
--------------------------------------------
26902677    Time Logging Guidelines V5.docx
46170401    Time Logging Guidelines V5.docx
157909073   Time Logging Guidelines V5.docx
157909072   Time Logging Guidelines V5.docx
355860497   Time Logging Guidelines V5.docx
535953771   Time Logging Guidelines V5.docx
540117589   Time Logging Guidelines V5.docx
554729950   Time Logging Guidelines V5.docx
1246646     Induction Plan Template.docx
472350756   Induction Plan Template.docx
535953845   Induction Plan Template.docx
544508546   Induction Plan Template.docx
544508547   Induction Plan Template.docx
</code>```

I need to delete all but the highest contentid for each title.  There are actually about 66k of rows of this type of fix

The end result for the output above:

```<code>554729950   Time Logging Guidelines V5.docx
544508547   Induction Plan Template.docx
</code>```

答:
If I understand you correctly, it is simply:

```<code>DELETE FROM CONTENT WHERE CONTENTID NOT IN (SELECT MAX(CONTENTID) FROM CONTENT GROUP BY TITLE)```

Body:
Data comes from:

SELECT
    CONTENTID, t1.TITLE, t1.PAGEID, COUNT, SPACENAME, CREATIONDATE, LASTMODDATE, VERSION
FROM
    (SELECT
         SPACEID, TITLE, PAGEID, COUNT(*) AS COUNT
     FROM
         CONTENT
     WHERE
         CONTENTTYPE = 'ATTACHMENT'
     GROUP BY
         TITLE, PAGEID, SPACEID
     HAVING
         COUNT(TITLE) > 1 AND COUNT(PAGEID) > 1) t1
JOIN
    (SELECT
         CONTENTID, CREATIONDATE, LASTMODDATE, VERSION, TITLE, PAGEID
     FROM
         CONTENT
     WHERE
         VERSION = 1) t4 ON t4.PAGEID = t1.PAGEID
JOIN
    (SELECT
         SPACEID, SPACENAME
     FROM
         SPACES) t2 ON t1.SPACEID = t2.SPACEID
ORDER BY
    t1.PAGEID,t1.TITLE, CREATIONDATE, LASTMODDATE

Output (removed some of the columns because it is just the first two needed to make the decision on what to remove and it is easier to display here):

CONTENTID   TITLE
--------------------------------------------
26902677    Time Logging Guidelines V5.docx
46170401    Time Logging Guidelines V5.docx
157909073   Time Logging Guidelines V5.docx
157909072   Time Logging Guidelines V5.docx
355860497   Time Logging Guidelines V5.docx
535953771   Time Logging Guidelines V5.docx
540117589   Time Logging Guidelines V5.docx
554729950   Time Logging Guidelines V5.docx
1246646     Induction Plan Template.docx
472350756   Induction Plan Template.docx
535953845   Induction Plan Template.docx
544508546   Induction Plan Template.docx
544508547   Induction Plan Template.docx

I need to delete all but the highest contentid for each title.  There are actually about 66k of rows of this type of fix

The end result for the output above:

554729950   Time Logging Guidelines V5.docx
544508547   Induction Plan Template.docx

Body:
If I understand you correctly, it is simply:

DELETE FROM CONTENT WHERE CONTENTID NOT IN (SELECT MAX(CONTENTID) FROM CONTENT GROUP BY TITLE)


问:
Gradle sync failed: Unable to load class 'org.gradle.internal.logging.LoggingManagerInternal'
I tried to import new library module in my android project (using android studio),
which work without any problem, but when I imported it I have this error (when trying to sync gradle):

```<code>Gradle sync failed: Unable to load class
'org.gradle.internal.logging.LoggingManagerInternal'.
</code>```

bulid.gradle for module

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
    applicationId "com.amazon.mysampleapp"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled = true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
    }
}

lintOptions {
    abortOnError false
}

sourceCompatibility = 1.7
targetCompatibility = 1.7
}

dependencies {
  compile fileTree(include: ['*.jar'], dir: 'libs')
  compile fileTree(include: ['*.jar'], dir: 'app/libs')
  compile 'com.android.support:appcompat-v7:23.1.0'
  compile 'com.android.support:support-v4:23.1.0'
  compile('com.amazonaws:aws-android-sdk-core:2.2.18')
  compile('com.amazonaws:aws-android-sdk-cognito:2.2.18')
  compile('com.amazonaws:aws-android-sdk-mobileanalytics:2.2.18')
  compile('com.amazonaws:aws-android-sdk-sns:2.2.18')
  compile 'com.google.android.gms:play-services-gcm:7.8.0'
  compile 'com.google.code.gson:gson:2.6.2'
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
  compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  compile 'io.reactivex:rxjava:1.1.6'
  compile 'io.reactivex:rxandroid:1.2.1'
  compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
  compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
}
</code>```

bulid.gradle for library

```<code>apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: "com.jfrog.bintray"

def siteUrl = 'https://github.com/Frederikos/RxImagePicker'
def gitUrl = 'https://github.com/Frederikos/RxImagePicker.git'

version = "1.1.9"
group = "com.mlsdev.rximagepicker"

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

bintray {
    user = properties.getProperty("bintray.user")
    key = properties.getProperty("bintray.apikey")
configurations = ['archives']
pkg {
    repo = "maven"
    name = "RxImagePicker"
    websiteUrl = siteUrl
    vcsUrl = gitUrl
    licenses = ["Apache-2.0"]
    publish = true
}
}

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 8
        versionName "1.1.9"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

install {
    repositories.mavenInstaller {
        pom {
            project {
                packaging 'aar'
                name 'RxImagePicker an easy way to get image from Gallery or Camera with request runtime permission on Android M. Using RxJava'
                url siteUrl
                licenses {
                    license {
                        name 'The Apache Software License, Version 2.0'
                        url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                    }
                }
                developers {
                    developer {
                        id 'frederikos'
                        name 'frederikos'
                        email 'frederikoss@gmail.com'
                    }
                }
                scm {
                    connection gitUrl
                    developerConnection gitUrl
                    url siteUrl

                }
            }
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
//    testCompile 'junit:junit:4.12'
}

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'
}

task javadoc(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}
artifacts {
    archives javadocJar
    archives sourcesJar
}

task findConventions << {
    println project.getConvention()
}
</code>```

root level bulid.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
        classpath 'me.tatarka:gradle-retrolambda:3.2.5'

    }
}

apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

Any Ideas help me.

答:
For me it worked after altering gradle-wrapper.properties.

distributionUrl=https://services.gradle.org/distributions/gradle-5.1.1-all.zip

Body:
I tried to import new library module in my android project (using android studio),
which work without any problem, but when I imported it I have this error (when trying to sync gradle):

Gradle sync failed: Unable to load class
'org.gradle.internal.logging.LoggingManagerInternal'.

bulid.gradle for module

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
    applicationId "com.amazon.mysampleapp"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled = true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
    }
}

lintOptions {
    abortOnError false
}

sourceCompatibility = 1.7
targetCompatibility = 1.7
}

dependencies {
  compile fileTree(include: ['*.jar'], dir: 'libs')
  compile fileTree(include: ['*.jar'], dir: 'app/libs')
  compile 'com.android.support:appcompat-v7:23.1.0'
  compile 'com.android.support:support-v4:23.1.0'
  compile('com.amazonaws:aws-android-sdk-core:2.2.18')
  compile('com.amazonaws:aws-android-sdk-cognito:2.2.18')
  compile('com.amazonaws:aws-android-sdk-mobileanalytics:2.2.18')
  compile('com.amazonaws:aws-android-sdk-sns:2.2.18')
  compile 'com.google.android.gms:play-services-gcm:7.8.0'
  compile 'com.google.code.gson:gson:2.6.2'
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
  compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  compile 'io.reactivex:rxjava:1.1.6'
  compile 'io.reactivex:rxandroid:1.2.1'
  compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
  compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
}

bulid.gradle for library

apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: "com.jfrog.bintray"

def siteUrl = 'https://github.com/Frederikos/RxImagePicker'
def gitUrl = 'https://github.com/Frederikos/RxImagePicker.git'

version = "1.1.9"
group = "com.mlsdev.rximagepicker"

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

bintray {
    user = properties.getProperty("bintray.user")
    key = properties.getProperty("bintray.apikey")
configurations = ['archives']
pkg {
    repo = "maven"
    name = "RxImagePicker"
    websiteUrl = siteUrl
    vcsUrl = gitUrl
    licenses = ["Apache-2.0"]
    publish = true
}
}

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 8
        versionName "1.1.9"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

install {
    repositories.mavenInstaller {
        pom {
            project {
                packaging 'aar'
                name 'RxImagePicker an easy way to get image from Gallery or Camera with request runtime permission on Android M. Using RxJava'
                url siteUrl
                licenses {
                    license {
                        name 'The Apache Software License, Version 2.0'
                        url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                    }
                }
                developers {
                    developer {
                        id 'frederikos'
                        name 'frederikos'
                        email 'frederikoss@gmail.com'
                    }
                }
                scm {
                    connection gitUrl
                    developerConnection gitUrl
                    url siteUrl

                }
            }
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
//    testCompile 'junit:junit:4.12'
}

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'
}

task javadoc(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}
artifacts {
    archives javadocJar
    archives sourcesJar
}

task findConventions << {
    println project.getConvention()
}

root level bulid.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
        classpath 'me.tatarka:gradle-retrolambda:3.2.5'

    }
}

apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'

allprojects {
    repositories {
        jcenter()
    }
}

Any Ideas help me.


问:
Reference array keys without knowing their names?
If I have an array like this:

```<code>$array = array('something'=>array('more'=>array('id'=> 34)));
</code>```

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.

答:
There are multiple possibilities.

You could use arrayiterator or simply foreach.
Perhaps even array_values could be your solution.

Body:
If I have an array like this:

$array = array('something'=>array('more'=>array('id'=> 34)));

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.


问:
Sort object keys with each and handlebars helper
I would like to sort objects keys with each:
test1, test4, test3 => test1, test3, test4
...

My json:

```<code>"tests": {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
}
</code>```

My handlebars code:

```<code>{{#each tests}}
    <h1>{{@key}}</h1>
    <ul>{{#eachSorted this}}<li>{{this}}</li>{{/eachSorted}}</ul>
{{/each}}
</code>```

I tried but does not work:

```<code>Handlebars.registerHelper('eachSorted', function(context, options) {
    var ret = ""
    Object.keys(context).sort().forEach(function(key) {
        ret = ret + options.fn({key: key, value: context[key]})
    })
    return ret
})
</code>```

答:
Replace the eachSorted function with this:

var tests = {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
};

function eachSorted(context) {
    var ret = {};
 Object.keys(context)
  .sort()
  .forEach(function(key) {
   ret[key] = context[key];
    });
    return ret;
}

console.log(eachSorted(tests.chapter1));```

Also, in your JSON tests is an object. Are you sure you can apply each to an object? Maybe you should use an array. You can change the JSON or you can make a registerHelper that creates an array from the values. Use: Object.values(tests).
Hope it helps.

Body:
I would like to sort objects keys with each:
test1, test4, test3 => test1, test3, test4
...

My json:

"tests": {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
}

My handlebars code:

{{#each tests}}

{{@key}}

{{#eachSorted this}}
{{this}}
{{/eachSorted}}

{{/each}}

I tried but does not work:

Handlebars.registerHelper('eachSorted', function(context, options) {
    var ret = ""
    Object.keys(context).sort().forEach(function(key) {
        ret = ret + options.fn({key: key, value: context[key]})
    })
    return ret
})

Body:
Replace the eachSorted function with this:

var tests = {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
};

function eachSorted(context) {
    var ret = {};
 Object.keys(context)
  .sort()
  .forEach(function(key) {
   ret[key] = context[key];
    });
    return ret;
}

console.log(eachSorted(tests.chapter1));

Also, in your JSON tests is an object. Are you sure you can apply each to an object? Maybe you should use an array. You can change the JSON or you can make a registerHelper that creates an array from the values. Use: Object.values(tests).
Hope it helps.


问:
Axios Async-Await in React
I'm trying to do some get, and post request, somehow the state got updated late (it should be .get, then .post)

```<code>async componentDidMount() {

    const {destination, weight} = this.state;

    axios.get(`https://myapi`)
        .then(res => {
            const customer = res.data;

            this.setState({ customer,
                destination: customer[0].address[0].city,
            }
        })

   axios.post(`https://myapi`, {destination, weight})
        .then((post)=>{
          const delivery = post.data;
            this.setState({ delivery,
              cost: delivery[0].cost[0].value
             });
        });

        return post;
}
</code>```

the state got updated, but somehow the post got error that destination should be filled. I find the solution of this is to use async await. I try to implement it but it doesn't work.

here's what i've tried

```<code>async componentDidMount() {

        const {destination, weight} = this.state;

        axios.get(`https://myapi`)
            .then(res => {
                const customer = res.data;

                this.setState({ customer,
                    destination: customer[0].address[0].city,
                }
            })

const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
            .then((post)=>{
          console.log(this.state.destination);
              const delivery = post.data;
                this.setState({ delivery,
                  cost: delivery[0].cost[0].value
                 });
            });

            return post;
}
</code>```

i tried to console log the state of destination and yes it's indeed updated. am i doing async await wrong? thank you for your help!

答:
```<code>try{
   let res = await axios.get(`https://myapi`);
   if (res) {
     const customer = res.data;
     this.setState({ customer,
        destination: customer[0].address[0].city,
     });
     const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
     if (postRes) {
       const delivery = post.data;
         this.setState({ delivery,
           cost: delivery[0].cost[0].value
         });
     }
   }
}catch (err) {
  console.log(err);
}
</code>```

If you want to use post outside if its upto you.

Title: Axios Async-Await in React

Body:
I'm trying to do some get, and post request, somehow the state got updated late (it should be .get, then .post)

async componentDidMount() {

    const {destination, weight} = this.state;

    axios.get(`https://myapi`)
        .then(res => {
            const customer = res.data;

            this.setState({ customer,
                destination: customer[0].address[0].city,
            }
        })

   axios.post(`https://myapi`, {destination, weight})
        .then((post)=>{
          const delivery = post.data;
            this.setState({ delivery,
              cost: delivery[0].cost[0].value
             });
        });

        return post;
}

the state got updated, but somehow the post got error that destination should be filled. I find the solution of this is to use async await. I try to implement it but it doesn't work.

here's what i've tried

async componentDidMount() {

        const {destination, weight} = this.state;

        axios.get(`https://myapi`)
            .then(res => {
                const customer = res.data;

                this.setState({ customer,
                    destination: customer[0].address[0].city,
                }
            })

const post = await axios.post(`https://api.cashless.vip/api/cost`, {destination, weight})
            .then((post)=>{
          console.log(this.state.destination);
              const delivery = post.data;
                this.setState({ delivery,
                  cost: delivery[0].cost[0].value
                 });
            });

            return post;
}

i tried to console log the state of destination and yes it's indeed updated. am i doing async await wrong? thank you for your help!

Body:
try{
   let res = await axios.get(`https://myapi`);
   if (res) {
     const customer = res.data;
     this.setState({ customer,
        destination: customer[0].address[0].city,
     });
     const postRes = await axios.post(`https://api.cashless.vip/api/cost`);
     if (postRes) {
       const delivery = post.data;
         this.setState({ delivery,
           cost: delivery[0].cost[0].value
         });
     }
   }
}catch (err) {
  console.log(err);
}

If you want to use post outside if its upto you.