问:
How to properly connect MySQL database with C# application?
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

```<code>static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";
</code>```

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

答:
```<code>using System;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace AzureMySqlExample
{
class MySqlCreate
{
    static async Task Main(string[] args)
    {
        var builder = new MySqlConnectionStringBuilder
        {
            Server = "YOUR-SERVER.mysql.database.azure.com",
            Database = "YOUR-DATABASE",
            UserID = "USER@YOUR-SERVER",
            Password = "PASSWORD",
            SslMode = MySqlSslMode.Required,
        };

        using (var conn = new MySqlConnection(builder.ConnectionString))
        {
            Console.WriteLine("Opening connection");
            await conn.OpenAsync();

            using (var command = conn.CreateCommand())
            {
                command.CommandText = "DROP TABLE IF EXISTS inventory;";
                await command.ExecuteNonQueryAsync();
                Console.WriteLine("Finished dropping table (if existed)");

                command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
                await command.ExecuteNonQueryAsync();
                Console.WriteLine("Finished creating table");

                command.CommandText = @"INSERT INTO inventory (name, quantity) VALUES (@name1, @quantity1),
                    (@name2, @quantity2), (@name3, @quantity3);";
                command.Parameters.AddWithValue("@name1", "banana");
                command.Parameters.AddWithValue("@quantity1", 150);
                command.Parameters.AddWithValue("@name2", "orange");
                command.Parameters.AddWithValue("@quantity2", 154);
                command.Parameters.AddWithValue("@name3", "apple");
                command.Parameters.AddWithValue("@quantity3", 100);

                int rowCount = await command.ExecuteNonQueryAsync();
                Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));
            }

            // connection will be closed by the 'using' block
            Console.WriteLine("Closing connection");
        }

        Console.WriteLine("Press RETURN to exit");
        Console.ReadLine();
    }
}
</code>```

<p>}</p>

Body:
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

Body:
using System;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace AzureMySqlExample
{
class MySqlCreate
{
    static async Task Main(string[] args)
    {
        var builder = new MySqlConnectionStringBuilder
        {
            Server = "YOUR-SERVER.mysql.database.azure.com",
            Database = "YOUR-DATABASE",
            UserID = "USER@YOUR-SERVER",
            Password = "PASSWORD",
            SslMode = MySqlSslMode.Required,
        };

        using (var conn = new MySqlConnection(builder.ConnectionString))
        {
            Console.WriteLine("Opening connection");
            await conn.OpenAsync();

            using (var command = conn.CreateCommand())
            {
                command.CommandText = "DROP TABLE IF EXISTS inventory;";
                await command.ExecuteNonQueryAsync();
                Console.WriteLine("Finished dropping table (if existed)");

                command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
                await command.ExecuteNonQueryAsync();
                Console.WriteLine("Finished creating table");

                command.CommandText = @"INSERT INTO inventory (name, quantity) VALUES (@name1, @quantity1),
                    (@name2, @quantity2), (@name3, @quantity3);";
                command.Parameters.AddWithValue("@name1", "banana");
                command.Parameters.AddWithValue("@quantity1", 150);
                command.Parameters.AddWithValue("@name2", "orange");
                command.Parameters.AddWithValue("@quantity2", 154);
                command.Parameters.AddWithValue("@name3", "apple");
                command.Parameters.AddWithValue("@quantity3", 100);

                int rowCount = await command.ExecuteNonQueryAsync();
                Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));
            }

            // connection will be closed by the 'using' block
            Console.WriteLine("Closing connection");
        }

        Console.WriteLine("Press RETURN to exit");
        Console.ReadLine();
    }
}

}


来源: stackexchange

问:
Building a valid heap
I just need some verification on whether or not I'm doing this correctly. I checked the wiki for a heapsort, but it seems in the animation to build the heap it inserts the numbers into the nodes and orders it as it goes.

The question asks to "Draw a valid heap with these elements.. {7, 12, 1, 3, 22, 5, 11} as a tree"

I've tried it on a few examples, and it seems I should layout the nodes first then reorder the nodes instead of ordering it as I go. Is the way I'm doing it correct?

For example, putting elements into the nodes

```<code>       7

   12     1

 3  22   5  11
</code>```

Ordering begins here: swap 1 and 7

```<code>       7

   12     1

 3  22   5  11
</code>```

Swap 3 and 12

```<code>       1

   12     7

 3  22   5  11
</code>```

Swap 5 and 7

```<code>       1

   3       7

 12  22   5  11
</code>```

done.

```<code>       1

   3       5

 12  22   7  11
</code>```

Actually that's not right.

The answer given is

```<code>       1

   7       3

 12  22   5  11
</code>```

If I begin to re-order the heap from the left side first (beginning with 3) then I get the right answer.

答:
Actually, the heap data structure as only one property, which can be defined as follows: "In a heap T, for every node v other than the root, the key stored at v is greater than or equal to the key stored at v's parent."

So there are many right representations of the heap based on elements (7, 12, 1, 3, 22, 5, 11). With these elements I applied an "insert-and-sort" algorithm and the result gives yet another version:

```<code>        1
   3         5
12   22   7    11
</code>```

ContentLicense: CC BY-SA 3.0

Title: Building a valid heap

Body:
I just need some verification on whether or not I'm doing this correctly. I checked the wiki for a heapsort, but it seems in the animation to build the heap it inserts the numbers into the nodes and orders it as it goes.

The question asks to "Draw a valid heap with these elements.. {7, 12, 1, 3, 22, 5, 11} as a tree"

I've tried it on a few examples, and it seems I should layout the nodes first then reorder the nodes instead of ordering it as I go. Is the way I'm doing it correct?

For example, putting elements into the nodes

       7

   12     1

 3  22   5  11

Ordering begins here: swap 1 and 7

       7

   12     1

 3  22   5  11

Swap 3 and 12

       1

   12     7

 3  22   5  11

Swap 5 and 7

       1

   3       7

 12  22   5  11

done.

       1

   3       5

 12  22   7  11

Actually that's not right.

The answer given is

       1

   7       3

 12  22   5  11

If I begin to re-order the heap from the left side first (beginning with 3) then I get the right answer.

Body:
Actually, the heap data structure as only one property, which can be defined as follows: "In a heap T, for every node v other than the root, the key stored at v is greater than or equal to the key stored at v's parent."

So there are many right representations of the heap based on elements (7, 12, 1, 3, 22, 5, 11). With these elements I applied an "insert-and-sort" algorithm and the result gives yet another version:

        1
   3         5
12   22   7    11


问:
Replacing Specific color code in css using jquery
I want to replace #789034 code to another code like #456780 where ever it finds in main.css using jquery

I am having a main.css file something like below :

```<code>.common-color
{
  color:#789034;
}

.new-cls
{
  border-color:#789034;
  height:300px;
}

.awesome-one
{
  background-color:#789034;
  height:200px;
  width:300px;
}
</code>```

I want to replace #789034 code to another code like #456780 where ever it finds in main.css using jquery like :

```<code>$(each where code=#789034)
{
  set code: #456780;
}
</code>```

答:
You can achieve this functionality by using CSS variables. Define a variable in your main.css file.

```<code>:root {
    --color1: #789034;
}
</code>```

and use this variable instead of color code.

```<code>.common-color
{
  color: var(--color1);
}
</code>```

Now you can change the color by implementing the following function through passing new color in the parameter.

```<code>function ChangeColor1(newColor)
{
  document.documentElement.style.setProperty('--color1',newColor);
}
</code>```

Body:
I want to replace #789034 code to another code like #456780 where ever it finds in main.css using jquery

I am having a main.css file something like below :

.common-color
{
  color:#789034;
}

.new-cls
{
  border-color:#789034;
  height:300px;
}

.awesome-one
{
  background-color:#789034;
  height:200px;
  width:300px;
}

I want to replace #789034 code to another code like #456780 where ever it finds in main.css using jquery like :

$(each where code=#789034)
{
  set code: #456780;
}

Body:
You can achieve this functionality by using CSS variables. Define a variable in your main.css file.

:root {
    --color1: #789034;
}

and use this variable instead of color code.

.common-color
{
  color: var(--color1);
}

Now you can change the color by implementing the following function through passing new color in the parameter.

function ChangeColor1(newColor)
{
  document.documentElement.style.setProperty('--color1',newColor);
}

ContentLicense: CC BY-SA 4.0


问:
quick black panel when click show\hide button
I have an application in C#, and I added one button to show and hide panel2, but when clicked the panel 2 is works perfect to showing and hide itself. but something wrong when click the button show/hide panel2 gives a quick black things, i don't know how to fix it.

this is my show/hide button syntax:

```<code> if (Panel2.Visible == false) {
            Panel2.BackColor = Color.Transparent;
            Panel2.Visible = true;
            PictureBox2.Image = Properties.Resources.downmen;

        } else {
            Panel2.BackColor = Color.Transparent;
            Panel2.Visible = true;
            Panel2.Visible = false;
            PictureBox2.Image = Properties.Resources.upmen;
        }
</code>```

this is my problem show:

答:
May be too late for the answer. Set the default height and width (size) of Panel2 to 0.
Set size of Panel2 based on the visibility of control</p>

Body:
I have an application in C#, and I added one button to show and hide panel2, but when clicked the panel 2 is works perfect to showing and hide itself. but something wrong when click the button show/hide panel2 gives a quick black things, i don't know how to fix it.

this is my show/hide button syntax:

 if (Panel2.Visible == false) {
            Panel2.BackColor = Color.Transparent;
            Panel2.Visible = true;
            PictureBox2.Image = Properties.Resources.downmen;

        } else {
            Panel2.BackColor = Color.Transparent;
            Panel2.Visible = true;
            Panel2.Visible = false;
            PictureBox2.Image = Properties.Resources.upmen;
        }

this is my problem show:


问:
Wget and Curl stopped working with HTTPS. Wrongly complain about an expired certificate
I have a script that runs every day on an Ubuntu 14.04 server. The script is a simple wget command that downloads a file from a remote server and saves it to the local file system:

```<code>wget https://example.com/resources/scripts/myfile.php -O myfile.php
</code>```

It has worked fine for months until this morning when suddenly when I run it I get:

```<code>--2020-05-30 11:57:16--  https://example.com/resources/scripts/myfile.php
Resolving example.com (example.com)... xx.xx.xx.xx
Connecting to example.com (example.com)|xx.xx.xx.xx|:443... connected.
ERROR: cannot verify example.com's certificate, issued by ‘/C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo RSA Domain Validation Secure Server CA’:
  Issued certificate has expired.
To connect to example.com insecurely, use `--no-check-certificate'.
</code>```

The SSL for the domain is valid and expires in Jan. 2022. Nothing has changed on that front. And yet somehow wget no longer sees that.

Here is another interesting fact. If I run this same exact command on an Ubuntu 18 box, it works like a charm without any complaints. This tells me something is wrong with my Ubuntu 14.04 machine.

Curl produces the same error:

```<code>curl https://example.com
curl: (60) SSL certificate problem: certificate has expired
</code>```

This post suggest that the certificate bundle is out of date. I have downloaded the suggested PEM file and tried running wget with by specifying the --ca-certificate=cacert.pem option, but to no avail.

I have also tried running: apt install ca-certificates and update-ca-certificates, but that did not work either.

Again, everything works great on an Ubuntu 18 box, but not Ubuntu 14 or 16. Also why did it work fine until this morning when I know nobody has touched the box? Clearly something is out of date, but I can't seem to figure out how to fix it.

Does anybody have any suggestions?

答:
I had the same error two days ago with Comodo Certificate and ubuntu 16.04.
The problem was like say mrmuggles this https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT.

I fixed with this steps:

vi /etc/ca-certificates.conf

Remove the line (or comment)
specifying AddTrust_External_Root.crt

apt update && apt install ca-certificates

update-ca-certificates -f -v

Body:
I have a script that runs every day on an Ubuntu 14.04 server. The script is a simple wget command that downloads a file from a remote server and saves it to the local file system:

wget https://example.com/resources/scripts/myfile.php -O myfile.php

It has worked fine for months until this morning when suddenly when I run it I get:

--2020-05-30 11:57:16--  https://example.com/resources/scripts/myfile.php
Resolving example.com (example.com)... xx.xx.xx.xx
Connecting to example.com (example.com)|xx.xx.xx.xx|:443... connected.
ERROR: cannot verify example.com's certificate, issued by ‘/C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo RSA Domain Validation Secure Server CA’:
  Issued certificate has expired.
To connect to example.com insecurely, use `--no-check-certificate'.

The SSL for the domain is valid and expires in Jan. 2022. Nothing has changed on that front. And yet somehow wget no longer sees that.

Here is another interesting fact. If I run this same exact command on an Ubuntu 18 box, it works like a charm without any complaints. This tells me something is wrong with my Ubuntu 14.04 machine.

Curl produces the same error:

curl https://example.com
curl: (60) SSL certificate problem: certificate has expired

This post suggest that the certificate bundle is out of date. I have downloaded the suggested PEM file and tried running wget with by specifying the --ca-certificate=cacert.pem option, but to no avail.

I have also tried running: apt install ca-certificates and update-ca-certificates, but that did not work either.

Again, everything works great on an Ubuntu 18 box, but not Ubuntu 14 or 16. Also why did it work fine until this morning when I know nobody has touched the box? Clearly something is out of date, but I can't seem to figure out how to fix it.

Does anybody have any suggestions?


问:
React: 2 way binding props
How can I do a 2 way binding of a variable from the parent component (Form.js), such that changes occurred in the child component (InputText.js) will be updated in the parent component?

Expected result: typing values in the input in InputText.js will update the state of Form.js

In Form.js

```<code>render() {
    return (
      <div>
        <InputText
          title="Email"
          data={this.state.formInputs.email}
        />

        <div>
          Value: {this.state.formInputs.email} // <-- this no change
        </div>

      </div>
    )
  }
</code>```

In InputText.js

```<code>export default class InputText extends React.Component {

  constructor(props) {
    super(props);
    this.state = props;
    this.handleKeyChange = this.keyUpHandler.bind(this);
  }

  keyUpHandler(e) {
    this.setState({
      data: e.target.value
    });
  }

  render() {
    return (
      <div>
        <label className="label">{this.state.title}</label>
        <input type="text" value={this.state.data} onChange={this.handleKeyChange} /> // <-- type something here
        value: ({this.state.data}) // <-- this changed
      </div>
    )
  }
}
</code>```

答:
You can manage state in the parent component itself instead of managing that on child like this (lifting state up):

In Form.js

```<code>constructor(props) {
  super(props);
  this.handleKeyChange = this.keyUpHandler.bind(this);
}

keyUpHandler(e) {
  const { formInputs } = this.state;
  formInputs.email = e.target.value
  this.setState({
    formInputs: formInputs
  });
}

render() {
    // destructuring
    const { email } = this.state.formInputs;
    return (
      <div>
        <InputText
          title="Email"
          data={email}
          changed={this.handleKeyChange}
        />

        <div>
          Value: {email}
        </div>

      </div>
    )
  }
</code>```

In InputText.js

```<code>export default class InputText extends React.Component {
  render() {
    // destructuring
    const { title, data, changed } = this.props;
    return (
      <div>
        <label className="label">{title}</label>
        <input type="text" value={data} onChange={changed} />
        value: ({data})
      </div>
    )
  }
}
</code>```

You can also make your InputText.js a functional component instead of class based component as it is stateless now.

Update: (How to reuse the handler method)

You can add another argument to the function which would return the attribute name like this:

```<code>keyUpHandler(e, attribute) {
  const { formInputs } = this.state;
  formInputs[attribute] = e.target.value
  this.setState({
    formInputs: formInputs
  });
}
</code>```

And from your from you can send it like this:

```<code><input type="text" value={data} onChange={ (event) => changed(event, 'email') } />
</code>```

This assumes that you have different inputs for each form input or else you can pass that attribute name also from parent in props to the child and use it accordingly.

Title: React: 2 way binding props

Body:
How can I do a 2 way binding of a variable from the parent component (Form.js), such that changes occurred in the child component (InputText.js) will be updated in the parent component?

Expected result: typing values in the input in InputText.js will update the state of Form.js

In Form.js

render() {
    return (

        <InputText
          title="Email"
          data={this.state.formInputs.email}
        />

          Value: {this.state.formInputs.email} // <-- this no change

    )
  }

In InputText.js

export default class InputText extends React.Component {

  constructor(props) {
    super(props);
    this.state = props;
    this.handleKeyChange = this.keyUpHandler.bind(this);
  }

  keyUpHandler(e) {
    this.setState({
      data: e.target.value
    });
  }

  render() {
    return (

        {this.state.title}
        <input type="text" value={this.state.data} onChange={this.handleKeyChange} /> // <-- type something here
        value: ({this.state.data}) // <-- this changed

    )
  }
}

Body:
You can manage state in the parent component itself instead of managing that on child like this (lifting state up):

In Form.js

constructor(props) {
  super(props);
  this.handleKeyChange = this.keyUpHandler.bind(this);
}

keyUpHandler(e) {
  const { formInputs } = this.state;
  formInputs.email = e.target.value
  this.setState({
    formInputs: formInputs
  });
}

render() {
    // destructuring
    const { email } = this.state.formInputs;
    return (
      <div>
        <InputText
          title="Email"
          data={email}
          changed={this.handleKeyChange}
        />

        <div>
          Value: {email}
        </div>

      </div>
    )
  }

In InputText.js

export default class InputText extends React.Component {
  render() {
    // destructuring
    const { title, data, changed } = this.props;
    return (
      <div>
        <label className="label">{title}</label>
        <input type="text" value={data} onChange={changed} />
        value: ({data})
      </div>
    )
  }
}

You can also make your InputText.js a functional component instead of class based component as it is stateless now.

Update: (How to reuse the handler method)

You can add another argument to the function which would return the attribute name like this:

keyUpHandler(e, attribute) {
  const { formInputs } = this.state;
  formInputs[attribute] = e.target.value
  this.setState({
    formInputs: formInputs
  });
}

And from your from you can send it like this:

<input type="text" value={data} onChange={ (event) => changed(event, 'email') } />

This assumes that you have different inputs for each form input or else you can pass that attribute name also from parent in props to the child and use it accordingly.


问:
How do I change the user agent of a device in Kaiosrt or WebIDE?
I can see the following fields in “Device Preferences”.

However, none of these preferences seem to control navigator.userAgent. I also tried looking into “Device Settings” but that doesn't have any field related to the user agent at all.

For reference, here is my runtime info.

As you can see, the user agent is Mozilla 5.0 (Mobile; rv:48.0) Gecko/48.0 Firefox/48.0. I want to change the user agent to Mozilla/5.0 (Mobile; LYF/LF-2403/LYF-LF2403-000-01-3D-191217-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.0 to match the device user agent.

答:
The trick is to treat it like a firefox browser:

Open "Device Preferences" and add a new string config with key general.useragent.override and value as whatever you need.

Restart your app in the simulator.

The overriden user agent in step 1 should start reflecting.


问:
Problems with displaying links using Illuminate/pagination
I want to use the Illuminate/pagination library outside of Laravel in my project. I use the Eloquent for models and in the controller I call the static paginate method to make pagination:

```<code>public function index()
{
    $tasks = Task::paginate(3);
    $this->setView("home/index", ["tasks" => $tasks] );

}
</code>```

When I try to display items in view only first 3 of them are shown and there is an error in the bottom of it:

Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\AbstractPaginator.php on line 519

Fatal error: Uncaught Error: Call to a member function make() on null
  in
  E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\LengthAwarePaginator.php:91
  Stack trace: #0
  E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\LengthAwarePaginator.php(79):
  Illuminate\Pagination\LengthAwarePaginator->render(NULL, Array) #1
  E:\OSPanel\domains\MVCtodo\app\views\home\index.php(82):
  Illuminate\Pagination\LengthAwarePaginator->links() #2
  E:\OSPanel\domains\MVCtodo\app\core\Controller.php(13):
  require_once('E:\OSPanel\doma...') #3
  E:\OSPanel\domains\MVCtodo\app\controllers\HomeController.php(9):
  Controller->setView('home/index', Array) #4
  E:\OSPanel\domains\MVCtodo\app\core\Route.php(16):
  HomeController->index() #5
  E:\OSPanel\domains\MVCtodo\app\core\page.php(8): Route->__construct()

6 E:\OSPanel\domains\MVCtodo\index.php(4): require_once('E:\OSPanel\doma...') #7 {main} thrown in

E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\LengthAwarePaginator.php
  on line 91

Here is the peace of code in the view:

```<code><table id="myTable" border="1" width="80%" class="tablesorter">
    <thead>
        <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Task</th>
            <th>Accepted</th>
        </tr>
    </thead>
    <tbody>
        <?php
            $taskNumber = 1;

            foreach($data['tasks'] as $task)
                {   $accepted = $task->accepted ? "<i class='fa fa-check-square-o fa-2x'></i>" : "";
                    echo "<tr>
                    <td>$taskNumber. $task->username</td>
                    <td>$task->email</td>
                    <td>$task->task</td>
                    <td>$accepted</td>
                    </tr>
                    ";
                    $taskNumber++;
                }

            ?>
    </tbody>
</table>
<?php echo $data['tasks']->links(); ?>
</code>```

答:
I Suggest that in your controller, if you know the view path, then do this,

```<code>public function index()
{
    $tasks = Task::paginate(3);
    return view("home.index", ["tasks" => $tasks] );
}
</code>```

that is if the view is in the home folder, and its called index.
then in the view its self,

```<code><table id="myTable" border="1" width="80%" class="tablesorter">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Task</th>
                            <th>Accepted</th>
                        </tr>
                    </thead>
                    <tbody>
                            @foreach($tasks as $task)
                              $accepted = $task->accepted ? "<i class='fa fa-check-square-o fa-2x'></i>" : "";
                              <tr>
                                    <td>$taskNumber. $task->username</td>
                                    <td>$task->email</td>
                                    <td>$task->task</td>
                                    <td>$accepted</td>
                              </tr>;
                          @endforeach
                    </tbody>
                </table>
                {{ $tasks->links()}}

</code>```

Body:
I want to use the Illuminate/pagination library outside of Laravel in my project. I use the Eloquent for models and in the controller I call the static paginate method to make pagination:

public function index()
{
    $tasks = Task::paginate(3);
    $this->setView("home/index", ["tasks" => $tasks] );

}

When I try to display items in view only first 3 of them are shown and there is an error in the bottom of it:

Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\AbstractPaginator.php on line 519

Fatal error: Uncaught Error: Call to a member function make() on null
  in
  E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\LengthAwarePaginator.php:91
  Stack trace: #0
  E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\LengthAwarePaginator.php(79):
  Illuminate\Pagination\LengthAwarePaginator->render(NULL, Array) #1
  E:\OSPanel\domains\MVCtodo\app\views\home\index.php(82):
  Illuminate\Pagination\LengthAwarePaginator->links() #2
  E:\OSPanel\domains\MVCtodo\app\core\Controller.php(13):
  require_once('E:\OSPanel\doma...') #3
  E:\OSPanel\domains\MVCtodo\app\controllers\HomeController.php(9):
  Controller->setView('home/index', Array) #4
  E:\OSPanel\domains\MVCtodo\app\core\Route.php(16):
  HomeController->index() #5
  E:\OSPanel\domains\MVCtodo\app\core\page.php(8): Route->__construct()

6 E:\OSPanel\domains\MVCtodo\index.php(4): require_once('E:\OSPanel\doma...') #7 {main} thrown in

E:\OSPanel\domains\MVCtodo\vendor\illuminate\pagination\LengthAwarePaginator.php
  on line 91

Here is the peace of code in the view:

            Username
            Email
            Task
            Accepted

        <?php
            $taskNumber = 1;

            foreach($data['tasks'] as $task)
                {   $accepted = $task->accepted ? "" : "";
                    echo "

                    $taskNumber. $task->username
                    $task->email
                    $task->task
                    $accepted

                    ";
                    $taskNumber++;
                }

            ?>

<?php echo $data['tasks']->links(); ?>

Body:
I Suggest that in your controller, if you know the view path, then do this,

public function index()
{
    $tasks = Task::paginate(3);
    return view("home.index", ["tasks" => $tasks] );
}

that is if the view is in the home folder, and its called index.
then in the view its self,

<table id="myTable" border="1" width="80%" class="tablesorter">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Task</th>
                            <th>Accepted</th>
                        </tr>
                    </thead>
                    <tbody>
                            @foreach($tasks as $task)
                              $accepted = $task->accepted ? "<i class='fa fa-check-square-o fa-2x'></i>" : "";
                              <tr>
                                    <td>$taskNumber. $task->username</td>
                                    <td>$task->email</td>
                                    <td>$task->task</td>
                                    <td>$accepted</td>
                              </tr>;
                          @endforeach
                    </tbody>
                </table>
                {{ $tasks->links()}}


问:
Certificate Pinning in Concurrent requests Swift
I'm writing an app in swift 5 that needs to connect to my server. I have the full certificate chain. i have implemented certificate pinning and i have a success connection when i have one request but it fail when multiple requests at the same time
why certificate pinning not work with multiple requests in the same time in swift?</p>

答: i find the solution, so the issue is due to the allocation of the session, i have created a static variable session to void the allocation and it worked successfully </p>


问:
Override console.log in JavaScript
I want to override console.log method to invoke a set of tasks whenever console.log is called. I referred other Stackoverflow answers but that give me the error:

Uncaught RangeError: Maximum call stack size exceeded.

This is what I want to do:

```<code>backupconsolelog = console.log;

console.log = function(arguments)
{
    //do my tasks;

    backupconsolelog(arguments);
}
</code>```

Update 1: Somehow managed to over-ride console.log successfully, but I'm now unable to execute console.log(displaySomethingInConsole) in the same .js file where over-riding is done. This somehow causes recursive call to console.log, and gives again Uncaught RangeError: Maximum call stack size exceeded.

How do I use console.log() in the same .js file?

Update 2: I've have a check() function which is called by over-rided console.log. But, there was a console.log call inside the check() function which caused Maximum call stack size exceeded. error.

Update 3: Error again! :(

Uncaught TypeError: Illegal invocation

```<code>var _log = window.console.log;
window.console.log = function () {
_log.apply(this, arguments);
check();
};

_log("aaa");
check() {};
</code>```

Update 4: Binding console to _log, i.e., console.log.bind(console) cleared it.

答:
After some problems, I managed to get console.log replacement with winston + express to work.

I use winston-sugar as it makes configuration easier but anything should work. (.config/winston.json is created when you do npm install winston-sugar)
People wanting to replace console.log with something else can just look at the last 5 lines as it gives very clean code.

I think this is a very neat way to get express logged into files along with console.log

```<code>const morgan = require('morgan');
const winstonLoader = require('winston-sugar');
winstonLoader.config('./config/winston.json');
const log = winstonLoader.getLogger('app');
log.stream = {
  write: function (message, encoding) {
    log.info(message);
  },
};

// Add some lines indicating that the program started to track restarts.
log.info('----------------------------------');
log.info('--');
log.info('-- Starting program');
log.info('--');
log.info('----------------------------------');

console.log = (...args) => log.info(...args);
console.info = (...args) => log.info(...args);
console.warn = (...args) => log.warn(...args);
console.error = (...args) => log.error(...args);
console.debug = (...args) => log.debug(...args);
</code>```

And later in the code if you are running express.

```<code>// app.use(morgan('combined')); //replaced with the next line to get morgan logs into the winston logfiles.
app.use(morgan('combined', { stream: log.stream }));
</code>```

Title: Override console.log in JavaScript

Body:
I want to override console.log method to invoke a set of tasks whenever console.log is called. I referred other Stackoverflow answers but that give me the error:

Uncaught RangeError: Maximum call stack size exceeded.

This is what I want to do:

backupconsolelog = console.log;

console.log = function(arguments)
{
    //do my tasks;

    backupconsolelog(arguments);
}

Update 1: Somehow managed to over-ride console.log successfully, but I'm now unable to execute console.log(displaySomethingInConsole) in the same .js file where over-riding is done. This somehow causes recursive call to console.log, and gives again Uncaught RangeError: Maximum call stack size exceeded.

How do I use console.log() in the same .js file?

Update 2: I've have a check() function which is called by over-rided console.log. But, there was a console.log call inside the check() function which caused Maximum call stack size exceeded. error.

Update 3: Error again! :(

Uncaught TypeError: Illegal invocation

var _log = window.console.log;
window.console.log = function () {
_log.apply(this, arguments);
check();
};

_log("aaa");
check() {};

Update 4: Binding console to _log, i.e., console.log.bind(console) cleared it.

Body:
After some problems, I managed to get console.log replacement with winston + express to work.

I use winston-sugar as it makes configuration easier but anything should work. (.config/winston.json is created when you do npm install winston-sugar)
People wanting to replace console.log with something else can just look at the last 5 lines as it gives very clean code.

I think this is a very neat way to get express logged into files along with console.log

const morgan = require('morgan');
const winstonLoader = require('winston-sugar');
winstonLoader.config('./config/winston.json');
const log = winstonLoader.getLogger('app');
log.stream = {
  write: function (message, encoding) {
    log.info(message);
  },
};

// Add some lines indicating that the program started to track restarts.
log.info('----------------------------------');
log.info('--');
log.info('-- Starting program');
log.info('--');
log.info('----------------------------------');

console.log = (...args) => log.info(...args);
console.info = (...args) => log.info(...args);
console.warn = (...args) => log.warn(...args);
console.error = (...args) => log.error(...args);
console.debug = (...args) => log.debug(...args);

And later in the code if you are running express.

// app.use(morgan('combined')); //replaced with the next line to get morgan logs into the winston logfiles.
app.use(morgan('combined', { stream: log.stream }));


问:
Handling of android app uninstallation
I have created some files through my android application. I want to remove these files when the application is removed from the device. How can I get it done. Any help will be appreciated..

Thanks in advance..

答: please read the link http://developer.android.com/guide/topics/data/data-storage.html</p>

Title: Handling of android app uninstallation


问:
Cannot assign session variables in php
There are similar questions related to the topic but none of them have solved my problem. Its kind of weird but my $_SESSION is working on the same page but not on any other page. If I put isset($_POST['submit') the condition doesn't satisfy and without it the $_SESSION remains null.

This is my code.

This is the login page.

```<code><!-- Login.php  -->
<?php
session_start();
?>
<html>
<body>
<form method="post" action="profile.php">
<fieldset>

<legend>
Login
</legend>
<label> User ID  :</label>   <input type="text" placeholder="Username" name="user"><br>
<label> Password  :</label>   <input type="password" placeholder="Password" name="password">

<input type="submit" name="submit" value="Login">
</fieldset>
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$_SESSION['USER']= $_POST['user'];
$_SESSION['PASS']=$_POST['password'];
}
?>
</code>```

This is where I want my session variable to appear.

```<code><!--  profile.php  -->
<?php
session_start();
echo "Session user is ".$_SESSION['USER']."<br>";
unset($_SESSION['USER']);
unset($_SESSION['PASS']);
session_unset();
session_destroy();
?>
</code>```

This is what I have tried :

Changing form method to GET.

Using $_REQUEST and $_GET.

Using $_SESSION on the same page. It works on the same page.

Checking session id. The session on the other pages are present but values are either null or empty.

Running the code without isset(). In that case all the session variables remain NULL.

答:
$_POST['submit'] and the rest of the post parameters are not available in Login.php
They are available only in profile.php because your form action points to it.

You may move the following code after the session_start() in profile.php.

```<code>if(isset($_POST['submit'])){
$_SESSION['USER']= $_POST['user'];
$_SESSION['PASS']=$_POST['password'];
}
</code>```

Keep in mind that you unset the session values in the end of profile.php

Title: Cannot assign session variables in php

Body:
There are similar questions related to the topic but none of them have solved my problem. Its kind of weird but my $_SESSION is working on the same page but not on any other page. If I put isset($_POST['submit') the condition doesn't satisfy and without it the $_SESSION remains null.

This is my code.

This is the login page.

<?php
session_start();
?>

<form method="post" action="profile.php">
<fieldset>

<legend>
Login
</legend>
 User ID  :   <input type="text" placeholder="Username" name="user">

 Password  :   <input type="password" placeholder="Password" name="password">

<input type="submit" name="submit" value="Login">
</fieldset>
</form>

<?php
if(isset($_POST['submit'])){
$_SESSION['USER']= $_POST['user'];
$_SESSION['PASS']=$_POST['password'];
}
?>

This is where I want my session variable to appear.

<?php
session_start();
echo "Session user is ".$_SESSION['USER']."
";
unset($_SESSION['USER']);
unset($_SESSION['PASS']);
session_unset();
session_destroy();
?>

This is what I have tried :

Changing form method to GET.

Using $_REQUEST and $_GET.

Using $_SESSION on the same page. It works on the same page.

Checking session id. The session on the other pages are present but values are either null or empty.

Running the code without isset(). In that case all the session variables remain NULL.

Body:
$_POST['submit'] and the rest of the post parameters are not available in Login.php
They are available only in profile.php because your form action points to it.

You may move the following code after the session_start() in profile.php.

if(isset($_POST['submit'])){
$_SESSION['USER']= $_POST['user'];
$_SESSION['PASS']=$_POST['password'];
}

Keep in mind that you unset the session values in the end of profile.php


问:
How to melt pairwise.wilcox.test output using dplyr?
I want to apply pairwise.wilcox.test for multiple independent variables at a time and then want to have the output in long format. For a particular Wavelength, I could do it using the following code

```<code>try <- pairwise.wilcox.test(df$WV_350, as.factor(df$Class), p.adjust.method="bonf")$p.value
</code>```

and the ultimate output what I want is

```<code>reshape2::melt(try)
#>  Var1 Var2      value
#> 1     2    1 1.00000000
#> 2     3    1 0.07936508
#> 3     4    1 0.07936508
#> 4     5    1 0.07936508
#> 5     2    2         NA
#> 6     3    2 0.07936508
#> 7     4    2 0.07936508
#> 8     5    2 0.07936508
#> 9     2    3         NA
#> 10    3    3         NA
#> 11    4    3 1.00000000
#> 12    5    3 0.74912899
#> 13    2    4         NA
#> 14    3    4         NA
#> 15    4    4         NA
#> 16    5    4 0.55555556
</code>```

Now to apply it for all the wavelengths at a time, I have used dplyr package (Newest version 1.0.0) like

```<code>library(tidyverse)
tbl_df(df)%>%
  pivot_longer(cols = -Class, names_to = "Wavelengths", values_to = "value") %>%
  group_by(Wavelengths) %>%
  summarize(out = pairwise.wilcox.test(value, as.factor(Class), p.adjust.method="bonf")$p.value)
</code>```

which returns me

```<code>#> `summarise()` regrouping output by 'Wavelengths' (override with `.groups` argument)
#> # A tibble: 16 x 2
#> # Groups:   Wavelengths [4]
#>    Wavelengths pval[,1]    [,2]   [,3]   [,4]
#>    <chr>          <dbl>   <dbl>  <dbl>  <dbl>
#>  1 WV_350        1      NA      NA     NA
#>  2 WV_350        0.0794  0.0794 NA     NA
#>  3 WV_350        0.0794  0.0794  1     NA
#>  4 WV_350        0.0794  0.0794  0.749  0.556
#>  5 WV_351        1      NA      NA     NA
#>  6 WV_351        0.0794  0.0794 NA     NA
#>  7 WV_351        0.0794  0.0794  1     NA
#>  8 WV_351        0.0794  0.0794  0.556  0.556
#>  9 WV_352        1      NA      NA     NA
#> 10 WV_352        0.0794  0.0794 NA     NA
#> 11 WV_352        0.0794  0.0794  1     NA
#> 12 WV_352        0.0794  0.0794  0.556  0.749
#> 13 WV_353        1      NA      NA     NA
#> 14 WV_353        0.0794  0.0794 NA     NA
#> 15 WV_353        0.0794  0.0794  1     NA
#> 16 WV_353        0.0794  0.0794  0.556  0.317
</code>```

Now how to have the output in long format like

```<code>Wavelength Var1 Var2      value
</code>```

Data

```<code>df = structure(list(Class = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3,
3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5), WV_350 = c(0.0196, 0.0206,
0.023, 0.0264, 0.029, 0.0201, 0.0181, 0.0216, 0.0225, 0.019,
0.0165, 0.0121, 0.0129, 0.0123, 0.0149, 0.0137, 0.0116, 0.0151,
0.0138, 0.0167, 0.0149, 0.0112, 0.0107, 0.01, 0.0099), WV_351 = c(0.0197,
0.0206, 0.0229, 0.0265, 0.029, 0.0199, 0.0183, 0.0216, 0.0225,
0.0187, 0.0165, 0.0118, 0.0127, 0.0122, 0.0148, 0.0138, 0.0114,
0.0145, 0.0132, 0.0164, 0.0144, 0.0108, 0.01, 0.0093, 0.0095),
    WV_352 = c(0.0199, 0.0207, 0.0233, 0.027, 0.0299, 0.0203,
    0.0186, 0.0219, 0.0232, 0.019, 0.0169, 0.0124, 0.0133, 0.0126,
    0.0152, 0.0145, 0.0118, 0.0148, 0.0132, 0.0168, 0.0148, 0.0111,
    0.0102, 0.0096, 0.0098), WV_353 = c(0.0204, 0.0213, 0.0238,
    0.0277, 0.0307, 0.0208, 0.0194, 0.0229, 0.0241, 0.0199, 0.0173,
    0.013, 0.0142, 0.0134, 0.0161, 0.0152, 0.0126, 0.0153, 0.0137,
    0.0175, 0.0151, 0.0116, 0.0105, 0.01, 0.0098)), row.names = c(NA,
25L), class = "data.frame")
</code>```

答:
A bit verbose and Im sure it could be made more efficient:</p>

```<code>library(tidyverse)
library(broom)
res <-
  tbl_df(df)%>%
  pivot_longer(cols = -Class, names_to = "Wavelengths", values_to = "value") %>%
  group_by(Wavelengths) %>%
  summarise(pw_wt = list(pairwise.wilcox.test(value,as.factor(Class),
                                              p.adjust.method = "bonf")$p.value)) %>%
  ungroup() %>%
  mutate(pw_wt_t = map(pw_wt, broom::tidy)) %>%
  unnest(pw_wt_t)
</code>```

Body:
I want to apply pairwise.wilcox.test for multiple independent variables at a time and then want to have the output in long format. For a particular Wavelength, I could do it using the following code

try <- pairwise.wilcox.test(df$WV_350, as.factor(df$Class), p.adjust.method="bonf")$p.value

and the ultimate output what I want is

reshape2::melt(try)
#>  Var1 Var2      value
#> 1     2    1 1.00000000
#> 2     3    1 0.07936508
#> 3     4    1 0.07936508
#> 4     5    1 0.07936508
#> 5     2    2         NA
#> 6     3    2 0.07936508
#> 7     4    2 0.07936508
#> 8     5    2 0.07936508
#> 9     2    3         NA
#> 10    3    3         NA
#> 11    4    3 1.00000000
#> 12    5    3 0.74912899
#> 13    2    4         NA
#> 14    3    4         NA
#> 15    4    4         NA
#> 16    5    4 0.55555556

Now to apply it for all the wavelengths at a time, I have used dplyr package (Newest version 1.0.0) like

library(tidyverse)
tbl_df(df)%>%
  pivot_longer(cols = -Class, names_to = "Wavelengths", values_to = "value") %>%
  group_by(Wavelengths) %>%
  summarize(out = pairwise.wilcox.test(value, as.factor(Class), p.adjust.method="bonf")$p.value)

which returns me

#> `summarise()` regrouping output by 'Wavelengths' (override with `.groups` argument)
#> # A tibble: 16 x 2
#> # Groups:   Wavelengths [4]
#>    Wavelengths pval[,1]    [,2]   [,3]   [,4]
#>    <chr>          <dbl>   <dbl>  <dbl>  <dbl>
#>  1 WV_350        1      NA      NA     NA
#>  2 WV_350        0.0794  0.0794 NA     NA
#>  3 WV_350        0.0794  0.0794  1     NA
#>  4 WV_350        0.0794  0.0794  0.749  0.556
#>  5 WV_351        1      NA      NA     NA
#>  6 WV_351        0.0794  0.0794 NA     NA
#>  7 WV_351        0.0794  0.0794  1     NA
#>  8 WV_351        0.0794  0.0794  0.556  0.556
#>  9 WV_352        1      NA      NA     NA
#> 10 WV_352        0.0794  0.0794 NA     NA
#> 11 WV_352        0.0794  0.0794  1     NA
#> 12 WV_352        0.0794  0.0794  0.556  0.749
#> 13 WV_353        1      NA      NA     NA
#> 14 WV_353        0.0794  0.0794 NA     NA
#> 15 WV_353        0.0794  0.0794  1     NA
#> 16 WV_353        0.0794  0.0794  0.556  0.317

Now how to have the output in long format like

Wavelength Var1 Var2      value

Data

df = structure(list(Class = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3,
3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5), WV_350 = c(0.0196, 0.0206,
0.023, 0.0264, 0.029, 0.0201, 0.0181, 0.0216, 0.0225, 0.019,
0.0165, 0.0121, 0.0129, 0.0123, 0.0149, 0.0137, 0.0116, 0.0151,
0.0138, 0.0167, 0.0149, 0.0112, 0.0107, 0.01, 0.0099), WV_351 = c(0.0197,
0.0206, 0.0229, 0.0265, 0.029, 0.0199, 0.0183, 0.0216, 0.0225,
0.0187, 0.0165, 0.0118, 0.0127, 0.0122, 0.0148, 0.0138, 0.0114,
0.0145, 0.0132, 0.0164, 0.0144, 0.0108, 0.01, 0.0093, 0.0095),
    WV_352 = c(0.0199, 0.0207, 0.0233, 0.027, 0.0299, 0.0203,
    0.0186, 0.0219, 0.0232, 0.019, 0.0169, 0.0124, 0.0133, 0.0126,
    0.0152, 0.0145, 0.0118, 0.0148, 0.0132, 0.0168, 0.0148, 0.0111,
    0.0102, 0.0096, 0.0098), WV_353 = c(0.0204, 0.0213, 0.0238,
    0.0277, 0.0307, 0.0208, 0.0194, 0.0229, 0.0241, 0.0199, 0.0173,
    0.013, 0.0142, 0.0134, 0.0161, 0.0152, 0.0126, 0.0153, 0.0137,
    0.0175, 0.0151, 0.0116, 0.0105, 0.01, 0.0098)), row.names = c(NA,
25L), class = "data.frame")

Body:
A bit verbose and Im sure it could be made more efficient:

library(tidyverse)
library(broom)
res <-
  tbl_df(df)%>%
  pivot_longer(cols = -Class, names_to = "Wavelengths", values_to = "value") %>%
  group_by(Wavelengths) %>%
  summarise(pw_wt = list(pairwise.wilcox.test(value,as.factor(Class),
                                              p.adjust.method = "bonf")$p.value)) %>%
  ungroup() %>%
  mutate(pw_wt_t = map(pw_wt, broom::tidy)) %>%
  unnest(pw_wt_t)


问:
Postgres upsert using on conflict - multiple fields in on conflict condition
I'm trying to implement the concept of liking / disliking an item in a postgres db - when the user likes / dislikes something, I want to insert an item into my DB to represent this.

This is my schema:

```<code>id | postID | userID | type
 1      2        1      like
</code>```

Now if the user has already liked the item, and now they decide to dislike it - I want to update the type field, from like to dislike.

Similarly, if they've disliked something and now decided to like it, I want to perform the opposite update.

Furthermore, a user can only like / dislike something once - so if the user has liked / disliked the post previously and now decides to like / dislike it again, nothing should happen.

This means I need to implement an upsert statement in postgres, which inserts a new row, if the user has not interacted with the post previously, and updates the type field, if a row with the specified postID + userID + type already exists.

I was looking at doing this using the on conflict syntax -

```<code>INSERT INTO table_name(postID,userID,type)
VALUES(2,1,'like')
ON CONFLICT (????) DO UPDATE
  SET type = 'like'
</code>```

but I'm not sure what to pass into the ON CONFLICT section, since the match needs to happen on multiple fields.

I considered setting a unique index on the (postID, userID) fields - something like this:

create unique index idx_1 on table (postID, userID)

The problem is I want to use this DB in the future to store comment information, and a user is allowed to comment on the same post multiple times.

An example would be:

```<code>id | postID | userID | type
 1      2       1      comment
 2      2       1      comment
 3      2       1      like
</code>```

答:
If you want to limit the number of updates to a row, you can use a check constraint and secondary column counting the updates.

```<code>alter table t add column num_updates int default 1 check (num_updates <= 2);
</code>```

Then, if you want to prevent duplicate rows on types other than comment, you can use a filtered unique index:

create unique index unq_table_name_postid_userid
    on table_name(postid, userid)
    where type <> 'comment';

Then I think you can express the logic using on conflict:

```<code>INSERT INTO table_name (postID, userID, type)
    VALUES(2, 1, 'like')
    ON CONFLICT (postID, userID) DO UPDATE
         SET type = 'like',
             num_updates = excluded.num_updates + 1;
</code>```

This allows only one update.  You might want more refined logic, such as updating the value only if type changes:

```<code>num_update = (excluded.num_updates = num_updates)::int + 1
</code>```

Body:
I'm trying to implement the concept of liking / disliking an item in a postgres db - when the user likes / dislikes something, I want to insert an item into my DB to represent this.

This is my schema:

id | postID | userID | type
 1      2        1      like

Now if the user has already liked the item, and now they decide to dislike it - I want to update the type field, from like to dislike.

Similarly, if they've disliked something and now decided to like it, I want to perform the opposite update.

Furthermore, a user can only like / dislike something once - so if the user has liked / disliked the post previously and now decides to like / dislike it again, nothing should happen.

This means I need to implement an upsert statement in postgres, which inserts a new row, if the user has not interacted with the post previously, and updates the type field, if a row with the specified postID + userID + type already exists.

I was looking at doing this using the on conflict syntax -

INSERT INTO table_name(postID,userID,type)
VALUES(2,1,'like')
ON CONFLICT (????) DO UPDATE
  SET type = 'like'

but I'm not sure what to pass into the ON CONFLICT section, since the match needs to happen on multiple fields.

I considered setting a unique index on the (postID, userID) fields - something like this:

create unique index idx_1 on table (postID, userID)

The problem is I want to use this DB in the future to store comment information, and a user is allowed to comment on the same post multiple times.

An example would be:

id | postID | userID | type
 1      2       1      comment
 2      2       1      comment
 3      2       1      like

Body:
If you want to limit the number of updates to a row, you can use a check constraint and secondary column counting the updates.

alter table t add column num_updates int default 1 check (num_updates <= 2);

Then, if you want to prevent duplicate rows on types other than comment, you can use a filtered unique index:

create unique index unq_table_name_postid_userid
    on table_name(postid, userid)
    where type <> 'comment';

Then I think you can express the logic using on conflict:

INSERT INTO table_name (postID, userID, type)
    VALUES(2, 1, 'like')
    ON CONFLICT (postID, userID) DO UPDATE
         SET type = 'like',
             num_updates = excluded.num_updates + 1;

This allows only one update.  You might want more refined logic, such as updating the value only if type changes:

num_update = (excluded.num_updates = num_updates)::int + 1


问:
Can I use libjpeg to read JPEGs with an alpha channel?
There seems to be some debate about whether JPEGs with alpha channels are valid or not.  The answer I had always understood to be correct is that in the JPEG FAQ, which is essentially "No".  (This is reiterated in another question on Stack Overflow.)

However, Java's JPEGImageWriter in Sun's ImageIO library will happily write and read grayscale and RGB images with an alpha channel, even though there are virtually no applications on Linux I've tried so far that will load such JPEGs correctly.  This has been reported in the past as a bug, but Sun's response is that these are valid files:

This is not an Image I/O bug, but rather a deficiency in the other applications
  the submitter mentions.  The IIO JPEGImageWriter is able to write images with
  a color model that contains an alpha channel (referred to in the IJG native
  source code as the "NIFTY" color spaces, such as RGBA, YCbCrA, etc.), but many applications are not aware of these color spaces.  So even though these images
  written by the IIO JPEG writer are compliant with the JPEG specification (which
  is blind to the various color space possiblities), some applications may not
  recognize color spaces that contain an alpha channel and may throw an
  error or render a corrupted image, as the submitter describes.

Developers wishing to maintain compatibility with these other alpha-unaware
  applications should write images that do not contain an alpha channel (such as
  TYPE_INT_RGB).  Developers who want the capability of writing/reading an image
  containing an alpha channel in the JPEG format can do so using the Image I/O
  API, but need to be aware that many native applications out there are not quite
  compliant with the YCbCrA and RGBA formats.

For more information, see the Image I/O JPEG Metadata Format Specification and Usage Notes:
  http://java.sun.com/j2se/1.4.1/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html

Closing as "not a bug".
    xxxxx@xxxxx   2003-03-24

I'm working with a Java application that creates files like these, and want to write some C code that will load these as fast as possible. (Essentially the problem is that the Java ImageIO library is remarkably slow at decompressing these files, and we would like to replace the loader with native code via JNI that improves this - it's a performance bottleneck at the moment.)

There are some example files here - apologies to anyone who's coulrophobic:

http://mythic-beasts.com/~mark/example-jpegs/

And here you can see the results of trying to view the grayscale+alpha and RGB+alpha images with various bit of Linux software that I believe use libjpeg:

grayscale image with alpha channel view with various programs http://mythic-beasts.com/~mark/all-alpha-bridges.png

(source: mark at mythic-beasts.com)

So it looks as if the color space is just being misinterpreted in each case.  The only allowed values in jpeglib.h are:

```<code>/* Known color spaces. */

typedef enum {
        JCS_UNKNOWN,            /* error/unspecified */
        JCS_GRAYSCALE,          /* monochrome */
        JCS_RGB,                /* red/green/blue */
        JCS_YCbCr,              /* Y/Cb/Cr (also known as YUV) */
        JCS_CMYK,               /* C/M/Y/K */
        JCS_YCCK                /* Y/Cb/Cr/K */
} J_COLOR_SPACE;
</code>```

... which doesn't look promising.

If I load these images with a slightly modified version of example.c from libjpeg, the values of cinfo.jpeg_color_space and cinfo.out_color_space for each image after reading the header are as follows:

```<code>gray-normal.jpg: jpeg_color_space is JCS_GRAYSCALE, out_color_space is JCS_GRAYSCALE
gray-alpha.jpg: jpeg_color_space is JCS_CMYK, out_color_space is JCS_CMYK

rgb-normal.jpg: jpeg_color_space is JCS_YCbCr, out_color_space is JCS_RGB
rgb-alpha.jpg: jpeg_color_space is JCS_CMYK, out_color_space is JCS_CMYK
</code>```

So, my questions are:

Can libjpeg be used to correctly read these files?

If not, is there an alternative C library I can use which will cope with them?

Obviously there are at least two other solutions to the more general problem:

Change the software to output normal JPEGs + a PNG file representing the alpha channel

Somehow improve the performance of Sun's ImageIO

... but the first would involve a lot of code changes, and it's not clear how to go about the latter.  In any case, I think that the question of how to use libjpeg to load such files is likely to be one of more general interest.

Any suggestions would be much appreciated.

答: Have you already tried libjpeg-turbo? It is supposed to be able to decode RGBA and there is already a Java wrapper for it.</p>

Body:
There seems to be some debate about whether JPEGs with alpha channels are valid or not.  The answer I had always understood to be correct is that in the JPEG FAQ, which is essentially "No".  (This is reiterated in another question on Stack Overflow.)

However, Java's JPEGImageWriter in Sun's ImageIO library will happily write and read grayscale and RGB images with an alpha channel, even though there are virtually no applications on Linux I've tried so far that will load such JPEGs correctly.  This has been reported in the past as a bug, but Sun's response is that these are valid files:

This is not an Image I/O bug, but rather a deficiency in the other applications
  the submitter mentions.  The IIO JPEGImageWriter is able to write images with
  a color model that contains an alpha channel (referred to in the IJG native
  source code as the "NIFTY" color spaces, such as RGBA, YCbCrA, etc.), but many applications are not aware of these color spaces.  So even though these images
  written by the IIO JPEG writer are compliant with the JPEG specification (which
  is blind to the various color space possiblities), some applications may not
  recognize color spaces that contain an alpha channel and may throw an
  error or render a corrupted image, as the submitter describes.

Developers wishing to maintain compatibility with these other alpha-unaware
  applications should write images that do not contain an alpha channel (such as
  TYPE_INT_RGB).  Developers who want the capability of writing/reading an image
  containing an alpha channel in the JPEG format can do so using the Image I/O
  API, but need to be aware that many native applications out there are not quite
  compliant with the YCbCrA and RGBA formats.

For more information, see the Image I/O JPEG Metadata Format Specification and Usage Notes:
  http://java.sun.com/j2se/1.4.1/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html

Closing as "not a bug".
    xxxxx@xxxxx   2003-03-24

I'm working with a Java application that creates files like these, and want to write some C code that will load these as fast as possible. (Essentially the problem is that the Java ImageIO library is remarkably slow at decompressing these files, and we would like to replace the loader with native code via JNI that improves this - it's a performance bottleneck at the moment.)

There are some example files here - apologies to anyone who's coulrophobic:

http://mythic-beasts.com/~mark/example-jpegs/

And here you can see the results of trying to view the grayscale+alpha and RGB+alpha images with various bit of Linux software that I believe use libjpeg:

grayscale image with alpha channel view with various programs http://mythic-beasts.com/~mark/all-alpha-bridges.png

(source: mark at mythic-beasts.com)

So it looks as if the color space is just being misinterpreted in each case.  The only allowed values in jpeglib.h are:

/* Known color spaces. */

typedef enum {
        JCS_UNKNOWN,            /* error/unspecified */
        JCS_GRAYSCALE,          /* monochrome */
        JCS_RGB,                /* red/green/blue */
        JCS_YCbCr,              /* Y/Cb/Cr (also known as YUV) */
        JCS_CMYK,               /* C/M/Y/K */
        JCS_YCCK                /* Y/Cb/Cr/K */
} J_COLOR_SPACE;

... which doesn't look promising.

If I load these images with a slightly modified version of example.c from libjpeg, the values of cinfo.jpeg_color_space and cinfo.out_color_space for each image after reading the header are as follows:

gray-normal.jpg: jpeg_color_space is JCS_GRAYSCALE, out_color_space is JCS_GRAYSCALE
gray-alpha.jpg: jpeg_color_space is JCS_CMYK, out_color_space is JCS_CMYK

rgb-normal.jpg: jpeg_color_space is JCS_YCbCr, out_color_space is JCS_RGB
rgb-alpha.jpg: jpeg_color_space is JCS_CMYK, out_color_space is JCS_CMYK

So, my questions are:

Can libjpeg be used to correctly read these files?

If not, is there an alternative C library I can use which will cope with them?

Obviously there are at least two other solutions to the more general problem:

Change the software to output normal JPEGs + a PNG file representing the alpha channel

Somehow improve the performance of Sun's ImageIO

... but the first would involve a lot of code changes, and it's not clear how to go about the latter.  In any case, I think that the question of how to use libjpeg to load such files is likely to be one of more general interest.

Any suggestions would be much appreciated.


问:
Not able to change a value in one page with respect to the value from another page in flutter
i want to change the indexvalue (pictogramindex) of one page when we click nextbutton on another screen.I will explain briefly , I have 2 screens in my scenario the first screen contains an image and it's name , a textfield and nextbutton (i have provided a dummy data contains a list of image and it's names) the logic behind this is , when we complete the textfield box and click next button(after validate) the textfield value checks with  the correctvalue which i was given in the dummy data and show it's synonym which also provided. when we click the next button we will go to another page which contains the correct answer(passed from first page) and a textfield in this  the user can write about the correct answer ( validated) when click next button in this page (till this my applicationworks perfectly) i want to load the first page with it's index updated (+1) which i initialised as 0 (var pictogramindex=0). But in my case when coming back to first page the index is not updating it will automatically stores the initialised value. what i want is i want to update index on the first page when i click next button in the Second page .

my source code of first screen is shown here

```<code>class Pictogramscreen extends StatefulWidget {
  final int length;

  const Pictogramscreen({Key key, this.length}) : super(key: key);
  @override
  _PictogramscreenState createState() => _PictogramscreenState();
}

class _PictogramscreenState extends State<Pictogramscreen> {
  @override
  final _Key = GlobalKey<FormState>();
  Color defaultcolor = Colors.blue[50];
  Color trueColor = Colors.green;
  Color falseColor = Colors.red;

  Widget defcorrect = Text('');
  var pictogramindex = 0;

  TextEditingController usertitleInput = TextEditingController();

  nextPictogram() {
    setState(() {
      pictogramindex++;
    });
  }

  fillColor() {
    setState(() {
      usertitleInput.text == pictdata[pictogramindex]['pictcorrectword']
          ? defaultcolor = trueColor
          : defaultcolor = falseColor;
    });
  }

  correctText() {
    setState(() {
      usertitleInput.text == pictdata[pictogramindex]['pictcorrectword']
          ? defcorrect = Text(pictdata[pictogramindex]['pictsynonym'])
          : defcorrect = Text(pictdata[pictogramindex]['pictcorrectword']);
    });
  }

  reset() {
    setState(() {
      defaultcolor = Colors.blue[50];
      defcorrect = Text('');

      usertitleInput.clear();
    });
  }

  void description(BuildContext ctx) {
    Navigator.of(context).pushNamed('/user-description', arguments: {
      'id': pictdata[pictogramindex]['pictid'],
      'word': pictdata[pictogramindex]['pictcorrectword']
    });
  }

  Widget build(BuildContext context) {
    int length = pictdata.length;

    return Scaffold(
        body: pictogramindex < pictdata.length
            ? ListView(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 20),
                    padding: EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Card(
                          margin: EdgeInsets.only(top: 20),
                          child: Image.network(
                              pictdata[pictogramindex]['pictimg']),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          pictdata[pictogramindex]['pictword'],
                          style: TextStyle(
                            fontSize: 25,
                          ),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        //Card(
                        //color: Colors.blue,
                        // child: TextField(
                        // decoration: InputDecoration.collapsed(
                        // hintText: 'type here'),
                        //textAlign: TextAlign.center,
                        // onSubmitted: (value) {
                        // usertitleInput = value;

                        // print(usertitleInput);
                        // },
                        // ),
                        //),

                        Form(
                          key: _Key,
                          child: TextFormField(
                              controller: usertitleInput,
                              validator: (usertitleInput) {
                                if (usertitleInput.isEmpty) {
                                  return 'Answer cannot be empty';
                                } else {
                                  return null;
                                }
                              },
                              textAlign: TextAlign.center,
                              decoration: InputDecoration(
                                enabledBorder: OutlineInputBorder(
                                    borderSide:
                                        BorderSide(color: Colors.blueAccent),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(15),
                                    )),
                                labelText: 'Type your Answer',
                                filled: true,
                                fillColor: defaultcolor,
                              ),
                              onFieldSubmitted: (value) {
                                usertitleInput.text = value;
                                fillColor();
                                correctText();
                                print(usertitleInput.text);
                              }),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        defcorrect,
                        SizedBox(
                          height: 10,
                        ),
                        RaisedButton(
                          onPressed: () {
                            if (_Key.currentState.validate()) {
                              description(context);
                              // nextPictogram();
                              reset();
                            }
                            //
                            //if (_Key.currentState.validate() == correctText()) {
                            //  nextPictogram;
                            // }
                          },
                          child: Text('Next'),
                        )
                      ],
                    ),
                  ),
                ],
              )
            : Center(
                child: Text('completed'),
              ));
  }
}

</code>```

my source code of the second screen is show here

```<code>class Userinputscreen extends StatefulWidget {
  final String id;
  final String word;

  const Userinputscreen({Key key, this.id, this.word}) : super(key: key);

  @override
  _UserinputscreenState createState() => _UserinputscreenState();
}

class _UserinputscreenState extends State<Userinputscreen> {
  final _Keey = GlobalKey<FormState>();

  TextEditingController userdescription = TextEditingController();
  var pictogramindex;

  void nextpict(BuildContext context) {
    Navigator.of(context).pushNamed('/main-screen');
  }
  // void nextpict(BuildContext context, int index) {
  //   Navigator.push(
  //       context,
  //       MaterialPageRoute(
  //           builder: (ctx) => Pictogramscreen(
  //                 index: i = 0,
  //               )));
  // }

  @override
  Widget build(BuildContext context) {
    final routeArgs =
        ModalRoute.of(context).settings.arguments as Map<String, String>;

    final correctWord = routeArgs['word'];
    return MaterialApp(
      home: Scaffold(
          body: ListView(children: <Widget>[
        Padding(
          padding: EdgeInsets.only(top: 50),
          child: Center(
            child: Container(
              padding: EdgeInsets.all(20),
              margin: EdgeInsets.only(top: 100),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    correctWord,
                    style: TextStyle(fontSize: 26),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Form(
                    key: _Keey,
                    child: TextFormField(
                        controller: userdescription,
                        validator: (userdescription) {
                          if (userdescription.isEmpty) {
                            return 'Answer cannot be empty';
                          } else {
                            return null;
                          }
                        },
                        textAlign: TextAlign.center,
                        decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.blueAccent),
                              borderRadius: BorderRadius.all(
                                Radius.circular(15),
                              )),
                          labelText: 'Type your Answer',
                          filled: true,
                        ),
                        onFieldSubmitted: (value) {
                          userdescription.text = value;

                          print(userdescription.text);
                        }),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (_Keey.currentState.validate()) {
                        nextpict(context);
                      }
                    },
                    child: Text('Next'),
                  )
                ],
              ),
            ),
          ),
        ),
      ])),
    );
  }
}

</code>```

答:
If I get it right, you basically want to tell the initial page that it's state is updated(the index) elsewhere. You basically need to make your app "reactive".

As is said in Google Developers Tutorial:

One of the advantages of Flutter is that it uses reactive views, which you can take to the next level by also applying reactive principles to your app’s data model.

Use some sort of state management. You need to choose from and use either Bloc, InheritedWidget and InheritedModel, Provider(ScopedModel), or the like.

Check this article on flutter about state management, or this for a complete list of approaches

Body:
i want to change the indexvalue (pictogramindex) of one page when we click nextbutton on another screen.I will explain briefly , I have 2 screens in my scenario the first screen contains an image and it's name , a textfield and nextbutton (i have provided a dummy data contains a list of image and it's names) the logic behind this is , when we complete the textfield box and click next button(after validate) the textfield value checks with  the correctvalue which i was given in the dummy data and show it's synonym which also provided. when we click the next button we will go to another page which contains the correct answer(passed from first page) and a textfield in this  the user can write about the correct answer ( validated) when click next button in this page (till this my applicationworks perfectly) i want to load the first page with it's index updated (+1) which i initialised as 0 (var pictogramindex=0). But in my case when coming back to first page the index is not updating it will automatically stores the initialised value. what i want is i want to update index on the first page when i click next button in the Second page .

my source code of first screen is shown here

class Pictogramscreen extends StatefulWidget {
  final int length;

  const Pictogramscreen({Key key, this.length}) : super(key: key);
  @override
  _PictogramscreenState createState() => _PictogramscreenState();
}

class _PictogramscreenState extends State<Pictogramscreen> {
  @override
  final _Key = GlobalKey<FormState>();
  Color defaultcolor = Colors.blue[50];
  Color trueColor = Colors.green;
  Color falseColor = Colors.red;

  Widget defcorrect = Text('');
  var pictogramindex = 0;

  TextEditingController usertitleInput = TextEditingController();

  nextPictogram() {
    setState(() {
      pictogramindex++;
    });
  }

  fillColor() {
    setState(() {
      usertitleInput.text == pictdata[pictogramindex]['pictcorrectword']
          ? defaultcolor = trueColor
          : defaultcolor = falseColor;
    });
  }

  correctText() {
    setState(() {
      usertitleInput.text == pictdata[pictogramindex]['pictcorrectword']
          ? defcorrect = Text(pictdata[pictogramindex]['pictsynonym'])
          : defcorrect = Text(pictdata[pictogramindex]['pictcorrectword']);
    });
  }

  reset() {
    setState(() {
      defaultcolor = Colors.blue[50];
      defcorrect = Text('');

      usertitleInput.clear();
    });
  }

  void description(BuildContext ctx) {
    Navigator.of(context).pushNamed('/user-description', arguments: {
      'id': pictdata[pictogramindex]['pictid'],
      'word': pictdata[pictogramindex]['pictcorrectword']
    });
  }

  Widget build(BuildContext context) {
    int length = pictdata.length;

    return Scaffold(
        body: pictogramindex < pictdata.length
            ? ListView(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 20),
                    padding: EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Card(
                          margin: EdgeInsets.only(top: 20),
                          child: Image.network(
                              pictdata[pictogramindex]['pictimg']),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          pictdata[pictogramindex]['pictword'],
                          style: TextStyle(
                            fontSize: 25,
                          ),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        //Card(
                        //color: Colors.blue,
                        // child: TextField(
                        // decoration: InputDecoration.collapsed(
                        // hintText: 'type here'),
                        //textAlign: TextAlign.center,
                        // onSubmitted: (value) {
                        // usertitleInput = value;

                        // print(usertitleInput);
                        // },
                        // ),
                        //),

                        Form(
                          key: _Key,
                          child: TextFormField(
                              controller: usertitleInput,
                              validator: (usertitleInput) {
                                if (usertitleInput.isEmpty) {
                                  return 'Answer cannot be empty';
                                } else {
                                  return null;
                                }
                              },
                              textAlign: TextAlign.center,
                              decoration: InputDecoration(
                                enabledBorder: OutlineInputBorder(
                                    borderSide:
                                        BorderSide(color: Colors.blueAccent),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(15),
                                    )),
                                labelText: 'Type your Answer',
                                filled: true,
                                fillColor: defaultcolor,
                              ),
                              onFieldSubmitted: (value) {
                                usertitleInput.text = value;
                                fillColor();
                                correctText();
                                print(usertitleInput.text);
                              }),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        defcorrect,
                        SizedBox(
                          height: 10,
                        ),
                        RaisedButton(
                          onPressed: () {
                            if (_Key.currentState.validate()) {
                              description(context);
                              // nextPictogram();
                              reset();
                            }
                            //
                            //if (_Key.currentState.validate() == correctText()) {
                            //  nextPictogram;
                            // }
                          },
                          child: Text('Next'),
                        )
                      ],
                    ),
                  ),
                ],
              )
            : Center(
                child: Text('completed'),
              ));
  }
}

my source code of the second screen is show here

class Userinputscreen extends StatefulWidget {
  final String id;
  final String word;

  const Userinputscreen({Key key, this.id, this.word}) : super(key: key);

  @override
  _UserinputscreenState createState() => _UserinputscreenState();
}

class _UserinputscreenState extends State<Userinputscreen> {
  final _Keey = GlobalKey<FormState>();

  TextEditingController userdescription = TextEditingController();
  var pictogramindex;

  void nextpict(BuildContext context) {
    Navigator.of(context).pushNamed('/main-screen');
  }
  // void nextpict(BuildContext context, int index) {
  //   Navigator.push(
  //       context,
  //       MaterialPageRoute(
  //           builder: (ctx) => Pictogramscreen(
  //                 index: i = 0,
  //               )));
  // }

  @override
  Widget build(BuildContext context) {
    final routeArgs =
        ModalRoute.of(context).settings.arguments as Map<String, String>;

    final correctWord = routeArgs['word'];
    return MaterialApp(
      home: Scaffold(
          body: ListView(children: <Widget>[
        Padding(
          padding: EdgeInsets.only(top: 50),
          child: Center(
            child: Container(
              padding: EdgeInsets.all(20),
              margin: EdgeInsets.only(top: 100),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    correctWord,
                    style: TextStyle(fontSize: 26),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Form(
                    key: _Keey,
                    child: TextFormField(
                        controller: userdescription,
                        validator: (userdescription) {
                          if (userdescription.isEmpty) {
                            return 'Answer cannot be empty';
                          } else {
                            return null;
                          }
                        },
                        textAlign: TextAlign.center,
                        decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.blueAccent),
                              borderRadius: BorderRadius.all(
                                Radius.circular(15),
                              )),
                          labelText: 'Type your Answer',
                          filled: true,
                        ),
                        onFieldSubmitted: (value) {
                          userdescription.text = value;

                          print(userdescription.text);
                        }),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (_Keey.currentState.validate()) {
                        nextpict(context);
                      }
                    },
                    child: Text('Next'),
                  )
                ],
              ),
            ),
          ),
        ),
      ])),
    );
  }
}


问:
vue js select (vuetify) + axios population
I have a stack with vue js (vuetify) + laravel + axios.
I am trying to populate a dropdown select using axios.
I have setup an API route on laravel so I can pull data from database table "Categories".
The api return the following:

```<code>[
{
    "id": 1,
    "category_name": "Electronics",
    "category_synonym": "Computer Accessories",
    "created_at": "2020-05-31T20:11:56.000000Z",
    "updated_at": "2020-05-31T20:11:56.000000Z"
},
{
    "id": 2,
    "category_name": "Hardware",
    "category_synonym": "hardware",
    "created_at": "2020-05-31T20:17:13.000000Z",
    "updated_at": "2020-05-31T20:17:13.000000Z"
},
{
    "id": 3,
    "category_name": "Kitchenware",
    "category_synonym": null,
    "created_at": "2020-05-31T20:49:32.000000Z",
    "updated_at": "2020-05-31T20:49:32.000000Z"
},
{
    "id": 4,
    "category_name": "Textile",
    "category_synonym": null,
    "created_at": "2020-05-31T21:29:30.000000Z",
    "updated_at": "2020-05-31T21:29:30.000000Z"
}
</code>```

]

I would like to put the category_name into a vue js dropdown contained into a foram.
How to make it simply ?

答:
You can try something like this:

<v-select v-model="currentCategory" :items="resultFromAPI" item-text="category_name" item-value="id" />
```

<p>To fetch the data with Axios you can try something like this:</p>

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

const ajax = axios.create({
  baseURL: 'https://example.com/api',
  headers: {
    'Content-Type': 'application/json'
  }
});

export default
{
  data()
  {
    return {
      categories: [],
      currentCategory: null,
    }
  },
  mounted()
  {
    this.fetchData();
  },
  methods:
  {
    fetchData()
    {
      ajax.get('/categories').then(response =>
      {
        this.currentCategory = null;
        this.categories = response || [];
      });
    }
  }
}
</code>```

Body:
I have a stack with vue js (vuetify) + laravel + axios.
I am trying to populate a dropdown select using axios.
I have setup an API route on laravel so I can pull data from database table "Categories".
The api return the following:

[
{
    "id": 1,
    "category_name": "Electronics",
    "category_synonym": "Computer Accessories",
    "created_at": "2020-05-31T20:11:56.000000Z",
    "updated_at": "2020-05-31T20:11:56.000000Z"
},
{
    "id": 2,
    "category_name": "Hardware",
    "category_synonym": "hardware",
    "created_at": "2020-05-31T20:17:13.000000Z",
    "updated_at": "2020-05-31T20:17:13.000000Z"
},
{
    "id": 3,
    "category_name": "Kitchenware",
    "category_synonym": null,
    "created_at": "2020-05-31T20:49:32.000000Z",
    "updated_at": "2020-05-31T20:49:32.000000Z"
},
{
    "id": 4,
    "category_name": "Textile",
    "category_synonym": null,
    "created_at": "2020-05-31T21:29:30.000000Z",
    "updated_at": "2020-05-31T21:29:30.000000Z"
}

]

I would like to put the category_name into a vue js dropdown contained into a foram.
How to make it simply ?

Body:
You can try something like this:

<v-select v-model="currentCategory" :items="resultFromAPI" item-text="category_name" item-value="id" />

To fetch the data with Axios you can try something like this:

import axios from 'axios';

const ajax = axios.create({
  baseURL: 'https://example.com/api',
  headers: {
    'Content-Type': 'application/json'
  }
});

export default
{
  data()
  {
    return {
      categories: [],
      currentCategory: null,
    }
  },
  mounted()
  {
    this.fetchData();
  },
  methods:
  {
    fetchData()
    {
      ajax.get('/categories').then(response =>
      {
        this.currentCategory = null;
        this.categories = response || [];
      });
    }
  }
}


问:
C printf optional decimal places
In C# I can do the following:

```<code>Console.Write("{0}, ", string.Format("{0:0.00###########}", someFloatValue));
</code>```

to get at least 2 decimal places for some arbitrary float value up to some certain number of optional decimal places, in this case 13.

I was wondering if the same was possible with printf in C?

答:
Lop off trailing zero digits.

```<code>void formatDouble(char* buf, double val, int precMin, int precMax) {
  int length = sprintf(buf, "%.*f", precMax, val);
  if (isfinite(val) && length > 0) {
    for (int i = precMax; i > precMin; i--) {
      if (buf[length - 1] == '0') {
        buf[--length] = '\0';
      } else {
        break;
      }
    }
  }
}

void fooo(double d) {
  char buf[100];
  formatDouble(buf, d, 2,6);
  printf("<%s>\n", buf);
}

int main(void) {
  fooo(0.1234567890);
  fooo(0.123450);
  fooo(0.12300);
}
</code>```

Output

```<code><0.123457>
<0.12345>
<0.123>
</code>```

Title: C printf optional decimal places

Body:
In C# I can do the following:

Console.Write("{0}, ", string.Format("{0:0.00###########}", someFloatValue));

to get at least 2 decimal places for some arbitrary float value up to some certain number of optional decimal places, in this case 13.

I was wondering if the same was possible with printf in C?

Body:
Lop off trailing zero digits.

void formatDouble(char* buf, double val, int precMin, int precMax) {
  int length = sprintf(buf, "%.*f", precMax, val);
  if (isfinite(val) && length > 0) {
    for (int i = precMax; i > precMin; i--) {
      if (buf[length - 1] == '0') {
        buf[--length] = '\0';
      } else {
        break;
      }
    }
  }
}

void fooo(double d) {
  char buf[100];
  formatDouble(buf, d, 2,6);
  printf("<%s>\n", buf);
}

int main(void) {
  fooo(0.1234567890);
  fooo(0.123450);
  fooo(0.12300);
}

Output

<0.123457>
<0.12345>
<0.123>


问:
How to make this with a for-loop?
Trying to make a batteship game and want to make the code more smooth...

```<code>#Board:
A = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"]
B = ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"]
C = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
D = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
E = ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"]
F = ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"]
G = ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"]
H = ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]
I = ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"]
J = ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]
print("\n",A,"\n",B,"\n",C,"\n",D,"\n",E,"\n",F,"\n",G,"\n",H,"\n",I,"\n",J)

#Variables
A_set = set(A)
B_set = set(B)
C_set = set(C)
D_set = set(D)
E_set = set(E)
F_set = set(F)
G_set = set(G)
H_set = set(H)
I_set = set(I)
J_set = set(J)
</code>```

When i check if the placed codinate are within the board I use this code:

```<code>def user_ship1():
    global nr1_user_ship
    nr1_user_ship = []
    print("Hide a ship within the board.")
    user_ship1 = input("")

    user_ship1 = user_ship1.capitalize()

    battlefield_check = set(user_ship1.split())

    within_battlefield0 = battlefield_check.intersection(A_set)
    within_battlefield1 = battlefield_check.intersection(B_set)
    within_battlefield2 = battlefield_check.intersection(C_set)
    within_battlefield3 = battlefield_check.intersection(D_set)
    within_battlefield4 = battlefield_check.intersection(E_set)
    within_battlefield5 = battlefield_check.intersection(F_set)
    within_battlefield6 = battlefield_check.intersection(G_set)
    within_battlefield7 = battlefield_check.intersection(H_set)
    within_battlefield8 = battlefield_check.intersection(I_set)
    within_battlefield9 = battlefield_check.intersection(J_set)

    if((within_battlefield0 == set()) and (within_battlefield1 == set()) and (within_battlefield2 == set()) and (within_battlefield3 == set()) and (within_battlefield4 == set()) and (within_battlefield5 == set()) and (within_battlefield6 == set()) and (within_battlefield7 == set()) and (within_battlefield8 == set()) and (within_battlefield9 == set())):
        print("Ship needs to be within the board.")
        exit()
    else:
        print("Great! Place another ship.")
    nr1_user_ship.append(user_ship1)
</code>```

So how can I use this in a forloop instead and how do I change the code so I don't use the "global" variable

Title: How to make this with a for-loop?

Body:
Trying to make a batteship game and want to make the code more smooth...

#Board:
A = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"]
B = ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"]
C = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
D = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"]
E = ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"]
F = ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"]
G = ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"]
H = ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"]
I = ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"]
J = ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]
print("\n",A,"\n",B,"\n",C,"\n",D,"\n",E,"\n",F,"\n",G,"\n",H,"\n",I,"\n",J)

#Variables
A_set = set(A)
B_set = set(B)
C_set = set(C)
D_set = set(D)
E_set = set(E)
F_set = set(F)
G_set = set(G)
H_set = set(H)
I_set = set(I)
J_set = set(J)

When i check if the placed codinate are within the board I use this code:

def user_ship1():
    global nr1_user_ship
    nr1_user_ship = []
    print("Hide a ship within the board.")
    user_ship1 = input("")

    user_ship1 = user_ship1.capitalize()

    battlefield_check = set(user_ship1.split())

    within_battlefield0 = battlefield_check.intersection(A_set)
    within_battlefield1 = battlefield_check.intersection(B_set)
    within_battlefield2 = battlefield_check.intersection(C_set)
    within_battlefield3 = battlefield_check.intersection(D_set)
    within_battlefield4 = battlefield_check.intersection(E_set)
    within_battlefield5 = battlefield_check.intersection(F_set)
    within_battlefield6 = battlefield_check.intersection(G_set)
    within_battlefield7 = battlefield_check.intersection(H_set)
    within_battlefield8 = battlefield_check.intersection(I_set)
    within_battlefield9 = battlefield_check.intersection(J_set)

    if((within_battlefield0 == set()) and (within_battlefield1 == set()) and (within_battlefield2 == set()) and (within_battlefield3 == set()) and (within_battlefield4 == set()) and (within_battlefield5 == set()) and (within_battlefield6 == set()) and (within_battlefield7 == set()) and (within_battlefield8 == set()) and (within_battlefield9 == set())):
        print("Ship needs to be within the board.")
        exit()
    else:
        print("Great! Place another ship.")
    nr1_user_ship.append(user_ship1)

So how can I use this in a forloop instead and how do I change the code so I don't use the "global" variable

Body:
Your code contains alot of boilerplate code, eg. code with repeated logic.

Imagine if you wanted to change the size of the board - that would take too much time with the code you are producing.

Replace your code with lists of lists like so:

board = [["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"],
         ["B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"],
         ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"],
         ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9"],
         ["E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9"],
         ["F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9"],
         ["G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"],
         ["H0", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9"],
         ["I0", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8", "I9"],
         ["J0", "J1", "J2", "J3", "J4", "J5", "J6", "J7", "J8", "J9"]]

print(board[0])
>>> ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']
print(board[0][0])
>>> A0

This allows for more compact code:

print(any('B4' in sublist for sublist in board))
>>> True
print(any('BB' in sublist for sublist in board))
>>> False


问:
Create Custom SQL Server Role in SQL 2008 Server
I want to add new custom SQL Server Role and assign the new users to these appropriate roles respectively.  I try to find how to create role, but I could not find the place to add that.  Could you please guide me how to achieve my requirement?</p>

答: You can create Database level roles see Create Role and the links on the page for more detail.</p>