问:
Trying to find how a specific 32 hex character webform is generated from Netgear Managed Switch local UI webpage
I am trying to simulate navigating Netgear Managed Switch (GC108PP) local UI webpage in C#. When sending HttpWebRequest using a Chrome browser, I've learned using Fiddler - there are 3 WebForms that are generated when hitting this URL:

http://192.168.50.101

ends up being:

http://192.168.50.101/cgi/get.cgi?cmd=home_login&dummy=1582137153063&bj4=3f104a21e12a9584d36372142f16e35b

WebForms:

cmd=home_login

dummy=1582137153063 (time since epoch, this one was easy to figure out)

bj4=3f104a21e12a9584d36372142f16e35b (trying to figure out how to generate this one)

There is no HTTP API to reference from Netgear. I have tried just generating a 32 char string with:

```<code>private static Random random = new Random();
public static string randomString(int length)
{
    const string chars = "abcdef0123456789";
    return new string(Enumerable.Repeat(chars, length).Select(s =>s[random.Next(s.Length)]).ToArray());
}
</code>```

However, I get ERROR 400 Bad Request.If I use a bj4 key/ID that gets generated by my browser statically in my code it works, but I want to be generating this webform properly.

Any ideas on how this WebForm might be be generated?

答:
Found it in the JS...</p>

```<code>function gotoLogin()
{
  document.cookie = \"testcookie\";
  cookieEnabled = (document.cookie.indexOf(\"testcookie\") != -1) ? true : false;
  if (cookieEnabled == false)
  {
    alert(\"Browser does not accept cookies. Please configure your browser to accept cookies in order to access the Web Interface.\");
  }

  var fileVer = (new Date().getTime());
  var url = \"login.html?aj4=\"+fileVer;
  url = url + '&bj4=' + md5(url.split('?')[1]); //here!!!
  window.location.href=url;
}
</code>```

Body:
I am trying to simulate navigating Netgear Managed Switch (GC108PP) local UI webpage in C#. When sending HttpWebRequest using a Chrome browser, I've learned using Fiddler - there are 3 WebForms that are generated when hitting this URL:

http://192.168.50.101

ends up being:

http://192.168.50.101/cgi/get.cgi?cmd=home_login&dummy=1582137153063&bj4=3f104a21e12a9584d36372142f16e35b

WebForms:

cmd=home_login

dummy=1582137153063 (time since epoch, this one was easy to figure out)

bj4=3f104a21e12a9584d36372142f16e35b (trying to figure out how to generate this one)

There is no HTTP API to reference from Netgear. I have tried just generating a 32 char string with:

private static Random random = new Random();
public static string randomString(int length)
{
    const string chars = "abcdef0123456789";
    return new string(Enumerable.Repeat(chars, length).Select(s =>s[random.Next(s.Length)]).ToArray());
}

However, I get ERROR 400 Bad Request.If I use a bj4 key/ID that gets generated by my browser statically in my code it works, but I want to be generating this webform properly.

Any ideas on how this WebForm might be be generated?

Body:
Found it in the JS...

function gotoLogin()
{
  document.cookie = \"testcookie\";
  cookieEnabled = (document.cookie.indexOf(\"testcookie\") != -1) ? true : false;
  if (cookieEnabled == false)
  {
    alert(\"Browser does not accept cookies. Please configure your browser to accept cookies in order to access the Web Interface.\");
  }

  var fileVer = (new Date().getTime());
  var url = \"login.html?aj4=\"+fileVer;
  url = url + '&bj4=' + md5(url.split('?')[1]); //here!!!
  window.location.href=url;
}


来源: stackexchange

问:
How to make percentage of counts in Report Builder?
I'm using Report Builder to create a report.
I grouped data in MATRIX by column 'Names' and counted the number of occurencies (for some factor named Visits with 2 variables: Visit1 and Visit2).
Need to count percentage per row referring to the sum of column, e.g.:

```<code>Names   Visit1   Visit2  Total  Percentage
Adam      5         2       7       35%
Mick      3         1       4       20%
Robert    1         1       2       10%
Anna      4         3       7       35%
Total                       20
</code>```

I tried to do this in many ways but in vain.
Expression which counts total is:

```<code>=Count(Fields!Visits.Value)
</code>```

I added new column (to the right) and tried with diferent expressions but none of them works properly.

```<code>=Count(Fields!Visits.Value)/Sum(Count(Fields!Visits.Value))
=Count(Fields!Status_wyceny.Value)/Count(Fields!Status_wyceny.Value,"Visits_group")
=Count(Fields!Visits.Value)/Fields!Total.Value
</code>```

In most cases I got '1' as a result:

```<code>Names   Visit1   Visit2  Total  Percentage
Adam      5         2       7       1
Mick      3         1       4       1
Robert    1         1       2       1
Anna      4         3       7       1
Total                       20
</code>```

How can I solve it I get correct result?

答:
I believe you want the SUM of the visits for each group by the SUM of all visits in the dataset.</p>

```<code>=SUM(Fields!Visits.Value) / SUM(Fields!Visits.Value,"Dataset1")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Report Builder to create a report.
I grouped data in MATRIX by column 'Names' and counted the number of occurencies (for some factor named Visits with 2 variables: Visit1 and Visit2).
Need to count percentage per row referring to the sum of column, e.g.:

Names   Visit1   Visit2  Total  Percentage
Adam      5         2       7       35%
Mick      3         1       4       20%
Robert    1         1       2       10%
Anna      4         3       7       35%
Total                       20

I tried to do this in many ways but in vain.
Expression which counts total is:

=Count(Fields!Visits.Value)

I added new column (to the right) and tried with diferent expressions but none of them works properly.

=Count(Fields!Visits.Value)/Sum(Count(Fields!Visits.Value))
=Count(Fields!Status_wyceny.Value)/Count(Fields!Status_wyceny.Value,"Visits_group")
=Count(Fields!Visits.Value)/Fields!Total.Value

In most cases I got '1' as a result:

Names   Visit1   Visit2  Total  Percentage
Adam      5         2       7       1
Mick      3         1       4       1
Robert    1         1       2       1
Anna      4         3       7       1
Total                       20

How can I solve it I get correct result?

Body:
I believe you want the SUM of the visits for each group by the SUM of all visits in the dataset.

=SUM(Fields!Visits.Value) / SUM(Fields!Visits.Value,"Dataset1")


问:
Finding the render route if validation fails in Rails
I am trying to create a basic survey tool as my first Rails project.
At the moment I am working on the validation for submitting a new answer to a survey question. The following is my answer model.

```<code>class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :text, presence: true,
            length: { minimum: 5, maximum: 100 }
end

</code>```

I have set up an if statement that takes you to the next question if passes validation. My problem is I'm not sure what to render inside the else for this statement.

For similar validation in other controllers I have written the render statement to be the pages URL. For example: View all questions + add new question are rendered on the studies/id page. So if question validation fails then render will be 'studies/show'.

The URL to add a new answer looks like this.
http://localhost:3000/studies/20/questions/47/answers/new

For more context here is some of my code:

```<code>*Answers Controller*

class AnswersController < ApplicationController
  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end

  def create
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @answer = @question.answers.build(answer_params)

    if @answer.save
      next_question = @question.next_question
      redirect_to next_question_path(next_question, @answer) if next_question.present?

    else
      #I want to render the current page the participant is on to display errors here.
    end
  end

  ***some private functions here***

end

</code>```

```<code>* New Answer View *
<div class="wrap">
  <h1 class="med-header"><%= @question.question %></h1>

  <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    <%= form.hidden_field :participant_id %>

    <% @question.answers.each do |answer| %>
        <% if answer.errors.any? %>
          <div id="error_explanation">
            <h2>
              <%= pluralize(answer.errors.count, "error") %> prohibited
              this answer from being saved:
            </h2>
            <ul>
              <% answer.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
              <% end %>
            </ul>
          </div>
        <% end %>
      <% end %>

    <%= form.text_area :text %><br>
    <%= form.submit %>
  <% end %>
</div>
</code>```

What do I render in the else?

答:
The cheap way of doing this:

```<code>   if @answer.save
      next_question = @question.next_question
      redirect_to next_question_path(next_question, @answer) if next_question.present?
    else
      flash[:notice] = @answer.errors.full_messages.first
      render :new
    end
</code>```

render :new will render the new view as you can infer.

Anecdotally, your next_question_path(next_question, @answer) if next_question.present? is an unlocked gate if there's no next_question :)

Body:
I am trying to create a basic survey tool as my first Rails project.
At the moment I am working on the validation for submitting a new answer to a survey question. The following is my answer model.

class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :text, presence: true,
            length: { minimum: 5, maximum: 100 }
end

I have set up an if statement that takes you to the next question if passes validation. My problem is I'm not sure what to render inside the else for this statement.

For similar validation in other controllers I have written the render statement to be the pages URL. For example: View all questions + add new question are rendered on the studies/id page. So if question validation fails then render will be 'studies/show'.

The URL to add a new answer looks like this.
http://localhost:3000/studies/20/questions/47/answers/new

For more context here is some of my code:

*Answers Controller*

class AnswersController < ApplicationController
  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end

  def create
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @answer = @question.answers.build(answer_params)

    if @answer.save
      next_question = @question.next_question
      redirect_to next_question_path(next_question, @answer) if next_question.present?

    else
      #I want to render the current page the participant is on to display errors here.
    end
  end

  ***some private functions here***

end

* New Answer View *

<%= @question.question %>

  <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    <%= form.hidden_field :participant_id %>

    <% @question.answers.each do |answer| %>
        <% if answer.errors.any? %>

              <%= pluralize(answer.errors.count, "error") %> prohibited
              this answer from being saved:

              <% answer.errors.full_messages.each do |msg| %>

<%= msg %>

              <% end %>

        <% end %>
      <% end %>

    <%= form.text_area :text %>

    <%= form.submit %>
  <% end %>

What do I render in the else?

Body:
The cheap way of doing this:

   if @answer.save
      next_question = @question.next_question
      redirect_to next_question_path(next_question, @answer) if next_question.present?
    else
      flash[:notice] = @answer.errors.full_messages.first
      render :new
    end

render :new will render the new view as you can infer.

Anecdotally, your next_question_path(next_question, @answer) if next_question.present? is an unlocked gate if there's no next_question :)


问:
Gradle: how to zip/tar output from other zip/tar task?
I have a project that has a task called shadowDistTar, which is provided by the shadow plugin.  The output of this task is a tar file.

I wish to create another Tar task that will include the output tar file into a new tar file, containing the first tar file and some new files.  However, I cannot get the tar file to be included in new archive.

```<code>task("myNewTarTask", type: Tar) {
    // configure the Tar task here...

    project.afterEvaluate {

        // we put things in afterEvaluate so the outputs of shadowDistTar are known
        dependsOn shadowDistTar

        shadowDistTar.getOutputs().getFiles().each {
            include it.toString()
        }
    }
}
</code>```

I think the issue here is that the include should take an ANT style include spec, which should be relative to the source directory of the Tar task, rather than absolute paths, which is what I get with getOutputs().  How can I either get the outputs as an ANT style include, or otherwise include the tar file created by shadowDistTar into the second tar, without resorting to hard-coding the path into the include?

答:
See Project.tarTree(...). Eg:</p>

```<code>task("myNewTarTask", type: Tar) {
   dependsOn shadowDistTar
   from tarTree(shadowDistTar.archiveFile)
   from 'path/to/extra/files'
}
</code>```

Body:
I have a project that has a task called shadowDistTar, which is provided by the shadow plugin.  The output of this task is a tar file.

I wish to create another Tar task that will include the output tar file into a new tar file, containing the first tar file and some new files.  However, I cannot get the tar file to be included in new archive.

task("myNewTarTask", type: Tar) {
    // configure the Tar task here...

    project.afterEvaluate {

        // we put things in afterEvaluate so the outputs of shadowDistTar are known
        dependsOn shadowDistTar

        shadowDistTar.getOutputs().getFiles().each {
            include it.toString()
        }
    }
}

I think the issue here is that the include should take an ANT style include spec, which should be relative to the source directory of the Tar task, rather than absolute paths, which is what I get with getOutputs().  How can I either get the outputs as an ANT style include, or otherwise include the tar file created by shadowDistTar into the second tar, without resorting to hard-coding the path into the include?

Body:
See Project.tarTree(...). Eg:

task("myNewTarTask", type: Tar) {
   dependsOn shadowDistTar
   from tarTree(shadowDistTar.archiveFile)
   from 'path/to/extra/files'
}


问:
Does creating a CTE in this case helps?
I have a query written very poorly in SQL Server 2008

```<code>UPDATE  PatientChartImages
SET     PatientChartImages.IsLockDown = @IsLockdown
WHERE   PatientChartImages.IsLockDown = @IsNotLockdown
    AND PatientChartId IN (
    SELECT  PatientCharts.PatientChartId
    FROM    PatientCharts
    WHERE   ( PatientCharts.ChartStatusID = @ChartCompletedStatusID
              OR PatientCharts.ChartStatusID = @ChartOnBaseStatusID
            )
            AND PatientCharts.IsLockDown = @IsNotLockdown
            AND PatientCharts.CompletedOn IS NOT NULL
            AND DATEDIFF(MINUTE, PatientCharts.CompletedOn, GETUTCDATE()) >= ( SELECT
                                                          tf.LockUpInterval
                                                          FROM
                                                          @tblFacCOnf tf
                                                          WHERE
                                                          tf.facilityId = PatientCharts.FacilityId
                                                          ) )
</code>```

This query locks the main table and results in TimeOut. IF i create a CTE first of all the updateable records and then update the main table by joining to the CTE. Will it help ??

答:
First thing i advice you to do is to substitute IN condition with EXISTS. Second is to move all this conditional logic into CTE. Third is to substitute sub-select with @tblFacCOnf with join.

Last advice depends on your business logic and is not so important in my opinion

So at the end you will get something as

```<code>WITH search_cte as (
  SELECT  PatientCharts.PatientChartId
  FROM    PatientCharts
  JOIN @tblFacCOnf tf on tf.facilityId = PatientCharts.FacilityId
  WHERE   ( PatientCharts.ChartStatusID = @ChartCompletedStatusID
          OR PatientCharts.ChartStatusID = @ChartOnBaseStatusID
        )
        AND PatientCharts.IsLockDown = @IsNotLockdown
        AND PatientCharts.CompletedOn IS NOT NULL
        AND DATEDIFF(MINUTE, PatientCharts.CompletedOn, GETUTCDATE()) >= tf.LockUpInterval
) --cte end
UPDATE  PatientChartImages
SET     PatientChartImages.IsLockDown = @IsLockdown
WHERE   PatientChartImages.IsLockDown = @IsNotLockdown
AND EXISTS (select 1 from PatientChartImages where PatientChartImages.PatientChartId = search_cte.PatientChartId)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Does creating a CTE in this case helps?

Body:
I have a query written very poorly in SQL Server 2008

UPDATE  PatientChartImages
SET     PatientChartImages.IsLockDown = @IsLockdown
WHERE   PatientChartImages.IsLockDown = @IsNotLockdown
    AND PatientChartId IN (
    SELECT  PatientCharts.PatientChartId
    FROM    PatientCharts
    WHERE   ( PatientCharts.ChartStatusID = @ChartCompletedStatusID
              OR PatientCharts.ChartStatusID = @ChartOnBaseStatusID
            )
            AND PatientCharts.IsLockDown = @IsNotLockdown
            AND PatientCharts.CompletedOn IS NOT NULL
            AND DATEDIFF(MINUTE, PatientCharts.CompletedOn, GETUTCDATE()) >= ( SELECT
                                                          tf.LockUpInterval
                                                          FROM
                                                          @tblFacCOnf tf
                                                          WHERE
                                                          tf.facilityId = PatientCharts.FacilityId
                                                          ) )

This query locks the main table and results in TimeOut. IF i create a CTE first of all the updateable records and then update the main table by joining to the CTE. Will it help ??

Body:
First thing i advice you to do is to substitute IN condition with EXISTS. Second is to move all this conditional logic into CTE. Third is to substitute sub-select with @tblFacCOnf with join.

Last advice depends on your business logic and is not so important in my opinion

So at the end you will get something as

WITH search_cte as (
  SELECT  PatientCharts.PatientChartId
  FROM    PatientCharts
  JOIN @tblFacCOnf tf on tf.facilityId = PatientCharts.FacilityId
  WHERE   ( PatientCharts.ChartStatusID = @ChartCompletedStatusID
          OR PatientCharts.ChartStatusID = @ChartOnBaseStatusID
        )
        AND PatientCharts.IsLockDown = @IsNotLockdown
        AND PatientCharts.CompletedOn IS NOT NULL
        AND DATEDIFF(MINUTE, PatientCharts.CompletedOn, GETUTCDATE()) >= tf.LockUpInterval
) --cte end
UPDATE  PatientChartImages
SET     PatientChartImages.IsLockDown = @IsLockdown
WHERE   PatientChartImages.IsLockDown = @IsNotLockdown
AND EXISTS (select 1 from PatientChartImages where PatientChartImages.PatientChartId = search_cte.PatientChartId)


问:
Bootstrap modal and jQuery: form inputs are empty
I'm using form inside a modal window in my application which uses Bootstrap.
Form looks like this:

```<code><div class="modal fade" id="my_modal">
    <div class="modal-dialog modal-lg">
        <div class="form-group">
            <form class="form-horizontal" id="my_form">
                <div class="form-group">
                    <div class="col-sm-10">
                        <input type="file" name="file" id="my_file">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10">
                        <input type="text" name="my_text" id="my_text" class="form-control select-resource-form-control">
                    </div>
                </div>
                <button id="my_button" type="button" class="btn btn-primary btn-send">Send</button>
            </form>
        </div>
    </div>
</div>
</code>```

When I'm trying to send form data of this form, both file and text fields are empty at the recieveing part, and following commands in console also confirm that the form is empty:

when I use modal fade

If I replace the modal fade attribute in the root tag,for example, with modal-body, everything works just fine, but I need a modal window for my purposes, which shows up, sends the response and closes.
when I use modal-body

Would appreciate any ideas/workarounds about this

UPDATE:
ajax for the query is:

```<code>let form = $("#my_form").get(0);
$.ajax({
        url: "some/url/Im/sending/data/to",
        method: "POST",
        data: new FormData(form),
        cache: false,
        contentType: false,
        processData: false,
    }
}
</code>```

答:
Firstly, it appears that the structure of your modal is missing some items. It should look something like this:

```<code><div class="modal fade" ...
   <div class="modal-dialog" ...
      <div class="modal-content">
          <div class="modal-body">
              your form
</code>```

Also, I believe form-group's are only supposed to be inside forms.

Body:
I'm using form inside a modal window in my application which uses Bootstrap.
Form looks like this:

            <form class="form-horizontal" id="my_form">

                        <input type="file" name="file" id="my_file">

                        <input type="text" name="my_text" id="my_text" class="form-control select-resource-form-control">

                <button id="my_button" type="button" class="btn btn-primary btn-send">Send</button>
            </form>

When I'm trying to send form data of this form, both file and text fields are empty at the recieveing part, and following commands in console also confirm that the form is empty:

when I use modal fade

If I replace the modal fade attribute in the root tag,for example, with modal-body, everything works just fine, but I need a modal window for my purposes, which shows up, sends the response and closes.
when I use modal-body

Would appreciate any ideas/workarounds about this

UPDATE:
ajax for the query is:

let form = $("#my_form").get(0);
$.ajax({
        url: "some/url/Im/sending/data/to",
        method: "POST",
        data: new FormData(form),
        cache: false,
        contentType: false,
        processData: false,
    }
}

Body:
Firstly, it appears that the structure of your modal is missing some items. It should look something like this:

<div class="modal fade" ...
   <div class="modal-dialog" ...
      <div class="modal-content">
          <div class="modal-body">
              your form

Also, I believe form-group's are only supposed to be inside forms.


问:
How can I print variable and string on same line in Python?
I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it?

Here is my code:

```<code>currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " births "births"
</code>```

答:
If you use a comma inbetween the strings and the variable, like this:</p>

```<code>print "If there was a birth every 7 seconds, there would be: ", births, "births"
</code>```

Body:
I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it?

Here is my code:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " births "births"

Body:
If you use a comma inbetween the strings and the variable, like this:

print "If there was a birth every 7 seconds, there would be: ", births, "births"


问:
Cypher Query in Neo4j to ORDER BY some data
I got a spring application with a query that looks like that.

```<code>MATCH (d:Drug) WHERE toLower(d.tradingName) CONTAINS toLower({0}) OR toLower(d.expire) CONTAINS
toLower({0}) RETURN (d)-[]-() ORDER BY d.expire
</code>```

d.expire is a string in my pojos so the query i posted sorts everyting alphabetical. Thats not what i want.

How is it possible to parse d.expire as a date and order the results as Dates ?

答:
This may be a slight improvement on @TheTeacher's fine answer.

The =~ operator can be used with a regular expression to perform case-insensitive comparisons. Also, WITH the clause is not needed.

```<code>WITH "(?i).*" + {0} + ".*" AS regex
MATCH (d:Drug)
WHERE d.tradingName =~ regex OR d.expire =~ regex
RETURN (d)--() ORDER BY datetime(d.expire)
</code>```

Body:
I got a spring application with a query that looks like that.

MATCH (d:Drug) WHERE toLower(d.tradingName) CONTAINS toLower({0}) OR toLower(d.expire) CONTAINS
toLower({0}) RETURN (d)-[]-() ORDER BY d.expire

d.expire is a string in my pojos so the query i posted sorts everyting alphabetical. Thats not what i want.

How is it possible to parse d.expire as a date and order the results as Dates ?

Body:
This may be a slight improvement on @TheTeacher's fine answer.

The =~ operator can be used with a regular expression to perform case-insensitive comparisons. Also, WITH the clause is not needed.

WITH "(?i).*" + {0} + ".*" AS regex
MATCH (d:Drug)
WHERE d.tradingName =~ regex OR d.expire =~ regex
RETURN (d)--() ORDER BY datetime(d.expire)


问:
Extract all values when I have key : value and store all value in an array
If I have an array,I want to extract each values in each line (values after (:) )

```<code>Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}
</code>```

Imagine I have several key : value then I want to extract Just value like bellow:

```<code>Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

</code>```

I have the result like this :

```<code>var result = ["value","value2",value3","value5","value6","value7"];
</code>```

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

答:
You can just map through each object in your array and use the Object.values() method to extract each value like this:</p>

```<code>const result = Array.map(e => Object.values(e));
</code>```

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value2",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

Body:
You can just map through each object in your array and use the Object.values() method to extract each value like this:

const result = Array.map(e => Object.values(e));


问:
Difference between android Home key and Back key and their behaviour
Can anyone point me out or explain what is the difference between android Home key and Back key and their respective behavior related to an android app/activity.

Thank you.

答:
The home key takes you to the home screen, the back key takes you back to the previous activity (or home if there's no activity to go back to.)

If you are at the home screen and launch Messaging, then hit back, it's the same as hitting the home key.

If you're in Email and get an alert for a text message, and you choose the notification which takes you to Messaging, then hit Back, you'll go back to Email.

edit: as mentioned by Tim Coker, when the back button takes you to the home screen, it usually terminates the activity.  I think this is based on the app, whether it terminates or stays resident.


问:
Struct union in C#, get exception when new the struct
My question is to new a union-struct, but get exception (about incorrect alignment) while running. Is there something wrong with my partial code? Any better method to solve without using "unsafe"?</p>

```<code>enter code here

public struct SR_CONFIG
{
   public UInt32    dwRate;
   public int       bVAD;
   public UInt16    wSilenceStart;
   public UInt16    wSilenceEnd;
   public UInt16    wMaxLength;
}

[StructLayout(LayoutKind.Explicit)]
public struct CmdStruct_Union
{
   [FieldOffset(0)] public SR_CONFIG    SrParams;

   [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
   [FieldOffset(0)] public Byte[] rev;
}

CmdStruct_Union myStruct = new CmdStruct_Union(); // <----- get exception when running
</code>```

答:
If you can enable unsafe code in the project, then this solution works:

[StructLayout(LayoutKind.Explicit)]
public unsafe struct CmdStruct_Union
{
    [FieldOffset(0)] public SR_CONFIG SrParams;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    [FieldOffset(0)] public fixed byte rev[16];
}
```

Accessing to the rev items is same as in regular arrays in C# (but method must be also marked as "unsafe", like struct above). Remember that debugger will show you only the first element of fixed array.

More about fixed size buffers: https://learn.microsoft.com/en-US/dotnet/csharp/programming-guide/unsafe-code-pointers/fixed-size-buffers

Body:
My question is to new a union-struct, but get exception (about incorrect alignment) while running. Is there something wrong with my partial code? Any better method to solve without using "unsafe"?

enter code here

public struct SR_CONFIG
{
   public UInt32    dwRate;
   public int       bVAD;
   public UInt16    wSilenceStart;
   public UInt16    wSilenceEnd;
   public UInt16    wMaxLength;
}

[StructLayout(LayoutKind.Explicit)]
public struct CmdStruct_Union
{
   [FieldOffset(0)] public SR_CONFIG    SrParams;

   [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
   [FieldOffset(0)] public Byte[] rev;
}

CmdStruct_Union myStruct = new CmdStruct_Union(); // <----- get exception when running

Body:
If you can enable unsafe code in the project, then this solution works:

[StructLayout(LayoutKind.Explicit)]
public unsafe struct CmdStruct_Union
{
    [FieldOffset(0)] public SR_CONFIG SrParams;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    [FieldOffset(0)] public fixed byte rev[16];
}

Accessing to the rev items is same as in regular arrays in C# (but method must be also marked as "unsafe", like struct above). Remember that debugger will show you only the first element of fixed array.

More about fixed size buffers: https://learn.microsoft.com/en-US/dotnet/csharp/programming-guide/unsafe-code-pointers/fixed-size-buffers


问:
Access Method in Separate Project, C#, VB
I have a Form in a C# solution where I have a method that toggle's the visibility of an element on the form Sample Code:

```<code>namespace formplace.formlocation.Ui
{
 public class Form1: Mainform
  {
   ...
    public void activatepanel()
    {
     this.panel.visible = true;
    }
  }
}
</code>```

In a separate solution, I have a VB Solution that handles an event. I want to be able to call the method from the first solution in the second:

```<code>Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)Handles Button.Click
  ...
  Call activatepanel somehow here
  ...
End Sub
</code>```

Currently when I include Reference to C# Solution, Form1. (Suggestions here) Does not show the method activate panel. What can I do to achieve this?

答:
It's a bit unclear (at least, for me) why you want to do this. The control you want to hide in the C# projects form is displayed at runtime so MAYBE you want to hide it from the VB program when both the programs are running, with some interprocess communication.
Anyway, before you can access the method activatepanel() you need to have an instance of that class, either creating it or getting it in some other way.

Something like this:

```<code>Imports formplace.formlocation.Ui

....

  Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)Handles Button.Click
      ...
      Dim csf As formplace.formlocation.Ui.Form1
      csf = New formplace.formlocation.Ui.Form1()
      csf.activatepanel()
      ...
    End Sub
</code>```

Body:
I have a Form in a C# solution where I have a method that toggle's the visibility of an element on the form Sample Code:

namespace formplace.formlocation.Ui
{
 public class Form1: Mainform
  {
   ...
    public void activatepanel()
    {
     this.panel.visible = true;
    }
  }
}

In a separate solution, I have a VB Solution that handles an event. I want to be able to call the method from the first solution in the second:

Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)Handles Button.Click
  ...
  Call activatepanel somehow here
  ...
End Sub

Currently when I include Reference to C# Solution, Form1. (Suggestions here) Does not show the method activate panel. What can I do to achieve this?

Body:
It's a bit unclear (at least, for me) why you want to do this. The control you want to hide in the C# projects form is displayed at runtime so MAYBE you want to hide it from the VB program when both the programs are running, with some interprocess communication.
Anyway, before you can access the method activatepanel() you need to have an instance of that class, either creating it or getting it in some other way.

Something like this:

Imports formplace.formlocation.Ui

....

  Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)Handles Button.Click
      ...
      Dim csf As formplace.formlocation.Ui.Form1
      csf = New formplace.formlocation.Ui.Form1()
      csf.activatepanel()
      ...
    End Sub


问:
How to combine two table cells in the same table row?
How can I merge the date td/cell into the time td/cell?

I would like the table row to consist of 3 cells, the middle cell should read date time.

My Code:

```<code>$dom = new DOMDocument;
$dom->loadHTMLFile("test.html");
$dom->validateOnParse = true;
$xpath                = new DOMXPath($dom);
$table = $xpath->query("//*[@class='mytable']//tbody")->item(0);
$td = $table->getElementsbytagname("td");
</code>```

test.html file contents:

```<code><table class="mytable">
  <tbody><tr>
      <td>date</td>
      <td>td1</td>
      <td>time</td>
      <td>td2</td>
    </tr></tbody>
</table>
</code>```

Desired result:

```<code><table class="mytable">
  <tbody><tr>
      <td>td1</td>
      <td>date time</td>
      <td>td2</td>
    </tr></tbody>
</table>
</code>```

答:
Collect the tbody tr cells.  Overwrite the 3rd occurring cell's text using the 1st occurring cell' text, then delete the first cell.

Code (Demo)

```<code>$html = <<<HTML
<table class="mytable">
  <tbody><tr>
      <td>date</td>
      <td>td1</td>
      <td>time</td>
      <td>td2</td>
    </tr></tbody>
</table>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//table[@class='mytable']/tbody/tr") as $tr) {
    $tds = $tr->getElementsByTagName("td");
    $tds->item(2)->nodeValue = $tds->item(0)->nodeValue .
                               ' ' . $tds->item(2)->nodeValue;
    $tr->removeChild($tds->item(0));
}
echo $dom->saveHTML();
</code>```

Output:

```<code><table class="mytable">
  <tbody><tr>

      <td>td1</td>
      <td>date time</td>
      <td>td2</td>
    </tr></tbody>
</table>
</code>```

Body:
How can I merge the date td/cell into the time td/cell?

I would like the table row to consist of 3 cells, the middle cell should read date time.

My Code:

$dom = new DOMDocument;
$dom->loadHTMLFile("test.html");
$dom->validateOnParse = true;
$xpath                = new DOMXPath($dom);
$table = $xpath->query("//*[@class='mytable']//tbody")->item(0);
$td = $table->getElementsbytagname("td");

test.html file contents:

      date
      td1
      time
      td2

Desired result:

      td1
      date time
      td2

Body:
Collect the tbody tr cells.  Overwrite the 3rd occurring cell's text using the 1st occurring cell' text, then delete the first cell.

Code (Demo)

$html = <<<HTML
<table class="mytable">
  <tbody><tr>
      <td>date</td>
      <td>td1</td>
      <td>time</td>
      <td>td2</td>
    </tr></tbody>
</table>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//table[@class='mytable']/tbody/tr") as $tr) {
    $tds = $tr->getElementsByTagName("td");
    $tds->item(2)->nodeValue = $tds->item(0)->nodeValue .
                               ' ' . $tds->item(2)->nodeValue;
    $tr->removeChild($tds->item(0));
}
echo $dom->saveHTML();

Output:

<table class="mytable">
  <tbody><tr>

      <td>td1</td>
      <td>date time</td>
      <td>td2</td>
    </tr></tbody>
</table>


问:
Angular 6 Nav tab is not active when I click the hyperlinks
I have created a routing example in angular Working Demo. The output of the routing example looks like as shown below.

When I click the Players tab, the table is made active, but when I click the View Players and View Players (Script) hyperlinks inside Dashboard tab then it navigates to Players tab but the tab is not active (active class is not added to the tab)  like as shown below

Can anyone please help me on this

答:
It's because you've set the exact route to true and the routerLink inside it wasn't directing to the main players route.

```<code><li [routerLinkActiveOptions]="{ exact: false }" routerLinkActive="active">
  <a [routerLink]="['/players']">Players</a>
</li>
</code>```

Body:
It's because you've set the exact route to true and the routerLink inside it wasn't directing to the main players route.

<li [routerLinkActiveOptions]="{ exact: false }" routerLinkActive="active">
  <a [routerLink]="['/players']">Players</a>
</li>


问:
Stop-start an elasticsearch instance having all the primary shards
I have an Elasticsearch (v5.6.10) cluster with 3 nodes.

Node A : Master

Node B : Master + Data

Node C : Master + Data

There are 6 shards per data node with replication set as 1. All 6 primary nodes are in Node B and all 6 replicas are in Node C.

My requirement is to take out the Node B, do some maintenance work and put it back in cluster without any downtime.

I checked elastic documentation, discussion forum and stackoverflow questions. I found that I should execute the below request first in order to to allocate the shards on that node to the remaining nodes.

```<code>curl -XPUT localhost:9200/_cluster/settings -H 'Content-Type: application/json' -d '{
  "transient" :{
      "cluster.routing.allocation.exclude._ip" : <Node B IP>
   }
}';echo

</code>```

Once all the shards have been reallocated I can shutdown the node and do my maintenance work. Once I am done, I have to include the node again for allocation and Elasticsearch will rebalance the shards again.

Now I also found another discussion where the user faced an issue of yellow/red cluster health issue due to having only one data node but wrongly setting replication as one, causing unassigned shards. It seems to me while doing this exercise I am taking my cluster towards that state.

So, my concern here is whether I am following the correct way keeping in mind all my primary shards are in the node (Node B) which I am taking out of a cluster having replication factor as 1.

答:
With only two data nodes and you wanting to shut down one, you can't really reallocate the shards. Elasticsearch never allocates primary and replica shards on the same nodes; it wouldn't add any benefit in availability or performance and would only double the disk space. So your reallocation command wouldn't add any benefit here since the shards cannot be moved anywhere.

Do a synced flush and then an orderly shutdown of the node. The replica shards on the remaining node will automatically be promoted to primary shards. Your cluster will go yellow until the other node joins again, but there isn't really a way around it in your scenario (without being either a hack or an overkill). But this is fine — as long as you always have a replica it will be on the other node and your cluster will keep working as expected.

Body:
I have an Elasticsearch (v5.6.10) cluster with 3 nodes.

Node A : Master

Node B : Master + Data

Node C : Master + Data

There are 6 shards per data node with replication set as 1. All 6 primary nodes are in Node B and all 6 replicas are in Node C.

My requirement is to take out the Node B, do some maintenance work and put it back in cluster without any downtime.

I checked elastic documentation, discussion forum and stackoverflow questions. I found that I should execute the below request first in order to to allocate the shards on that node to the remaining nodes.

curl -XPUT localhost:9200/_cluster/settings -H 'Content-Type: application/json' -d '{
  "transient" :{
      "cluster.routing.allocation.exclude._ip" : <Node B IP>
   }
}';echo

Once all the shards have been reallocated I can shutdown the node and do my maintenance work. Once I am done, I have to include the node again for allocation and Elasticsearch will rebalance the shards again.

Now I also found another discussion where the user faced an issue of yellow/red cluster health issue due to having only one data node but wrongly setting replication as one, causing unassigned shards. It seems to me while doing this exercise I am taking my cluster towards that state.

So, my concern here is whether I am following the correct way keeping in mind all my primary shards are in the node (Node B) which I am taking out of a cluster having replication factor as 1.


问:
How do I modify my Django REST endpoint to automatically create a dependent model when creating the submitted model?
I'm using the djangorestframework module to set up an API to update/read my models.  I have these models ...

```<code>from django.db import models

from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField
from address.models import State
from address.models import Country

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        unique_together = ("name",)

class Coop(models.Model):
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()
</code>```

and I have these view classes ...

```<code>class CoopList(APIView):
    """
    List all coops, or create a new coop.
    """
    def get(self, request, format=None):
        coops = Coop.objects.all()
        serializer = CoopSerializer(coops, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = CoopSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CoopDetail(APIView):
    """
    Retrieve, update or delete a coop instance.
    """
    def get_object(self, pk):
        try:
            return Coop.objects.get(pk=pk)
            raise Http404

    def get(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        coop = self.get_object(pk)
        coop.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

Problem is, I would like to submit JSON like this

```<code>{
        "name": "1872",
        "type": {
            "name": "Coworking Space"
        },
</code>```

with the intention being that for the dependent CoopType model, I would either create one of use an existing one before creating my Coop model.  However, right now, submitting the above results in a 400 response ...

```<code>{"type":["Incorrect type. Expected pk value, received dict."]
</code>```

How should I modify my view class to accommodate what I'm trying to do?

Edit: the serializers ...

```<code>from rest_framework import serializers
from maps.models import Coop, CoopType
from address.models import Address, AddressField, Locality, State, Country

class CoopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Coop
        fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site']

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['type'] = CoopTypeSerializer(instance.type).data
        rep['address'] = AddressSerializer(instance.address).data
        return rep

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Coop.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Coop` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.type = validated_data.get('type', instance.type)
        instance.address = validated_data.get('address', instance.address)
        instance.enabled = validated_data.get('enabled', instance.enabled)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.email = validated_data.get('email', instance.email)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.save()
        return instance

class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance
</code>```

Edit 2: The curl request ...

```<code>#!/bin/bash

read -d '' req << EOF
{
        "name": "1872",
        "type": {
            "name": "Coworking Space"
        },
        "address": {
            "id": 1,
            "street_number": "222",
            "route": "1212",
            "raw": "222 W. Merchandise Mart Plaza, Suite 1212",
            "formatted": "222 W. Merchandise Mart Plaza, Suite 1212",
            "latitude": 41.88802611,
            "longitude": -87.63612199,
            "locality": {
                "id": 29,
                "name": "Chicago",
                "postal_code": "60654",
                "state": {
                    "id": 1,
                    "name": "IL",
                    "code": "",
                    "country": {
                        "id": 484,
                        "name": "United States",
                        "code": "US"
                    }
                }
            }
        },
        "enabled": true,
        "phone": null,
        "email": null,
        "web_site": "http://www.1871.com/"
}
EOF

echo $req

curl -v --header "Content-type: application/json" --data "$req" --request POST "http://127.0.0.1/coops/"
</code>```

答: Based on the current serializer, the CoopType needs to be made ahead of time (or fetched ahead of time if it exists) so that the id can be passed along. If you want to still make the CoopType with nested data in the Coop serializer (or use it to find the CoopType to use), Django Rest Framework talks about how in their docs under Writable nested serializers.

Body:
I'm using the djangorestframework module to set up an API to update/read my models.  I have these models ...

from django.db import models

from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField
from address.models import State
from address.models import Country

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        unique_together = ("name",)

class Coop(models.Model):
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

and I have these view classes ...

class CoopList(APIView):
    """
    List all coops, or create a new coop.
    """
    def get(self, request, format=None):
        coops = Coop.objects.all()
        serializer = CoopSerializer(coops, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = CoopSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CoopDetail(APIView):
    """
    Retrieve, update or delete a coop instance.
    """
    def get_object(self, pk):
        try:
            return Coop.objects.get(pk=pk)
            raise Http404

    def get(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        coop = self.get_object(pk)
        coop.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Problem is, I would like to submit JSON like this

{
        "name": "1872",
        "type": {
            "name": "Coworking Space"
        },

with the intention being that for the dependent CoopType model, I would either create one of use an existing one before creating my Coop model.  However, right now, submitting the above results in a 400 response ...

{"type":["Incorrect type. Expected pk value, received dict."]

How should I modify my view class to accommodate what I'm trying to do?

Edit: the serializers ...

from rest_framework import serializers
from maps.models import Coop, CoopType
from address.models import Address, AddressField, Locality, State, Country

class CoopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Coop
        fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site']

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['type'] = CoopTypeSerializer(instance.type).data
        rep['address'] = AddressSerializer(instance.address).data
        return rep

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Coop.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Coop` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.type = validated_data.get('type', instance.type)
        instance.address = validated_data.get('address', instance.address)
        instance.enabled = validated_data.get('enabled', instance.enabled)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.email = validated_data.get('email', instance.email)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.save()
        return instance

class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance

Edit 2: The curl request ...

#!/bin/bash

read -d '' req << EOF
{
        "name": "1872",
        "type": {
            "name": "Coworking Space"
        },
        "address": {
            "id": 1,
            "street_number": "222",
            "route": "1212",
            "raw": "222 W. Merchandise Mart Plaza, Suite 1212",
            "formatted": "222 W. Merchandise Mart Plaza, Suite 1212",
            "latitude": 41.88802611,
            "longitude": -87.63612199,
            "locality": {
                "id": 29,
                "name": "Chicago",
                "postal_code": "60654",
                "state": {
                    "id": 1,
                    "name": "IL",
                    "code": "",
                    "country": {
                        "id": 484,
                        "name": "United States",
                        "code": "US"
                    }
                }
            }
        },
        "enabled": true,
        "phone": null,
        "email": null,
        "web_site": "http://www.1871.com/"
}
EOF

echo $req

curl -v --header "Content-type: application/json" --data "$req" --request POST "http://127.0.0.1/coops/"


问:
somthing's wrong with django messages
I have a view function like this:

```<code>@login_required
def delete_deal(request, id_deal):
    id_deal = int(id_deal)
    user = get_object_or_404(User, id=request.user.id)
    user_deals = Deal.objects.filter(user=user)
    if not user_deals.exists():
        messages.add_message(request, messages.INFO,
                                        'You have no deal.')

        return redirect('index')

    return render(request, 'booking/confirmation_delete.html', {'title': title})
</code>```

If I test with a user who does not have a deal the message is not displayed the first time but if I redo the message is displayed 2 times, what is wrong ?

I have another view function which returns a message and it displays it normally !!

If you need more info tell me

Update:

Here is my url.py of the application where the view function above is located:

```<code>urlpatterns = [
    url(r'^create_deal/$', views.create_deal, name='create_deal'),
    url(r'^delete_deal/(?P<id_deal>[0-9]+)/$', views.delete_deal, name='delete_deal'),
]
</code>```

The view.py function:

```<code>def index(request):
    all_deals = Deal.objects.all()

    return render(request, 'base.html', locals())
</code>```

template.html:

```<code>{% if messages %}
  {% for message in messages %}
      <div>{{ message }}</div>
  {% endfor %}
{% endif %}
</code>```

答: It looks like it adds the message both times and will redirect to 'index' both times... So perhaps the problem is either in the urls and view for 'index' or somehow in the template being rendered. Show us the urls.py, the associated view function/opject and template.</p>

Title: somthing's wrong with django messages

Body:
I have a view function like this:

@login_required
def delete_deal(request, id_deal):
    id_deal = int(id_deal)
    user = get_object_or_404(User, id=request.user.id)
    user_deals = Deal.objects.filter(user=user)
    if not user_deals.exists():
        messages.add_message(request, messages.INFO,
                                        'You have no deal.')

        return redirect('index')

    return render(request, 'booking/confirmation_delete.html', {'title': title})

If I test with a user who does not have a deal the message is not displayed the first time but if I redo the message is displayed 2 times, what is wrong ?

I have another view function which returns a message and it displays it normally !!

If you need more info tell me

Update:

Here is my url.py of the application where the view function above is located:

urlpatterns = [
    url(r'^create_deal/$', views.create_deal, name='create_deal'),
    url(r'^delete_deal/(?P<id_deal>[0-9]+)/$', views.delete_deal, name='delete_deal'),
]

The view.py function:

def index(request):
    all_deals = Deal.objects.all()

    return render(request, 'base.html', locals())

template.html:

{% if messages %}
  {% for message in messages %}

{{ message }}

  {% endfor %}
{% endif %}


问:
Console app not parsing correctly args with white spaces
I've created a .NET console application that gets some command line arguments.

When I pass args with white spaces, I use quotes to embrace these arguments so that they are not splitted by cmd:

```<code>C:\MyAppDir> MyApp argument1 "argument 2" "the third argument"
</code>```

If I execute the app in Windows XP it works fine: it gets 3 arguments:

argument1

argument 2

the third argument

However, if i execute it in Windows Server 2008 it seems to ignore quotes: it gets 6 arguments:

argument1

"argument

2"

"the

third

argument"

Any ideas why?

NOTE: I printed arguments just when Main starts execution using this code:

```<code>Console.WriteLine("Command line arguments:");
foreach (string arg in args)
{
    Console.WriteLine("# " + arg);
}
</code>```

答:
You can try, put each arguments between Quota"" and in the paths put double backslash for example like that:

generadorPlantillasPDF.exe "C:\GDI\desarrollos\celula canales\proyectos\Progreso\curso xml\" generadorprogreso.xml C:\Temp\ BVI "C:\GDI\desarrollos\celula canales\proyectos\Progreso\plantilla\" "C:\GDI\desarrollos\celula canales\proyectos\Progreso\" "Formulario Progreso Version 2.0.docx" C:\Temp\

Body:
I've created a .NET console application that gets some command line arguments.

When I pass args with white spaces, I use quotes to embrace these arguments so that they are not splitted by cmd:

C:\MyAppDir> MyApp argument1 "argument 2" "the third argument"

If I execute the app in Windows XP it works fine: it gets 3 arguments:

argument1

argument 2

the third argument

However, if i execute it in Windows Server 2008 it seems to ignore quotes: it gets 6 arguments:

argument1

"argument

2"

"the

third

argument"

Any ideas why?

NOTE: I printed arguments just when Main starts execution using this code:

Console.WriteLine("Command line arguments:");
foreach (string arg in args)
{
    Console.WriteLine("# " + arg);
}


问:
different results array shortcode PHP
I have a question about the differents between the normal array code and the shortcode.
The output from the shortcode version has all the results.
But the normal code has only the last record of the data from the database.

Please is there somebody who can explain this?

Below the shortcode

```<code><?php
while ($data = mysqli_fetch_assoc($result)) {
 $output[$data['category']][] = $data['type'];
}
?>
</code>```

Below the normal code

```<code><?php
while ($data = mysqli_fetch_assoc($result)) {
    //alleen laatste database result
    $output = array($data['category'] => array($data['type']));
}
?>
</code>```

答:
When you assign

```<code>$output = <anything>;
</code>```

you discard all the previous contents of $output, and replace it with the value of <anything>. So each time through the loop in the second version, you replace the variable with the data from the current row. When the loop is done, it just has the data from the last row.

You don't want to replace all of $output. It should be a multi-dimensional array, where the first dimension is associative with categories as keys, and the second dimension is an array of all type values in that category. Assigning to

```<code>$output[$data['category']][]
</code>```

does two things:

$output[$data['category']] creates the category key in the first dimension if it doesn't already exist.

Assigning to [] pushes a new element onto the array in the second dimension.

It's equivalent to the following long code

```<code>while ($data = mysqli_fetch_assoc($result)) {
    $cat = $data['category'];
    if (!isset($output[$cat])) {
        $output[$cat] = array();
    }
    array_push($output[$cat], $data['type']);
}
</code>```

Title: different results array shortcode PHP

Body:
I have a question about the differents between the normal array code and the shortcode.
The output from the shortcode version has all the results.
But the normal code has only the last record of the data from the database.

Please is there somebody who can explain this?

Below the shortcode

<?php
while ($data = mysqli_fetch_assoc($result)) {
 $output[$data['category']][] = $data['type'];
}
?>

Below the normal code

<?php
while ($data = mysqli_fetch_assoc($result)) {
    //alleen laatste database result
    $output = array($data['category'] => array($data['type']));
}
?>

Body:
When you assign

$output = <anything>;

you discard all the previous contents of $output, and replace it with the value of <anything>. So each time through the loop in the second version, you replace the variable with the data from the current row. When the loop is done, it just has the data from the last row.

You don't want to replace all of $output. It should be a multi-dimensional array, where the first dimension is associative with categories as keys, and the second dimension is an array of all type values in that category. Assigning to

$output[$data['category']][]

does two things:

$output[$data['category']] creates the category key in the first dimension if it doesn't already exist.

Assigning to [] pushes a new element onto the array in the second dimension.

It's equivalent to the following long code

while ($data = mysqli_fetch_assoc($result)) {
    $cat = $data['category'];
    if (!isset($output[$cat])) {
        $output[$cat] = array();
    }
    array_push($output[$cat], $data['type']);
}


问:
TapGestureRecognition in Xamarin Forms Listview
I need to check if the empty part of a Xamarin Forms Listview is tapped. For example, there are 5 rows and the space below those filled rows is tapped a method should be called.
I tried adding Tapgesturerecognizer to the Listview and the page containing the listview but this didnt work.
Is there a way to check if someone tapped the empty space in the listview?</p>

```<code><ListView x:Name="ItemsListView"
                ItemsSource="{Binding Items}"
                VerticalOptions="FillAndExpand"
                HasUnevenRows="true"
                RefreshCommand="{Binding LoadItemsCommand}"
                IsPullToRefreshEnabled="true"
                IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                CachingStrategy="RecycleElement"
                ItemSelected="OnItemSelected">
            <d:ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>First Item</x:String>
                    <x:String>Second Item</x:String>
                    <x:String>Third Item</x:String>
                    <x:String>Fourth Item</x:String>
                    <x:String>Fifth Item</x:String>
                    <x:String>Sixth Item</x:String>
                </x:Array>
            </d:ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10">
                            <Label Text="{Binding Text}"
                                d:Text="{Binding .}"
                                LineBreakMode="NoWrap"
                                Style="{DynamicResource ListItemTextStyle}"
                                FontSize="16" />
                            <Label Text="{Binding Description}"
                                d:Text="Item descripton"
                                LineBreakMode="NoWrap"
                                Style="{DynamicResource ListItemDetailTextStyle}"
                                FontSize="13" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>
            <ListView.GestureRecognizers>
                <TapGestureRecognizer Tapped="OnTapGestureRecognizerTapped" NumberOfTapsRequired="1"></TapGestureRecognizer>
            </ListView.GestureRecognizers>
        </ListView>
</code>```

答:
Try to adding footer to the Listview

```<code><ListView
    x:Name="ItemsListView"
    ...>

    <ListView.Footer>
        <ContentView>
            <ContentView.GestureRecognizers>
                <TapGestureRecognizer />
            <ContentView.GestureRecognizers>
        </ContentView>
    </ListView.Footer>
</ListView>
</code>```

set footer view and place your TapGestureRecognizer

Body:
I need to check if the empty part of a Xamarin Forms Listview is tapped. For example, there are 5 rows and the space below those filled rows is tapped a method should be called.
I tried adding Tapgesturerecognizer to the Listview and the page containing the listview but this didnt work.
Is there a way to check if someone tapped the empty space in the listview?

<ListView x:Name="ItemsListView"
                ItemsSource="{Binding Items}"
                VerticalOptions="FillAndExpand"
                HasUnevenRows="true"
                RefreshCommand="{Binding LoadItemsCommand}"
                IsPullToRefreshEnabled="true"
                IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                CachingStrategy="RecycleElement"
                ItemSelected="OnItemSelected">
            <d:ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>First Item</x:String>
                    <x:String>Second Item</x:String>
                    <x:String>Third Item</x:String>
                    <x:String>Fourth Item</x:String>
                    <x:String>Fifth Item</x:String>
                    <x:String>Sixth Item</x:String>
                </x:Array>
            </d:ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10">

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>
            <ListView.GestureRecognizers>
                <TapGestureRecognizer Tapped="OnTapGestureRecognizerTapped" NumberOfTapsRequired="1"></TapGestureRecognizer>
            </ListView.GestureRecognizers>
        </ListView>

Body:
Try to adding footer to the Listview

<ListView
    x:Name="ItemsListView"
    ...>

    <ListView.Footer>
        <ContentView>
            <ContentView.GestureRecognizers>
                <TapGestureRecognizer />
            <ContentView.GestureRecognizers>
        </ContentView>
    </ListView.Footer>
</ListView>

set footer view and place your TapGestureRecognizer


问:
Text wrap for plot titles
I have a long title for a plot in R and it keeps extending outside the plot
window. How can I wrap the title over 2 rows? </p>

答:
In case you want to go with one of the "\n" solutions, keep in mind it's also possible for the title to get too tall and spill over the top. If your generating lines dynamically, you can keep track of the line count and solve the problem like this:</p>

```<code>mar = par()$mar #get the current margins
mar[3] = mar[3] + line_count #increase the top margin if the title has too many lines
par(mar = mar) #set the new margins
hist(rnorm(100), main = title)
</code>```

Title: Text wrap for plot titles

Body:
In case you want to go with one of the "\n" solutions, keep in mind it's also possible for the title to get too tall and spill over the top. If your generating lines dynamically, you can keep track of the line count and solve the problem like this:

mar = par()$mar #get the current margins
mar[3] = mar[3] + line_count #increase the top margin if the title has too many lines
par(mar = mar) #set the new margins
hist(rnorm(100), main = title)


问:
R Shiny - saving values of function in data table after action button press
I am trying to create a way to track opening and closing of the breathing organ (i.e. a mouth) of several animals at the same time over the course of 45 minutes. The goal is to be able to calculate the total open time and frequency of opening for each animal. Basically, the idea is to have several stopwatches operating in parallel, while tracking two lists of values per animal: open time and close time.

The experiment would ideally go like this: I start the experiment and therefore the stopwatch. Every time animal 1 opens its breathing organ, I press open, and once it closes its breathing organ, I press close. The time of each, relative to the stopwatch started at the beginning of the experiment, are recorded in a dataframe for animal 1. This process repeats 10-15 times throughout 45 minutes. At the same time, another animal is opening and closing its breathing organ, and a separate dataframe for animal 2 is created using a different set of buttons. I would like to have this be possible for up to 10 animals simultaneously.

I have been able to make the stopwatches (example code below) using a watch function, as well as include action buttons that output text corresponding to the difference in system time between start time of the experiment and time of pressing the open or close buttons. However, I am unsure of how to store these values in a dataframe for each animal.

I have looked around stackoverflow and found nothing that works, including this thread: r Shiny action button and data table output
and this one:
Add values to a reactive table in shiny

Let me know if you need any more info! Thanks in advance.

library(lubridate)
library(shiny)
library(DT)

# stopwatch function ----

stop_watch = function() {
  start_time = stop_time = open_time = close_time = NULL
  start = function() start_time <<- Sys.time()
  stop = function() {
    stop_time <<- Sys.time()
    as.numeric(difftime(stop_time, start_time))
  }
  open = function() {
    open_time <<- Sys.time()
    as.numeric(difftime(open_time, start_time))
  }
  close = function() {
    close_time <<- Sys.time()
    as.numeric(difftime(close_time, start_time))
  }
  list(start=start, open=open, close=close, stop=stop)
}
watch = stop_watch()

# ui ----

ui <- fluidPage(
  titlePanel("Lymnaea stopwatch"),

  sidebarLayout(
    sidebarPanel(

      selectInput(
        "select",
        label = "Number of animals",
        choices = c(1,2,3,4,5,6,7,8,9,10),
        selected = c("1")
      )
  # action button conditionals ----
    ),
    mainPanel(
      h4("Start/Stop Experiment:"),
      actionButton('start1',"Start"),
      actionButton('stop1', "Stop"),
      textOutput('initial1'),
      textOutput('start1'),
      textOutput('stop1'),
      textOutput('stoptime1'),

     conditionalPanel(
       h4("Animal 1"),
      condition = "input.select == '1'||input.select == '2'||input.select == '3'||input.select == '4'||input.select == '5'||input.select == '6'||input.select == '7'||input.select == '8'||input.select == '9'||input.select == '10'",
       actionButton('open1', "Open"),
       actionButton('close1', "Close"),
       textOutput('open1'),
       textOutput('opentime1'),
       textOutput('close1'),
       textOutput('closetime1'),

     )

  )
)
)

# server ----

server <- function(input, output, session) {

values <- reactiveValues()

values$df <- data.frame(colnames(c("Open", "Close")))

newEntry <- observe({
  if(input$open1 > 0) {
    newLine <- isolate(c(({watch$start()})))
    isolate(values$df <- rbind(values$df, newLine))
  }
})

output$table <- renderTable({values$df})

  # n = 1 animal  ----
  observeEvent(input$start1, {
    watch$start()
    output$initial1 <- renderText(
      "Timer started."
      )
  })

  observeEvent(input$open1, {
    watch$open()
    output$open1 <- renderText(
      "Time of opening:"
    )
    output$opentime1 <- renderText({
      watch$open()
    })
 })

  observeEvent(input$close1, {
    watch$close()
    output$close1 <- renderText({
      "Time of closing:"
    })
    output$closetime1 <- renderText({
      watch$close()
    })
  })

}

shinyApp(ui, server)
```

答:
I think there may be a number of ways you could set this up differently.

One recommendation I have is to avoid putting output inside of your observers.

Another is calling your stopwatch functions only once - for data integrity, to make sure your display and data collected are the same.

In addition, it might be helpful to have a single data table store all of your open and close events, with an additional column for animal number. It would be relatively easy to work with a table like this for future analyses.

Here is a quick example you can try out, just to get a sense of the behavior. Please also add tableOutput('table') to your ui after your conditionalPanel to view the data frame.

```<code># ui ----

ui <- fluidPage(
  titlePanel("Lymnaea stopwatch"),

  sidebarLayout(
    sidebarPanel(

      selectInput(
        "select",
        label = "Number of animals",
        choices = c(1,2,3,4,5,6,7,8,9,10),
        selected = c("1")
      )
      # action button conditionals ----
    ),
    mainPanel(
      h4("Start/Stop Experiment:"),
      actionButton('start1',"Start"),
      actionButton('stop1', "Stop"),
      textOutput('initial1'),
      textOutput('start1'),
      textOutput('stop1'),
      textOutput('stoptime1'),

      conditionalPanel(
        h4("Animal 1"),
        condition = "input.select == '1'||input.select == '2'||input.select == '3'||input.select == '4'||input.select == '5'||input.select == '6'||input.select == '7'||input.select == '8'||input.select == '9'||input.select == '10'",
        actionButton('open1', "Open"),
        actionButton('close1', "Close"),
        textOutput('open1'),
        textOutput('opentime1'),
        textOutput('close1'),
        textOutput('closetime1'),
      ),
      tableOutput('table')
    )
  )
)

# server ----

server <- function(input, output, session) {

  values <- reactiveValues(df = data.frame(Animal = integer(),
                                           Event = character(),
                                           Time = as.POSIXct(character()),
                                           stringsAsFactors = FALSE),
                           timer = "Timer Off")

  output$initial1 <- renderText({
    values$timer
  })

  output$opentime1 <- renderText({
    paste("Opened at:", tail(values$df[values$df[["Animal"]] == 1 & values$df[["Event"]] == "Open", "Time"], 1))
  })

  output$closetime1 <- renderText({
    paste("Closed at:", tail(values$df[values$df[["Animal"]] == 1 & values$df[["Event"]] == "Close", "Time"], 1))
  })

  output$table <- renderTable({
    values$df
  })

  observeEvent(input$start1, {
    watch$start()
    values$timer <- "Timer Started"
  })

  observeEvent(input$open1, {
    values$df <- rbind(values$df, data.frame(Animal = 1, Event = "Open", Time = watch$open()))
  })

  observeEvent(input$close1, {
    values$df <- rbind(values$df, data.frame(Animal = 1, Event = "Close", Time = watch$close()))
  })

}
</code>```

This could be scaled up for 10 animals, and there are alternative ways to provide feedback to user on data.

Let me know what you think, and if this is in the direction you had in mind.

Body:
I think there may be a number of ways you could set this up differently.

One recommendation I have is to avoid putting output inside of your observers.

Another is calling your stopwatch functions only once - for data integrity, to make sure your display and data collected are the same.

In addition, it might be helpful to have a single data table store all of your open and close events, with an additional column for animal number. It would be relatively easy to work with a table like this for future analyses.

Here is a quick example you can try out, just to get a sense of the behavior. Please also add tableOutput('table') to your ui after your conditionalPanel to view the data frame.

# ui ----

ui <- fluidPage(
  titlePanel("Lymnaea stopwatch"),

  sidebarLayout(
    sidebarPanel(

      selectInput(
        "select",
        label = "Number of animals",
        choices = c(1,2,3,4,5,6,7,8,9,10),
        selected = c("1")
      )
      # action button conditionals ----
    ),
    mainPanel(
      h4("Start/Stop Experiment:"),
      actionButton('start1',"Start"),
      actionButton('stop1', "Stop"),
      textOutput('initial1'),
      textOutput('start1'),
      textOutput('stop1'),
      textOutput('stoptime1'),

      conditionalPanel(
        h4("Animal 1"),
        condition = "input.select == '1'||input.select == '2'||input.select == '3'||input.select == '4'||input.select == '5'||input.select == '6'||input.select == '7'||input.select == '8'||input.select == '9'||input.select == '10'",
        actionButton('open1', "Open"),
        actionButton('close1', "Close"),
        textOutput('open1'),
        textOutput('opentime1'),
        textOutput('close1'),
        textOutput('closetime1'),
      ),
      tableOutput('table')
    )
  )
)

# server ----

server <- function(input, output, session) {

  values <- reactiveValues(df = data.frame(Animal = integer(),
                                           Event = character(),
                                           Time = as.POSIXct(character()),
                                           stringsAsFactors = FALSE),
                           timer = "Timer Off")

  output$initial1 <- renderText({
    values$timer
  })

  output$opentime1 <- renderText({
    paste("Opened at:", tail(values$df[values$df[["Animal"]] == 1 & values$df[["Event"]] == "Open", "Time"], 1))
  })

  output$closetime1 <- renderText({
    paste("Closed at:", tail(values$df[values$df[["Animal"]] == 1 & values$df[["Event"]] == "Close", "Time"], 1))
  })

  output$table <- renderTable({
    values$df
  })

  observeEvent(input$start1, {
    watch$start()
    values$timer <- "Timer Started"
  })

  observeEvent(input$open1, {
    values$df <- rbind(values$df, data.frame(Animal = 1, Event = "Open", Time = watch$open()))
  })

  observeEvent(input$close1, {
    values$df <- rbind(values$df, data.frame(Animal = 1, Event = "Close", Time = watch$close()))
  })

}

This could be scaled up for 10 animals, and there are alternative ways to provide feedback to user on data.

Let me know what you think, and if this is in the direction you had in mind.


答:
You can use Array.reduce in conjunction with Object.values to get all the values from your array of objects:

const arr = [{
    key1: "value",
    Key2: "value2",
    key3: "value3"
  },
  {
    key1: "value5",
    Key2: "value6",
    key3: "value7"
  }
];

let result = arr.reduce(
  (c, v) => c.concat(Object.values(v)), []
);
console.log(result);```

Title: Extract all values when I have key : value and store all value in an array

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value2",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start


问:
LWC deployment Error while deploying from VS Code
Hi I am having issue while deploying the new created LWC component from the VS Code to my dev hub org.

Please find the error as below :

```<code>19:18:39.577 sfdx force:source:deploy --sourcepath c:\Users\ABHIJEET KUMAR\Downloads\OCT\Documents\TrailheadBasic\HelloWordLightningComponent\force-app\main\default --json --loglevel fatal
</code>```

19:18:44.413 sfdx force:source:deploy --sourcepath c:\Users\ABHIJEET KUMAR\Downloads\OCT\Documents\TrailheadBasic\HelloWordLightningComponent\force-app\main\default --json --loglevel fatal ended with exit code 1

```<code>SFDX: Deploy Source to Org failed to run
</code>```

Error is here :

```<code>MissingMessageError: Missing message mdapi_deploy:mdDeployCommandCliCheckOnly for locale en_US.
at Messages.getMessageWithMap (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/core/lib/messages.js:277:19)
at Messages.getMessage (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/core/lib/messages.js:261:21)
at Object.<anonymous> (C:/Program Files/Salesforce CLI/client/node_modules/salesforce-alm/dist/commands/force/source/deploy.js:38:36)
at Module._compile (C:/Program Files/Salesforce CLI/client/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
at LazyLoader.loadModule (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/lazy-require/lib/LazyLoader.js:139:21)
at Function._load (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/lazy-require/lib/LazyLoader.js:115:29)
at require (C:/Program Files/Salesforce CLI/client/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
at fetch (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/plugin.js:111:21)
at Plugin.findCommand (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/plugin.js:125:21)
at Object.load (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/plugin.js:58:72)
at Config.runCommand (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/config.js:149
</code>```

答:
Here are a few steps to cross-check before deploying to org.

(1) Make sure your org is on API version 45.0 or above
Log into the target org where you're trying to deploy, go on setup --> Apex Classes --> New and click on the Version Settings" tab. If the default version you can select is 45.0 or above, awesome; otherwise, you may have to wait until your org instance is upgraded (or spin a new trailhead playground).

(2) Install upgrades to the salesforcedx CLI
On your terminal or cmd.exe, run sfdx plugins:install salesforcedx@latest
You shouldn't have to install the pre-release plugins after February 9th, but if so you could run

sfdx plugins:install salesforcedx@pre-release

(3) Make sure your lightning web component API version AND your overall project API version is 45.0 (or latest)
in Visual Studio Code, open the following files:

In the root folder:
sfdx-project.json and make sure that "sourceApiVersion": "45.0".

In the lwc component folder:
helloWorld.js-meta.xml and make sure that the API version is 45.0

Then re-run the command deploy source to Org and it should work (it reads the overall API version of the output from the root folder project definition).

Body:
Hi I am having issue while deploying the new created LWC component from the VS Code to my dev hub org.

Please find the error as below :

19:18:39.577 sfdx force:source:deploy --sourcepath c:\Users\ABHIJEET KUMAR\Downloads\OCT\Documents\TrailheadBasic\HelloWordLightningComponent\force-app\main\default --json --loglevel fatal

19:18:44.413 sfdx force:source:deploy --sourcepath c:\Users\ABHIJEET KUMAR\Downloads\OCT\Documents\TrailheadBasic\HelloWordLightningComponent\force-app\main\default --json --loglevel fatal ended with exit code 1

SFDX: Deploy Source to Org failed to run

Error is here :

MissingMessageError: Missing message mdapi_deploy:mdDeployCommandCliCheckOnly for locale en_US.
at Messages.getMessageWithMap (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/core/lib/messages.js:277:19)
at Messages.getMessage (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/core/lib/messages.js:261:21)
at Object.<anonymous> (C:/Program Files/Salesforce CLI/client/node_modules/salesforce-alm/dist/commands/force/source/deploy.js:38:36)
at Module._compile (C:/Program Files/Salesforce CLI/client/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
at LazyLoader.loadModule (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/lazy-require/lib/LazyLoader.js:139:21)
at Function._load (C:/Program Files/Salesforce CLI/client/node_modules/@salesforce/lazy-require/lib/LazyLoader.js:115:29)
at require (C:/Program Files/Salesforce CLI/client/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
at fetch (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/plugin.js:111:21)
at Plugin.findCommand (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/plugin.js:125:21)
at Object.load (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/plugin.js:58:72)
at Config.runCommand (C:/Program Files/Salesforce CLI/client/node_modules/@oclif/config/lib/config.js:149


问:
Where to store files for user in Android?
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.

I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.

What are the alternatives?

答:
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.  </p>

```<code>public static void save(float[] input_array, String name)
{
    final String TAG2 = "->save()";

    String string_array = Arrays.toString(input_array);

    String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
    String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";

    File folder = new File(path);
    if(!folder.exists())
    {
        folder.mkdirs();
    }

    BufferedWriter buf;

    try
    {
        buf = new BufferedWriter(new FileWriter(fullName));
        buf.write(string_array,0,string_array.length());
        buf.close();
        Log.d(TAG+TAG2, "array saved as document. ");
    }
    catch (IOException e)
    {
        Log.e(TAG+TAG2, "problems while saving the file. ");
    }

}
</code>```

Body:
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.

public static void save(float[] input_array, String name)
{
    final String TAG2 = "->save()";

    String string_array = Arrays.toString(input_array);

    String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
    String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";

    File folder = new File(path);
    if(!folder.exists())
    {
        folder.mkdirs();
    }

    BufferedWriter buf;

    try
    {
        buf = new BufferedWriter(new FileWriter(fullName));
        buf.write(string_array,0,string_array.length());
        buf.close();
        Log.d(TAG+TAG2, "array saved as document. ");
    }
    catch (IOException e)
    {
        Log.e(TAG+TAG2, "problems while saving the file. ");
    }

}


问:
Using the addition function over the natural numbers, give a recursive definition of multiplication of natural numbers?
I have the following exercise but am not sure on how I should begin. The wording doesn't make sense to me:

Using the addition function over the
  natural numbers, give a recursive
  definition of multiplication of
  natural numbers.

答: You can think of 3 * 5 as 5 + 5 + 5, i.e. adding 5 for 3 times. If you want to do it recursively, then you can think of it like this: the result of a * b is equal to adding b to the result of (a-1) * b. From here to a Haskell recursive function, the step is small :)


问:
How to have 2 different previews running on Camera2 Api?
I want to have previews running from 2 different cameras, like the front and rear (or rear wide and rear ultra-wide) both are being previewed at the same time. I am able to create a single preview but don't know how to have 2 previews running.
Any guide on how to do that? Also if there any changes that need to be done on the HAL side, please tell about that too.</p>

答:
You just operate the two cameras separately. Open both cameras, configure each with a single output. However, most devices don't support this on the hardware level, because they share some of the processing pipeline between the two cameras.

So be prepared to have the second camera open to fail, on most Android devices.
On devices where it works, try to minimize the resolution you configure, since that increases the likelihood the device can run both cameras at the same time.


问:
Are spatial queries possible using Python and cx_Oracle?
I am trying to execute a spatial query on an Oracle spatial table via python using the cx_Oracle package.

I can make generic queries successfully, but when I try a spatial query it results in errors.

This is what I have tried:

```<code>import cx_Oracle
...

lon = -120.494352
lat = 36.585289

# open a connection to oracle
con = cx_Oracle.connect('myuser/mypass@spatialdb')

# create a cursor
cur = con.cursor()

# Create and populate Oracle objects
typeObj = con.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = con.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = con.gettype("MDSYS.SDO_ORDINATE_ARRAY")
obj = typeObj.newobject()
obj.SDO_GTYPE = 2001
obj.SDO_SRID = 8307
obj.SDO_ELEM_INFO = elementInfoTypeObj.newobject()
obj.SDO_ELEM_INFO.extend([1, 1, 1])
obj.SDO_ORDINATES = ordinateTypeObj.newobject()
obj.SDO_ORDINATES.extend([lon, lat])
print("Created object", obj)

# set up a distance-calculating sql statement
sql = "select id into :id from spatialtbl s where sdo_nn(s.geometry, :obj, 'sdo_num_res=1', 1) = 'TRUE'"

try:
    # execute the distance sql
    cur.execute(sql, id=id, obj=obj)
    print(f'The id is {id.getvalue()}')
except cx_Oracle.Error as error:
    print(error)
</code>```

which results in the error:

```<code>ORA-01036: illegal variable name/number
</code>```

Can anyone tell me what I may be doing wrong code-wise or if spatial queries are even possible using Python and cx_Oracle? The cx_Oracle documentation doesn't specifically address this as far as I can tell/find.

答:
I think the "select into" was the problem (reserved for pl/sql?).

By doing the following I was able to obtain the answer:

```<code># set up a distance-calculating sql statement
sql = """select id from spatialtbl s where sdo_nn(s.geometry, :ob, 'sdo_num_res=1', 1) = 'TRUE'"""

try:
    # execute the distance sql
    cur.execute(sql, ob=obj)
    id = cur.fetchone()
    print(f'The id is {id}')
except cx_Oracle.Error as error:
    print(error)
</code>```

Body:
I am trying to execute a spatial query on an Oracle spatial table via python using the cx_Oracle package.

I can make generic queries successfully, but when I try a spatial query it results in errors.

This is what I have tried:

import cx_Oracle
...

lon = -120.494352
lat = 36.585289

# open a connection to oracle
con = cx_Oracle.connect('myuser/mypass@spatialdb')

# create a cursor
cur = con.cursor()

# Create and populate Oracle objects
typeObj = con.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = con.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = con.gettype("MDSYS.SDO_ORDINATE_ARRAY")
obj = typeObj.newobject()
obj.SDO_GTYPE = 2001
obj.SDO_SRID = 8307
obj.SDO_ELEM_INFO = elementInfoTypeObj.newobject()
obj.SDO_ELEM_INFO.extend([1, 1, 1])
obj.SDO_ORDINATES = ordinateTypeObj.newobject()
obj.SDO_ORDINATES.extend([lon, lat])
print("Created object", obj)

# set up a distance-calculating sql statement
sql = "select id into :id from spatialtbl s where sdo_nn(s.geometry, :obj, 'sdo_num_res=1', 1) = 'TRUE'"

try:
    # execute the distance sql
    cur.execute(sql, id=id, obj=obj)
    print(f'The id is {id.getvalue()}')
except cx_Oracle.Error as error:
    print(error)

which results in the error:

ORA-01036: illegal variable name/number

Can anyone tell me what I may be doing wrong code-wise or if spatial queries are even possible using Python and cx_Oracle? The cx_Oracle documentation doesn't specifically address this as far as I can tell/find.

Body:
I think the "select into" was the problem (reserved for pl/sql?).

By doing the following I was able to obtain the answer:

# set up a distance-calculating sql statement
sql = """select id from spatialtbl s where sdo_nn(s.geometry, :ob, 'sdo_num_res=1', 1) = 'TRUE'"""

try:
    # execute the distance sql
    cur.execute(sql, ob=obj)
    id = cur.fetchone()
    print(f'The id is {id}')
except cx_Oracle.Error as error:
    print(error)