问:
Displaying self referencing entity in twig
I'm trying to render a tree of links using Doctrine's self referencing association. I have an entity like:

```<code><?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="link")
 * @ORM\Entity(repositoryClass="App\Repository\LinkRepository")
 */
class Link
{
    /**
     * @ORM\Column(name="link_id", type="integer", nullable=false, options={"unsigned"=true})
         * @ORM\Id()
         * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $linkId;

    /**
     * @ORM\Column(name="name", type="string", length=50)
     */
    private $name;

    /**
     * @ORM\Column(name="url", type="string", length=500)
     */
    private $url;

    /**
     * @ORM\Column(name="parent_id", type="integer")
     */
    private $parentId;

    /**
     * @ORM\OneToMany(targetEntity="Link", mappedBy="parent")
     */
    private $children;

    /**
     * @ORM\ManyToOne(targetEntity="Link", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="link_id")
     */
    private $parent;

    public function __construct()
    {
        $this->children = new ArrayCollection();
    }

    public function getLinkId(): ?int
    {
        return $this->linkId;
    }

    // Getters and setters ...

    /**
     * @return ArrayCollection
     */
    public function getChildren()
    {
        return $this->children;
    }
}
</code>```

and in my controller I have it fetching the link and calling the twig template like:

```<code>public function link(int $linkId, LinkRepository $linkRepository)
{
    $link = $linkRepository->findOneBy(['linkId' => $linkId]);

    return $this->render('link.html.twig',
    [
        'link' => $link
    ]);
}
</code>```

And the twig template is something like this:

```<code>{% extends 'base.html.twig' %}

{% block body %}
    {{ link.name }}

    <h2>Children:</h2>

    {% import _self as macros %}
    <ul>
        <li>{{ link.name }}
            {{ macros.link_tree(link) }}
        </li>

    </ul>
{% endblock %}

{% macro link_tree(link) %}
    {% import _self as macros %}
    <ul>
    {% for linkChild in link.children %}
        <li>
            {{ link.name }}
            {% if linkChild.children %}
                <ul>
                    {{ macros.link_tree(linkChild.children) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
    </ul>
{% endmacro %}
</code>```

Although when I call this controller it gives me this error:

Neither the property "children" nor one of the methods "children()",
  "getchildren()"/"ischildren()"/"haschildren()" or "__call()" exist and
  have public access in class "Doctrine\ORM\PersistentCollection".

This seems to be when I make reference to linkChild.children in the twig template.

How can I loop recursively over children() in twig?

答:
So it turns out I was sending the wrong thing to the macro, it was expecting linkChild and I was passing linkChild.children. Inside the macro it was trying to reference linkChild.children.children

This was fixed by using:

```<code>{{ link.name }}
{% if linkChild.children %}
  <ul>
    {{ macros.link_tree(linkChild) }}
  </ul>
{% endif %}
</code>```

Body:
I'm trying to render a tree of links using Doctrine's self referencing association. I have an entity like:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="link")
 * @ORM\Entity(repositoryClass="App\Repository\LinkRepository")
 */
class Link
{
    /**
     * @ORM\Column(name="link_id", type="integer", nullable=false, options={"unsigned"=true})
         * @ORM\Id()
         * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $linkId;

    /**
     * @ORM\Column(name="name", type="string", length=50)
     */
    private $name;

    /**
     * @ORM\Column(name="url", type="string", length=500)
     */
    private $url;

    /**
     * @ORM\Column(name="parent_id", type="integer")
     */
    private $parentId;

    /**
     * @ORM\OneToMany(targetEntity="Link", mappedBy="parent")
     */
    private $children;

    /**
     * @ORM\ManyToOne(targetEntity="Link", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="link_id")
     */
    private $parent;

    public function __construct()
    {
        $this->children = new ArrayCollection();
    }

    public function getLinkId(): ?int
    {
        return $this->linkId;
    }

    // Getters and setters ...

    /**
     * @return ArrayCollection
     */
    public function getChildren()
    {
        return $this->children;
    }
}

and in my controller I have it fetching the link and calling the twig template like:

public function link(int $linkId, LinkRepository $linkRepository)
{
    $link = $linkRepository->findOneBy(['linkId' => $linkId]);

    return $this->render('link.html.twig',
    [
        'link' => $link
    ]);
}

And the twig template is something like this:

{% extends 'base.html.twig' %}

{% block body %}
    {{ link.name }}

Children:

    {% import _self as macros %}

{{ link.name }}
            {{ macros.link_tree(link) }}

{% endblock %}

{% macro link_tree(link) %}
    {% import _self as macros %}

    {% for linkChild in link.children %}

            {{ link.name }}
            {% if linkChild.children %}

                    {{ macros.link_tree(linkChild.children) }}

            {% endif %}

    {% endfor %}

{% endmacro %}

Although when I call this controller it gives me this error:

Neither the property "children" nor one of the methods "children()",
  "getchildren()"/"ischildren()"/"haschildren()" or "__call()" exist and
  have public access in class "Doctrine\ORM\PersistentCollection".

This seems to be when I make reference to linkChild.children in the twig template.

How can I loop recursively over children() in twig?

Body:
So it turns out I was sending the wrong thing to the macro, it was expecting linkChild and I was passing linkChild.children. Inside the macro it was trying to reference linkChild.children.children

This was fixed by using:

{{ link.name }}
{% if linkChild.children %}
  <ul>
    {{ macros.link_tree(linkChild) }}
  </ul>
{% endif %}


来源: stackexchange

问:
Tf in Visual Studio 2015 is not working
Using a fresh install of VS 2015, I am having a bunch of issues with TFS. Checkin Policies are broken, and TF command line is broken.

For example, going to Developer Command Prompt for VS2015 and typing tf causes a crash. It complains about not being able to access the Microsoft.TeamFoundation.Client.

```<code>Unhandled Exception: System.IO.FileNotFoundException: Could not load file or   assembly 'Microsoft.TeamFoundation.Client, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
</code>```

I believe that I understand that some of the needed dll's are not a part of the VS install, and are a nuget package.

[1] Where can I find Microsoft.TeamFoundation.VersionControl.Client.dll in Visual Studio 2015 installation?

[2]Where can I find Microsoft.TeamFoundation.Build.Client in Visual Studio 2015?

However installing the package via the command below does not fix access to tf.exe in the command line.

```<code>Install-Package Microsoft.TeamFoundationServer.ExtendedClient
</code>```

This all works no problem if you upgrade from VS 2012/2013 because the dll's are in the correct/old location.
Does anyone know how to fix this?

答:
Following worked for me:

1) Install TFS Power Tools 2015 (skip if Power Tools were already installed)

2) Open an elevated command prompt (cmd.exe)

3) Copy Dlls of power tools to the CommonExtensions\Microsoft\TeamFoundation\Team Explorer\ folder of VS2015

Example:

```<code>cd "C:\Program Files (x86)\Microsoft Team Foundation Server 2015 Power Tools"
copy *.dll "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\"
</code>```

Inside the "Microsoft Team Foundation Server 2015 Power Tools" folder you should see those missing dlls like Microsoft.TeamFoundation.Build.Client.dll, Microsoft.TeamFoundation.Build.Common.dll etc.

ContentLicense: CC BY-SA 3.0

Title: Tf in Visual Studio 2015 is not working

Body:
Using a fresh install of VS 2015, I am having a bunch of issues with TFS. Checkin Policies are broken, and TF command line is broken.

For example, going to Developer Command Prompt for VS2015 and typing tf causes a crash. It complains about not being able to access the Microsoft.TeamFoundation.Client.

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or   assembly 'Microsoft.TeamFoundation.Client, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I believe that I understand that some of the needed dll's are not a part of the VS install, and are a nuget package.

[1] Where can I find Microsoft.TeamFoundation.VersionControl.Client.dll in Visual Studio 2015 installation?

[2]Where can I find Microsoft.TeamFoundation.Build.Client in Visual Studio 2015?

However installing the package via the command below does not fix access to tf.exe in the command line.

Install-Package Microsoft.TeamFoundationServer.ExtendedClient

This all works no problem if you upgrade from VS 2012/2013 because the dll's are in the correct/old location.
Does anyone know how to fix this?

Body:
Following worked for me:

1) Install TFS Power Tools 2015 (skip if Power Tools were already installed)

2) Open an elevated command prompt (cmd.exe)

3) Copy Dlls of power tools to the CommonExtensions\Microsoft\TeamFoundation\Team Explorer\ folder of VS2015

Example:

cd "C:\Program Files (x86)\Microsoft Team Foundation Server 2015 Power Tools"
copy *.dll "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\"

Inside the "Microsoft Team Foundation Server 2015 Power Tools" folder you should see those missing dlls like Microsoft.TeamFoundation.Build.Client.dll, Microsoft.TeamFoundation.Build.Common.dll etc.

ContentLicense: CC BY-SA 4.0


问:
How can I solve this datatype problem with only one function,best with pattern matching
I'm doing my Haskell Datentyp homework, and have try to solve this problem for a whole day.

The question is like this .

Use this Datentyp and only one function tokenize, other functions in the library are not permitted.

```<code>data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
</code>```

The brace is the sign of Placeholder

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

I have tried for a whole day, only Text output or Placehold is OK, but I have several problems:

How to handle curly brackets {}

How to use pattern match to match "{longtext...}"

Because of Datentype [token],  tokenize (x: xs) = x :[ Text (xs:[])] do not works , so how to deal with it

how to combine the comma and all of them together, with only type [token] result function,I have tried ++ and : , but they all report error.

According to 4, there is a common question besides this homework: when using Datentype, and type of result doesn't fits type of input,  how to use recursion.

This is the last edition of my answer, it is still far away

```<code>data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize [] = []
tokenize ('{':x:xs) = [ Placeholder (x:xs)]
tokenize (x: xs) = [ Text (x:xs)]
otherwise = error "TODO: Implementierung vervollstaendigen"

</code>```

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

Suppose all the input without internal bracket and are correctly denoted by curly brackets{}

答:
Since we are writing a parser, we can benefit a great deal from using traditional parser techniques. The key point is that you want a parse function to parse only a part of the string at once, and so it is most convenient for it to return two things: the tokens parsed so far, and the remainder of the string: what's left to be parsed after handling those tokens.

So, our main recursive function will be

```<code>parse :: String -> (String, [Token])
</code>```

This signature does not match the required signature of tokenize, but it is easy to write tokenize to delegate to it:

```<code>tokenize :: String -> [Token]
tokenize s = case parse s of
  ("", r) -> r
  (s, r) -> error ("unexpected text " ++ s)
</code>```

Makes sense, right? If we parsed the stream and there's somehow text left, something went wrong; otherwise, the remainder is empty, so what's been parsed so far must be all of it.

parse itself is responsible for deciding, based on the first character it sees, whether to produce a Text or a Placeholder. In either case, it consumes the corresponding token, using break to identify the closing } (in the case of Placeholder), or the next opening { (in the case of Text). It conses the generated token onto the result of the recursive call to parse:

```<code>parse :: String -> (String, [Token])
parse "" = ("", [])
parse ('{':s) = let (name, ('}':s')) = break (== '}') s
                in (Placeholder name :) <$> parse s'
parse s = let (text, s') = break (== '{') s
          in (Text text :) <$> parse s'
</code>```

Note that there is a hidden failure mode here, not exposed in the type signature: if the input contains a { character with no matching }, we will have a runtime error. But the signature of tokenize gives us little other choice: we have no way to indicate an invalid parse in the result type, so we can either lie by claiming there was a valid parse, or terminate the program abnormally; I prefer the latter.

Body:
I'm doing my Haskell Datentyp homework, and have try to solve this problem for a whole day.

The question is like this .

Use this Datentyp and only one function tokenize, other functions in the library are not permitted.

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]

The brace is the sign of Placeholder

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

I have tried for a whole day, only Text output or Placehold is OK, but I have several problems:

How to handle curly brackets {}

How to use pattern match to match "{longtext...}"

Because of Datentype [token],  tokenize (x: xs) = x :[ Text (xs:[])] do not works , so how to deal with it

how to combine the comma and all of them together, with only type [token] result function,I have tried ++ and : , but they all report error.

According to 4, there is a common question besides this homework: when using Datentype, and type of result doesn't fits type of input,  how to use recursion.

This is the last edition of my answer, it is still far away

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize [] = []
tokenize ('{':x:xs) = [ Placeholder (x:xs)]
tokenize (x: xs) = [ Text (x:xs)]
otherwise = error "TODO: Implementierung vervollstaendigen"

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

Suppose all the input without internal bracket and are correctly denoted by curly brackets{}

Body:
Since we are writing a parser, we can benefit a great deal from using traditional parser techniques. The key point is that you want a parse function to parse only a part of the string at once, and so it is most convenient for it to return two things: the tokens parsed so far, and the remainder of the string: what's left to be parsed after handling those tokens.

So, our main recursive function will be

parse :: String -> (String, [Token])

This signature does not match the required signature of tokenize, but it is easy to write tokenize to delegate to it:

tokenize :: String -> [Token]
tokenize s = case parse s of
  ("", r) -> r
  (s, r) -> error ("unexpected text " ++ s)

Makes sense, right? If we parsed the stream and there's somehow text left, something went wrong; otherwise, the remainder is empty, so what's been parsed so far must be all of it.

parse itself is responsible for deciding, based on the first character it sees, whether to produce a Text or a Placeholder. In either case, it consumes the corresponding token, using break to identify the closing } (in the case of Placeholder), or the next opening { (in the case of Text). It conses the generated token onto the result of the recursive call to parse:

parse :: String -> (String, [Token])
parse "" = ("", [])
parse ('{':s) = let (name, ('}':s')) = break (== '}') s
                in (Placeholder name :) <$> parse s'
parse s = let (text, s') = break (== '{') s
          in (Text text :) <$> parse s'

Note that there is a hidden failure mode here, not exposed in the type signature: if the input contains a { character with no matching }, we will have a runtime error. But the signature of tokenize gives us little other choice: we have no way to indicate an invalid parse in the result type, so we can either lie by claiming there was a valid parse, or terminate the program abnormally; I prefer the latter.


问:
How to pass parameter dynamically to JQuery click event from HTML elements?
First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.

Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:

I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.

Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.

This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).

```<code><ul>
    <li class="item">Item1</li> <!-- this item has id=1 in the database -->
    <li class="item">Item2</li> <!-- this item has id=2 in the database -->
    <li class="item">Item3</li> <!-- this item has id=3 in the database -->
</ul>
</code>```

Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.

```<code>    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $(".item").click(function() {
                var item_id = ??
                var data = {"item_id":item_id};
                $.getJSON("/item/json", data, function(data) {
                    var name = data[0]["fields"]["name"]
                    var description = data[0]["fields"]["description"]
                    popup.call(this, name, description);
                });
            });
        });
    </script>
</code>```

Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.

Here is an example that is similar to what I am looking for.

http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P

答: If your item names are unique, then send the item names via Ajax.That way you can avoid Item ID's.</p>

Body:
First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.

Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:

I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.

Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.

This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).

Item1

Item2

Item3

Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.

Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.

Here is an example that is similar to what I am looking for.

http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P


问:
Linking Button Onclick With Select Menu Onchange
I currently have a select menu that has an onchange function that will print an HTML message when a new option is selected. I also have a button that has an onclick function that will change the current celected option in the select menu, however, when the button is clicked and the select menu is changed, the onchange function does not initiate. How can I get the onchange function to work when I click the button? I do not want to merely initiate the onchange function as an onclick option in the button because I want to change the select menu as well.</p>

```<code><html>
    <select id="sel" onchange='myFunction()'>
        <option value="car">1</option>
        <option value="bike">2</option>
        <option value="cycle">3</option>
    </select>

    <button onclick='selectChange()'>Click me</button>

    <p id="demo"></p>

    <script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "Hello World";
    }

    function selectChange(){
        document.getElementById('sel').value = "bike";
    }
    </script>
</html>
</code>```

答:
Simply call myFunction() from within selectChange():

<select id="sel" onchange='myFunction()'>
  <option value="car">1</option>
  <option value="bike">2</option>
  <option value="cycle">3</option>
</select>

<button onclick='selectChange()'>Click me</button>

```
</div>
</div>
</p>

<p>Note, however, that you should also make use of <em>Unobstructive JavaScript</em>, and use <em>event listeners</em> rather than <code>onchange</code> and <code>onclick</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById('sel').addEventListener('change', myFunction);
document.getElementsByTagName('button')[0].addEventListener('click', selectChange);

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}

function selectChange() {
  document.getElementById('sel').value = "bike";
  myFunction();
}</code>```

<select id="sel">
  <option value="car">1</option>
  <option value="bike">2</option>
  <option value="cycle">3</option>
</select>

<button>Click me</button>

```

Body:
I currently have a select menu that has an onchange function that will print an HTML message when a new option is selected. I also have a button that has an onclick function that will change the current celected option in the select menu, however, when the button is clicked and the select menu is changed, the onchange function does not initiate. How can I get the onchange function to work when I click the button? I do not want to merely initiate the onchange function as an onclick option in the button because I want to change the select menu as well.

    <select id="sel" onchange='myFunction()'>
        <option value="car">1</option>
        <option value="bike">2</option>
        <option value="cycle">3</option>
    </select>

    <button onclick='selectChange()'>Click me</button>

Body:
Simply call myFunction() from within selectChange():

<html>
<select id="sel" onchange='myFunction()'>
  <option value="car">1</option>
  <option value="bike">2</option>
  <option value="cycle">3</option>
</select>

<button onclick='selectChange()'>Click me</button>

<p id="demo"></p>

<script>
  function myFunction() {
    document.getElementById("demo").innerHTML = "Hello World";
  }

  function selectChange() {
    document.getElementById('sel').value = "bike";
     myFunction();
  }
</script>

</html>

Note, however, that you should also make use of Unobstructive JavaScript, and use event listeners rather than onchange and onclick:

document.getElementById('sel').addEventListener('change', myFunction);
document.getElementsByTagName('button')[0].addEventListener('click', selectChange);

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}

function selectChange() {
  document.getElementById('sel').value = "bike";
  myFunction();
}

<select id="sel">
  <option value="car">1</option>
  <option value="bike">2</option>
  <option value="cycle">3</option>
</select>

<button>Click me</button>

<p id="demo"></p>


问:
Click and drag scroll to have momentum when releasing
Two things I need are that you could choose the speed of the scroll when dragging and upon release it would still move a bit, not stop instantly.

codepen: https://codepen.io/rKaiser/pen/qGomdR

I can set the speed close enough. Reasonable to add some momentum? or perhaps there is a more fitting plugin to use here? Thanks.

```<code>const slider = document.querySelector('.container');
let isDown = false;
let startX;
let scrollLeft;
slider.addEventListener('mousedown', (e) => {
  isDown = true;
  slider.classList.add('active');
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
});
slider.addEventListener('mouseleave', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mousemove', (e) => {
  if(!isDown) return;
  e.preventDefault();
  const x = e.pageX - slider.offsetLeft;
  const walk = (x - startX) * 0.3; //scroll-speed
  slider.scrollLeft = scrollLeft - walk;
});
</code>```

答:
You need to increase scrollLeft with certain amount with every frame, after mouseup, till speed becomes 0. Something like=></p>

```<code>slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
  speed = (-scrollLeft+slider.scrollLeft)/(new Date()-t)*500; //t is time of mouse down start

  const draw=()=>{
    if(speed>0){
      slider.scrollLeft = slider.scrollLeft + speed--; //increase by certain amount
    }else{
      momentum=false;
    }
    requestAnimationFrame(draw);
  }
    momentum=true;
    draw();
});

slider.addEventListener('mousemove', (e) => {
  if(!isDown && !momentum){
    return;
  }..
</code>```

Body:
Two things I need are that you could choose the speed of the scroll when dragging and upon release it would still move a bit, not stop instantly.

codepen: https://codepen.io/rKaiser/pen/qGomdR

I can set the speed close enough. Reasonable to add some momentum? or perhaps there is a more fitting plugin to use here? Thanks.

const slider = document.querySelector('.container');
let isDown = false;
let startX;
let scrollLeft;
slider.addEventListener('mousedown', (e) => {
  isDown = true;
  slider.classList.add('active');
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
});
slider.addEventListener('mouseleave', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mousemove', (e) => {
  if(!isDown) return;
  e.preventDefault();
  const x = e.pageX - slider.offsetLeft;
  const walk = (x - startX) * 0.3; //scroll-speed
  slider.scrollLeft = scrollLeft - walk;
});

Body:
You need to increase scrollLeft with certain amount with every frame, after mouseup, till speed becomes 0. Something like=>

slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
  speed = (-scrollLeft+slider.scrollLeft)/(new Date()-t)*500; //t is time of mouse down start

  const draw=()=>{
    if(speed>0){
      slider.scrollLeft = slider.scrollLeft + speed--; //increase by certain amount
    }else{
      momentum=false;
    }
    requestAnimationFrame(draw);
  }
    momentum=true;
    draw();
});

slider.addEventListener('mousemove', (e) => {
  if(!isDown && !momentum){
    return;
  }..


问:
A problem with optimization of function that contains loops
I have a problem with optimizing of a function that contains loops.
I start with paricular lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]
of floats and the intervals `(0,k*0.0025),(0.005,k*0.005),(0.005,k*0.0125), where upper border depends. So, depending on which of the interval the float of list belong to, I assign to the function one of values k*0.005,k*0.01,k*0.025 and k*0.05 that also depend on k.

I want to minimize k such that the sum (new scalar function) of values of assign(k) or sum(assign(k)) is equal to 0.32.

I used scipy.optimize procedure to do that. My constraint is constraint=sum(assign(k))-0.32 and objective function iz fun(k)=k. So, I minimized k to satisfy the constraint.

```<code>import scipy
from scipy.optimize import minimize

lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]

def assign(k):
    return list(map(lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001)
    else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in
    np.arange(0.005,k*0.0125,0.001) else k*0.05), lista))

def constraint(k):
    return sum(assign(k))-0.32

def fun(k):
    return k

k0=0
bnds=[(0,10)]
cons={'type':'eq','fun':constraint}
res=minimize(fun,k0,bounds=bnds,method='SLSQP',constraints=cons,options={'maxiter':2000})
print(res)
</code>```

I got k=1.1999 which is a strange result, it does not satisfy the constraint. It should be 2 since sum(assign(2))=0.52.
I also got a error message:

```<code>  message: 'Iteration limit exceeded'
</code>```

Does anyone knows how to overcome this limitation?
Thank you in advance!

答:
You wrote:

```<code>lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001)
else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in
np.arange(0.005,k*0.0125,0.001) else k*0.05)
</code>```

Please don't do that.
A short lambda function is fine,
but this one is long enough to deserve a name and a readable function definition:

```<code>def assign1(x, k):
    if x in np.arange(0, k * 0.0025, 0.001):
        return k * .01
    if x in np.arange(0.0025, k * 0.005, 0.001):
        return k * .025
    ...
</code>```

But having taken a moment to start writing that out, it immediately appears to be wrong.

I cannot believe you meant .0025, rather than k * .0025, as a lower bound.

Suppose some random noise is added, so rather than x we have x + epsilon. Then your function returns a constant of 5% of k, which seems Bad.

In general, we do not expect that int(x * 1000) == x.
So code it using proper ranges:

```<code>def assign1(x, k):
    if 0 <= x < k * .0025:
        return k * .01
    if k * .0025 <= x < k * .0050:
        return k * .025
    ...
</code>```

Supply a better constraint and I believe you will be happier
with how the optimizer converges.

EDIT

The optimization tutorial suggests that for this SLSQP method
you should be passing in both fun and jac.

Also, the full_output=True exit mode
offers diagnostic advice about what went wrong.

Body:
I have a problem with optimizing of a function that contains loops.
I start with paricular lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]
of floats and the intervals `(0,k*0.0025),(0.005,k*0.005),(0.005,k*0.0125), where upper border depends. So, depending on which of the interval the float of list belong to, I assign to the function one of values k*0.005,k*0.01,k*0.025 and k*0.05 that also depend on k.

I want to minimize k such that the sum (new scalar function) of values of assign(k) or sum(assign(k)) is equal to 0.32.

I used scipy.optimize procedure to do that. My constraint is constraint=sum(assign(k))-0.32 and objective function iz fun(k)=k. So, I minimized k to satisfy the constraint.

import scipy
from scipy.optimize import minimize

lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]

def assign(k):
    return list(map(lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001)
    else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in
    np.arange(0.005,k*0.0125,0.001) else k*0.05), lista))

def constraint(k):
    return sum(assign(k))-0.32

def fun(k):
    return k

k0=0
bnds=[(0,10)]
cons={'type':'eq','fun':constraint}
res=minimize(fun,k0,bounds=bnds,method='SLSQP',constraints=cons,options={'maxiter':2000})
print(res)

I got k=1.1999 which is a strange result, it does not satisfy the constraint. It should be 2 since sum(assign(2))=0.52.
I also got a error message:

  message: 'Iteration limit exceeded'

Does anyone knows how to overcome this limitation?
Thank you in advance!

Body:
You wrote:

lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001)
else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in
np.arange(0.005,k*0.0125,0.001) else k*0.05)

Please don't do that.
A short lambda function is fine,
but this one is long enough to deserve a name and a readable function definition:

def assign1(x, k):
    if x in np.arange(0, k * 0.0025, 0.001):
        return k * .01
    if x in np.arange(0.0025, k * 0.005, 0.001):
        return k * .025
    ...

But having taken a moment to start writing that out, it immediately appears to be wrong.

I cannot believe you meant .0025, rather than k * .0025, as a lower bound.

Suppose some random noise is added, so rather than x we have x + epsilon. Then your function returns a constant of 5% of k, which seems Bad.

In general, we do not expect that int(x * 1000) == x.
So code it using proper ranges:

def assign1(x, k):
    if 0 <= x < k * .0025:
        return k * .01
    if k * .0025 <= x < k * .0050:
        return k * .025
    ...

Supply a better constraint and I believe you will be happier
with how the optimizer converges.

EDIT

The optimization tutorial suggests that for this SLSQP method
you should be passing in both fun and jac.

Also, the full_output=True exit mode
offers diagnostic advice about what went wrong.


问:
display picture
hi everybody
i'm trying to get bmp file then display it and i should do this by get header information of bmp and load it pixel by pixel in to an array then set pixel to display bmp picture without using bitmap class.

```<code>enter code here
enter code here  public void display(String filename)
    {

        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        string headerCode = br.ReadChar().ToString() + br.ReadChar().ToString();
        MessageBox.Show(headerCode);
        if (headerCode == "BM")
        {
            int bfSize = br.ReadInt32();
            int bfReserved1 = br.ReadInt16();
            int bfReserved2 = br.ReadInt16();
            int bfoffbits = br.ReadInt32();
            int biSize = br.ReadInt32();
            int biWidth = br.ReadInt32();
            int biHeight = br.ReadInt32();
            int biPlanes = br.ReadInt16();
            int biBitCount = br.ReadInt16();
            int biCompression = br.ReadInt32();
            int biSizeImage = br.ReadInt32();
            int biXPelsPerMeter = br.ReadInt32();
            int biYPelsPerMeter = br.ReadInt32();
            int biClrUsed = br.ReadInt32();
            int biClrImportant = br.ReadInt32();
            int rgbRed = 0;
            int rgbGreen = 0;
            int rgbBlue = 0;
            Bitmap bmp = new Bitmap(biWidth, biHeight);
             PictureBox1.Size = new System.Drawing.Size(biWidth, biHeight);

            try
            {

                PictureBox1.Image = bmp;
</code>```

i should do this but no with bitmap class and buffer , ishould get the  header of bmp file and load it in the array then read the file to get the height and width and other information that need to display bmp pixel by oixel but without using bitmap class

答: I would load the bitmap into c# and then convert it to jpg/png etc. Bmp is not good for web as they are way to big.</p>

Title: display picture

Body:
hi everybody
i'm trying to get bmp file then display it and i should do this by get header information of bmp and load it pixel by pixel in to an array then set pixel to display bmp picture without using bitmap class.

enter code here
enter code here  public void display(String filename)
    {

        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        string headerCode = br.ReadChar().ToString() + br.ReadChar().ToString();
        MessageBox.Show(headerCode);
        if (headerCode == "BM")
        {
            int bfSize = br.ReadInt32();
            int bfReserved1 = br.ReadInt16();
            int bfReserved2 = br.ReadInt16();
            int bfoffbits = br.ReadInt32();
            int biSize = br.ReadInt32();
            int biWidth = br.ReadInt32();
            int biHeight = br.ReadInt32();
            int biPlanes = br.ReadInt16();
            int biBitCount = br.ReadInt16();
            int biCompression = br.ReadInt32();
            int biSizeImage = br.ReadInt32();
            int biXPelsPerMeter = br.ReadInt32();
            int biYPelsPerMeter = br.ReadInt32();
            int biClrUsed = br.ReadInt32();
            int biClrImportant = br.ReadInt32();
            int rgbRed = 0;
            int rgbGreen = 0;
            int rgbBlue = 0;
            Bitmap bmp = new Bitmap(biWidth, biHeight);
             PictureBox1.Size = new System.Drawing.Size(biWidth, biHeight);

            try
            {

                PictureBox1.Image = bmp;

i should do this but no with bitmap class and buffer , ishould get the  header of bmp file and load it in the array then read the file to get the height and width and other information that need to display bmp pixel by oixel but without using bitmap class


问:
Linked list, count even and uneven positions, unsing recursion
I want to create two methods, "private int sumEven (Node node){}" for suming up even positions in a linked list and "sumOdd (Node node) {}" for suming up odd positions. I want to use recursion.

This is how far i've come, but i dont know what should I do next.
Does any one have a tipp or a hint for me, what should i do next?

```<code>public class RecursiveListTest {
   static Node head;
   static boolean found = false;
   static int counter = 0;

   public static void main(String[] args) {
       RecursiveListTest list = new RecursiveListTest();

       list.addNumber(3);
       list.addNumber(5);
       list.addNumber(2);
       list.addNumber(7);
       list.addNumber(5);
       list.addNumber(1);
       list.addNumber(4);
       list.printList();

       int sumEven = list.sumEven(head);
       int sumOdd = list.sumOdd(head);

       System.out.println();
       System.out.println("Sum of even Positions: " + sumEven);
       System.out.println();
       System.out.println("Sum of odd Positions: " + sumOdd);
       System.out.println();
   }

   // Node
   private class Node {
       Node next;
       int value;

       Node(int value, Node next) {
           this.value = value;
           this.next = next;
       }
   }

   private int sumEven(Node n) {
       int sumEven = 0;
       int sumOdd = 0;

       counter = counter + 1;

       if (counter % 2 == 0) {
           sumEven = sumEven + n.value;
           if (n.next.next != null) {
               sumEven = sumEven + sumEven(n.next.next);
           }
       }

       else if (counter % 2 == 1) {
           if (n.next != null) {
               sumEven = sumEven + sumEven(n.next);
           }
       }

       return sumEven;
   }

   private int sumOdd(Node n) {
       return 0;
   }

   private void addNumber(int number) {
       Node curr = head;
       Node prev = null;

       if (head == null) {
           head = new Node(number, null);
       } else {
           while (curr != null) {
               prev = curr;
               curr = curr.next;
           }

           Node newNode = new Node(number, null);
           prev.next = newNode;
       }
   }

   private void printList() {
       Node curr = head;
       Node prev = null;

       while (curr != null) {
           System.out.print(curr.value + " ");

           prev = curr;
           curr = curr.next;
       }
   }
}
</code>```

答:
You should consider using variables private static int evenSum, oddSum and your methods could be:

```<code>private int sumEven() {

    evenSum = 0;
    sumEvenHelper(head);
    return evenSum;

}

private int sumOdd() {

    oddSum = 0;
    sumEvenHelper(head);
    return oddSum;

}

private void sumEvenHelper(Node n) {

    if(n != null) {

        evenSum += n.value;
        sumOddHelper(n.next);

    }

}

private void sumOddHelper(Node n) {

    if(n != null) {

        oddSum += n.value;
        sumEvenHelper(n.next);

    }

}
</code>```

My code assumes head is list element 0. Otherwise you will call sumOddHelper(head) inside the sumEven and sumOdd methods.

Body:
I want to create two methods, "private int sumEven (Node node){}" for suming up even positions in a linked list and "sumOdd (Node node) {}" for suming up odd positions. I want to use recursion.

This is how far i've come, but i dont know what should I do next.
Does any one have a tipp or a hint for me, what should i do next?

public class RecursiveListTest {
   static Node head;
   static boolean found = false;
   static int counter = 0;

   public static void main(String[] args) {
       RecursiveListTest list = new RecursiveListTest();

       list.addNumber(3);
       list.addNumber(5);
       list.addNumber(2);
       list.addNumber(7);
       list.addNumber(5);
       list.addNumber(1);
       list.addNumber(4);
       list.printList();

       int sumEven = list.sumEven(head);
       int sumOdd = list.sumOdd(head);

       System.out.println();
       System.out.println("Sum of even Positions: " + sumEven);
       System.out.println();
       System.out.println("Sum of odd Positions: " + sumOdd);
       System.out.println();
   }

   // Node
   private class Node {
       Node next;
       int value;

       Node(int value, Node next) {
           this.value = value;
           this.next = next;
       }
   }

   private int sumEven(Node n) {
       int sumEven = 0;
       int sumOdd = 0;

       counter = counter + 1;

       if (counter % 2 == 0) {
           sumEven = sumEven + n.value;
           if (n.next.next != null) {
               sumEven = sumEven + sumEven(n.next.next);
           }
       }

       else if (counter % 2 == 1) {
           if (n.next != null) {
               sumEven = sumEven + sumEven(n.next);
           }
       }

       return sumEven;
   }

   private int sumOdd(Node n) {
       return 0;
   }

   private void addNumber(int number) {
       Node curr = head;
       Node prev = null;

       if (head == null) {
           head = new Node(number, null);
       } else {
           while (curr != null) {
               prev = curr;
               curr = curr.next;
           }

           Node newNode = new Node(number, null);
           prev.next = newNode;
       }
   }

   private void printList() {
       Node curr = head;
       Node prev = null;

       while (curr != null) {
           System.out.print(curr.value + " ");

           prev = curr;
           curr = curr.next;
       }
   }
}

Body:
You should consider using variables private static int evenSum, oddSum and your methods could be:

private int sumEven() {

    evenSum = 0;
    sumEvenHelper(head);
    return evenSum;

}

private int sumOdd() {

    oddSum = 0;
    sumEvenHelper(head);
    return oddSum;

}

private void sumEvenHelper(Node n) {

    if(n != null) {

        evenSum += n.value;
        sumOddHelper(n.next);

    }

}

private void sumOddHelper(Node n) {

    if(n != null) {

        oddSum += n.value;
        sumEvenHelper(n.next);

    }

}

My code assumes head is list element 0. Otherwise you will call sumOddHelper(head) inside the sumEven and sumOdd methods.


问:
How do I use darknet architecture for image classification with fastai
I could make training run with for example squeezenet, but I'm new to this so I'm not able to figure out what other architectures (like darknet, xception or xresnet) require to be instantiated successfully.

In my notebook I tried:

```<code>arch = models.Darknet(num_classes = 2, num_blocks = 4) // whats numblocks
learn2 = cnn_learner(data = data, base_arch = arch , metrics=[accuracy, error_rate], pretrained = True)
</code>```

I get error:

```<code>----> 1 arch = models.Darknet(num_classes = 2,num_blocks = 4)
      2 learn2 = cnn_learner(data = data, base_arch = arch , metrics=[accuracy, error_rate], pretrained = True)

/usr/local/lib/python3.6/dist-packages/fastai/vision/models/darknet.py in __init__(self, num_blocks, num_classes, nf)
     31         super().__init__()
     32         layers = [conv_bn_lrelu(3, nf, ks=3, stride=1)]
---> 33         for i,nb in enumerate(num_blocks):
     34             layers += self.make_group_layer(nf, nb, stride=2-(i==1))
     35             nf *= 2

TypeError: 'int' object is not iterable```

```

答:
From the docs

Create a Darknet with blocks of sizes given in num_blocks, ending with
  num_classes and using nf initial features. Darknet53 uses num_blocks =
  [1,2,8,8,4].

learn more about darknet here

Body:
I could make training run with for example squeezenet, but I'm new to this so I'm not able to figure out what other architectures (like darknet, xception or xresnet) require to be instantiated successfully.

In my notebook I tried:

arch = models.Darknet(num_classes = 2, num_blocks = 4) // whats numblocks
learn2 = cnn_learner(data = data, base_arch = arch , metrics=[accuracy, error_rate], pretrained = True)

I get error:

----> 1 arch = models.Darknet(num_classes = 2,num_blocks = 4)
      2 learn2 = cnn_learner(data = data, base_arch = arch , metrics=[accuracy, error_rate], pretrained = True)

/usr/local/lib/python3.6/dist-packages/fastai/vision/models/darknet.py in __init__(self, num_blocks, num_classes, nf)
     31         super().__init__()
     32         layers = [conv_bn_lrelu(3, nf, ks=3, stride=1)]
---> 33         for i,nb in enumerate(num_blocks):
     34             layers += self.make_group_layer(nf, nb, stride=2-(i==1))
     35             nf *= 2

TypeError: 'int' object is not iterable```


问:
create a vue component using another page
How to load divs from page 2 into page 1 with VueJs.

localhost/getnew

```<code><html>
<head>
<title> title </title>
<body>
<div id="main">
<div id="content2"> this is content2</div>
<div id="content3"> this is content3</div>
</div>
</body>
</html>
</code>```

I want to get and use the id content2 from getnew to create a div into home with the content of that div, after the link was clicked and deleted, and do the same with content3, content4 and successively.

localhost/homepage

```<code><html>
<head>
<title> title </title>
<body>
<div id="main">
<div id="content1"> this is content1</div>
<a href="#"> get content</a>
</div>
</body>
</html>
</code>```

And then would be like that.

```<code><html>
<head>
<title> title </title>
<body>
<div id="main">
<div id="content1"> this is content1</div>
<div>this is content2</div>
<div>this is content3</div>
</div>
</body>
</html>
</code>```

I'm new in VueJs and I have no idea how to do that. If someone can help. Thanks.

答:
In Vue, like in most SPA's, the page (DOM) doesn't hold data.

The page is a rendering tool which displays data held in the source. The source can be:

local data, kept in vm.data() (typically holding specific data for current component - it can be passed down to child components, though)

global data, held in a specialized module for holding data and managing state, passed to vm through computed (getters).

This specialized data module is called Vuex.

You interact with it dispatching actions, which commit mutations to Vuex state.

Any component, on any page, listening to the the Vuex data will be updated automatically on any change, regardless of which component triggered the mutation.

If your data is not overly complex, you might be able to manage it without Vuex, using a simple state management pattern.

So, in a nutshell, you don't get the div with some #id from one page to another. You just mutate the store and then everywhere that data is used it updates.

Body:
How to load divs from page 2 into page 1 with VueJs.

localhost/getnew

<title> title </title>

 this is content2

 this is content3

I want to get and use the id content2 from getnew to create a div into home with the content of that div, after the link was clicked and deleted, and do the same with content3, content4 and successively.

localhost/homepage

<title> title </title>

 this is content1

 get content

And then would be like that.

<title> title </title>

 this is content1

this is content2

this is content3

I'm new in VueJs and I have no idea how to do that. If someone can help. Thanks.


问:
How to print out for loop of table values in flask/python
So I have two arrays of data. One has a list of bot_ids, The other has names.

Im trying to print out the arrays to an html page in table format.

I want the html to have one row with the names and then another row with the bot_id.

I tried doing two loops. One loop is the for names, the other is for the ids. I also tried doing doing one loop with both bot_ids and names but It

```<code>names = []
bot_ids = []
for item in data['response']:
    name = item['name']
    bot_id = item['bot_id']
    names.append(name)
    bot_ids.append(bot_id)

print names
print bot_ids

return render_template("ids.html", data=bot_ids, theNames=names) for 2 separate arrays so it wont work.

<table>
 <tr>
  <th> Names </th>
  <th> Bot Ids </th>
 </tr>
    {%for names in theNames%}
    {%for ids in data%}
  <tr>
    <td> {{names}} </td>
    <td> {{ids}} </td>
  </tr>
  {%endfor%}
  {%endfor%}

</table>
</code>```

The problem that I ran into was that it would print out DUPLICATES of the ids and names. The html ended up looking like this:

```<code>Names   Bot Ids
Johnny Five 240b08e530d42f286f30a75379
Johnny Five 64395a02a9382796f7cd7616ef
Johnny Five 42aacdb69615721d68c31d71c0
Johnny Five d45a95b6bbb344639104fd6a3a
Johnny Five 240b08e530d42f286f30a75379
Johnny Five 64395a02a9382796f7cd7616ef
Johnny Five 42aacdb69615721d68c31d71c0
Johnny Five d45a95b6bbb344639104fd6a3a
suck ya mom 240b08e530d42f286f30a75379
suck ya mom 64395a02a9382796f7cd7616ef
suck ya mom 42aacdb69615721d68c31d71c0
suck ya mom d45a95b6bbb344639104fd6a3a
The goat    240b08e530d42f286f30a75379
The goat    64395a02a9382796f7cd7616ef
The goat    42aacdb69615721d68c31d71c0
The goat    d45a95b6bbb344639104fd6a3a
</code>```

I want it to only print out the elements once each time but its producing many duplicates

the first code fence IS whats running in the app.py file
The second part is what is in the html file.

答:
You are doing 2 loops of the same length. You should zip them together and do it in one loop:

```<code>  {%for id, name in zip(data, theNames)%}
<tr>
  <td> {{id}} </td>
  <td> {{name}} </td>
</tr>
  {%endfor%}
</code>```

The indentation may need fixing but that should work.

Body:
So I have two arrays of data. One has a list of bot_ids, The other has names.

Im trying to print out the arrays to an html page in table format.

I want the html to have one row with the names and then another row with the bot_id.

I tried doing two loops. One loop is the for names, the other is for the ids. I also tried doing doing one loop with both bot_ids and names but It

names = []
bot_ids = []
for item in data['response']:
    name = item['name']
    bot_id = item['bot_id']
    names.append(name)
    bot_ids.append(bot_id)

print names
print bot_ids

return render_template("ids.html", data=bot_ids, theNames=names) for 2 separate arrays so it wont work.

   Names
   Bot Ids

    {%for names in theNames%}
    {%for ids in data%}

     {{names}}
     {{ids}}

  {%endfor%}
  {%endfor%}

The problem that I ran into was that it would print out DUPLICATES of the ids and names. The html ended up looking like this:

Names   Bot Ids
Johnny Five 240b08e530d42f286f30a75379
Johnny Five 64395a02a9382796f7cd7616ef
Johnny Five 42aacdb69615721d68c31d71c0
Johnny Five d45a95b6bbb344639104fd6a3a
Johnny Five 240b08e530d42f286f30a75379
Johnny Five 64395a02a9382796f7cd7616ef
Johnny Five 42aacdb69615721d68c31d71c0
Johnny Five d45a95b6bbb344639104fd6a3a
suck ya mom 240b08e530d42f286f30a75379
suck ya mom 64395a02a9382796f7cd7616ef
suck ya mom 42aacdb69615721d68c31d71c0
suck ya mom d45a95b6bbb344639104fd6a3a
The goat    240b08e530d42f286f30a75379
The goat    64395a02a9382796f7cd7616ef
The goat    42aacdb69615721d68c31d71c0
The goat    d45a95b6bbb344639104fd6a3a

I want it to only print out the elements once each time but its producing many duplicates

the first code fence IS whats running in the app.py file
The second part is what is in the html file.

Body:
You are doing 2 loops of the same length. You should zip them together and do it in one loop:

  {%for id, name in zip(data, theNames)%}
<tr>
  <td> {{id}} </td>
  <td> {{name}} </td>
</tr>
  {%endfor%}

The indentation may need fixing but that should work.


问:
WAMP - PHP loads too many Extensions
i am using WAMP 2.1 with

Apache Version :   2.2.17

PHP Version :    5.3.3

MySQL Version :  5.5.8

By default WAMP loads these extensions

      Core, bcmath, calendar, com_dotnet, ctype, date, ereg, filter, tp, hash, iconv, json, mcrypt, session, odbc, pcre, Reflection, standard, SPL, mysqlnd, tokenizer, zip, zlib, libxml, dom, PDO, Phar, SimpleXML, wddx, xml, xmlreader, xmlwriter, apache2handler, gd, mbstring, mysql, mysqli, mhash

i really dont need all these !
so i opened PHP.INI and put a ; before those  lines which i dont want, so now it looks like
;extension=php_zip.dll but WAMP still shows ZIP extensions as loaded !

what is wrong ?

i restarted WAMP but with no effect !

答:
To be able to change extension loading settings, you MUST run WampServer as administrator. (Right Click WampServer shortcut -> Run As Administrator). This should work now.

Click the Wamp icon in the system tray, then click PHP > PHP Extensions and try checking/unchecking the items there. This should work. <-- Checking/unchecking these items is the same as editing php.ini

Title: WAMP - PHP loads too many Extensions


问:
Will Google Cloud Run support GPU/TPU some day?
So far Google Cloud Run support CPU. Is there any plan to support GPU? It would be super cool if GPU available, then I can demo the DL project without really running a super expensive GPU instance.</p>

答:
So far Google Cloud Run support CPU. Is there any plan to support GPU?
  It would be super cool if GPU available, then I can demo the DL
  project without really running a super expensive GPU instance.

I seriously doubt it. GPU/TPUs are specialized hardware. Cloud Run is a managed container service that:

Enables you to run stateless containers that are invokable via HTTP requests. This means that CPU intensive applications are not supported. Inbetween HTTP request/response the CPU is idled to near zero. Your expensive GPU/TPUs would sit idle.

Autoscales based upon the number of requests per second. Launching 10,000 instances in seconds is easy to achieve. Imagine the billing support nightmare for Google if customers could launch that many GPU/TPUs and the size of the bills.

Is billed in 100 ms time intervals. Most requests fit into a few hundred milliseconds of execution. This is not a good execution or business model for CPU/GPU/TPU integration.

Provides a billing model which significantly reduces the cost of web services to near zero when not in use. You just pay for the costs to store your container images. When an HTTP request is received at the service URL, the container image is loaded into an execution unit and processing requests resume. Once requests stop, billing and resource usage also stop.

GPU/TPU types of data processing are best delivered by backend instances that protect and manage the processing power and costs that these processor devices provide.


问:
Flutter app doesn't show images larger than 2Mb
I made a simple app that selects images from the mobile phone gallery and places them in an Image.file. works well for images less than 2Mb. When I select an image larger than 2Mb, it simply doesn't show it and does not send me an error message.

I'm using the image_picker package.

File image;
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar( title: Text(widget.title), ),
    body: Center(
      child: image == null ?
        Text('Select an image')
      :
        Image.file(
          image,
          height: 350.0,
          width: 200.0,
          fit: BoxFit.cover,
        )
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () async {
        var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);
        setState(() => image = tempImage);
      },
      child: Icon(Icons.image),
    ),
  );
}
```

答: Have you tried placing the image in a container instead of relying on the image constraints? </p>


问:
How to Use posix_spawn() in Java
I've inherited a legacy application that uses ProcessBuilder.start() to execute a script on a Solaris 10 server.

Unfortunately, this script call fails due to a memory issue, as documented here

Oracle's recommendation is to use posix_spawn() since, under the covers, ProcessBuilder.start() is using fork/exec.

I have been unable to find any examples (e.g., how to call "myScript.sh")

using posix_spawn() in Java, or even what are the packages that are required.

Could you please, point me to a simple example on how to use posix_spawn() in Java?

答:
A much simpler solution would be to keep your code unchanged and simply add more virtual memory to your server.

i.e.:

```<code>mkfile 2g /somewhere/swap-1
swap -a /somewhere/swap-1
</code>```

Edit: To clarify as the link present in the question is now broken:

the question is about a system out of virtual memory due to the JVM being forked. Eg, assuming the JVM uses 2 GB of VM, an extra 2 GB of VM is required for the fork to succeed on Solaris. There is no pagination involved here, just memory reservation. Unlike the Linux kernel which by default overcommits memory, Solaris makes sure allocated memory is backed by either RAM or swap. As there is not enough swap available, fork is failing. Enlarging the swap allows the fork to succeed without any performance impact. Just after the fork, the exec "unreserves" this 2GB of RAM and revert to a situation identical to the posix_spawn one.

See also this page for an explanation about memory allocation under Solaris and other OSes.

Title: How to Use posix_spawn() in Java

Body:
A much simpler solution would be to keep your code unchanged and simply add more virtual memory to your server.

i.e.:

mkfile 2g /somewhere/swap-1
swap -a /somewhere/swap-1

Edit: To clarify as the link present in the question is now broken:

the question is about a system out of virtual memory due to the JVM being forked. Eg, assuming the JVM uses 2 GB of VM, an extra 2 GB of VM is required for the fork to succeed on Solaris. There is no pagination involved here, just memory reservation. Unlike the Linux kernel which by default overcommits memory, Solaris makes sure allocated memory is backed by either RAM or swap. As there is not enough swap available, fork is failing. Enlarging the swap allows the fork to succeed without any performance impact. Just after the fork, the exec "unreserves" this 2GB of RAM and revert to a situation identical to the posix_spawn one.

See also this page for an explanation about memory allocation under Solaris and other OSes.


问:
Organize views in RecyclerView by their Position
So this is my FeedAdapter:

```<code>public class FeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {

    private final int VIEW_TYPE_VERTICAL = 1;
    private final int VIEW_TYPE_HORIZONTAL = 2;
    private final int VIEW_TYPE_AD = 3;
    private Context context;
    private ArrayList<Object> items;
    private List<Vertical> listVertical;
    private List<Horizontal> listHorizontal;
    private List<Adlist> listAd;

    public FeedAdapter(Context context, ArrayList<Object> items, List<Vertical> listVertical,List<Horizontal> listHorizontal, List <Adlist> adList) {
    this.context = context;
    this.items = items;
    this.listVertical = listVertical;
    this.listHorizontal = listHorizontal;
    this.listAd = adList;
    }
</code>```

I have a horizontal, vertical and a alternative AD view (this has nothing to do with Goggle Ad Service btw) in my Feed.
Items = three different items, so three different views

Fot a better understanding: this the onCreate Method:

```<code>public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view;
RecyclerView.ViewHolder holder = null;

switch (viewType) {
    case VIEW_TYPE_VERTICAL:
        view = inflater.inflate(R.layout.newsfeed_vertical,viewGroup,false);
        holder = new VerticalViewHolder(view);
        break;
    case VIEW_TYPE_HORIZONTAL:
        view = inflater.inflate(R.layout.newsfeed_horizontal,viewGroup,false);
        holder = new HorizontalViewHolder(view);
        break;
    case VIEW_TYPE_AD:
        view = inflater.inflate(R.layout.newsfeed_vertical,viewGroup,false);
        holder = new AdViewHolder(view);
        break;
</code>```

an this the onBindViewHolder:

```<code>@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    if (holder.getItemViewType() == VIEW_TYPE_VERTICAL)
        verticalView((VerticalViewHolder) holder);

    else if (holder.getItemViewType() == VIEW_TYPE_HORIZONTAL)
        horizontalView((HorizontalViewHolder) holder);

    else if (holder.getItemViewType() == VIEW_TYPE_AD)
        adView((AdViewHolder) holder);
}
    public void verticalView (VerticalViewHolder holder ){

    VerticalScrollAdapter adapter_v = new VerticalScrollAdapter(listVertical);
    holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
    holder.recyclerView.setAdapter(adapter_v);

}

public void horizontalView (HorizontalViewHolder holder) {
    HorizontalScrollAdapter adapter_h = new HorizontalScrollAdapter(listHorizontal);
    holder.recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
    holder.recyclerView.setAdapter(adapter_h);
}

public void adView (AdViewHolder holder) {
    AdScrollAdapter adapter_ad = new AdScrollAdapter(adList);
    holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
    holder.recyclerView.setAdapter(adapter_ad);

}
</code>```

So I'm using the getItemViewType to understand which view I'm parsing:

```<code>@Override
public int getItemCount() {
    Log.e("items.size", String.valueOf(items.size()));
    return items.size();
}

@Override
public int getItemViewType(int position) {

    if (items.get(position) instanceof Vertical)
        return VIEW_TYPE_VERTICAL;

    if (items.get(position) instanceof Horizontal)
        return VIEW_TYPE_HORIZONTAL;

    if(items.get(position) instanceof Adlist)
        return VIEW_TYPE_AD;
    return -1;
}
</code>```

But with this my Feed get's the following structure:

VERTICAL VIEW

HORIZONTAL VIEW

AD VIEW

I'd like to organize my Feed like this

```<code>VERTIAL VIEW [0] = only 1 view (a box basically) with the first position of the LinearLayout Manager
HORIZONTAL VIEW = full list of my horizontal Views here / second position of my LinearLayoutManager
AD VIEW [0] = at the third position
VERTICAL VIEW [1-5]
AD VIEW [1] = @ position 6 in the LinearLayout
VERTICAL VIEW [5- ** ]
</code>```

So I know I have to work with findViewHolderForAdapterPosition and findViewHolderForLayoutPosition, but: Where do I have put these in my Code?

答:
Sort/construct your items list so that it has the items in the correct order.

Ideally, you'd start with your three types partitioned (i.e. one list of Vertical items, a second list of Horizontal items, and a third list of Ad items). Then you could build your overall list like this:

```<code>this.items = new ArrayList<>();

if (listVertical.size() > 0) {
    items.add(listVertical.remove(0));
}

if (listHorizontal.size() > 0) {
    items.add(listHorizontal.remove(0));
}

while (listVertical.size() > 0 || listAd.size() > 0) {
    if (listAd.size() > 0) {
        items.add(listAd.remove(0));
    }

    int count = 5;

    while (count > 0 && listVertical.size() > 0) {
        items.add(listVertical.remove(0));
    }
}
</code>```

This will add one vertical view, then one horizontal view, and then one ad view + five vertical views in a loop until you "run out" of both ad views and vertical views. I believe that matches your desired structure.

At the end, your three lists will be empty (because you will have remove()d all items from them). If you need to avoid this, you can create copies:

```<code>List<Vertical> verticalCopy = new ArrayList<>(listVertical);
// and so on
</code>```

And then you can just use verticalCopy instead of listVertical in the above code.

Body:
So this is my FeedAdapter:

public class FeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {

    private final int VIEW_TYPE_VERTICAL = 1;
    private final int VIEW_TYPE_HORIZONTAL = 2;
    private final int VIEW_TYPE_AD = 3;
    private Context context;
    private ArrayList<Object> items;
    private List<Vertical> listVertical;
    private List<Horizontal> listHorizontal;
    private List<Adlist> listAd;

    public FeedAdapter(Context context, ArrayList<Object> items, List<Vertical> listVertical,List<Horizontal> listHorizontal, List <Adlist> adList) {
    this.context = context;
    this.items = items;
    this.listVertical = listVertical;
    this.listHorizontal = listHorizontal;
    this.listAd = adList;
    }

I have a horizontal, vertical and a alternative AD view (this has nothing to do with Goggle Ad Service btw) in my Feed.
Items = three different items, so three different views

Fot a better understanding: this the onCreate Method:

public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view;
RecyclerView.ViewHolder holder = null;

switch (viewType) {
    case VIEW_TYPE_VERTICAL:
        view = inflater.inflate(R.layout.newsfeed_vertical,viewGroup,false);
        holder = new VerticalViewHolder(view);
        break;
    case VIEW_TYPE_HORIZONTAL:
        view = inflater.inflate(R.layout.newsfeed_horizontal,viewGroup,false);
        holder = new HorizontalViewHolder(view);
        break;
    case VIEW_TYPE_AD:
        view = inflater.inflate(R.layout.newsfeed_vertical,viewGroup,false);
        holder = new AdViewHolder(view);
        break;

an this the onBindViewHolder:

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    if (holder.getItemViewType() == VIEW_TYPE_VERTICAL)
        verticalView((VerticalViewHolder) holder);

    else if (holder.getItemViewType() == VIEW_TYPE_HORIZONTAL)
        horizontalView((HorizontalViewHolder) holder);

    else if (holder.getItemViewType() == VIEW_TYPE_AD)
        adView((AdViewHolder) holder);
}
    public void verticalView (VerticalViewHolder holder ){

    VerticalScrollAdapter adapter_v = new VerticalScrollAdapter(listVertical);
    holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
    holder.recyclerView.setAdapter(adapter_v);

}

public void horizontalView (HorizontalViewHolder holder) {
    HorizontalScrollAdapter adapter_h = new HorizontalScrollAdapter(listHorizontal);
    holder.recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
    holder.recyclerView.setAdapter(adapter_h);
}

public void adView (AdViewHolder holder) {
    AdScrollAdapter adapter_ad = new AdScrollAdapter(adList);
    holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
    holder.recyclerView.setAdapter(adapter_ad);

}

So I'm using the getItemViewType to understand which view I'm parsing:

@Override
public int getItemCount() {
    Log.e("items.size", String.valueOf(items.size()));
    return items.size();
}

@Override
public int getItemViewType(int position) {

    if (items.get(position) instanceof Vertical)
        return VIEW_TYPE_VERTICAL;

    if (items.get(position) instanceof Horizontal)
        return VIEW_TYPE_HORIZONTAL;

    if(items.get(position) instanceof Adlist)
        return VIEW_TYPE_AD;
    return -1;
}

But with this my Feed get's the following structure:

VERTICAL VIEW

HORIZONTAL VIEW

AD VIEW

I'd like to organize my Feed like this

VERTIAL VIEW [0] = only 1 view (a box basically) with the first position of the LinearLayout Manager
HORIZONTAL VIEW = full list of my horizontal Views here / second position of my LinearLayoutManager
AD VIEW [0] = at the third position
VERTICAL VIEW [1-5]
AD VIEW [1] = @ position 6 in the LinearLayout
VERTICAL VIEW [5- ** ]

So I know I have to work with findViewHolderForAdapterPosition and findViewHolderForLayoutPosition, but: Where do I have put these in my Code?

Body:
Sort/construct your items list so that it has the items in the correct order.

Ideally, you'd start with your three types partitioned (i.e. one list of Vertical items, a second list of Horizontal items, and a third list of Ad items). Then you could build your overall list like this:

this.items = new ArrayList<>();

if (listVertical.size() > 0) {
    items.add(listVertical.remove(0));
}

if (listHorizontal.size() > 0) {
    items.add(listHorizontal.remove(0));
}

while (listVertical.size() > 0 || listAd.size() > 0) {
    if (listAd.size() > 0) {
        items.add(listAd.remove(0));
    }

    int count = 5;

    while (count > 0 && listVertical.size() > 0) {
        items.add(listVertical.remove(0));
    }
}

This will add one vertical view, then one horizontal view, and then one ad view + five vertical views in a loop until you "run out" of both ad views and vertical views. I believe that matches your desired structure.

At the end, your three lists will be empty (because you will have remove()d all items from them). If you need to avoid this, you can create copies:

List<Vertical> verticalCopy = new ArrayList<>(listVertical);
// and so on

And then you can just use verticalCopy instead of listVertical in the above code.


问:
How to save selected Items to Qsettings from QListWidget, QTableWidget
I am Using PyQt5 and Py3.7, I am trying to loop through all my Qlistwidgets and save their string data, but also save all selected items on that widget. I slightly modified the loop from here, but am having some trouble getting the selected items to save and restore using the listwidget array loop. I checked the docs but can't seem to understand how to add additional options into the array (such as save all selected items), from the Qt docs for SetArrayIndex, here.

My listWidgets have selectionMode set to MultiSelection.
I am currently saving using this:

```<code>def save_list_data(self):
    self.settings = QSettings("data.ini", QSettings.IniFormat)
    for name, obj in inspect.getmembers(self):
        if isinstance(obj, QListWidget):
            name = obj.objectName()
            self.settings.beginWriteArray(name)
            for i in range(obj.count()):
                self.settings.setArrayIndex(i)
                self.settings.setValue(name, obj.item(i).text())
            self.settings.endArray()
</code>```

And then restoring the listWidget data using:

```<code>def open_list_data(self):
    self.settings = QSettings("data.ini", QSettings.IniFormat)
    for name, obj in inspect.getmembers(self):
        if isinstance(obj, QListWidget):
            name = obj.objectName()
            size = self.settings.beginReadArray(name)
            for i in range(size):
                self.settings.setArrayIndex(i)
                value = self.settings.value(name)
                if value != None:
                    obj.addItem(value)
            self.settings.endArray()
</code>```

This works fine for the data, but how can I get the selectedItems from the ListWidgets to save and restore as well?

答:
For my solution take into account the following:

Using the inspect module may be beneficial for other libraries, but for Qt the widget is not necessarily a member of the class so it is best to use the Qt introspection itself using findChildren.

In the example you use, you are only saving the text but a QListWidgetItem can have more information associated with the roles such as background color, foreground color, etc. So instead I will use the QDataStream operator since this take and save takes the item information.

I will use the "objectname/property" format to save the information since the same widget can have several properties that you want to save.

To save the information of the selected items, it is only necessary to save the row.

Considering the above, the solution is:

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listwidget_1 = QtWidgets.QListWidget(
            objectName="listwidget_1",
            selectionMode=QtWidgets.QAbstractItemView.MultiSelection
        )
        listwidget_2 = QtWidgets.QListWidget(
            objectName="listwidget_2",
            selectionMode=QtWidgets.QAbstractItemView.MultiSelection
        )

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.listwidget_1)
        lay.addWidget(listwidget_2)

        self.read_settings()

    def closeEvent(self, event):
        self.write_settings()
        super().closeEvent(event)

    def read_settings(self):
        settings = QtCore.QSettings("data.ini", QtCore.QSettings.IniFormat)
        childrens = self.findChildren(QtWidgets.QWidget)
        for children in childrens:
            if isinstance(children, QtWidgets.QListWidget) and children.objectName():
                settings.beginGroup(children.objectName())
                items = settings.value("items")
                selecteditems = settings.value("selecteditems")
                selectionMode = settings.value("selectionMode", type=QtWidgets.QAbstractItemView.SelectionMode)
                children.setSelectionMode(selectionMode)
                # In the first reading the initial values must be established
                if items is None:
                    if children.objectName() == "listwidget_1":
                        for i in range(10):
                            children.addItem(QtWidgets.QListWidgetItem(str(i)))
                    elif children.objectName() == "listwidget_2":
                        for i in "abcdefghijklmnopqrstuvwxyz":
                            children.addItem(QtWidgets.QListWidgetItem(i))
                else:
                    stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
                    while not stream.atEnd():
                        it = QtWidgets.QListWidgetItem()
                        stream >> it
                        children.addItem(it)
                    stream = QtCore.QDataStream(selecteditems, QtCore.QIODevice.ReadOnly)
                    while not stream.atEnd():
                        row = stream.readInt()
                        it = children.item(row)
                        it.setSelected(True)
                settings.endGroup()

    def write_settings(self):
        settings = QtCore.QSettings("data.ini", QtCore.QSettings.IniFormat)
        childrens = self.findChildren(QtWidgets.QWidget)
        for children in childrens:
            if isinstance(children, QtWidgets.QListWidget) and children.objectName():
                settings.beginGroup(children.objectName())
                items = QtCore.QByteArray()
                stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
                for i in range(children.count()):
                    stream << children.item(i)
                selecteditems = QtCore.QByteArray()
                stream = QtCore.QDataStream(selecteditems, QtCore.QIODevice.WriteOnly)
                for it in children.selectedItems():
                    stream.writeInt(children.row(it))
                settings.setValue("items", items)
                settings.setValue("selecteditems", selecteditems)
                settings.setValue("selectionMode", children.selectionMode())
                settings.endGroup()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
```

<p><strong>Plus:</strong></p>

<pre class="lang-py prettyprint-override"><code>import contextlib
from PyQt5 import QtCore, QtGui, QtWidgets

class SettingsManager:
    def __init__(self, filename):
        self.m_settings = QtCore.QSettings(filename, QtCore.QSettings.IniFormat)

    @property
    def settings(self):
        return self.m_settings

    def read(self, widget):
        self.settings.beginGroup(widget.objectName())
        if isinstance(widget, QtWidgets.QAbstractItemView):
            selectionMode = self.settings.value(
                "selectionMode", type=QtWidgets.QAbstractItemView.SelectionMode
            )
            widget.setSelectionMode(selectionMode)
        if isinstance(widget, QtWidgets.QListWidget):
            items = self.settings.value("items")
            selecteditems = self.settings.value("selecteditems")
            # In the first reading the initial values must be established
            if items is None:
                self.read_defaults(widget)
            else:
                stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
                while not stream.atEnd():
                    it = QtWidgets.QListWidgetItem()
                    stream >> it
                    widget.addItem(it)
                stream = QtCore.QDataStream(
                    selecteditems, QtCore.QIODevice.ReadOnly
                )
                while not stream.atEnd():
                    row = stream.readInt()
                    it = widget.item(row)
                    if it is not None:
                        it.setSelected(True)
        if isinstance(widget, QtWidgets.QTableWidget):
            rowCount = self.settings.value("rowCount", type=int)
            columnCount = self.settings.value("columnCount", type=int)
            widget.setRowCount(rowCount)
            widget.setColumnCount(columnCount)
            items = self.settings.value("items")
            if items is None:
                self.read_defaults(widget)
            else:
                stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
                while not stream.atEnd():
                    it = QtWidgets.QTableWidgetItem()
                    i = stream.readInt()
                    j = stream.readInt()
                    stream >> it
                    widget.setItem(i, j, it)
                selecteditems = self.settings.value("selecteditems")
                stream = QtCore.QDataStream(
                    selecteditems, QtCore.QIODevice.ReadOnly
                )
                while not stream.atEnd():
                    i = stream.readInt()
                    j = stream.readInt()
                    it = widget.item(i, j)
                    if it is not None:
                        it.setSelected(True)
        self.settings.endGroup()

    def write(self, widget):
        self.settings.beginGroup(widget.objectName())
        if isinstance(widget, QtWidgets.QAbstractItemView):
            self.settings.setValue("selectionMode", widget.selectionMode())
        if isinstance(widget, QtWidgets.QListWidget):
            items = QtCore.QByteArray()
            stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
            for i in range(widget.count()):
                stream << widget.item(i)
            self.settings.setValue("items", items)
            selecteditems = QtCore.QByteArray()
            stream = QtCore.QDataStream(
                selecteditems, QtCore.QIODevice.WriteOnly
            )
            for it in widget.selectedItems():
                stream.writeInt(widget.row(it))

            self.settings.setValue("selecteditems", selecteditems)
        if isinstance(widget, QtWidgets.QTableWidget):
            self.settings.setValue("rowCount", widget.rowCount())
            self.settings.setValue("columnCount", widget.columnCount())
            items = QtCore.QByteArray()
            stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
            for i in range(widget.rowCount()):
                for j in range(widget.columnCount()):
                    it = widget.item(i, j)
                    if it is not None:
                        stream.writeInt(i)
                        stream.writeInt(j)
                        stream << it
            self.settings.setValue("items", items)
            selecteditems = QtCore.QByteArray()
            stream = QtCore.QDataStream(
                selecteditems, QtCore.QIODevice.WriteOnly
            )
            for it in widget.selectedItems():
                # print(it.row(), it.column())
                stream.writeInt(it.row())
                stream.writeInt(it.column())
            self.settings.setValue("selecteditems", selecteditems)
        self.settings.endGroup()

    def release(self):
        self.m_settings.sync()

    def read_defaults(self, widget):
        if widget.objectName() == "listwidget_1":
            widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
            for i in range(10):
                widget.addItem(QtWidgets.QListWidgetItem(str(i)))
        elif widget.objectName() == "listwidget_2":
            widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
            for i in "abcdefghijklmnopqrstuvwxyz":
                widget.addItem(QtWidgets.QListWidgetItem(i))
        elif widget.objectName() == "tablewidget":
            widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
            widget.setRowCount(10)
            widget.setColumnCount(10)
            for i in range(widget.rowCount()):
                for j in range(widget.columnCount()):
                    it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
                    widget.setItem(i, j, it)

@contextlib.contextmanager
def settingsContext(filename):
    manager = SettingsManager(filename)
    try:
        yield manager
    finally:
        manager.release()

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listwidget_1 = QtWidgets.QListWidget(objectName="listwidget_1")
        listwidget_2 = QtWidgets.QListWidget(objectName="listwidget_2")

        tablewidget = QtWidgets.QTableWidget(objectName="tablewidget")

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.listwidget_1)
        lay.addWidget(listwidget_2)
        lay.addWidget(tablewidget)

        self.read_settings()

    def closeEvent(self, event):
        self.write_settings()
        super().closeEvent(event)

    def read_settings(self):
        with settingsContext("data.ini") as m:
            for children in self.findChildren(QtWidgets.QWidget):
                if children.objectName():
                    m.read(children)

    def write_settings(self):
        with settingsContext("data.ini") as m:
            for children in self.findChildren(QtWidgets.QWidget):
                if children.objectName():
                    m.write(children)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
I am Using PyQt5 and Py3.7, I am trying to loop through all my Qlistwidgets and save their string data, but also save all selected items on that widget. I slightly modified the loop from here, but am having some trouble getting the selected items to save and restore using the listwidget array loop. I checked the docs but can't seem to understand how to add additional options into the array (such as save all selected items), from the Qt docs for SetArrayIndex, here.

My listWidgets have selectionMode set to MultiSelection.
I am currently saving using this:

def save_list_data(self):
    self.settings = QSettings("data.ini", QSettings.IniFormat)
    for name, obj in inspect.getmembers(self):
        if isinstance(obj, QListWidget):
            name = obj.objectName()
            self.settings.beginWriteArray(name)
            for i in range(obj.count()):
                self.settings.setArrayIndex(i)
                self.settings.setValue(name, obj.item(i).text())
            self.settings.endArray()

And then restoring the listWidget data using:

def open_list_data(self):
    self.settings = QSettings("data.ini", QSettings.IniFormat)
    for name, obj in inspect.getmembers(self):
        if isinstance(obj, QListWidget):
            name = obj.objectName()
            size = self.settings.beginReadArray(name)
            for i in range(size):
                self.settings.setArrayIndex(i)
                value = self.settings.value(name)
                if value != None:
                    obj.addItem(value)
            self.settings.endArray()

This works fine for the data, but how can I get the selectedItems from the ListWidgets to save and restore as well?

Body:
For my solution take into account the following:

Using the inspect module may be beneficial for other libraries, but for Qt the widget is not necessarily a member of the class so it is best to use the Qt introspection itself using findChildren.

In the example you use, you are only saving the text but a QListWidgetItem can have more information associated with the roles such as background color, foreground color, etc. So instead I will use the QDataStream operator since this take and save takes the item information.

I will use the "objectname/property" format to save the information since the same widget can have several properties that you want to save.

To save the information of the selected items, it is only necessary to save the row.

Considering the above, the solution is:

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listwidget_1 = QtWidgets.QListWidget(
            objectName="listwidget_1",
            selectionMode=QtWidgets.QAbstractItemView.MultiSelection
        )
        listwidget_2 = QtWidgets.QListWidget(
            objectName="listwidget_2",
            selectionMode=QtWidgets.QAbstractItemView.MultiSelection
        )

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.listwidget_1)
        lay.addWidget(listwidget_2)

        self.read_settings()

    def closeEvent(self, event):
        self.write_settings()
        super().closeEvent(event)

    def read_settings(self):
        settings = QtCore.QSettings("data.ini", QtCore.QSettings.IniFormat)
        childrens = self.findChildren(QtWidgets.QWidget)
        for children in childrens:
            if isinstance(children, QtWidgets.QListWidget) and children.objectName():
                settings.beginGroup(children.objectName())
                items = settings.value("items")
                selecteditems = settings.value("selecteditems")
                selectionMode = settings.value("selectionMode", type=QtWidgets.QAbstractItemView.SelectionMode)
                children.setSelectionMode(selectionMode)
                # In the first reading the initial values must be established
                if items is None:
                    if children.objectName() == "listwidget_1":
                        for i in range(10):
                            children.addItem(QtWidgets.QListWidgetItem(str(i)))
                    elif children.objectName() == "listwidget_2":
                        for i in "abcdefghijklmnopqrstuvwxyz":
                            children.addItem(QtWidgets.QListWidgetItem(i))
                else:
                    stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
                    while not stream.atEnd():
                        it = QtWidgets.QListWidgetItem()
                        stream >> it
                        children.addItem(it)
                    stream = QtCore.QDataStream(selecteditems, QtCore.QIODevice.ReadOnly)
                    while not stream.atEnd():
                        row = stream.readInt()
                        it = children.item(row)
                        it.setSelected(True)
                settings.endGroup()

    def write_settings(self):
        settings = QtCore.QSettings("data.ini", QtCore.QSettings.IniFormat)
        childrens = self.findChildren(QtWidgets.QWidget)
        for children in childrens:
            if isinstance(children, QtWidgets.QListWidget) and children.objectName():
                settings.beginGroup(children.objectName())
                items = QtCore.QByteArray()
                stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
                for i in range(children.count()):
                    stream << children.item(i)
                selecteditems = QtCore.QByteArray()
                stream = QtCore.QDataStream(selecteditems, QtCore.QIODevice.WriteOnly)
                for it in children.selectedItems():
                    stream.writeInt(children.row(it))
                settings.setValue("items", items)
                settings.setValue("selecteditems", selecteditems)
                settings.setValue("selectionMode", children.selectionMode())
                settings.endGroup()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Plus:

import contextlib
from PyQt5 import QtCore, QtGui, QtWidgets

class SettingsManager:
    def __init__(self, filename):
        self.m_settings = QtCore.QSettings(filename, QtCore.QSettings.IniFormat)

    @property
    def settings(self):
        return self.m_settings

    def read(self, widget):
        self.settings.beginGroup(widget.objectName())
        if isinstance(widget, QtWidgets.QAbstractItemView):
            selectionMode = self.settings.value(
                "selectionMode", type=QtWidgets.QAbstractItemView.SelectionMode
            )
            widget.setSelectionMode(selectionMode)
        if isinstance(widget, QtWidgets.QListWidget):
            items = self.settings.value("items")
            selecteditems = self.settings.value("selecteditems")
            # In the first reading the initial values must be established
            if items is None:
                self.read_defaults(widget)
            else:
                stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
                while not stream.atEnd():
                    it = QtWidgets.QListWidgetItem()
                    stream >> it
                    widget.addItem(it)
                stream = QtCore.QDataStream(
                    selecteditems, QtCore.QIODevice.ReadOnly
                )
                while not stream.atEnd():
                    row = stream.readInt()
                    it = widget.item(row)
                    if it is not None:
                        it.setSelected(True)
        if isinstance(widget, QtWidgets.QTableWidget):
            rowCount = self.settings.value("rowCount", type=int)
            columnCount = self.settings.value("columnCount", type=int)
            widget.setRowCount(rowCount)
            widget.setColumnCount(columnCount)
            items = self.settings.value("items")
            if items is None:
                self.read_defaults(widget)
            else:
                stream = QtCore.QDataStream(items, QtCore.QIODevice.ReadOnly)
                while not stream.atEnd():
                    it = QtWidgets.QTableWidgetItem()
                    i = stream.readInt()
                    j = stream.readInt()
                    stream >> it
                    widget.setItem(i, j, it)
                selecteditems = self.settings.value("selecteditems")
                stream = QtCore.QDataStream(
                    selecteditems, QtCore.QIODevice.ReadOnly
                )
                while not stream.atEnd():
                    i = stream.readInt()
                    j = stream.readInt()
                    it = widget.item(i, j)
                    if it is not None:
                        it.setSelected(True)
        self.settings.endGroup()

    def write(self, widget):
        self.settings.beginGroup(widget.objectName())
        if isinstance(widget, QtWidgets.QAbstractItemView):
            self.settings.setValue("selectionMode", widget.selectionMode())
        if isinstance(widget, QtWidgets.QListWidget):
            items = QtCore.QByteArray()
            stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
            for i in range(widget.count()):
                stream << widget.item(i)
            self.settings.setValue("items", items)
            selecteditems = QtCore.QByteArray()
            stream = QtCore.QDataStream(
                selecteditems, QtCore.QIODevice.WriteOnly
            )
            for it in widget.selectedItems():
                stream.writeInt(widget.row(it))

            self.settings.setValue("selecteditems", selecteditems)
        if isinstance(widget, QtWidgets.QTableWidget):
            self.settings.setValue("rowCount", widget.rowCount())
            self.settings.setValue("columnCount", widget.columnCount())
            items = QtCore.QByteArray()
            stream = QtCore.QDataStream(items, QtCore.QIODevice.WriteOnly)
            for i in range(widget.rowCount()):
                for j in range(widget.columnCount()):
                    it = widget.item(i, j)
                    if it is not None:
                        stream.writeInt(i)
                        stream.writeInt(j)
                        stream << it
            self.settings.setValue("items", items)
            selecteditems = QtCore.QByteArray()
            stream = QtCore.QDataStream(
                selecteditems, QtCore.QIODevice.WriteOnly
            )
            for it in widget.selectedItems():
                # print(it.row(), it.column())
                stream.writeInt(it.row())
                stream.writeInt(it.column())
            self.settings.setValue("selecteditems", selecteditems)
        self.settings.endGroup()

    def release(self):
        self.m_settings.sync()

    def read_defaults(self, widget):
        if widget.objectName() == "listwidget_1":
            widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
            for i in range(10):
                widget.addItem(QtWidgets.QListWidgetItem(str(i)))
        elif widget.objectName() == "listwidget_2":
            widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
            for i in "abcdefghijklmnopqrstuvwxyz":
                widget.addItem(QtWidgets.QListWidgetItem(i))
        elif widget.objectName() == "tablewidget":
            widget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
            widget.setRowCount(10)
            widget.setColumnCount(10)
            for i in range(widget.rowCount()):
                for j in range(widget.columnCount()):
                    it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
                    widget.setItem(i, j, it)

@contextlib.contextmanager
def settingsContext(filename):
    manager = SettingsManager(filename)
    try:
        yield manager
    finally:
        manager.release()

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.listwidget_1 = QtWidgets.QListWidget(objectName="listwidget_1")
        listwidget_2 = QtWidgets.QListWidget(objectName="listwidget_2")

        tablewidget = QtWidgets.QTableWidget(objectName="tablewidget")

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.listwidget_1)
        lay.addWidget(listwidget_2)
        lay.addWidget(tablewidget)

        self.read_settings()

    def closeEvent(self, event):
        self.write_settings()
        super().closeEvent(event)

    def read_settings(self):
        with settingsContext("data.ini") as m:
            for children in self.findChildren(QtWidgets.QWidget):
                if children.objectName():
                    m.read(children)

    def write_settings(self):
        with settingsContext("data.ini") as m:
            for children in self.findChildren(QtWidgets.QWidget):
                if children.objectName():
                    m.write(children)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())