问:
How to properly update a model on laravel? Method Illuminate\Database\Eloquent\Collection::update does not exist
I made a page for a user to update his company information, all companies default values are null, when a user is created. When a user fills the information, i get this error:

```<code> Method Illuminate\Database\Eloquent\Collection::update does not exist
</code>```

I am sure this error is because of my CompanyController@edit

```<code>     public function edit(Request $request)
{
    $this->validate($request, [
        'company_name' => 'alpha|max:50',
        'phone' => 'integer|max:50',
        'gst_hst_number' => 'integer|max:50',
        'country' => 'alpha|max:50',
    ]);

    $companies = Company::where('id', Auth::user()->id)->get();

    $companies->update([
        'company_name' => $request->input('company_name'),
        'phone' => $request->input('phone'),
        'gst_hst_number' => $request->input('gst_hst_number'),
        'country' => $request->input('country')
    ]);

    return redirect()->route('company.index')->with('info', 'Company information was updated.');
}
</code>```

I am stuck quite some time on this issue, would gladly apriciate help and information how to properly update my company models fillable fields.

答:
Your using update method on collection, but collection doesn't have update method,

what you need is remove the get(), so you can use update method on eloquent builder:

$companies = Company::where('id', Auth::user()->id);
$companies->update([
        'company_name' => $request->input('company_name'),
        'phone' => $request->input('phone'),
        'gst_hst_number' => $request->input('gst_hst_number'),
        'country' => $request->input('country')
]);
```

Body:
I made a page for a user to update his company information, all companies default values are null, when a user is created. When a user fills the information, i get this error:

 Method Illuminate\Database\Eloquent\Collection::update does not exist

I am sure this error is because of my CompanyController@edit

     public function edit(Request $request)
{
    $this->validate($request, [
        'company_name' => 'alpha|max:50',
        'phone' => 'integer|max:50',
        'gst_hst_number' => 'integer|max:50',
        'country' => 'alpha|max:50',
    ]);

    $companies = Company::where('id', Auth::user()->id)->get();

    $companies->update([
        'company_name' => $request->input('company_name'),
        'phone' => $request->input('phone'),
        'gst_hst_number' => $request->input('gst_hst_number'),
        'country' => $request->input('country')
    ]);

    return redirect()->route('company.index')->with('info', 'Company information was updated.');
}

I am stuck quite some time on this issue, would gladly apriciate help and information how to properly update my company models fillable fields.


来源: stackexchange

问:
How do I extract a certain amount of lines after a pattern in perl?
Lets say I have a text file:

```<code>Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

So far all I have is code to find the target and print it out:

```<code>use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}
</code>```

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

答:
Later edit, after reading a bit more documentation:

```<code>perl -ne 'print if $s = /Target/ ... $s == 2; print "\n" if $s == 3' sample.txt
</code>```

range operator:

```<code>~# perl -ne 'print if (($l = $.) && /Target/) .. $. == $l+2; print "\n" if  $. == $l+2' sample.txt
Target Name1
Line 3
Line 4

Target Name2
Line 7
Line 8
</code>```

Note: This is just some academic exercise kind of answer, I don't recommend using this, it's too cumbersome. I just wanted to see if it can be done, and when done I just posted it maybe someone would find it interesting. zdim`s answer is the way to go.

Note: according to the documentation documentation .. even if it't behaves differently in scalar context, it doesn't have a special name, it's still a range operator. However some people like to call it flip-flop. I always associated it with line-range, and that's the name I use.

ContentLicense: CC BY-SA 4.0

Body:
Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

Body:
Later edit, after reading a bit more documentation:

perl -ne 'print if $s = /Target/ ... $s == 2; print "\n" if $s == 3' sample.txt

range operator:

~# perl -ne 'print if (($l = $.) && /Target/) .. $. == $l+2; print "\n" if  $. == $l+2' sample.txt
Target Name1
Line 3
Line 4

Target Name2
Line 7
Line 8

Note: This is just some academic exercise kind of answer, I don't recommend using this, it's too cumbersome. I just wanted to see if it can be done, and when done I just posted it maybe someone would find it interesting. zdim`s answer is the way to go.

Note: according to the documentation documentation .. even if it't behaves differently in scalar context, it doesn't have a special name, it's still a range operator. However some people like to call it flip-flop. I always associated it with line-range, and that's the name I use.


问:
Sample all but first elements from flux in project reactor
In project reactor flux there is a sample method Flux#sample java doc. It changes flux so that it emits events only at the ends of specified periods.

Is it possible to tweak this behaviour and achieve this : on first element - emit it instantly , start sampling with delay from 2nd up to the end. Basically I want to exclude first (and only first) element from sampling so that it is emmited without initial wait.

Would it be possible to achieve using built-in operators ? If not then does anybody have an idea how to approach this problem ?

Here is a simplest example of what I want to achieve :

```<code>Flux<String> inputFlux = Flux.just("first", "second", "third").delayElements(Duration.ofMillis(400));
Flux<String> transformed = /*do some magic with input flux*/;

StepVerifier.create(transformed)
    .expectNext("first")//first should always be emmited instantly
    //second arrives 400ms after first
    //third arrives 400ms after second
    .expectNoEvent(Duration.ofSeconds(1))
    .expectNext("third")//after sample period last received element should be received
    .verifyComplete();
</code>```

答:
You could achieve it with Flux#sample(org.reactivestreams.Publisher) method.

```<code>yourFlux.take(1)
        .mergeWith(yourFlux.sample(Flux.interval(yourInterval)
                .delaySubscription(yourFlux.take(1))))
</code>```

Body:
In project reactor flux there is a sample method Flux#sample java doc. It changes flux so that it emits events only at the ends of specified periods.

Is it possible to tweak this behaviour and achieve this : on first element - emit it instantly , start sampling with delay from 2nd up to the end. Basically I want to exclude first (and only first) element from sampling so that it is emmited without initial wait.

Would it be possible to achieve using built-in operators ? If not then does anybody have an idea how to approach this problem ?

Here is a simplest example of what I want to achieve :

Flux<String> inputFlux = Flux.just("first", "second", "third").delayElements(Duration.ofMillis(400));
Flux<String> transformed = /*do some magic with input flux*/;

StepVerifier.create(transformed)
    .expectNext("first")//first should always be emmited instantly
    //second arrives 400ms after first
    //third arrives 400ms after second
    .expectNoEvent(Duration.ofSeconds(1))
    .expectNext("third")//after sample period last received element should be received
    .verifyComplete();

Body:
You could achieve it with Flux#sample(org.reactivestreams.Publisher<U>) method.

yourFlux.take(1)
        .mergeWith(yourFlux.sample(Flux.interval(yourInterval)
                .delaySubscription(yourFlux.take(1))))


问:
How to pass data from one component to another while using API in reactjs
In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in?
When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

```<code>{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "qwerty@yahoo.com",
      "password": "Aertyuio",
    }
  ]
}
</code>```

答:
One possible solution would be to use some state management library such as redux.

Otherwise you will need to have a component that will do this fetching stuff and this component should be a common ancestor to the components that will be at least affected with the data changes from API.

My objective is how to pass the the user name while user is getting logged in. When User gets logged in then it should show "welcome Username".

As a more generic solution, you can create a HOC that will do the fetching API stuff and return a new component with the data from the API injected as props.

Body:
In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in?
When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "qwerty@yahoo.com",
      "password": "Aertyuio",
    }
  ]
}


问:
How to send progress success message after every bulk operation in asp.net Core
I have an excel sheet that contains 50,000 rows, Now I have to update these using EF.
but Without full-cycle complete, I can't send any success message to the user, and the web page shows "Processing....." and every other operation is stopped, when the operation is done after 10-15 min later, then the user can see the success message.
Now I want to do: User can see progress, such as "1000/ 50000 data updated", "2000/ 50000 data updated", "50000/ 50000 data updated". and user can do other operation between the current operation.

I tried using Async, But I can't find out the exact result.

Technology:
Asp.Net Core MVC 3.1
EF Core 3.1
SQL server 2017

答:
The async and await keywords don't cause additional threads to be created.

So, It means if you want a job run in the background separately, you should use Threads nor async. foo more explanation about the difference of thread and async you can follow this Eric Lippert's answer.

But fortunately, there are exist some library that you can use for handling Background workers, such as Hangfire. They define themself as below:

An easy way to perform background processing in .NET and .NET Core applications. No Windows Service or separate process required. Backed by persistent storage. Open and free for commercial use.

and you said you want to display a progress bar to the user, that you can handle tracking progress by hangfire too.

good luck.


问:
Is it possible to find all unused CSS?

Possible Duplicate:

  Tool to identify unused css definitions

I have quite big CSS file, that already contains style definition for classes/elements that are not used by markup any more.

It is possible to find those quick?

答: you can get the Dust-Me Selectors plug in for Firefox to test pages individually or spider a whole site.</p>

ContentLicense: CC BY-SA 3.0

Title: Is it possible to find all unused CSS?


答:
Try this. ->get() is for multiple collections here you can directly update your records.

```<code>$companies = Company::where('id', Auth::user()->id)->update([
    'company_name' => $request->input('company_name'),
    'phone' => $request->input('phone'),
    'gst_hst_number' => $request->input('gst_hst_number'),
    'country' => $request->input('country')
]);;
</code>```

Title: How to properly update a model on laravel? Method Illuminate\Database\Eloquent\Collection::update does not exist

Body:
Try this. ->get() is for multiple collections here you can directly update your records.

$companies = Company::where('id', Auth::user()->id)->update([
    'company_name' => $request->input('company_name'),
    'phone' => $request->input('phone'),
    'gst_hst_number' => $request->input('gst_hst_number'),
    'country' => $request->input('country')
]);;


问:
Getting undefined value for input control
In the following html and javascript code(codepen - https://codepen.io/manuchadha/pen/OJVXdzb), I wan to print the value of the input control but I am getting the value as undefined - filename is  undefined. Why?

```<code><!DOCTYPE html>
<html>
  <head>
    <title>some title</title>
    <script src="jquery/jquery-3.3.1.min.js"></script>
    <script src="index.js"></script>
  </head>
  <body>
    <div id="add-more-answer-div">
      <div id="answer-filename-div">
        <label id="filename-label" for="answer-filename">Name</label>
        <input type="text" id="answer-filename" />
        <button
          type="button"
          id="more-answer-button"
          onclick="createNewAnswerSection()"
        >
          Add More Sections
        </button>
      </div>
    </div>
  </body>
</html>
</code>```

```<code>function createNewAnswerSection() {
  console.log("will create new answer section");
  var answerNameControl = $("#answer-filename");

  console.log("answer name control is ", answerNameControl);
  if (answerNameControl.value === "") {
    alert("give a filename to the answer");
  } else {
    console.log("filename is ", answerNameControl.value);
  }
}
</code>```

答:
You are missing the syntax of jQuery , You are using answerNameControl.value which is not the valid synatx instead you can use $(answerNameControl).val() to get the value
Your updated code is as below

<title>some title</title>

                        Name
                        <input type="text" id="answer-filename">
                        <button type="button" id="more-answer-button" onclick="createNewAnswerSection()">Add More Sections</button>

Body:
In the following html and javascript code(codepen - https://codepen.io/manuchadha/pen/OJVXdzb), I wan to print the value of the input control but I am getting the value as undefined - filename is  undefined. Why?

<!DOCTYPE html>

    <title>some title</title>

        Name
        <input type="text" id="answer-filename" />
        <button
          type="button"
          id="more-answer-button"
          onclick="createNewAnswerSection()"
        >
          Add More Sections
        </button>

function createNewAnswerSection() {
  console.log("will create new answer section");
  var answerNameControl = $("#answer-filename");

  console.log("answer name control is ", answerNameControl);
  if (answerNameControl.value === "") {
    alert("give a filename to the answer");
  } else {
    console.log("filename is ", answerNameControl.value);
  }
}

Body:
You are missing the syntax of jQuery , You are using answerNameControl.value which is not the valid synatx instead you can use $(answerNameControl).val() to get the value
Your updated code is as below

<html>
<head>
<title>some title</title>
<script src="jquery/jquery-3.3.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>

                  <div  id="add-more-answer-div">
                    <div id="answer-filename-div">
                        <label id="filename-label" for="answer-filename">Name</label>
                        <input type="text" id="answer-filename">
                        <button type="button" id="more-answer-button" onclick="createNewAnswerSection()">Add More Sections</button>
                    </div>
                  </div>

</body>

</html>
<script>
function createNewAnswerSection(){
    console.log("will create new answer section");
    var answerNameControl = $("#answer-filename");

            console.log("answer name control is ",answerNameControl);
            if($(answerNameControl).val() === ''){
                alert("give a filename to the answer");
            } else {
                    console.log("filename is ",$(answerNameControl).val());
            }
    }


问:
How to Rearrange WPBakery Page Builder Categories?
When I use vc_map() to add a new element to the content element list there is the category parameter to put the element in a certain tab.

If there are to many category tabs, VC will put some of them in a dropdown list on the right hand side. Is there a way to rearrange the order of all tabs?

答:
Don't know why someone would need this? Still you can arrange this as per your choice by jumping into plugin's code.

Con:

It will get reset, when in future you will be updating the plugin. And as per our understanding for WPBakery Page Builder plugin, you can't survive by without updating it.


问:
Python: changing .py file to .exe
I need some help with changing .py file to .exe file. I am trying to do it with cx_Freeze module, i managed to do the setup.py file, the only problem is, i dont know what should i put in my command prompt?

setup.py file looks like this:

```<code>import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"include_files": ["postevanka.ui,beep.wav,gang.wav"]}

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "Poštevanka",
        version = "0.1",
        description = "Postevanka",
        options = {"build_exe": build_exe_options},
        executables = [Executable("postevanka.py", base=base)])
</code>```

答:
You can create start.bat file and use it like exe

```<code>"C:\Program Files\Python37\python.exe" "C:\package\script.py"
</code>```

Title: Python: changing .py file to .exe

Body:
I need some help with changing .py file to .exe file. I am trying to do it with cx_Freeze module, i managed to do the setup.py file, the only problem is, i dont know what should i put in my command prompt?

setup.py file looks like this:

import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"include_files": ["postevanka.ui,beep.wav,gang.wav"]}

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "Poštevanka",
        version = "0.1",
        description = "Postevanka",
        options = {"build_exe": build_exe_options},
        executables = [Executable("postevanka.py", base=base)])

Body:
You can create start.bat file and use it like exe

"C:\Program Files\Python37\python.exe" "C:\package\script.py"


答:
As the error message says, you are using the update method on a collection, you have to change the select query to this:

```<code>$companies = Company::where('id', Auth::user()->id)->first();
</code>```

Because the get() method returns a collection, not a single record.

Body:
As the error message says, you are using the update method on a collection, you have to change the select query to this:

$companies = Company::where('id', Auth::user()->id)->first();

Because the get() method returns a collection, not a single record.


问:
Why is "Promise { <pending> }" not resolving?
I am trying to fetch data from the Storm Glass API.  I am using their template Fetch request (https://docs.stormglass.io/?javascript#point-request).

When I run the script the console reads out "Promise { <pending> }" indefinitely.  So, the request is not returning a value but I can't work out why. Any ideas?

I have replaced my API key with <My API key>

```<code>const http = require('http')
const fetch = require('isomorphic-fetch');

http.createServer((req, res) => {

////////////////////////////////////////////////App code
const lat = 58.7984;
const lng = 17.8081;
const params = 'waveHeight,airTemperature';

fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
}).then(function(response) {
  // Do something with response data.
  const jsonData = response.json();
  console.log(jsonData)
});

/////////////////////////////////////////////////////////
}).listen(3000);

console.log("service running on http://localhost:3000");
</code>```

答:
You can resolve promise by using async/awiat.</p>

```<code>fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
})
.then(async response => {
    const jsonData = await response.json();
    console.log(jsonData)
})
</code>```

Body:
I am trying to fetch data from the Storm Glass API.  I am using their template Fetch request (https://docs.stormglass.io/?javascript#point-request).

When I run the script the console reads out "Promise { <pending> }" indefinitely.  So, the request is not returning a value but I can't work out why. Any ideas?

I have replaced my API key with <My API key>

const http = require('http')
const fetch = require('isomorphic-fetch');

http.createServer((req, res) => {

////////////////////////////////////////////////App code
const lat = 58.7984;
const lng = 17.8081;
const params = 'waveHeight,airTemperature';

fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
}).then(function(response) {
  // Do something with response data.
  const jsonData = response.json();
  console.log(jsonData)
});

/////////////////////////////////////////////////////////
}).listen(3000);

console.log("service running on http://localhost:3000");

Body:
You can resolve promise by using async/awiat.

fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
})
.then(async response => {
    const jsonData = await response.json();
    console.log(jsonData)
})


问:
By using Jetpack Navigation Compnent
I couldn't get any idea or anything online so here I am. I'm using the jetpack navigation component and I want to navigate from fragmentA to fragmentB, and then fragmentB will have bottomnavigation with different fragments such as fragmentC, fragmentD, fragmentE, and fragmentE have viewpagers with different fragments such as fragmentF, fragmentG, fragmentH

答:
create navigation as your requirement as:

```<code><navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_share"
        android:name="com.package.share.ShareFragment"
        android:label="@string/menu_share"
        tools:layout="@layout/fragment_share" />

    <fragment
        android:id="@+id/nav_send"
        android:name="com.package.SendFragment"
        android:label="@string/comments"
        tools:layout="@layout/fragment_send" />
</navigation>
</code>```

and navigate to the fragment with respective menu and navHostFragment

```<code><fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/user_navigation" />
</code>```

now find your nav host fragment and set up your configuration...

hope this helps.......happy coding

Title: By using Jetpack Navigation Compnent

Body:
create navigation as your requirement as:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_share"
        android:name="com.package.share.ShareFragment"
        android:label="@string/menu_share"
        tools:layout="@layout/fragment_share" />

    <fragment
        android:id="@+id/nav_send"
        android:name="com.package.SendFragment"
        android:label="@string/comments"
        tools:layout="@layout/fragment_send" />
</navigation>

and navigate to the fragment with respective menu and navHostFragment

<fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/user_navigation" />

now find your nav host fragment and set up your configuration...

hope this helps.......happy coding


答: Please use answerNameControl.val() instead of answerNameControl.value</p>

Title: Getting undefined value for input control


问:
Draw horizontal line on chart in chart.js on v2
I have drawn a line chart using chart.js. For the labels and datasets i am getting values from the database. I am new to chart.js and its very powerful library, yet i am unable to completely understand it. I want to draw multiples horizontal lines. Like where if mean of dataset, standard deviation and min and max. I have tried the question here in stackoverflow but these are giving errors or may be i am not able to understand the working. This is my chart.js code</p>

```<code>function display_graph(id, label, data) {
var ctx = document.getElementById(id);
var data = {
    labels: data.labels,
    datasets: [
        {
            label: label,
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        }
    ]
};

//options
var options = {
    responsive: true,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    }
};
var Blanks_Chart=null;
Blanks_Chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});}
</code>```

答:
If you are using the NPM package chartjs-plugin-annotation.js, the important thing - which you may forget, is to register the plugin.

So first of all you installed the npm packages (here for React):

```<code>npm i react-chartjs-2                (depends on your framework)
npm i chartjs-plugin-annotation      (always required)
</code>```

See Vue.js or Angular for their framework depending packages.

Option 1: Global plugin registration

```<code>import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

Chart.plugins.register([ChartAnnotation]); // Global

// ...
render() {
    return (
        <Line data={chartData} options={chartOpts} />
    )
}
</code>```

Option 2: Per chart plugin registration

```<code>import { Line } from 'react-chartjs-2';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

// ...
render() {
    return (
                                                   {/* per chart */}
        <Line data={chartData} options={chartOpts} plugins={[ChartAnnotation]} />
    )
}
</code>```

chartData is equivalent to the data: { section and chartOpts to options: { from jordanwillis answer. See this github post for further information.

There are many other plugins available for chart.js.

Body:
I have drawn a line chart using chart.js. For the labels and datasets i am getting values from the database. I am new to chart.js and its very powerful library, yet i am unable to completely understand it. I want to draw multiples horizontal lines. Like where if mean of dataset, standard deviation and min and max. I have tried the question here in stackoverflow but these are giving errors or may be i am not able to understand the working. This is my chart.js code

function display_graph(id, label, data) {
var ctx = document.getElementById(id);
var data = {
    labels: data.labels,
    datasets: [
        {
            label: label,
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderWidth: 1,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: data.assay_value,
            spanGaps: false
        }
    ]
};

//options
var options = {
    responsive: true,
    title: {
        display: true,
        position: "top",
        text: label,
        fontSize: 18,
        fontColor: "#111"
    },
    legend: {
        display: true,
        position: "bottom",
        labels: {
            fontColor: "#333",
            fontSize: 16
        }
    }
};
var Blanks_Chart=null;
Blanks_Chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});}

Body:
If you are using the NPM package chartjs-plugin-annotation.js, the important thing - which you may forget, is to register the plugin.

So first of all you installed the npm packages (here for React):

npm i react-chartjs-2                (depends on your framework)
npm i chartjs-plugin-annotation      (always required)

See Vue.js or Angular for their framework depending packages.

Option 1: Global plugin registration

import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

Chart.plugins.register([ChartAnnotation]); // Global

// ...
render() {
    return (
        <Line data={chartData} options={chartOpts} />
    )
}

Option 2: Per chart plugin registration

import { Line } from 'react-chartjs-2';
import * as ChartAnnotation from 'chartjs-plugin-annotation';

// ...
render() {
    return (
                                                   {/* per chart */}
        <Line data={chartData} options={chartOpts} plugins={[ChartAnnotation]} />
    )
}

chartData is equivalent to the data: { section and chartOpts to options: { from jordanwillis answer. See this github post for further information.

There are many other plugins available for chart.js.


问:
Making a 5x5 Board using a grid in Tkinter
Im making one of my first programs, using python, tkinter and pillow.

This program is supposed to randomly select one of four tile images, create an image and repeat 25 times
Making a 5x5 Board using a grid to position the images in a square.

This is not what happened when i ran my code though

One or two columns and 4 rows are usually generated and not every coordinate is filled with an image.

And only the corner of the images are visible for some reason?

The images center seems to be placed in the top left corner of their grid.

A output might look something like this

X = coordinate filled with an image

O = coordinate filled with bg colour

X X

O X

O X

When i want it to look like this

X  X  X  X  X

X  X  X  X  X

X  X  X  X  X

X  X  X  X  X

X  X  X  X  X

The code thats supposed to place the images looks like this

```<code>while n < 25:
n = n + 1
number = random.randint(1,4)

if number == 1:

    TILE_FLOWER.grid(row = x, column = y)
    TILE_FLOWER.create_image(16,16, image = TILE_FLOWER_IMG)

elif number == 2:
    TILE_GRASS.grid(row = x, column = y)
    TILE_GRASS.create_image(16,16, image = TILE_GRASS_IMG)

elif number == 3:
    TILE_STONE.grid(row = x, column = y)
    TILE_STONE.create_image(16,16, image = TILE_STONE_IMG)

elif number == 4:
    TILE_WATER.grid(row = x, column = y,)
    TILE_WATER.create_image(16,16, image = TILE_WATER_IMG)

if x == 5:
    x = 0
    y = y + 1

else:
    x = x + 1

win.mainloop()
</code>```

The code defining my canvases looks like this

   They're the same size as the images i want to draw on them.

```<code>TILE_FLOWER = Canvas(win, height = 80, width = 80)
TILE_GRASS = Canvas(win, height = 80, width = 80)
TILE_STONE = Canvas(win, height = 80, width = 80)
TILE_WATER = Canvas(win, height = 80, width = 80)
</code>```

And lastly the code defining the images looks like this

```<code>TILE_FLOWER_IMG = PhotoImage(file = 'Path1.png')
TILE_GRASS_IMG = PhotoImage(file = 'Path2.png')
TILE_STONE_IMG = PhotoImage(file = 'Path3.png')
TILE_WATER_IMG = PhotoImage(file = 'Path4.png')
</code>```

Hope what i've written makes sense!

    And i would be super thankful if someone could help me fix this mess :)

答:
You need to create new Label or Canvas in each cell of the 5x5 grid:

```<code>import tkinter as tk
import random

root = tk.Tk()

imagelist = [
    tk.PhotoImage(file='Path1.png'),
    tk.PhotoImage(file='Path2.png'),
    tk.PhotoImage(file='Path3.png'),
    tk.PhotoImage(file='Path4.png'),
]

for i in range(25):
    image = random.choice(imagelist)
    tk.Label(root, image=image, width=80, height=80, bg='white').grid(row=i//5, column=i%5)
    '''
    # or using Canvas
    canvas = tk.Canvas(root, width=80, height=80, bg='white')
    canvas.create_image(40, 40, image=image)
    canvas.grid(row=i//5, column=i%5)
    '''

root.mainloop()
</code>```

Or using single Canvas:

```<code>canvas = tk.Canvas(root, width=400, height=400, bg='white')
canvas.pack()

for i in range(25):
    image = random.choice(imagelist)
    row = i // 5
    col = i % 5
    canvas.create_image(40+col*80, 40+row*80, image=image)
</code>```

Body:
Im making one of my first programs, using python, tkinter and pillow.

This program is supposed to randomly select one of four tile images, create an image and repeat 25 times
Making a 5x5 Board using a grid to position the images in a square.

This is not what happened when i ran my code though

One or two columns and 4 rows are usually generated and not every coordinate is filled with an image.

And only the corner of the images are visible for some reason?

The images center seems to be placed in the top left corner of their grid.

A output might look something like this

X = coordinate filled with an image

O = coordinate filled with bg colour

X X

O X

O X

When i want it to look like this

X  X  X  X  X

X  X  X  X  X

X  X  X  X  X

X  X  X  X  X

X  X  X  X  X

The code thats supposed to place the images looks like this

while n < 25:
n = n + 1
number = random.randint(1,4)

if number == 1:

    TILE_FLOWER.grid(row = x, column = y)
    TILE_FLOWER.create_image(16,16, image = TILE_FLOWER_IMG)

elif number == 2:
    TILE_GRASS.grid(row = x, column = y)
    TILE_GRASS.create_image(16,16, image = TILE_GRASS_IMG)

elif number == 3:
    TILE_STONE.grid(row = x, column = y)
    TILE_STONE.create_image(16,16, image = TILE_STONE_IMG)

elif number == 4:
    TILE_WATER.grid(row = x, column = y,)
    TILE_WATER.create_image(16,16, image = TILE_WATER_IMG)

if x == 5:
    x = 0
    y = y + 1

else:
    x = x + 1

win.mainloop()

The code defining my canvases looks like this

   They're the same size as the images i want to draw on them.

TILE_FLOWER = Canvas(win, height = 80, width = 80)
TILE_GRASS = Canvas(win, height = 80, width = 80)
TILE_STONE = Canvas(win, height = 80, width = 80)
TILE_WATER = Canvas(win, height = 80, width = 80)

And lastly the code defining the images looks like this

TILE_FLOWER_IMG = PhotoImage(file = 'Path1.png')
TILE_GRASS_IMG = PhotoImage(file = 'Path2.png')
TILE_STONE_IMG = PhotoImage(file = 'Path3.png')
TILE_WATER_IMG = PhotoImage(file = 'Path4.png')

Hope what i've written makes sense!

    And i would be super thankful if someone could help me fix this mess :)

Body:
You need to create new Label or Canvas in each cell of the 5x5 grid:

import tkinter as tk
import random

root = tk.Tk()

imagelist = [
    tk.PhotoImage(file='Path1.png'),
    tk.PhotoImage(file='Path2.png'),
    tk.PhotoImage(file='Path3.png'),
    tk.PhotoImage(file='Path4.png'),
]

for i in range(25):
    image = random.choice(imagelist)
    tk.Label(root, image=image, width=80, height=80, bg='white').grid(row=i//5, column=i%5)
    '''
    # or using Canvas
    canvas = tk.Canvas(root, width=80, height=80, bg='white')
    canvas.create_image(40, 40, image=image)
    canvas.grid(row=i//5, column=i%5)
    '''

root.mainloop()

Or using single Canvas:

canvas = tk.Canvas(root, width=400, height=400, bg='white')
canvas.pack()

for i in range(25):
    image = random.choice(imagelist)
    row = i // 5
    col = i % 5
    canvas.create_image(40+col*80, 40+row*80, image=image)


问:
Error: client_secrets.json issue when running a HTTP Azure Function
I have created this HTTP trigger azure function, which contains the code(below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

When I try to run the app, I am getting the following error:

Executed 'Function1' (Failed, Id=84400f0c-b6e4-4c78-bf55-30c4527a8b5f)
  System.Private.CoreLib: Exception while executing function: Function1.
  System.Private.CoreLib: Could not find file
  'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'.

It looks like a Google Authentication error, but I am not sure how to get this fixed.

Code:

```<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\Test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}
</code>```

答:
You are getting this error cause the client_secrets.json doesn't exist in the debug folder. I reproduce the error with this file default setting Copy to Output Directory, the default is Do not copy.

So just change it to Copy if newer or Copy always, the file will be in the debug folder.

Body:
I have created this HTTP trigger azure function, which contains the code(below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

When I try to run the app, I am getting the following error:

Executed 'Function1' (Failed, Id=84400f0c-b6e4-4c78-bf55-30c4527a8b5f)
  System.Private.CoreLib: Exception while executing function: Function1.
  System.Private.CoreLib: Could not find file
  'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'.

It looks like a Google Authentication error, but I am not sure how to get this fixed.

Code:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\Test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}


问:
Count points in a HTML test
I've got quite a few HTMLs, which make up a test. I need to count the points in all those files (whether the student has answered correctly or not), and in the final HTML pick a mark from a range of correct answers. There are 16 questions, and the last question uses matchimages.js library, meaning a student can get 7 points, depending on the number of correctly matched pictures. Found the library here: https://www.ssec.wisc.edu/QuizImage/match/</p>

答:
If I understand you correctly, you have several HTML-pages, each one with a form on it. Students fill these forms, and you want to evaluate the answers each student gave. Right?

This can not be answered in a single post. You have to learn about form filling, validating and evaluating. You will need at least HTML and some PHP.

And the js-library you use is a totally different thing … I suggest you start with handling forms with HTML/PHP. You can find a very basic example on this page: https://www.w3schools.com/php/php_forms.asp

Title: Count points in a HTML test


问:
How to get build status from GitLab CI?
I want to add in cap deploy scenario checking build status from GitLab CI.

Is it possible?

Does GitLab CI has some API to get build/pipeline status by commit SHA?

答:
API

Since GitLab 8.1, there is the new commit status API.

GitLab CI Commits API v4:

List the statuses of a commit

```<code>curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/17/repository/commits/18f3e63d05582537db6d183d9d557be09e1f90c8/statuses
</code>```

P.s. GitLabs tokens are being managed in the Personal Access Tokens  page (https://gitlab.example.com/profile/personal_access_tokens)

glab and lab

There are two great tools to work with GitLab:

zaquestion/lab: Lab wraps Git or Hub, making it simple to clone, fork, and interact with repositories on GitLab
profclems/glab: An open-source GitLab command line tool bringing GitLab's cool features to your command line

Both glab and lab are open-source tools with the same goal of bringing GitLab to your command line and simplifying the developer workflow. In many ways lab is to hub, what glab is to gh.

lab aims to feel familiar to a git user and leverages git to power many of it's commands. glab will feel more familiar to gh users and in turn is more interactive and likely more beginner friendly for that reason.

lab ci status

For textual representation of a CI pipeline with lab you may want:

```<code>lab ci status [branch] [flags]
</code>```

Examples

```<code>lab ci status
lab ci status upstream 608 --merge-request
lab ci status 600 --wait
lab ci status upstream 125 --merge-request --bridge 'security-tests'
</code>```

glab pipeline status

For textual representation of a CI pipeline with glab you may want:

glab pipeline status \[flags\]

Examples

```<code>$ glab pipeline status --live
$ glab pipeline status --branch=master   // Get pipeline for master branch
$ glab pipe status   // Get pipeline for current branch
</code>```

Title: How to get build status from GitLab CI?

Body:
API

Since GitLab 8.1, there is the new commit status API.

GitLab CI Commits API v4:

List the statuses of a commit

curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/17/repository/commits/18f3e63d05582537db6d183d9d557be09e1f90c8/statuses

P.s. GitLabs tokens are being managed in the Personal Access Tokens  page (https://gitlab.example.com/profile/personal_access_tokens)

glab and lab

There are two great tools to work with GitLab:

zaquestion/lab: Lab wraps Git or Hub, making it simple to clone, fork, and interact with repositories on GitLab
profclems/glab: An open-source GitLab command line tool bringing GitLab's cool features to your command line

Both glab and lab are open-source tools with the same goal of bringing GitLab to your command line and simplifying the developer workflow. In many ways lab is to hub, what glab is to gh.

lab aims to feel familiar to a git user and leverages git to power many of it's commands. glab will feel more familiar to gh users and in turn is more interactive and likely more beginner friendly for that reason.

lab ci status

For textual representation of a CI pipeline with lab you may want:

lab ci status [branch] [flags]

Examples

lab ci status
lab ci status upstream 608 --merge-request
lab ci status 600 --wait
lab ci status upstream 125 --merge-request --bridge 'security-tests'

glab pipeline status

For textual representation of a CI pipeline with glab you may want:

glab pipeline status \[flags\]

Examples

$ glab pipeline status --live
$ glab pipeline status --branch=master   // Get pipeline for master branch
$ glab pipe status   // Get pipeline for current branch


问:
how to add existing core to the solr search in local
How to add core in the local machine which is configured on the server?
I moved my core under "solr" directory but is not visible in solr panel (localhost:8983).

When I try to create a new one with the same name I got an error that core already exists. After that my core name is displayed in solr panel but can't able to import data using "/dataimport". it shows below response but not fetching any record.

```<code>{
"responseHeader": {
                  "status": 0,
                  "QTime": 3
                  },
"initArgs": ["defaults",["config","db-data-config.xml"]],
"command": "status",
"status": "busy",
"importResponse": "A command is still running...",
"statusMessages": {
"Time Elapsed": "0:0:0.5",
"Total Requests made to DataSource": "0",
"Total Rows Fetched": "0",
"Total Documents Processed": "0",
"Total Documents Skipped": "0",
"Full Dump Started": "2020-02-19 06:13:20"
}}
</code>```

But No record displayed in the "Execute query". Is there any doc to add an existing core to another solr search?

答:
do you have it in your solr.xml? only the cores listed in solr.xml will be visible in the cores list.

or you can do a add core through the GUI

Body:
How to add core in the local machine which is configured on the server?
I moved my core under "solr" directory but is not visible in solr panel (localhost:8983).

When I try to create a new one with the same name I got an error that core already exists. After that my core name is displayed in solr panel but can't able to import data using "/dataimport". it shows below response but not fetching any record.

{
"responseHeader": {
                  "status": 0,
                  "QTime": 3
                  },
"initArgs": ["defaults",["config","db-data-config.xml"]],
"command": "status",
"status": "busy",
"importResponse": "A command is still running...",
"statusMessages": {
"Time Elapsed": "0:0:0.5",
"Total Requests made to DataSource": "0",
"Total Rows Fetched": "0",
"Total Documents Processed": "0",
"Total Documents Skipped": "0",
"Full Dump Started": "2020-02-19 06:13:20"
}}

But No record displayed in the "Execute query". Is there any doc to add an existing core to another solr search?


问:
How to parsing string with comma from csv and output result using powershell script
Please see a sample test.csv file

```<code>??????????!??????????!??????????!??????????!??????????!??????????!??????????!??????????!??????????!??????????!"CalixE7" Wed Feb 19 15:12:51 2020

Username:
Password:
CalixE7>disable session pager
success: pager disabled
CalixE7>disable session alarm-notif
success: alarm notifications disabled
CalixE7>disable session event-notif
success: event notifications disabled
CalixE7>disable session tca-notif
success: TCA notifications disabled
CalixE7>show ont 1301 summary
ONT "1301" (enabled)
    serial number: 3421F0
    profile: 726GE
    - SIP IP host
        ip: 172.24.4.73, netmask: 255.255.254.0, gw: 172.24.4.11 (DHCP)
        service tag action: VOICE-ADDTAG (add-tag)
            outer tag: 4, outer p-bit: pbit7
            match list: all-untagged
    - TDM GW IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - H.248 IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - MGCP IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - ONT RF port "1301/r1" (enabled, AC up)
    - ONT Ethernet port "1301/g1" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT Ethernet port "1301/g2" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT Ethernet port "1301/g3" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT Ethernet port "1301/g4" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT POTS port "1301/p1" (enabled, AC up)
         signal type: loop-start
        - ONT SIP service (enabled)
            SIP gateway profile: AA-VoiceGW, user: 1682
    - ONT POTS port "1301/p2" (enabled, AC up)
         signal type: loop-start
        - ONT SIP service (user disabled)
            SIP gateway profile: AA-VoiceGW, user: 1682
    - ONT Residential GW port "1301/G1" (enabled)
         management-mode: native
             Eth-Svc for In-band TR69: Data1
         This port has these members:
             1301/g1         1301/g2         1301/g3
             1301/g4
        - Ethernet service "Data1" (enabled)
            multicast profile: <none>
            bandwidth profile: 100m/100m
            service tag action: HSDA-CHANGETAG (change-tag)
                outer tag: 3, outer p-bit: pbit0
                match list: AA-TAGGED-3
            pon upstream cos: derived
    - ONT Full Bridge port "1301/F1" (enabled)
         security profile: system-default
         This port has these members: <none>
CalixE7>show ont 1302 summary
ONT "1302" (enabled)
    serial number: 434B51
    profile: 726GE
    - SIP IP host
        ip: 172.24.4.201, netmask: 255.255.254.0, gw: 172.24.4.11 (DHCP)
        service tag action: VOICE-ADDTAG (add-tag)
            outer tag: 4, outer p-bit: pbit7
            match list: all-untagged
    - TDM GW IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - H.248 IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - MGCP IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - ONT RF port "1302/r1" (enabled, AC up)
    - ONT Ethernet port "1302/g1" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT Ethernet port "1302/g2" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT Ethernet port "1302/g3" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT Ethernet port "1302/g4" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT POTS port "1302/p1" (enabled, AC up)
         signal type: loop-start
        - ONT SIP service (enabled)
            SIP gateway profile: AA-VoiceGW, user: 1683
    - ONT POTS port "1302/p2" (enabled, AC up)
         signal type: loop-start
    - ONT Residential GW port "1302/G1" (enabled)
         management-mode: native
             Eth-Svc for In-band TR69: Data1
         This port has these members:
             1302/g1         1302/g2         1302/g3
             1302/g4
        - Ethernet service "Data1" (enabled)
            multicast profile: <none>
            bandwidth profile: 50m/50m
            service tag action: HSDA-CHANGETAG (change-tag)
                outer tag: 3, outer p-bit: pbit0
                match list: AA-TAGGED-3
            pon upstream cos: derived
    - ONT Full Bridge port "1302/F1" (enabled)
         security profile: system-default
         This port has these members: <none>
CalixE7>

</code>```

This is my code

```<code>$OutputPath = .\output.csv
$topheader = "TAG"+","+"Datetime Created"+","+"Ont"+","+"RF"+","+"SIP"+","+"Data"+","+"Bandwidth"
$ontdetail = Import-CSV -Path .\test.csv | Foreach-Object {

    foreach ($property in $_.PSObject.Properties){

            if($property.Value -Like 'ONT "*'){
                $header = $property.Name
                $length = $header.length
                $year = $header.substring($length -4,4)
                $month = $header.substring($length -20,3)
                $day = $header.substring($length -16,2)
                $time = $header.substring($length -13,8)
                $timestamp = $day+"-"+$month+"-"+$year+" "+ $time
                $ont = $property.Value
            }

            if($property.Value -Like "*RF*"){
                $rf = $property.Value
            }

            if($property.Value -Like "*ONT POTS*p1*"){
                $sip = $property.Value
            }

            if($property.Value -Like "*ONT Residential*"){
                $data = $property.Value
            }

            if($property.Value -Like "*bandwidth profile*"){
                $bandwidth = $property.Value
                $detail = "CalixE7"+","+$timestamp+","+$ont+","+$rf+","+$sip+","+$data+","+$bandwidth
                $detail
            }
    }
}

$ontdetail
($topheader,$ontdetail) | Out-File $OutputPath
</code>```

The output.csv file i'm getting

The expect file I'm trying to achieve

I have difficulty to have full "(enabled, AC up)" displayed but only display "(enabled" because comma.
I also want to remove "-" before ONT

Sorry for my poor editing skills.

Thanks for help

答:
Instead of importing it as one convoluted csv, you can use a switch statement and parse line by line (kind of like you are doing anyway) without the extra complexity of multiple columns.

How about this

```<code>$OutputPath = '.\output.csv'
$topheader = "TAG,Datetime Created,Ont,RF,SIP,Data,Bandwidth"

[string]$DateTimeCreated = $null
$ontdetail = switch -file .\test.csv -Wildcard
{
    '*CalixE7*'
    {
        if (!($DateTimeCreated)) # processed only for first line
        {
            $length = $_.Length
            $year = $_.substring($length -4,4)
            $month = $_.substring($length -20,3)
            $day = $_.substring($length -16,2)
            $time = $_.substring($length -13,8)
            $DateTimeCreated = "$($day)-$($month)-$($year) $($time)"
        }
    }

    '*ONT "*' {$ont = $_}
    '*RF*' {$rf = $_.Trim(' -')}
    '*ONT POTS*p1*' {$sip = $_.Trim(' -')}
    '*ONT Residential*' {$data = $_.Trim(' -')}
    '*bandwidth profile*' {"CalixE7,$($DateTimeCreated),$($ont),$($rf),$($sip),$($data),$($_.Trim())"}
}
$ontdetail
($topheader,$ontdetail) | Out-File $OutputPath
</code>```

Body:
Please see a sample test.csv file

??????????!??????????!??????????!??????????!??????????!??????????!??????????!??????????!??????????!??????????!"CalixE7" Wed Feb 19 15:12:51 2020

Username:
Password:
CalixE7>disable session pager
success: pager disabled
CalixE7>disable session alarm-notif
success: alarm notifications disabled
CalixE7>disable session event-notif
success: event notifications disabled
CalixE7>disable session tca-notif
success: TCA notifications disabled
CalixE7>show ont 1301 summary
ONT "1301" (enabled)
    serial number: 3421F0
    profile: 726GE
    - SIP IP host
        ip: 172.24.4.73, netmask: 255.255.254.0, gw: 172.24.4.11 (DHCP)
        service tag action: VOICE-ADDTAG (add-tag)
            outer tag: 4, outer p-bit: pbit7
            match list: all-untagged
    - TDM GW IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - H.248 IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - MGCP IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - ONT RF port "1301/r1" (enabled, AC up)
    - ONT Ethernet port "1301/g1" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT Ethernet port "1301/g2" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT Ethernet port "1301/g3" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT Ethernet port "1301/g4" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1301/G1"
    - ONT POTS port "1301/p1" (enabled, AC up)
         signal type: loop-start
        - ONT SIP service (enabled)
            SIP gateway profile: AA-VoiceGW, user: 1682
    - ONT POTS port "1301/p2" (enabled, AC up)
         signal type: loop-start
        - ONT SIP service (user disabled)
            SIP gateway profile: AA-VoiceGW, user: 1682
    - ONT Residential GW port "1301/G1" (enabled)
         management-mode: native
             Eth-Svc for In-band TR69: Data1
         This port has these members:
             1301/g1         1301/g2         1301/g3
             1301/g4
        - Ethernet service "Data1" (enabled)
            multicast profile: <none>
            bandwidth profile: 100m/100m
            service tag action: HSDA-CHANGETAG (change-tag)
                outer tag: 3, outer p-bit: pbit0
                match list: AA-TAGGED-3
            pon upstream cos: derived
    - ONT Full Bridge port "1301/F1" (enabled)
         security profile: system-default
         This port has these members: <none>
CalixE7>show ont 1302 summary
ONT "1302" (enabled)
    serial number: 434B51
    profile: 726GE
    - SIP IP host
        ip: 172.24.4.201, netmask: 255.255.254.0, gw: 172.24.4.11 (DHCP)
        service tag action: VOICE-ADDTAG (add-tag)
            outer tag: 4, outer p-bit: pbit7
            match list: all-untagged
    - TDM GW IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - H.248 IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - MGCP IP host
        ip: 0.0.0.0, netmask: 0.0.0.0, gw: 0.0.0.0 (DHCP)
        service tag action: <not configured>
    - ONT RF port "1302/r1" (enabled, AC up)
    - ONT Ethernet port "1302/g1" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT Ethernet port "1302/g2" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT Ethernet port "1302/g3" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT Ethernet port "1302/g4" (enabled, AC up)
         security profile: system-default
         member of: ONT Residential GW port "1302/G1"
    - ONT POTS port "1302/p1" (enabled, AC up)
         signal type: loop-start
        - ONT SIP service (enabled)
            SIP gateway profile: AA-VoiceGW, user: 1683
    - ONT POTS port "1302/p2" (enabled, AC up)
         signal type: loop-start
    - ONT Residential GW port "1302/G1" (enabled)
         management-mode: native
             Eth-Svc for In-band TR69: Data1
         This port has these members:
             1302/g1         1302/g2         1302/g3
             1302/g4
        - Ethernet service "Data1" (enabled)
            multicast profile: <none>
            bandwidth profile: 50m/50m
            service tag action: HSDA-CHANGETAG (change-tag)
                outer tag: 3, outer p-bit: pbit0
                match list: AA-TAGGED-3
            pon upstream cos: derived
    - ONT Full Bridge port "1302/F1" (enabled)
         security profile: system-default
         This port has these members: <none>
CalixE7>

This is my code

$OutputPath = .\output.csv
$topheader = "TAG"+","+"Datetime Created"+","+"Ont"+","+"RF"+","+"SIP"+","+"Data"+","+"Bandwidth"
$ontdetail = Import-CSV -Path .\test.csv | Foreach-Object {

    foreach ($property in $_.PSObject.Properties){

            if($property.Value -Like 'ONT "*'){
                $header = $property.Name
                $length = $header.length
                $year = $header.substring($length -4,4)
                $month = $header.substring($length -20,3)
                $day = $header.substring($length -16,2)
                $time = $header.substring($length -13,8)
                $timestamp = $day+"-"+$month+"-"+$year+" "+ $time
                $ont = $property.Value
            }

            if($property.Value -Like "*RF*"){
                $rf = $property.Value
            }

            if($property.Value -Like "*ONT POTS*p1*"){
                $sip = $property.Value
            }

            if($property.Value -Like "*ONT Residential*"){
                $data = $property.Value
            }

            if($property.Value -Like "*bandwidth profile*"){
                $bandwidth = $property.Value
                $detail = "CalixE7"+","+$timestamp+","+$ont+","+$rf+","+$sip+","+$data+","+$bandwidth
                $detail
            }
    }
}

$ontdetail
($topheader,$ontdetail) | Out-File $OutputPath

The output.csv file i'm getting

The expect file I'm trying to achieve

I have difficulty to have full "(enabled, AC up)" displayed but only display "(enabled" because comma.
I also want to remove "-" before ONT

Sorry for my poor editing skills.

Thanks for help

Body:
Instead of importing it as one convoluted csv, you can use a switch statement and parse line by line (kind of like you are doing anyway) without the extra complexity of multiple columns.

How about this

$OutputPath = '.\output.csv'
$topheader = "TAG,Datetime Created,Ont,RF,SIP,Data,Bandwidth"

[string]$DateTimeCreated = $null
$ontdetail = switch -file .\test.csv -Wildcard
{
    '*CalixE7*'
    {
        if (!($DateTimeCreated)) # processed only for first line
        {
            $length = $_.Length
            $year = $_.substring($length -4,4)
            $month = $_.substring($length -20,3)
            $day = $_.substring($length -16,2)
            $time = $_.substring($length -13,8)
            $DateTimeCreated = "$($day)-$($month)-$($year) $($time)"
        }
    }

    '*ONT "*' {$ont = $_}
    '*RF*' {$rf = $_.Trim(' -')}
    '*ONT POTS*p1*' {$sip = $_.Trim(' -')}
    '*ONT Residential*' {$data = $_.Trim(' -')}
    '*bandwidth profile*' {"CalixE7,$($DateTimeCreated),$($ont),$($rf),$($sip),$($data),$($_.Trim())"}
}
$ontdetail
($topheader,$ontdetail) | Out-File $OutputPath


问:
Modelling actions in Java
I am looking to standardize common actions using a design pattern but I am not sure which one is the best.

Let's say if we start off with two service Java classes with two operations/methods each.

```<code>class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

class Service2 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}
</code>```

Two services are sharing the same algorithms so naturally, I would want to refactor performSomething() and performSomethingElse(). My approach is to create two single-method classes for each refactored method.

```<code>interface Action {
    public void run();
}
class PerformSomething implements Action {
    public void run() {}
}
class PerformSomethingElse implements Action {
    public void run() {}
}

class Service1 {
    private PerformSomething algo1;
    private PerformSomethingElse algo2;

    public void businessUseCase1() {
        algo1.run();
        algo2.run();
    }

}
</code>```

I feel like this simple approach is naive and I am very sure there's a more suitable design pattern that can represent an Action instead of creating a custom interface to present Actions.

答:
With KISS and Spring in mind, I would just do the following:</p>

```<code>@Service
class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
    public void businessUseCase1() {
        performSomething();
        performSomethingElse();
    }

}

@Service
class Service2 {
    @Autowired
    Service1 service1;

    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
    public void businessUseCase1() {
        service1.performSomething();
        service1.performSomethingElse();
        // or
        service1.businessUseCase1();
    }

}
</code>```

Title: Modelling actions in Java

Body:
I am looking to standardize common actions using a design pattern but I am not sure which one is the best.

Let's say if we start off with two service Java classes with two operations/methods each.

class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

class Service2 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

Two services are sharing the same algorithms so naturally, I would want to refactor performSomething() and performSomethingElse(). My approach is to create two single-method classes for each refactored method.

interface Action {
    public void run();
}
class PerformSomething implements Action {
    public void run() {}
}
class PerformSomethingElse implements Action {
    public void run() {}
}

class Service1 {
    private PerformSomething algo1;
    private PerformSomethingElse algo2;

    public void businessUseCase1() {
        algo1.run();
        algo2.run();
    }

}

I feel like this simple approach is naive and I am very sure there's a more suitable design pattern that can represent an Action instead of creating a custom interface to present Actions.

Body:
With KISS and Spring in mind, I would just do the following:

@Service
class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
    public void businessUseCase1() {
        performSomething();
        performSomethingElse();
    }

}

@Service
class Service2 {
    @Autowired
    Service1 service1;

    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
    public void businessUseCase1() {
        service1.performSomething();
        service1.performSomethingElse();
        // or
        service1.businessUseCase1();
    }

}


问:
Binding action parameters to request cookies in ASP.NET MVC - what happened?
In several early previews of ASP.NET MVC, arguments to controller methods would be resolved by inspecting the query string, then the form, then the cookies and server variables collections, as documented in this post from Stephen Walther.

For example, this code used to work:

```<code>public class MyController : Controller {

    // This should bind to Request.Cookies["userId"].Value
    public ActionResult Welcome(int userId) {

        WebUser wu = WebUser.Load(userId);
        ViewData["greeting"] = "Welcome, " + wu.Name;
        return(View());
    }
}
</code>```

but now running against the release candidate, it throws an exception because it can't find a value for userId, even though userId definitely appears in the request cookies.

Was this change covered anywhere in the release notes? If this is a change to the framework, is there now a recommended alternative to binding cookies and server variables in this way?

EDIT: Thanks to those of you who have responded so far. I may have picked a bad example to demonstrate this; our code uses cookies for various forms of "convenient" but non-essential persistence (remembering ordering of search results, that kind of thing), so it's by no means purely an authentication issue. The security implications of relying on user cookies are well documented; I'm more interested in current recommendations for flexible, easily testable techniques for retrieving cookie values. (As I'm sure you can appreciate, the above example may have security implications, but is very, very easy to test!)

答:
Besides the obvious security implications, why would you need to pass the cookie through in the route anyway?

Surely you would be better off having an Authorize attribute on the action, indicating that the user should be authenticated before the action is executed.

At the end of the day, I think (hope) Microsoft has closed this as it's quite a large security issue. If this is the case, you should consider rewriting your application to comply with this.

OwnerDisplayName: Dylan Beattie

ContentLicense: CC BY-SA 2.5

Body:
In several early previews of ASP.NET MVC, arguments to controller methods would be resolved by inspecting the query string, then the form, then the cookies and server variables collections, as documented in this post from Stephen Walther.

For example, this code used to work:

public class MyController : Controller {

    // This should bind to Request.Cookies["userId"].Value
    public ActionResult Welcome(int userId) {

        WebUser wu = WebUser.Load(userId);
        ViewData["greeting"] = "Welcome, " + wu.Name;
        return(View());
    }
}

but now running against the release candidate, it throws an exception because it can't find a value for userId, even though userId definitely appears in the request cookies.

Was this change covered anywhere in the release notes? If this is a change to the framework, is there now a recommended alternative to binding cookies and server variables in this way?

EDIT: Thanks to those of you who have responded so far. I may have picked a bad example to demonstrate this; our code uses cookies for various forms of "convenient" but non-essential persistence (remembering ordering of search results, that kind of thing), so it's by no means purely an authentication issue. The security implications of relying on user cookies are well documented; I'm more interested in current recommendations for flexible, easily testable techniques for retrieving cookie values. (As I'm sure you can appreciate, the above example may have security implications, but is very, very easy to test!)

LastEditorDisplayName: Dylan Beattie

OwnerDisplayName: Dan Atkinson

LastEditorDisplayName: Dan Atkinson


问:
Android Studio change color of the app name
fHow can I change the color of the app name, I have changed the toolbar text color to white but the app name is still in black. I have also noticed if I change the color of the bar to black the app name color becomes white. I want the app name color to be like WhatsApp.

答: You can try Custom Toolbar with Custom Color Values..


问:
I am unable to build my flutter web project
When trying to run flutter build web i get "build web" is not currently supported.
I had previous errors where i was stuck with Dart 2.5.0-dev.4.0.flutter-be66176534 and required 2.5.0 or higher, this has now been solved but i am unable to build my project.

```<code>flutter doctor -v
[√] Flutter (Channel stable, v1.9.1+hotfix.2, on Microsoft Windows [Version 10.0.18932.1000], locale en-GB)
    • Flutter version 1.9.1+hotfix.2 at C:\src\flutter
    • Framework revision 2d2a1ffec9 (8 days ago), 2019-09-06 18:39:49 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at C:\Users\germa\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[!] Android Studio (version 3.4)
    • Android Studio at C:\Program Files\Android\Android Studio
    X Flutter plugin not installed; this adds Flutter specific functionality.
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[√] VS Code (version 1.38.1)
    • VS Code at C:\Users\germa\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.4.1
</code>```

I have tried

re-installing dart

re-installing flutter

re-installing Visual Studio code

copy file contents to a new web project (same error)

I couldn't find any information on what this is caused by and how to resolve it online

What can i do to resolve this error?

答:
So currently you are at stable channel . You have to switch to the beta channel as flutter web is not at a stable channel right now. In order to make it working run the following commands in the terminal.

flutter channel beta

flutter upgrade

flutter config --enable-web.

After that restart your IDE and build the web app.

Body:
When trying to run flutter build web i get "build web" is not currently supported.
I had previous errors where i was stuck with Dart 2.5.0-dev.4.0.flutter-be66176534 and required 2.5.0 or higher, this has now been solved but i am unable to build my project.

flutter doctor -v
[√] Flutter (Channel stable, v1.9.1+hotfix.2, on Microsoft Windows [Version 10.0.18932.1000], locale en-GB)
    • Flutter version 1.9.1+hotfix.2 at C:\src\flutter
    • Framework revision 2d2a1ffec9 (8 days ago), 2019-09-06 18:39:49 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at C:\Users\germa\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[!] Android Studio (version 3.4)
    • Android Studio at C:\Program Files\Android\Android Studio
    X Flutter plugin not installed; this adds Flutter specific functionality.
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[√] VS Code (version 1.38.1)
    • VS Code at C:\Users\germa\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.4.1

I have tried

re-installing dart

re-installing flutter

re-installing Visual Studio code

copy file contents to a new web project (same error)

I couldn't find any information on what this is caused by and how to resolve it online

What can i do to resolve this error?


问:
Mysql query returns duplicate rows when joining tables
I have a table that stores user_avatar filepath :

```<code>id | userid | file         | last_update |
1  | 23     | myphoto.png  | x_timestamp |
2  | 23     | myphoto2.png | x_timestamp |
3  | 25     | myavatar.png | x_timestamp |
</code>```

I have a table that returns user_score :

```<code>id | gamerid | score | last_update |
1  | 23      | 44    | x_timestamp |
2  | 25      | 99    | x_timestamp |
</code>```

This is the query I use to display user scores with their avatar

```<code>SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid
</code>```

Above query will return 2 duplicate rows for user 23 because he as downloaded 2 different photos in the user_avatar table. Right now it outputs like this:

```<code>GAMER SCORES RESULTS
myphoto.png  | 44
myphoto2.png | 44
myavatar.png | 99
</code>```

In reality, only one row should be returned for each user and the last avatar downloaded should be used as primary avatar. How can I fix this?

答:
You should select the value for the most recent avatar  .. probably related  ton the max id for user_id

```<code>SELECT ua.*, us.*
FROM user_score us
INNER JOIN  (
  select user_id, max(id) max_id
  from user_avatar
) t on t.user_id = us.user_id
LEFT JOIN user_avatar ua
  ON us.gamerid=ua.u serid
    AND t.max_id  = ua.id
</code>```

In reality, the last avatar downloa

Body:
I have a table that stores user_avatar filepath :

id | userid | file         | last_update |
1  | 23     | myphoto.png  | x_timestamp |
2  | 23     | myphoto2.png | x_timestamp |
3  | 25     | myavatar.png | x_timestamp |

I have a table that returns user_score :

id | gamerid | score | last_update |
1  | 23      | 44    | x_timestamp |
2  | 25      | 99    | x_timestamp |

This is the query I use to display user scores with their avatar

SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid

Above query will return 2 duplicate rows for user 23 because he as downloaded 2 different photos in the user_avatar table. Right now it outputs like this:

GAMER SCORES RESULTS
myphoto.png  | 44
myphoto2.png | 44
myavatar.png | 99

In reality, only one row should be returned for each user and the last avatar downloaded should be used as primary avatar. How can I fix this?

Body:
You should select the value for the most recent avatar  .. probably related  ton the max id for user_id

SELECT ua.*, us.*
FROM user_score us
INNER JOIN  (
  select user_id, max(id) max_id
  from user_avatar
) t on t.user_id = us.user_id
LEFT JOIN user_avatar ua
  ON us.gamerid=ua.u serid
    AND t.max_id  = ua.id

In reality, the last avatar downloa


问:
Android - Media Scanner not working on api 28-29
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));
```

<p>I used <code>Broadcast</code>, but it didn't work the same way. Because it is "deprecated".</p>

```java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");
```

答:
Beginning with Android 9 (API level 28), The NETWORK_STATE_CHANGED_ACTION broadcast doesn't receive information about the user's location or personally identifiable data.

In addition, if your app is installed on a device running Android 9 or higher, system broadcasts from Wi-Fi don't contain SSIDs, BSSIDs, connection information, or scan results. To get this information, call getConnectionInfo() instead

for more info use this doc link : https://developer.android.com/guide/components/broadcasts

Body:
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));

I used Broadcast, but it didn't work the same way. Because it is "deprecated".

java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");


问:
Storing what page I am currently are when scrolling to the bottom JAVASCRIPT
Currently I detect when I am at the bottom of the page.
I have a input hidden on the html, and when you scroll to the bottom, the input gets +1, but, when you get to the bottom, it adds alot of numbers.

How I add only +1 and it doesn't get alot of +1?

```<code>function finalPage() {
        $(window).scroll(function () {
            if ($(window).scrollTop() + $(window).height() > $(document).height() -500) {
                loadMore();
            }
        });
    }

var num = $("#page").val();
num++;
$("#page").val(num);
</code>```

答:
Try this:</p>

```<code>function finalPage() {
  $(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() > $(document).height() -500) {
      loadMore();

      $("#page").val($("#page").val()+1);
    }
  });
}
</code>```

Body:
Currently I detect when I am at the bottom of the page.
I have a input hidden on the html, and when you scroll to the bottom, the input gets +1, but, when you get to the bottom, it adds alot of numbers.

How I add only +1 and it doesn't get alot of +1?

function finalPage() {
        $(window).scroll(function () {
            if ($(window).scrollTop() + $(window).height() > $(document).height() -500) {
                loadMore();
            }
        });
    }

var num = $("#page").val();
num++;
$("#page").val(num);

Body:
Try this:

function finalPage() {
  $(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() > $(document).height() -500) {
      loadMore();

      $("#page").val($("#page").val()+1);
    }
  });
}


问:
Is there a way to calculate the stacking context of all DOM elements in order to compare any two elements for above position using JavaScript?
I am attempting to compare any two elements in the DOM to see if they were to be painted(rendered on screen) in the same area (coordinates overlapping) which one would be above the other. This question is not about overlapping calculation, rather it is about comparing any two elements from any part of the DOM tree for above position (calculating stacking context and z-index and HTML hierarchy...).

Although I am new to this area, my approach would traverse and assign a numerical value to each HTML element taking into consideration rules and standards. Another problem is getting them correctly. I was not able to find a JS library that already does this.

For css and full code example see...
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

The expected output is the ability to compare any two HTML elements for above or below position (3D). I will share my code if I get an idea from professionals here and be able to implement it. Thanks any help is appreciated.

答:
The easy way is to use document.elementsFromPoint() which will give you all the elements, well, at given point, in stacking order.

The complicated part is that you need to find a point where both elements will intersect.

Following example will search for the top-left-most shared point, and demonstrates that you must define more precisely your constraints since it will purposely miss elements that are still in between element:

test( 'red', 'blue' ); // -2 (blue:2, red:4)
test( 'red', 'green' ); // -2 (green:1, red:4) but at selected point blue is not visible
test( 'yellow', 'green' ); // -1 (yelow:3, green:1) but at selected point blue is not visible
test( 'blue', 'green' ); // -1 (blue:2, green: 1)

function test( class1, class2 ) {

  const elem1 = document.querySelector( '.' + class1 );
  const elem2 = document.querySelector( '.' + class2 );
  console.log( class1, class2, getStackDistance( elem1, elem2 ) );

}
function getStackDistance( elem1, elem2 ) {

  const shared_point = findSharedPoint( elem1, elem2 );
  if( !shared_point ) {
    console.error( 'no shared point' );
    return NaN;
  }
  const full_list = document.elementsFromPoint( shared_point.x, shared_point.y );

  return full_list.indexOf( elem1 ) - full_list.indexOf( elem2 );

}
// returns top-left-most shared point between two elements
function findSharedPoint( elem1, elem2 ) {

  const bbox1 = elem1.getBoundingClientRect( elem1 );
  const bbox2 = elem2.getBoundingClientRect( elem2 );
  const intersect_box = {
    left: Math.max( bbox1.left, bbox2.left ),
    right: Math.min( bbox1.right, bbox2.right ),
    top: Math.max( bbox1.top, bbox2.top ),
    bottom: Math.min( bbox1.bottom, bbox2.bottom )
  };
  if( intersect_box.left > intersect_box.right ||
    intersect_box.top > intersect_box.bottom ) {
    return null;
  }

  return { x: intersect_box.left, y: intersect_box.top };

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width: 50px;
  height: 50px;
  position: absolute;
  opacity: 0.7;
}
.red {
  background: red;
  top: 20px;
  left: 20px;
  z-index: 4;
}
.blue {
  background: blue;
  top: 40px;
  left: 40px;
  z-index: 2;
}
.yellow {
  background: yellow;
  top: 10px;
  left: 20px;
  z-index: 3;
}
.green {
  background: green;
  top: 40px;
  left: 10px;
  z-index: 1;
}</code>```

```

Body:
The easy way is to use document.elementsFromPoint() which will give you all the elements, well, at given point, in stacking order.

The complicated part is that you need to find a point where both elements will intersect.

Following example will search for the top-left-most shared point, and demonstrates that you must define more precisely your constraints since it will purposely miss elements that are still in between element:

test( 'red', 'blue' ); // -2 (blue:2, red:4)
test( 'red', 'green' ); // -2 (green:1, red:4) but at selected point blue is not visible
test( 'yellow', 'green' ); // -1 (yelow:3, green:1) but at selected point blue is not visible
test( 'blue', 'green' ); // -1 (blue:2, green: 1)

function test( class1, class2 ) {

  const elem1 = document.querySelector( '.' + class1 );
  const elem2 = document.querySelector( '.' + class2 );
  console.log( class1, class2, getStackDistance( elem1, elem2 ) );

}
function getStackDistance( elem1, elem2 ) {

  const shared_point = findSharedPoint( elem1, elem2 );
  if( !shared_point ) {
    console.error( 'no shared point' );
    return NaN;
  }
  const full_list = document.elementsFromPoint( shared_point.x, shared_point.y );

  return full_list.indexOf( elem1 ) - full_list.indexOf( elem2 );

}
// returns top-left-most shared point between two elements
function findSharedPoint( elem1, elem2 ) {

  const bbox1 = elem1.getBoundingClientRect( elem1 );
  const bbox2 = elem2.getBoundingClientRect( elem2 );
  const intersect_box = {
    left: Math.max( bbox1.left, bbox2.left ),
    right: Math.min( bbox1.right, bbox2.right ),
    top: Math.max( bbox1.top, bbox2.top ),
    bottom: Math.min( bbox1.bottom, bbox2.bottom )
  };
  if( intersect_box.left > intersect_box.right ||
    intersect_box.top > intersect_box.bottom ) {
    return null;
  }

  return { x: intersect_box.left, y: intersect_box.top };

}

.box {
  width: 50px;
  height: 50px;
  position: absolute;
  opacity: 0.7;
}
.red {
  background: red;
  top: 20px;
  left: 20px;
  z-index: 4;
}
.blue {
  background: blue;
  top: 40px;
  left: 40px;
  z-index: 2;
}
.yellow {
  background: yellow;
  top: 10px;
  left: 20px;
  z-index: 3;
}
.green {
  background: green;
  top: 40px;
  left: 10px;
  z-index: 1;
}

<div class="box red"></div>
<div class="box blue"></div>
<div class="box yellow"></div>
<div class="box green"></div>