问:
creating s3 bucket and folders inside it using node js in aws lambda function
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

```<code>const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};
</code>```

The code for creating folders inside the Lambda function is as following --

```<code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });
</code>```

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

```<code>aws s3api create-bucket --bucket psychology06 --region us-east-1

</code>```

I am not sure, where am i making a mistake.

答: Make sure the bucket with same name is not present.Please share log if possible.</p>

Body:
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};

The code for creating folders inside the Lambda function is as following --

var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

aws s3api create-bucket --bucket psychology06 --region us-east-1

I am not sure, where am i making a mistake.


来源: stackexchange

问:
How to resolve lists of IAsyncEnumerables as soon as a item is ready
```<code>public async IAsyncEnumerable<Entity> FindByIds(List<string> ids)
    {
        List<List<string>> splitIdsList = ids.Split(5);

        var entityList = splitIdsList.Select(x => FindByIdsQuery(x)).ToList();

        foreach (var entities in entityList)
        {
            await foreach (var entity in entities)
            {
                yield return entity;
            }
        }
    }

private async IAsyncEnumerable<Entity> FindByIdsQuery(List<string> ids)
    {
        var result = await Connection.QueryAsync(query, new {ids})

        foreach (var entity in result)
        {
            yield return entity;
        }
    }
</code>```

If I send 25 ids to this function. The first FindByIdsQuery takes 5000ms. The other 4 FindByIdsQuery takes 100ms. Then this solution wont output any Entities, until after 5000ms. Is there any solution that will start outputting entities as soon as there exist anyone to output. Or, if you could do something like in Task, with Task.WhenAny.

To be clear: Any of the 5 Queries can take 5000ms.

答:
The problem is that your code makes them wait. There is NO sense in an async foreach here because - you do not do async.

You do this:

var entityList = splitIdsList.Select(x => FindByIdsQuery(x)).ToList();

This is the part of the query that could run async, but it does not because you materialize the whole result set into a list. You then go on async looping over it, but at that point all results already are in memory.

The way to get async is simply to get rid of ToList. Dump the query into foreach, do not materialize it into memory. The async foreach should hit the ef level query (not query result) so you can process information as you get it from the database. ToList efficiently bypasses this.

Also understand that EF can not efficiently handle multiple id lookups. The only possibly way for it to do it is put them into an array and contains, which is a SQL "IN" clause - terribly inefficient for larger numbers as it forces table scan. The efficient SQL way would be to load them into a table valued variable with statistics and use a join, but there is no way to do that in EF - one of the limitations. The SQL limitations of long IN clauses are well documented. The limitations of the EF side not, but they are still there.

ContentLicense: CC BY-SA 4.0

Body:
public async IAsyncEnumerable<Entity> FindByIds(List<string> ids)
    {
        List<List<string>> splitIdsList = ids.Split(5);

        var entityList = splitIdsList.Select(x => FindByIdsQuery(x)).ToList();

        foreach (var entities in entityList)
        {
            await foreach (var entity in entities)
            {
                yield return entity;
            }
        }
    }

private async IAsyncEnumerable<Entity> FindByIdsQuery(List<string> ids)
    {
        var result = await Connection.QueryAsync(query, new {ids})

        foreach (var entity in result)
        {
            yield return entity;
        }
    }

If I send 25 ids to this function. The first FindByIdsQuery takes 5000ms. The other 4 FindByIdsQuery takes 100ms. Then this solution wont output any Entities, until after 5000ms. Is there any solution that will start outputting entities as soon as there exist anyone to output. Or, if you could do something like in Task, with Task.WhenAny.

To be clear: Any of the 5 Queries can take 5000ms.


问:
How to write sql to get data when using postgresql and EF?
I have the below C# and Entity framework 6.4 code to get data from

postgresql function

```<code>return Database.SqlQuery<TEntity>(sql, parameters).ToArrayAsync();
</code>```

and I tried

```<code>var sql = $@"select * from GetLogs(?,?,?,?,?,?,?,?,?,?,?,?,?)"; or
var sql = $@"select * from GetLogs($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";
</code>```

but got failed, anybody know about it?

I also try

```<code>var sql = "select * from GetLogs(TO_TIMESTAMP({0},'YYYY-MM-DD HH24:MI:SS'), TO_TIMESTAMP({1},'YYYY-MM-DD HH24:MI:SS'),{2},'{3}','{4}',{5},'{6}','{7}',{8},{9},{10})";
            var from = request.From.ToString("yyyy-MM-dd HH:mm:ss");
            var to = request.To.ToString("yyyy-MM-dd HH:mm:ss");
            return Database.SqlQuery<AdminLogMasterModel>(sql,
                from,
                to,
                request.HttpStatusCode,
                request.ServerName,
                request.Page,
                request.TrackingId,
                request.Content,
                request.SortBy,
                request.OrderBy == SortOrder.Ascending ? 0 : 1,
                request.Page,
                request.Rows).ToArrayAsync();
</code>```

This got no error but no date return. It seems postgresql didn't pass parameter in EF.

答:
I tried the below code can work</p>

```<code>        var sql = "select * from GetLogs(TO_TIMESTAMP(@p0,'YYYY-MM-DD HH24:MI:SS'),TO_TIMESTAMP(@p1,'YYYY-MM-DD HH24:MI:SS'),@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10)";
        var para = new NpgsqlParameter[]
            {
                new NpgsqlParameter("@p0", request.From.ToString("yyyy-MM-dd HH:mm:ss")),
                new NpgsqlParameter("@p1", request.To.ToString("yyyy-MM-dd HH:mm:ss")),
                new NpgsqlParameter("@p2", CreateRequestValueifNull(request.HttpStatusCode)),
                new NpgsqlParameter("@p3", CreateRequestValueifNull(request.ServerName)),
                new NpgsqlParameter("@p4", CreateRequestValueifNull(request.Path)),
                new NpgsqlParameter("@p5", CreateRequestValueifNull(request.TrackingId)),
                new NpgsqlParameter("@p6", CreateRequestValueifNull(request.Content)),
                new NpgsqlParameter("@p7", request.SortBy),
                new NpgsqlParameter("@p8", request.OrderBy == SortOrder.Ascending ? 0 : 1),
                new NpgsqlParameter("@p9", request.Page),
                new NpgsqlParameter("@p10", request.Rows),
            };
        return Database.SqlQuery<LogModel>(sql, para).ToArrayAsync();
</code>```

Body:
I have the below C# and Entity framework 6.4 code to get data from

postgresql function

return Database.SqlQuery<TEntity>(sql, parameters).ToArrayAsync();

and I tried

var sql = $@"select * from GetLogs(?,?,?,?,?,?,?,?,?,?,?,?,?)"; or
var sql = $@"select * from GetLogs($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)";

but got failed, anybody know about it?

I also try

var sql = "select * from GetLogs(TO_TIMESTAMP({0},'YYYY-MM-DD HH24:MI:SS'), TO_TIMESTAMP({1},'YYYY-MM-DD HH24:MI:SS'),{2},'{3}','{4}',{5},'{6}','{7}',{8},{9},{10})";
            var from = request.From.ToString("yyyy-MM-dd HH:mm:ss");
            var to = request.To.ToString("yyyy-MM-dd HH:mm:ss");
            return Database.SqlQuery<AdminLogMasterModel>(sql,
                from,
                to,
                request.HttpStatusCode,
                request.ServerName,
                request.Page,
                request.TrackingId,
                request.Content,
                request.SortBy,
                request.OrderBy == SortOrder.Ascending ? 0 : 1,
                request.Page,
                request.Rows).ToArrayAsync();

This got no error but no date return. It seems postgresql didn't pass parameter in EF.

Body:
I tried the below code can work

        var sql = "select * from GetLogs(TO_TIMESTAMP(@p0,'YYYY-MM-DD HH24:MI:SS'),TO_TIMESTAMP(@p1,'YYYY-MM-DD HH24:MI:SS'),@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10)";
        var para = new NpgsqlParameter[]
            {
                new NpgsqlParameter("@p0", request.From.ToString("yyyy-MM-dd HH:mm:ss")),
                new NpgsqlParameter("@p1", request.To.ToString("yyyy-MM-dd HH:mm:ss")),
                new NpgsqlParameter("@p2", CreateRequestValueifNull(request.HttpStatusCode)),
                new NpgsqlParameter("@p3", CreateRequestValueifNull(request.ServerName)),
                new NpgsqlParameter("@p4", CreateRequestValueifNull(request.Path)),
                new NpgsqlParameter("@p5", CreateRequestValueifNull(request.TrackingId)),
                new NpgsqlParameter("@p6", CreateRequestValueifNull(request.Content)),
                new NpgsqlParameter("@p7", request.SortBy),
                new NpgsqlParameter("@p8", request.OrderBy == SortOrder.Ascending ? 0 : 1),
                new NpgsqlParameter("@p9", request.Page),
                new NpgsqlParameter("@p10", request.Rows),
            };
        return Database.SqlQuery<LogModel>(sql, para).ToArrayAsync();


问:
Select value of selection field from javascript in odoo 12
I want to select the value of the selection field using javascript or jquery in odoo 12. e.g. I have a value of selection from javascript I want to select or set the value of the selection field. For that I am writing the following code :

```<code>var type_option = result['type'];
$('.select_question select').find('option[value="free_text"]').show();
$('.select_question select').val('option[value="free_text"]');
$('.select_question select').val(type_option);
$('.select_question select').text(type_option);
</code>```

But in selection field value is not selected. can any one please help.

Update

```<code>var FieldMany2ManyTags = relationalField.FieldMany2ManyTags.include({
    supportedFieldTypes: ['selection'],
    events: _.extend({}, relationalField.FieldMany2ManyTags.prototype.events, {
        'click .badge': '_onClickTag',
    }),

    _onClickTag: function(event){
        event.preventDefault();
            event.stopPropagation();
        var self = this;
        var id = $(event.target).parent().data('id');

        var data = this._rpc({
            model: 'survey.survey',
            method: 'get_id',
            args: [id],
        }).then(function (result) {

            //Display Question In question field
            $('.question_class').val(result['question']);

            //Show selection field
            var type_option = result['type'];//selection field value
            var type_option = result['type'];
            $('.select_question select').find('option[value="free_text"]').show();
            $('.select_question select').val('option[value="free_text"]');
            $('.select_question select').val(type_option);
            $('.select_question select').text(type_option);

            //For check Box
            $('.mandatory_class .custom-control-input input').val(result['constr_mandatory']);

            if(result['constr_mandatory'] === true){

                 var $checkbox = $('.custom-control-input');
                         $checkbox.prop('checked', true);

                if ($checkbox.is(':checked')) {
                            $('.mandatory_msg_class').val(result['constr_error_msg']);
                    $('.o_form_label').show();
                    $('.mandatory_msg_class').show();
                     }
            }else{

                var $checkbox = $('.custom-control-input');
                         $checkbox.prop('checked', false);
                if ($checkbox.not(':checked')) {
                    $('.mandatory_msg_class').hide();
                     }//close if
            }

        });

        return data;

    },
});//close FieldMany2ManyTags
</code>```

答:
To update a field value you need to trigger Odoo event field_change passing the record ID that you want to change and the field that will be changed along with some option for other fields:

    // this is the widget object
    this.trigger_up('field_changed',
                    dataPointID: this.dataPointID,
                    changes: changes, // change is an object {field_name: value, other_field_name: value}
                    viewType: this.viewType});
```

<p>This event is handled by the <code>BasicModel</code> at the end to update each record.</p>

<p>In you example things is more complicated because you want to go from a field in your one2many to the parent model, unfortunately in the widget of the question field we don't have the ID of the parent record only the ID of the page model or whatever is called. so I used a new custom odoo event (I named it <code>badge_clicked</code>) to handle it from the parent widget (<code>One2many field widget</code>) in this widget we have the ID of the parent record. Hope comments clears things for you:</p>

```/*
   Handle event trigged by the method that handle the badge click event
*/
FieldX2Many.include({
    custom_events: _.extend({}, FieldX2Many.prototype.custom_events, {
          badge_clicked: '_OnBadgeClicked',
    }),
    _OnBadgeClicked : function(ev){
        // do this only in edit mode
        if (this.mode != 'edit')
                return undefined;

        var result = ev.data.result;
        var changes = {};
        // this will trigger an update on the field it self,
        // odoo will wait for the type of operation

        //Display Question In question field ( I don't know the field names)
        // Very Big Note: the values must be valid you cannot give an interger value to char field for example
        changes['field_name'] = result['question'];
        changes['some_other_field'] = result['some_ther_field_to_set'];
        // if you want to check some field of the current record don't use JQuery to retrieve the value use the record attribute of the widget.
        // if (this.record.data['some_field'] === 'some_value'){
        //        do some thing
        // }

        // this is required(a dummy update to avoid unexpected behavior by the field_changed event)
        changes[this.name] = {
                operation: 'UPDATE',
                id: ev.data.dataPointID,
                changes: {} };

        // we did all of this just to trigger the field_changed from the One2many field because in the many2many tags we don't have the ID of the parent record.
        this.trigger_up('field_changed', {
            dataPointID: this.dataPointID,  // here the ID is the parent(global) record
            changes: changes,
            viewType: this.viewType});
     },
});

/*
   Handle click event to inform the parent widget.
*/
FieldMany2ManyTags.include({
    events: _.extend({}, FieldMany2ManyTags.prototype.events, {
        'click .badge': '_onClickTag',
    }),
     _onClickTag: function(event){
            var self = this;
            event.preventDefault();
            event.stopPropagation();
            // deactivate this for other model.
            // I tried the same thing with account.invoice and it worked perfectly
            // I don't know the name of the model in your one2many field in my case is invoice.line ^^
            if (self.model != 'account.invoice.line')
                return undefined;
            var self = this;
        var id = $(event.target).parent().data('id');

        var data = this._rpc({
            model: 'survey.survey',
            method: 'get_id',
            args: [id],
        }).then(function (result) {
           // trigger an event that will be handled by the parent widget
           self.trigger_up('badge_clicked', {
                result: result,
                // when we click the One2many field in edit mode, a field_change will be trigger
                // we need the ID of this record to trigger a dummy update
                dataPointID: self.dataPointID,  // here the ID is the record in the line of one2many field and we don't have the ID of the parent record at this point this why we are triggering this event to be handled by the one2many
           });
        }
     },
});
```

Note: I tried this and it worked perfectly I changed the comment field of the invoice model by clicking on the tax tags, the Idea is to trigger an Odoo event from the click event handler and handle that event at the parent widget witch is one2many to be able to trigger field_change event using the correct ID. I hope you this helps you

Body:
I want to select the value of the selection field using javascript or jquery in odoo 12. e.g. I have a value of selection from javascript I want to select or set the value of the selection field. For that I am writing the following code :

var type_option = result['type'];
$('.select_question select').find('option[value="free_text"]').show();
$('.select_question select').val('option[value="free_text"]');
$('.select_question select').val(type_option);
$('.select_question select').text(type_option);

But in selection field value is not selected. can any one please help.

Update

var FieldMany2ManyTags = relationalField.FieldMany2ManyTags.include({
    supportedFieldTypes: ['selection'],
    events: _.extend({}, relationalField.FieldMany2ManyTags.prototype.events, {
        'click .badge': '_onClickTag',
    }),

    _onClickTag: function(event){
        event.preventDefault();
            event.stopPropagation();
        var self = this;
        var id = $(event.target).parent().data('id');

        var data = this._rpc({
            model: 'survey.survey',
            method: 'get_id',
            args: [id],
        }).then(function (result) {

            //Display Question In question field
            $('.question_class').val(result['question']);

            //Show selection field
            var type_option = result['type'];//selection field value
            var type_option = result['type'];
            $('.select_question select').find('option[value="free_text"]').show();
            $('.select_question select').val('option[value="free_text"]');
            $('.select_question select').val(type_option);
            $('.select_question select').text(type_option);

            //For check Box
            $('.mandatory_class .custom-control-input input').val(result['constr_mandatory']);

            if(result['constr_mandatory'] === true){

                 var $checkbox = $('.custom-control-input');
                         $checkbox.prop('checked', true);

                if ($checkbox.is(':checked')) {
                            $('.mandatory_msg_class').val(result['constr_error_msg']);
                    $('.o_form_label').show();
                    $('.mandatory_msg_class').show();
                     }
            }else{

                var $checkbox = $('.custom-control-input');
                         $checkbox.prop('checked', false);
                if ($checkbox.not(':checked')) {
                    $('.mandatory_msg_class').hide();
                     }//close if
            }

        });

        return data;

    },
});//close FieldMany2ManyTags

Body:
To update a field value you need to trigger Odoo event field_change passing the record ID that you want to change and the field that will be changed along with some option for other fields:

    // this is the widget object
    this.trigger_up('field_changed',
                    dataPointID: this.dataPointID,
                    changes: changes, // change is an object {field_name: value, other_field_name: value}
                    viewType: this.viewType});

This event is handled by the BasicModel at the end to update each record.

In you example things is more complicated because you want to go from a field in your one2many to the parent model, unfortunately in the widget of the question field we don't have the ID of the parent record only the ID of the page model or whatever is called. so I used a new custom odoo event (I named it badge_clicked) to handle it from the parent widget (One2many field widget) in this widget we have the ID of the parent record. Hope comments clears things for you:

/*
   Handle event trigged by the method that handle the badge click event
*/
FieldX2Many.include({
    custom_events: _.extend({}, FieldX2Many.prototype.custom_events, {
          badge_clicked: '_OnBadgeClicked',
    }),
    _OnBadgeClicked : function(ev){
        // do this only in edit mode
        if (this.mode != 'edit')
                return undefined;

        var result = ev.data.result;
        var changes = {};
        // this will trigger an update on the field it self,
        // odoo will wait for the type of operation

        //Display Question In question field ( I don't know the field names)
        // Very Big Note: the values must be valid you cannot give an interger value to char field for example
        changes['field_name'] = result['question'];
        changes['some_other_field'] = result['some_ther_field_to_set'];
        // if you want to check some field of the current record don't use JQuery to retrieve the value use the record attribute of the widget.
        // if (this.record.data['some_field'] === 'some_value'){
        //        do some thing
        // }

        // this is required(a dummy update to avoid unexpected behavior by the field_changed event)
        changes[this.name] = {
                operation: 'UPDATE',
                id: ev.data.dataPointID,
                changes: {} };

        // we did all of this just to trigger the field_changed from the One2many field because in the many2many tags we don't have the ID of the parent record.
        this.trigger_up('field_changed', {
            dataPointID: this.dataPointID,  // here the ID is the parent(global) record
            changes: changes,
            viewType: this.viewType});
     },
});

/*
   Handle click event to inform the parent widget.
*/
FieldMany2ManyTags.include({
    events: _.extend({}, FieldMany2ManyTags.prototype.events, {
        'click .badge': '_onClickTag',
    }),
     _onClickTag: function(event){
            var self = this;
            event.preventDefault();
            event.stopPropagation();
            // deactivate this for other model.
            // I tried the same thing with account.invoice and it worked perfectly
            // I don't know the name of the model in your one2many field in my case is invoice.line ^^
            if (self.model != 'account.invoice.line')
                return undefined;
            var self = this;
        var id = $(event.target).parent().data('id');

        var data = this._rpc({
            model: 'survey.survey',
            method: 'get_id',
            args: [id],
        }).then(function (result) {
           // trigger an event that will be handled by the parent widget
           self.trigger_up('badge_clicked', {
                result: result,
                // when we click the One2many field in edit mode, a field_change will be trigger
                // we need the ID of this record to trigger a dummy update
                dataPointID: self.dataPointID,  // here the ID is the record in the line of one2many field and we don't have the ID of the parent record at this point this why we are triggering this event to be handled by the one2many
           });
        }
     },
});

Note: I tried this and it worked perfectly I changed the comment field of the invoice model by clicking on the tax tags, the Idea is to trigger an Odoo event from the click event handler and handle that event at the parent widget witch is one2many to be able to trigger field_change event using the correct ID. I hope you this helps you


问:
Is it possible for javascripts to have hrefs with IDs?
Is it possible to add an href containing an id to be inside runConfirm function? My aim is a pop-up to appear after I click accept and the accept button does the query from isset.

Here is my code for accepting.

```<code>$displaybody .= "<tr>
<td>" . $rows['lname'] . ", " . $rows['fname'] . "</td>
 <td>" . $rows['subject'] . "</td>
 <td>" . $rows['days'] . " " . $rows['rstime'] . " - " . $rows['retime'] . "
</td>
   <td>" . $rows['note'] . "</td>
  <td>
<a class='runConfirm' data-id='" . $rows['rid'] . "'>Accept</a>
<a href='home.php?decline=" . $rows['rid'] . "'>Decline</a>
</td>
</tr>"
</code>```

And here is my function for the popup. (Updated)

```<code><script type='text/javascript'>
        $(function(){
        $('.runConfirm').click(function(event){
          // get the id you want to act on
          var theId = $(this).data('rid');

          // ask user for confirmation
          alertify.confirm('Are you sure to accept this request?',

            // accepted
            function(){

              // go to the processing page
              window.location('/accept.php?rid=' + theId);
            },

            // declined
            function(){
              alertify.error('You clicked CANCEL');
          }).set('closable', false);

        });
        });
  </script>
</code>```

Accept.php containing the process for accepting the booking.

```<code>    <?php
    include("server.php");
    session_start();

    if(isset($_GET['accept']))
    {
      $rid=$_GET['accept'];
            $query=$mysqli->query("SELECT qid FROM requests WHERE rid='".$rid."'");
                if($query->num_rows>0)
                {
                        while($rows=$query->fetch_assoc())
                        {
                            $qid=$rows['qid'];
                        }
            }

     $query1=$mysqli->query("UPDATE qualified SET status='accepted' WHERE
   qid='".$qid."' ");
     $query=$mysqli->query("UPDATE requests SET action='accepted' WHERE
   rid='".$rid."'");

     header("Location:home.php");
   }

   ?>
</code>```

答:
When generating the DOM, you could add a data attribute to the "Confirm" link which you could then access from your runConfirm click callback function.

Assuming that the id you want to use is in $rows['rid'] that would give:
(showing only changed parts for clarity)

Dom generation

$displaybody .= "

  " . $rows['lname'] . ", " . $rows['fname'] . "
  " . $rows['subject'] . "
  " . $rows['days'] . " " . $rows['rstime'] . " - " . $rows['retime'] . "
  " . $rows['note'] . "

    Accept
    Decline

"
```

<p><strong>Popup handling</strong> (updated)</p>

<pre class="lang-js prettyprint-override"><code>$('.runConfirm').click(function(event){
  // get the id you want to act on
  var theId = $(this).data('id');

  // ask user for confirmation
  alertify.confirm('Are you sure to accept this request?',

    // accepted
    function(){

      // go to the processing page
      window.location = '/accept.php?rid=' + theId;
    },

    // declined
    function(){
      alertify.error('You clicked CANCEL');
  }).set('closable', false);

});
</code>```

And your third snippet would go in accept.php.

Your code will:

Render your table with row ids as data attribute

When clicking on "Accept", prompt the user for confirmation and send him to "accept.php" page.

Run the post-process code on the server which will eventually redirect the user to "home.php"

You can find out more on jQuery data in the doc: https://api.jquery.com/data/

Body:
Is it possible to add an href containing an id to be inside runConfirm function? My aim is a pop-up to appear after I click accept and the accept button does the query from isset.

Here is my code for accepting.

$displaybody .= "

" . $rows['lname'] . ", " . $rows['fname'] . "
 " . $rows['subject'] . "
 " . $rows['days'] . " " . $rows['rstime'] . " - " . $rows['retime'] . "

   " . $rows['note'] . "

Accept
Decline

"

And here is my function for the popup. (Updated)

Accept.php containing the process for accepting the booking.

    <?php
    include("server.php");
    session_start();

    if(isset($_GET['accept']))
    {
      $rid=$_GET['accept'];
            $query=$mysqli->query("SELECT qid FROM requests WHERE rid='".$rid."'");
                if($query->num_rows>0)
                {
                        while($rows=$query->fetch_assoc())
                        {
                            $qid=$rows['qid'];
                        }
            }

     $query1=$mysqli->query("UPDATE qualified SET status='accepted' WHERE
   qid='".$qid."' ");
     $query=$mysqli->query("UPDATE requests SET action='accepted' WHERE
   rid='".$rid."'");

     header("Location:home.php");
   }

   ?>

Body:
When generating the DOM, you could add a data attribute to the "Confirm" link which you could then access from your runConfirm click callback function.

Assuming that the id you want to use is in $rows['rid'] that would give:
(showing only changed parts for clarity)

Dom generation

$displaybody .= "<tr>
  <td>" . $rows['lname'] . ", " . $rows['fname'] . "</td>
  <td>" . $rows['subject'] . "</td>
  <td>" . $rows['days'] . " " . $rows['rstime'] . " - " . $rows['retime'] . "</td>
  <td>" . $rows['note'] . "</td>
  <td>
    <a class='runConfirm' data-id='" . $rows['rid'] . "'>Accept</a>
    <a href='home.php?decline=" . $rows['rid'] . "'>Decline</a>
  </td>
</tr>"

Popup handling (updated)

$('.runConfirm').click(function(event){
  // get the id you want to act on
  var theId = $(this).data('id');

  // ask user for confirmation
  alertify.confirm('Are you sure to accept this request?',

    // accepted
    function(){

      // go to the processing page
      window.location = '/accept.php?rid=' + theId;
    },

    // declined
    function(){
      alertify.error('You clicked CANCEL');
  }).set('closable', false);

});

And your third snippet would go in accept.php.

Your code will:

Render your table with row ids as data attribute

When clicking on "Accept", prompt the user for confirmation and send him to "accept.php" page.

Run the post-process code on the server which will eventually redirect the user to "home.php"

You can find out more on jQuery data in the doc: https://api.jquery.com/data/


问:
What's the most idiomatic way to pass data between embedded struct?
I have two structs

```<code>//Pseudo code
type task struct {}
type tasks struct []{
     t task
}
</code>```

I want to run one task and after it finished to pass information to tasks:  For example, after task1 and task2 finished, notify tasks , and then run task3. So this one task.finished() have to notify tasks. and tasks have to make sure both task1 and task2 have finished then to trigger task3.

```<code> //Pseudo code
 task1.start() and task2.start() at the same time

 if  task1.finished() && task2.finished():
     task3.run()
</code>```

What's the most idiomatic way to pass data between embedded structs?

I understand such logic should be proceed in tasks but how do task1 and task2 tell tasks they are finished?

Should I introduce a new struct that stores the information needed for exchange called "taskManager"?

答:
```<code>type tasks []*task

type task struct {
    Data       int
    onComplete chan struct{}
}

var wg sync.WaitGroup

// each task will in one goroutine
// pointer receiver
func (t *task) Run() {
    defer wg.Done()

    sleepTime := time.Second * time.Duration(t.Data)

    fmt.Println("Task:", t.Data, "sleeping for", sleepTime)
    time.Sleep(sleepTime)

    fmt.Println("Task:", t.Data, "done")

    // Once work is done, Inform, if we have to
    if t.onComplete != nil {
        t.onComplete <- struct{}{}
    }
}

// Run given tasks
func Run(ts tasks) {
    wg.Add(len(ts))

    for _, t := range ts {
        // run each task in seperate goroutines
        go t.Run()
    }
}

func (ts tasks) OnComplete(pending tasks) {
    tempChan := make(chan struct{})

    // all tasks should inform to `tempChan`,
    // once done
    for _, t := range ts {
        t.onComplete = tempChan
    }

    tasksNum := len(ts)

    wg.Add(1)
    go func() {
        // once we receive enough signals
        // i.e., once all `ts` tasks are done run pending tasks
        for range tempChan {
            tasksNum--
            if tasksNum == 0 {
                Run(pending)
                close(tempChan)
            }
        }
        wg.Done()
    }()
}

func main() {

    // define tasks
    mainTasks := tasks{
        {Data: 1},
        {Data: 2},
    }

    // tasks which need to run once certain tasks were done
    pendingTasks := tasks{
        {Data: 3},
    }

    // Inform to run pending tasks once mainTasks are done
    mainTasks.OnComplete(pendingTasks)

    // start runing your main tasks
    Run(mainTasks)

    wg.Wait()
}
</code>```

Go PlayGround

In-fact you can keep on chaining the work, were pendingTasks.OnComplete(someMoreTasks)

Then run mainTasks, once done will run PendingTasks, once done will run someMoreTasks.

Other kind of complex relations are possible as well.

Body:
I have two structs

//Pseudo code
type task struct {}
type tasks struct []{
     t task
}

I want to run one task and after it finished to pass information to tasks:  For example, after task1 and task2 finished, notify tasks , and then run task3. So this one task.finished() have to notify tasks. and tasks have to make sure both task1 and task2 have finished then to trigger task3.

 //Pseudo code
 task1.start() and task2.start() at the same time

 if  task1.finished() && task2.finished():
     task3.run()

What's the most idiomatic way to pass data between embedded structs?

I understand such logic should be proceed in tasks but how do task1 and task2 tell tasks they are finished?

Should I introduce a new struct that stores the information needed for exchange called "taskManager"?

Body:
type tasks []*task

type task struct {
    Data       int
    onComplete chan struct{}
}

var wg sync.WaitGroup

// each task will in one goroutine
// pointer receiver
func (t *task) Run() {
    defer wg.Done()

    sleepTime := time.Second * time.Duration(t.Data)

    fmt.Println("Task:", t.Data, "sleeping for", sleepTime)
    time.Sleep(sleepTime)

    fmt.Println("Task:", t.Data, "done")

    // Once work is done, Inform, if we have to
    if t.onComplete != nil {
        t.onComplete <- struct{}{}
    }
}

// Run given tasks
func Run(ts tasks) {
    wg.Add(len(ts))

    for _, t := range ts {
        // run each task in seperate goroutines
        go t.Run()
    }
}

func (ts tasks) OnComplete(pending tasks) {
    tempChan := make(chan struct{})

    // all tasks should inform to `tempChan`,
    // once done
    for _, t := range ts {
        t.onComplete = tempChan
    }

    tasksNum := len(ts)

    wg.Add(1)
    go func() {
        // once we receive enough signals
        // i.e., once all `ts` tasks are done run pending tasks
        for range tempChan {
            tasksNum--
            if tasksNum == 0 {
                Run(pending)
                close(tempChan)
            }
        }
        wg.Done()
    }()
}

func main() {

    // define tasks
    mainTasks := tasks{
        {Data: 1},
        {Data: 2},
    }

    // tasks which need to run once certain tasks were done
    pendingTasks := tasks{
        {Data: 3},
    }

    // Inform to run pending tasks once mainTasks are done
    mainTasks.OnComplete(pendingTasks)

    // start runing your main tasks
    Run(mainTasks)

    wg.Wait()
}

Go PlayGround

In-fact you can keep on chaining the work, were pendingTasks.OnComplete(someMoreTasks)

Then run mainTasks, once done will run PendingTasks, once done will run someMoreTasks.

Other kind of complex relations are possible as well.


问:
HTML Canvas Layering Frameworks
I'm building an app using the HTML 5 canvas tag, and so far it works great. The next step for the app is layering, so that I have a background image and them some more layers on top of that. Right now I'm doing this:

```<code>this.drawMarkers = function(markers) {
    selectedImage = null;
    map.width = map.width;
    for(var i in markers) {
        for(var j in markers[i]) {
            var holder = markers[i][j];
            if(holder !== null) {
                var marker = new Marker(new Cell(holder.row, holder.column), holder.type);
                marker.src = holder.src;
                marker.draw();
            }
        }
    }
    initGrid();
}
</code>```

where i is the layer and j is the things on that layer. The initial code for this just drew everything on one layer and it worked great, and this one does too if everything downloads in the correct order. If not, things get stacked incorrectly. For example, if the background is large and ends up downloading last, it ends up clearing out everything on top of it due to everything being asynchronous.

Are there any frameworks out there for adding layering to canvas to avoid this? I'm fine if things don't load in the correct order, so long as the stacking is preserved.

答:
First question to ask yourself:

If you draw it repeatedly, say every 100 milliseconds, does the problem go away?

If no, the "drawing in the wrong order" is something you are doing and not an async error. I suspect this might be the case.

Images may not draw, but nothing should draw in the wrong order, assuming your draw routine is correct and that you are redrawing everything each time. According to the canvas spec, a call to drawImage does nothing if the image isn't loaded, so incorrect stacking should be impossible unless it is the order of your own calls.

In any case, you should wait until all of the images you are going to use have loaded before you draw. Use their onload events and/or $(window).load() or jQuery(document).ready, etc.

Some other notes:

Depending on how interactive your canvas is and how the layers work, sometimes it is better to use multiple canvases stacked on top of each other to increase performance, especially if a top layer changes very little and a layer underneath changes often.

If your background is a static file such as a png, set the CSS background-image of the canvas to that image to make the drawing easier on yourself.

ContentLicense: CC BY-SA 3.0

Title: HTML Canvas Layering Frameworks

Body:
I'm building an app using the HTML 5 canvas tag, and so far it works great. The next step for the app is layering, so that I have a background image and them some more layers on top of that. Right now I'm doing this:

this.drawMarkers = function(markers) {
    selectedImage = null;
    map.width = map.width;
    for(var i in markers) {
        for(var j in markers[i]) {
            var holder = markers[i][j];
            if(holder !== null) {
                var marker = new Marker(new Cell(holder.row, holder.column), holder.type);
                marker.src = holder.src;
                marker.draw();
            }
        }
    }
    initGrid();
}

where i is the layer and j is the things on that layer. The initial code for this just drew everything on one layer and it worked great, and this one does too if everything downloads in the correct order. If not, things get stacked incorrectly. For example, if the background is large and ends up downloading last, it ends up clearing out everything on top of it due to everything being asynchronous.

Are there any frameworks out there for adding layering to canvas to avoid this? I'm fine if things don't load in the correct order, so long as the stacking is preserved.


问:
Golang: tests and working directory
I'm writing some unit tests for my application in Go. The tests fail however because it cannot find the configuration files. Normally the binary looks for the configuration files in the working directory under the path conf/*.conf.

I figured that browsing to the directory that has conf/ and running go test in it would solve it, but it still reports that the file system cannot find the path specified.

How can I tell go test to use a certain directory as the working directory so that the tests may actually be executed?

答:
To add init function into *_test.go under your test package.
Test package will run this function before test function start.</p>
```<code>func init() {
    _, filename, _, _ := runtime.Caller(0)
    // The ".." may change depending on you folder structure
    dir := path.Join(path.Dir(filename), "..")
    err := os.Chdir(dir)
    if err != nil {
        panic(err)
    }
}
</code>```

Title: Golang: tests and working directory

Body:
To add init function into *_test.go under your test package.
Test package will run this function before test function start.

func init() {
    _, filename, _, _ := runtime.Caller(0)
    // The ".." may change depending on you folder structure
    dir := path.Join(path.Dir(filename), "..")
    err := os.Chdir(dir)
    if err != nil {
        panic(err)
    }
}


问:
How can I access request object in the loopback operational hooks?
I'm using loopback 3.x and I've written an Access Hook. I want to add some condition on the basis of User Agent.

So I'm willing to access Request > Headers > User-Agent.

Is it even possible to access it? if no then is there any other way I can achieve it?

答:
So I have managed to this using Remote hooks.

ModelName.beforeRemote('findById', (ctx, data, next) => {
     // ctx has req object that further contains the headers and my work is done
})
```

But still I'm opening the question for the further question if it is possible to do in the access hooks

Body:
So I have managed to this using Remote hooks.

ModelName.beforeRemote('findById', (ctx, data, next) => {
     // ctx has req object that further contains the headers and my work is done
})

But still I'm opening the question for the further question if it is possible to do in the access hooks


问:
"flutter doctor" command just returns "'flutter' is not recognized as an internal or external command, operable program or batch file."
I am trying to start learning flutter, but I can't get it to work. I have downloaded the file, extracted all files to my C drive, I added it to my path, but when I put "flutter doctor" into the flutter console it says "'flutter' is not recognized as an internal or external command, operable program or batch file.". Does anyone have any ideas on how to fix this and get it working?</p>

答: Add path/to/flutter/bin in environment variables and try.</p>


问:
Firebase doesn't register new users
I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.

This is my register activity

```<code>
    MaterialEditText username,  email, password;

    Button btn_register;

    FirebaseAuth auth;
    DatabaseReference reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Регистрация");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        username = findViewById(R.id.username);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        btn_register = findViewById(R.id.btn_register);

        auth = FirebaseAuth.getInstance();

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt_username = username.getText().toString();
                String txt_email = email.getText().toString();
                String txt_password = password.getText().toString();

                if (TextUtils.isEmpty(txt_username)  || TextUtils.isEmpty(txt_email)  ||  TextUtils.isEmpty(txt_password)) {

                    Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
                } else if (txt_password.length() < 6 ){
                    Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
                } else {
                    register(txt_username, txt_email, txt_password);
                }

            }
        });
    }
    private void register(final String username, String email, String password){
        auth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            FirebaseUser firebaseUser= auth.getCurrentUser();
                            assert firebaseUser !=null;
                            String userid = firebaseUser.getUid();

                            reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

                            HashMap<String, String> HashMap = new HashMap<>();
                            HashMap.put("id", userid);
                            HashMap.put("username", username);
                            HashMap.put("imageURL", "default");

                            reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if(task.isSuccessful()){

                                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            });
                        }else {
                            Toast.makeText(RegisterActivity.this, "You cant register", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}
</code>```

答:
in manifest file allow internet permission. if you continue this err create failure listener and print failure  code</p>

```<code> Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
</code>```

Title: Firebase doesn't register new users

Body:
I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.

This is my register activity

    MaterialEditText username,  email, password;

    Button btn_register;

    FirebaseAuth auth;
    DatabaseReference reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Регистрация");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        username = findViewById(R.id.username);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        btn_register = findViewById(R.id.btn_register);

        auth = FirebaseAuth.getInstance();

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt_username = username.getText().toString();
                String txt_email = email.getText().toString();
                String txt_password = password.getText().toString();

                if (TextUtils.isEmpty(txt_username)  || TextUtils.isEmpty(txt_email)  ||  TextUtils.isEmpty(txt_password)) {

                    Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
                } else if (txt_password.length() < 6 ){
                    Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
                } else {
                    register(txt_username, txt_email, txt_password);
                }

            }
        });
    }
    private void register(final String username, String email, String password){
        auth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            FirebaseUser firebaseUser= auth.getCurrentUser();
                            assert firebaseUser !=null;
                            String userid = firebaseUser.getUid();

                            reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

                            HashMap<String, String> HashMap = new HashMap<>();
                            HashMap.put("id", userid);
                            HashMap.put("username", username);
                            HashMap.put("imageURL", "default");

                            reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if(task.isSuccessful()){

                                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            });
                        }else {
                            Toast.makeText(RegisterActivity.this, "You cant register", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}

Body:
in manifest file allow internet permission. if you continue this err create failure listener and print failure  code

 Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();


问:
Apply CSS style/class to div
I have some div elements

The structure is

```<code><div id="comment">
  <div id="m1">...</div>
  <div id="m2">...</div>
</div>
</code>```

I want to apply some CSS or Class to the even/odd inner div of comments (or to the m1/m2 div)

So i coded this, but it did not worked :(

```<code>$("div>div:even").addClass("evn");
</code>```

What i'm missing ?

答:
This link can help you to solve your proble

First , define the tables and div as shown below in the “index.html” file,

```<code><table border="1">
  <tr><td>Michael</td></tr>
  <tr><td>Sam</td></tr>
  <tr><td>John</td></tr>
  <tr><td>Jason</td></tr>
</table>
 <div>Michael</div>
 <div>Sam</div>
 <div>John</div>
 <div>Jason</div>
</code>```

Now, we need to write the script for displaying the different color in the alternate row,

```<code><script src="jquery.js"></script>
<script>
$(document).ready(function()
{
  //for div
  $("div:odd").css("background-color", "#F4F4F8");
  $("div:even").css("background-color", "#EFF1F1");
  //for table row
  $("tr:even").css("background-color", "#F4F4F8");
  $("tr:odd").css("background-color", "#EFF1F1");
});
</script>
</code>```

The filters “even” and “odd” can be used in jQuery for selecting odd or even index of the elements.As you can see above the background color of the odd and even “div” are changed using the “css” method and “odd” and “even” filters of jQuery and the same applies for the even and odd “tr” which means for the row of table.

Title: Apply CSS style/class to div

Body:
I have some div elements

The structure is

...

...

I want to apply some CSS or Class to the even/odd inner div of comments (or to the m1/m2 div)

So i coded this, but it did not worked :(

$("div>div:even").addClass("evn");

What i'm missing ?

Body:
This link can help you to solve your proble

First , define the tables and div as shown below in the “index.html” file,

<table border="1">
  <tr><td>Michael</td></tr>
  <tr><td>Sam</td></tr>
  <tr><td>John</td></tr>
  <tr><td>Jason</td></tr>
</table>
 <div>Michael</div>
 <div>Sam</div>
 <div>John</div>
 <div>Jason</div>

Now, we need to write the script for displaying the different color in the alternate row,

<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
  //for div
  $("div:odd").css("background-color", "#F4F4F8");
  $("div:even").css("background-color", "#EFF1F1");
  //for table row
  $("tr:even").css("background-color", "#F4F4F8");
  $("tr:odd").css("background-color", "#EFF1F1");
});
</script>

The filters “even” and “odd” can be used in jQuery for selecting odd or even index of the elements.As you can see above the background color of the odd and even “div” are changed using the “css” method and “odd” and “even” filters of jQuery and the same applies for the even and odd “tr” which means for the row of table.


问:
Moving Backgrounds With Mouse Position ReactJS
I am doing an ecommerce using react and redux. I would like to know how I could make the photo of the product when clicked receive zoom and could be controlled by the mouse. Like this

I found this  article and I tried to make the third example but I am not able to put it in my code.

This is the code of my Modal.js and the style.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Container, Image } from './styles';

export default class Modal extends Component {
  onClose = e => {
    this.props.onClose && this.props.onClose(e);
  };

  render() {
    if (!this.props.show) {
      return null;
    }
    return (
      <Container>
        <button type="submit" onClick={this.onClose}>
          close
        </button>
        <Image>

 /*This is */{this.props.children}

        </Image>
      </Container>
    );
  }
}
Modal.propTypes = {
  onClose: PropTypes.func.isRequired,
  show: PropTypes.bool.isRequired,
};
```

<p>Styles.js</p>

<pre class="lang-js prettyprint-override"><code>import styled from 'styled-components';

export const Container = styled.div`
  position: fixed;
  max-width: 100%;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  padding-top: 30px;
  padding-bottom: 30px;
  z-index: 5;
  background: rgba(0, 0, 0, 0.5);

  > button {
    border: 0;
    position: absolute;
    width: 40px;
    height: 40px;
    border-radius: 20px;
    background: #7159c1;
    margin-top: 10px;
    margin-right: 30px;
    right: 0;
    top: 0;
  }
`;
export const Image = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  padding: 0 10%;
  border: 1px solid #f00;
  background: #ebedee;

  img {
    position: fixed;
    transform: scale(1);
    background-repeat: no-repeat;
    background-position: 0;
    transition: background-position 0.25s;
  }
`;

</code>```

答: Is there any limitation that you cannot use any existing libraries? because i can recommend you this library.</p>

Body:
I am doing an ecommerce using react and redux. I would like to know how I could make the photo of the product when clicked receive zoom and could be controlled by the mouse. Like this

I found this  article and I tried to make the third example but I am not able to put it in my code.

This is the code of my Modal.js and the style.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Container, Image } from './styles';

export default class Modal extends Component {
  onClose = e => {
    this.props.onClose && this.props.onClose(e);
  };

  render() {
    if (!this.props.show) {
      return null;
    }
    return (
      <Container>
        <button type="submit" onClick={this.onClose}>
          close
        </button>
        <Image>

 /*This is */{this.props.children}

        </Image>
      </Container>
    );
  }
}
Modal.propTypes = {
  onClose: PropTypes.func.isRequired,
  show: PropTypes.bool.isRequired,
};

Styles.js

import styled from 'styled-components';

export const Container = styled.div`
  position: fixed;
  max-width: 100%;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  padding-top: 30px;
  padding-bottom: 30px;
  z-index: 5;
  background: rgba(0, 0, 0, 0.5);

  > button {
    border: 0;
    position: absolute;
    width: 40px;
    height: 40px;
    border-radius: 20px;
    background: #7159c1;
    margin-top: 10px;
    margin-right: 30px;
    right: 0;
    top: 0;
  }
`;
export const Image = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  padding: 0 10%;
  border: 1px solid #f00;
  background: #ebedee;

  img {
    position: fixed;
    transform: scale(1);
    background-repeat: no-repeat;
    background-position: 0;
    transition: background-position 0.25s;
  }
`;


答:
To check the exists column, this should work for you.

```<code>Result.GridViewDataTable.Columns.Contains(tmpColumnName)
</code>```

Then, if you need the number after the columnName, you just put index after it. By the way, this snippet is not the best solution but I hope it can give you an idea of how to solve it. Hope this helps.

```<code>int userID = 0;
string[] columnNameParts;
Result.GridViewDataTable = ds.Tables[3];
for (int currCol = 1; currCol < Result.GridViewDataTable.Columns.Count; currCol++)
{
    columnNameParts = Result.GridViewDataTable.Columns[currCol].ColumnName.Split(new string[] { "---" }, StringSplitOptions.RemoveEmptyEntries);
    userID = int.Parse(columnNameParts[columnNameParts.Length - 1]);

    string columnName = ds.Tables[2].Select("Id = " + userID)[0]["FirstName"].ToString()
        + " "
        + ds.Tables[2].Select("Id = " + userID)[0]["LastName"].ToString().Substring(0, 1);

    //index
    int n = 0;
    //Create new temporary columnName which will add to the Columns later
    string tmpColumnName = columnName;
    //Check if column name is duplicate.
    while (Result.GridViewDataTable.Columns.Contains(tmpColumnName))
    {
        //Add 1 to index
        n++;
        //Create new name such as Matthew W1,Matthew W2,Daniel G1,Matthew W3,...
        tmpColumnName = columnName + n.ToString();
    }
    //Add new unique column name to Columns
    Result.GridViewDataTable.Columns[currCol].ColumnName = columnName;
}
</code>```

Title: How to check column name already consists in table

Body:
I have the following two datatables:

Table[2]

+----+-----------+----------+
| id | FirstName | LastName |
+----+-----------+----------+
| 10 | Fred      | Ramirez  |
+----+-----------+----------+
| 20 | Willie    | James    |
+----+-----------+----------+
| 30 | Daniel    | Green    |
+----+-----------+----------+
| 40 | Matthew   | Walker   |
+----+-----------+----------+
| 50 | Aaron     | Wright   |
+----+-----------+----------+
| 60 | Richard   | Huey     |
+----+-----------+----------+
| 80 | Matthew   | Walker   |
+----+-----------+----------+

and

Table[3]

+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+
| Services | Fred ---10--- | Willie ---20--- | Daniel  ---30--- | Matthew  ---40--- | Aaron  ---50--- | Richard  ---60--- | Matthew  ---80--- |
+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+
| XXX      | 0             | 0               | 0                | 0                 | 0               | 0                 | 0                 |
+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+
| AAA      | 0             | 0               | 0                | 0                 | 0               | 0                 | 0                 |
+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+
| CCC      | 0             | 0               | 0                | 0                 | 0               | 0                 | 0                 |
+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+
| DDD      | 0             | 0               | 0                | 0                 | 0               | 0                 | 0                 |
+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+
| YYY      | 0             | 0               | 0                | 0                 | 0               | 0                 | 0                 |
+----------+---------------+-----------------+------------------+-------------------+-----------------+-------------------+-------------------+

I need to get LastName from the Table[2] and make assign to  column name as FirstName + LastName

My code as follows,

int userID = 0;
string[] columnNameParts;
Result.GridViewDataTable = ds.Tables[3];
for (int currCol = 1; currCol < Result.GridViewDataTable.Columns.Count; currCol++)
{
    columnNameParts = Result.GridViewDataTable.Columns[currCol].ColumnName.Split(new string[] { "---" }, StringSplitOptions.RemoveEmptyEntries);
    userID = int.Parse(columnNameParts[columnNameParts.Length - 1]);

    string columnName = ds.Tables[2].Select("Id = " + userID)[0]["FirstName"].ToString() + " " +
                                                           ds.Tables[2].Select("Id = " + userID)[0]["LastName"].ToString().Substring(0, 1);

    Result.GridViewDataTable.Columns[currCol].ColumnName = columnName;

}

With the above two tables data, I'm getting the following error.

A column named 'Matthew W' already belongs to this DataTable

It happen because Datatable have this (Matthew | Walker) record two times.

Once I setting a column name using this code,

string columnName = ds.Tables[2].Select("Id = " + userID)[0]["FirstName"].ToString() + " " +
                                                           ds.Tables[2].Select("Id = " + userID)[0]["LastName"].ToString().Substring(0, 1);

I need to check wether Datatable already consists that column name and if it's already exists I need to set 1 to end of the LastName. If same column name consists multiple time I need to add 1,2,3 likewise end of the LastName. As an example (Matthew W,Matthew W1,Matthew W2,) - how can I do it?

Body:
To check the exists column, this should work for you.

Result.GridViewDataTable.Columns.Contains(tmpColumnName)

Then, if you need the number after the columnName, you just put index after it. By the way, this snippet is not the best solution but I hope it can give you an idea of how to solve it. Hope this helps.

int userID = 0;
string[] columnNameParts;
Result.GridViewDataTable = ds.Tables[3];
for (int currCol = 1; currCol < Result.GridViewDataTable.Columns.Count; currCol++)
{
    columnNameParts = Result.GridViewDataTable.Columns[currCol].ColumnName.Split(new string[] { "---" }, StringSplitOptions.RemoveEmptyEntries);
    userID = int.Parse(columnNameParts[columnNameParts.Length - 1]);

    string columnName = ds.Tables[2].Select("Id = " + userID)[0]["FirstName"].ToString()
        + " "
        + ds.Tables[2].Select("Id = " + userID)[0]["LastName"].ToString().Substring(0, 1);

    //index
    int n = 0;
    //Create new temporary columnName which will add to the Columns later
    string tmpColumnName = columnName;
    //Check if column name is duplicate.
    while (Result.GridViewDataTable.Columns.Contains(tmpColumnName))
    {
        //Add 1 to index
        n++;
        //Create new name such as Matthew W1,Matthew W2,Daniel G1,Matthew W3,...
        tmpColumnName = columnName + n.ToString();
    }
    //Add new unique column name to Columns
    Result.GridViewDataTable.Columns[currCol].ColumnName = columnName;
}


问:
How to get data in component better?
Using service inside component:

```<code>ngOnInit() {
  this.layer = this.layerService.getObject(semantic);
}
</code>```

Or using @Input() and pass data from parent:

```<code>@Input() layers: any[] = [];
</code>```

Should component control DOM, for example show/hide DOM elements, or everythin should be in services?

Something there a lot of data and I am confused to use a lot of Inputs()

答:
Services should handle all the logical controls of your applications. The component should be a reusable element that use to show/manipulate DOM. In this case, what you are doing is correct. Service is passing the data and through the component, you are manipulating them to show on dom.

One other way you can do is using a get property to fetch the layerService.getObject(semantic); so that every time service change it logic, the component also gets updated.

```<code>public layers(): any[] {
  return this.layerService.getObject(semantic);
}
</code>```

Title: How to get data in component better?

Body:
Using service inside component:

ngOnInit() {
  this.layer = this.layerService.getObject(semantic);
}

Or using @Input() and pass data from parent:

@Input() layers: any[] = [];

Should component control DOM, for example show/hide DOM elements, or everythin should be in services?

Something there a lot of data and I am confused to use a lot of Inputs()

Body:
Services should handle all the logical controls of your applications. The component should be a reusable element that use to show/manipulate DOM. In this case, what you are doing is correct. Service is passing the data and through the component, you are manipulating them to show on dom.

One other way you can do is using a get property to fetch the layerService.getObject(semantic); so that every time service change it logic, the component also gets updated.

public layers(): any[] {
  return this.layerService.getObject(semantic);
}


问:
How i can remove duplicates array in object value?
Js Object, ReactJs</p>

```<code>{userId:1, userName:mahadi},
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]
</code>```

答:
there can be multiple solution to this particular problem. But here is simplified solution using reduce and some methods available in Prototype of Array.</p>

```<code>const arr = [{userId:1, userName:"mahadi"},
             {userId:2,userName:"hasan"},
             {userId:1, userName:"mahadi"}
            ]

const reducedArr = arr.reduce((accumulator, currentValue) =>{
   //check if your accumulator already does not includes an object with same username
    if(!accumulator.some(single => single.userName === currentValue.userName) ){
          return [...accumulator, currentValue]
      }
     return accumulator

//initialize accumulator here
  }, [])

 console.log(reducedArr)
</code>```

Body:
Js Object, ReactJs

{userId:1, userName:mahadi},
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]

Body:
there can be multiple solution to this particular problem. But here is simplified solution using reduce and some methods available in Prototype of Array.

const arr = [{userId:1, userName:"mahadi"},
             {userId:2,userName:"hasan"},
             {userId:1, userName:"mahadi"}
            ]

const reducedArr = arr.reduce((accumulator, currentValue) =>{
   //check if your accumulator already does not includes an object with same username
    if(!accumulator.some(single => single.userName === currentValue.userName) ){
          return [...accumulator, currentValue]
      }
     return accumulator

//initialize accumulator here
  }, [])

 console.log(reducedArr)


问:
how to show PDF from mobile storage in xamarin android c# app?
I am working in a xmarin android app in c#. I want to open a pdf file which is in a custom folder of internal storage "TESTFOLDER". code is given below, every time it is going to the catch section whiche it is going to start the activity. how to open it?

code

```<code>var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/TESTFOLDER";
                Java.IO.File file = new Java.IO.File(externalPath, "qdummy.pdf");
                if(file.Exists())
                {
                    try
                    {
                        file.SetReadable(true);
                        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetDataAndType(uri, "application/pdf");
                        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                        intent.SetFlags(ActivityFlags.NoHistory);
                        StartActivity(intent);
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(Application.Context, "No exx", ToastLength.Long).Show();
                }
</code>```

答:
According to your description and error message, you need to wrap your URI with FileProvider. Since android uri will give you file:// while FileProvider will give you content:// firstly.

```<code> Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);
</code>```

then you need to add FileProvider to your manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.pdfsample" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
    <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
    </provider>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>
</code>```

You also need to create Resources\xml folder with file_paths.xml

```<code><?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
 <external-files-path name="root" path="."/>
 <external-files-path name="files" path="files" />
 <external-path name="external_files" path="."/>
</paths>
</code>```

Open pdf code:

```<code> var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/testfolder";
        Java.IO.File file = new Java.IO.File(externalPath, "test.pdf");
        if(file.Exists())
        {
            var context = Android.App.Application.Context;
            try
            {

                Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);
                context.GrantUriPermission(context.PackageName, pdfPath, ActivityFlags.GrantReadUriPermission);
                Intent intent = new Intent();
                intent.SetFlags(ActivityFlags.GrantReadUriPermission);
                intent.SetAction(Android.Content.Intent.ActionView);
                intent.SetFlags(ActivityFlags.NoHistory);
                intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                intent.SetDataAndType(pdfPath, "application/pdf");
                context.StartActivity(intent);

            }
            catch (Exception ex)
            {
                Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
            }

        }
</code>```

Here is the same thread that you can take a look:

How do I open an internally created pdf in Xamarin.Android via a FileProvider in the default system pdf app?

Body:
I am working in a xmarin android app in c#. I want to open a pdf file which is in a custom folder of internal storage "TESTFOLDER". code is given below, every time it is going to the catch section whiche it is going to start the activity. how to open it?

code

var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/TESTFOLDER";
                Java.IO.File file = new Java.IO.File(externalPath, "qdummy.pdf");
                if(file.Exists())
                {
                    try
                    {
                        file.SetReadable(true);
                        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetDataAndType(uri, "application/pdf");
                        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                        intent.SetFlags(ActivityFlags.NoHistory);
                        StartActivity(intent);
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(Application.Context, "No exx", ToastLength.Long).Show();
                }

Body:
According to your description and error message, you need to wrap your URI with FileProvider. Since android uri will give you file:// while FileProvider will give you content:// firstly.

 Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);

then you need to add FileProvider to your manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.pdfsample" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
    <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
    </provider>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>

You also need to create Resources\xml folder with file_paths.xml

<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
 <external-files-path name="root" path="."/>
 <external-files-path name="files" path="files" />
 <external-path name="external_files" path="."/>
</paths>

Open pdf code:

 var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/testfolder";
        Java.IO.File file = new Java.IO.File(externalPath, "test.pdf");
        if(file.Exists())
        {
            var context = Android.App.Application.Context;
            try
            {

                Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);
                context.GrantUriPermission(context.PackageName, pdfPath, ActivityFlags.GrantReadUriPermission);
                Intent intent = new Intent();
                intent.SetFlags(ActivityFlags.GrantReadUriPermission);
                intent.SetAction(Android.Content.Intent.ActionView);
                intent.SetFlags(ActivityFlags.NoHistory);
                intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                intent.SetDataAndType(pdfPath, "application/pdf");
                context.StartActivity(intent);

            }
            catch (Exception ex)
            {
                Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
            }

        }

Here is the same thread that you can take a look:

How do I open an internally created pdf in Xamarin.Android via a FileProvider in the default system pdf app?


问:
Java Stream filter - how can i filter data without wrapping the filter code in 'if' condition for checking null on the filtering keys?
I am doing the following:

```<code>List<Objects> filtered = objects.stream()
    .filter(o -> source.equals(o.getSource()) && date.equals(o.getDate()) && id.equals(o.getId()))
    .collect(Collectors.toList());
</code>```

where both date and id could possibiliy be null, as the are coming from method parameters.

How can I ignore them if null, without wrapping the above code in an if statement tp check 'id' and 'date' for null values ? I want to do it inside the filter.

Edit : To make it more clear, i want the filter to act only on the non-null values, i.e if date is non-null and id is null, then filter only on date and ignore id, and so on..

Thanks

答:
An additional option is to do the null checks in the predicate:</p>

```<code>.filter(o -> source.equals(o.getSource())
             && (null == date || date.equals(o.getDate()))
             && (null == id || id.equals(o.getId())))
</code>```

Body:
I am doing the following:

List<Objects> filtered = objects.stream()
    .filter(o -> source.equals(o.getSource()) && date.equals(o.getDate()) && id.equals(o.getId()))
    .collect(Collectors.toList());

where both date and id could possibiliy be null, as the are coming from method parameters.

How can I ignore them if null, without wrapping the above code in an if statement tp check 'id' and 'date' for null values ? I want to do it inside the filter.

Edit : To make it more clear, i want the filter to act only on the non-null values, i.e if date is non-null and id is null, then filter only on date and ignore id, and so on..

Thanks

Body:
An additional option is to do the null checks in the predicate:

.filter(o -> source.equals(o.getSource())
             && (null == date || date.equals(o.getDate()))
             && (null == id || id.equals(o.getId())))


问:
Get names of the params passed to a C# method
```<code>void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }
</code>```

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

```<code>string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);
</code>```

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)

答:
This is totally impossible.

Here are just a few cases where it doesn't even make sense:

```<code>MyMethod("abc", new object[5]);
MyMethod("abc", "def");
MyMethod("abc", var1 + var2);
MyMethod("abc", SomeMethod());
MyMethod("abc", b ? a : c);
MyMethod("abc", new object());
MyMethod("abc", null);
</code>```

In fact, local variable names aren't even compiled into the assembly.

Body:
void MyMethod(string something, params object[] parameters)
    {
      foreach (object parameter in parameters)
      {
        // Get the name of each passed parameter
      }
    }

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)

Body:
This is totally impossible.

Here are just a few cases where it doesn't even make sense:

MyMethod("abc", new object[5]);
MyMethod("abc", "def");
MyMethod("abc", var1 + var2);
MyMethod("abc", SomeMethod());
MyMethod("abc", b ? a : c);
MyMethod("abc", new object());
MyMethod("abc", null);

In fact, local variable names aren't even compiled into the assembly.


答:
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null

String userid = firebaseUser.getUid();

reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

```

<p>Instead, initialize the reference to the Users node</p>

<pre class="lang-java prettyprint-override"><code>String userid = firebaseUser.getUid();

reference = FirebaseDatabase.getInstance().getReference("Users");

</code>```

Then when saving the user's data you can save to their userId:

reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
    ...
});
```

Title: Firebase doesn't register new users

Body:
I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.

This is my register activity

    MaterialEditText username,  email, password;

    Button btn_register;

    FirebaseAuth auth;
    DatabaseReference reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Регистрация");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        username = findViewById(R.id.username);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        btn_register = findViewById(R.id.btn_register);

        auth = FirebaseAuth.getInstance();

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt_username = username.getText().toString();
                String txt_email = email.getText().toString();
                String txt_password = password.getText().toString();

                if (TextUtils.isEmpty(txt_username)  || TextUtils.isEmpty(txt_email)  ||  TextUtils.isEmpty(txt_password)) {

                    Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
                } else if (txt_password.length() < 6 ){
                    Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
                } else {
                    register(txt_username, txt_email, txt_password);
                }

            }
        });
    }
    private void register(final String username, String email, String password){
        auth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            FirebaseUser firebaseUser= auth.getCurrentUser();
                            assert firebaseUser !=null;
                            String userid = firebaseUser.getUid();

                            reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

                            HashMap<String, String> HashMap = new HashMap<>();
                            HashMap.put("id", userid);
                            HashMap.put("username", username);
                            HashMap.put("imageURL", "default");

                            reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if(task.isSuccessful()){

                                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            });
                        }else {
                            Toast.makeText(RegisterActivity.this, "You cant register", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}

Body:
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null

String userid = firebaseUser.getUid();

reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

Instead, initialize the reference to the Users node

String userid = firebaseUser.getUid();

reference = FirebaseDatabase.getInstance().getReference("Users");

Then when saving the user's data you can save to their userId:

reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
    ...
});


问:
Matplotlib - Scatter Plot, How to fill in the space between each individual point?
I am plotting the following data:

```<code>fig, ax = plt.subplots()
im = ax.scatter(std_sorted[:, [1]], std_sorted[:, [2]], s=5, c=std_sorted[:, [0]])
</code>```

With the following result:

My question is: can I fill the space between each point in the plot by extrapolating and then coloring that extrapolated space accordingly, so I get a uniform plot without any points?

So basically I'm looking for this result (This is simply me "squeezing" the above picture to show the desired result and not dealing with the space between the points):

答:
The simplest thing to do in this case, is to use a short vertical line a marker, and set the markersize large enough such that there is no white space left.

Another option is to use tricontourf to create a filled image of x, y and z.

Note that neither a scatter plot nor tricontourf need the points to be sorted in any order.
If you do have your points sorted into an orderded grid, plt.imshow should give the best result.

Here is some code to show how it could look like. First some dummy data slightly similar to the example are generated. As the x,y are random, they don't fill the complete space. This might leave some blank spots in the scatter plot. The spots are nicely interpolated for the contourf, except possibly in the corners.

import numpy as np
import matplotlib.pyplot as plt

N = 50000
xmin = 0
xmax = 0.20
ymin = -0.01
ymax = 0.01

std_sorted = np.zeros((N, 3))
std_sorted[:,1] = np.random.uniform(xmin, xmax, N)
std_sorted[:,2] = np.random.choice(np.linspace(ymin, ymax, 80), N)
std_sorted[:,0] = np.cos(3*(std_sorted[:,1] - 0.04 - 100*std_sorted[:,2]**2))**10

fig, ax = plt.subplots(ncols=2)
# im = ax[0].scatter(std_sorted[:, 1], std_sorted[:, 2], s=20, c=std_sorted[:, 0], marker='|')
im = ax[0].scatter(std_sorted[:, 1], std_sorted[:, 2], s=5, c=std_sorted[:, 0], marker='.')
ax[0].set_xlim(xmin, xmax)
ax[0].set_ylim(ymin, ymax)
ax[0].set_title("scatter plot")
ax[1].tricontourf(std_sorted[:, 1], std_sorted[:, 2], std_sorted[:, 0], 256)
ax[1].set_title("tricontourf")

plt.tight_layout()
plt.show()
```

Body:
I am plotting the following data:

fig, ax = plt.subplots()
im = ax.scatter(std_sorted[:, [1]], std_sorted[:, [2]], s=5, c=std_sorted[:, [0]])

With the following result:

My question is: can I fill the space between each point in the plot by extrapolating and then coloring that extrapolated space accordingly, so I get a uniform plot without any points?

So basically I'm looking for this result (This is simply me "squeezing" the above picture to show the desired result and not dealing with the space between the points):