问:
how to use the wait(long timeout) on jpanel
I am taking an introductory java class and I have an inheritance related problem. I have to implement a system that has classes for various figures. the superclass is Figures and subclasses are Circle, Box and Rectangle and I am supposed to output the figures in the JPanel. I have designed all the classes and my code is below but I need to define the center() method on the figure class which when called on an object should draw and also erase the object. so within the main method of the JPanel class, I want to use the center() method to draw the three shapes and use the wait(long timeout) method to make the shapes change to random positions after 15 seconds.

```<code>import java.awt.Graphics;
import javax.swing.JPanel;

public abstract class Figure extends JPanel {

protected int xCoord;
protected int yCoord;

public Figure() {
}

public void erase() {

}

public void draw() {

}

public void center() {

}
}
</code>```

the rectangle sub class is:

```<code>import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Rectangle extends Figure {
int width;
int height;

public Rectangle() {

    this.width = 0;
    this.height = 0;
}

public Rectangle(int xCoord, int yCoord, int width, int height)

{
    this.xCoord = xCoord;
    this.yCoord = yCoord;
    this.width = width;
    this.height = height;
}

public void draw(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(xCoord, yCoord, width, height);
}

public void erase(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, 0, 0);
}

}
</code>```

the circle subclass:

```<code>public class Circle extends Figure {

private int radius;

 public Circle ()
  {
     this.radius = 0;
  }

 public Circle (int xCoord, int yCoord, int radius)
  {
     this.xCoord = xCoord;
     this.yCoord = yCoord;
     this.radius = radius;
  }

 public void draw(Graphics g){
      super.paintComponent(g);
      g.setColor(Color.BLACK);
      g.fillOval(xCoord, yCoord, radius, radius);
  }

 public void erase(Graphics g){
      super.paintComponent(g);
      g.setColor(Color.BLACK);
      g.fillOval(0,0,0,0);
  }

}
</code>```

the box subclass:

```<code>import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Box extends Figure {

private int edgeLength;

public Box() {
    this.edgeLength = 0;
}

public Box(int xCoord, int yCoord, int edgeLength)// Creating Rectangle
                                                    // Class given width and
                                                    // height
{
    this.xCoord = xCoord;
    this.yCoord = yCoord;
    this.edgeLength = edgeLength;
}

public void draw(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(xCoord, yCoord, edgeLength, edgeLength);
}

public void erase(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, 0, 0);
}

}
</code>```

the JPanel class

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SamplePanel extends JPanel {

private static final int PANEL_HEIGHT = 400;
private static final int PANEL_WIDTH = 400;
Rectangle rect = new Rectangle(75, 85, 50,30);
Circle circle = new Circle(275, 75, 50);
Box box = new Box (75, 275, 50);

public SamplePanel() {

    setPreferredSize(new Dimension(PANEL_HEIGHT, PANEL_WIDTH));
    setBackground(Color.WHITE);
    //Rectangle rect = new Rectangle(100, 100, 15,10);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    rect.draw(g);
    circle.draw(g);
    box.draw(g);
    g.drawLine(200, 0, 200, 400);
    g.drawLine(0, 200, 400, 200);

}

/**
 * @param layout
 */
public SamplePanel(LayoutManager layout) {
    super(layout);
}

/**
 * @param isDoubleBuffered
 */
public SamplePanel(boolean isDoubleBuffered) {
    super(isDoubleBuffered);
}

/**
 * @param layout
 * @param isDoubleBuffered
 */
public SamplePanel(LayoutManager layout, boolean isDoubleBuffered) {
    super(layout, isDoubleBuffered);
}

public static void main(String[] args) {
    JFrame frame = new JFrame("Window Title Here");
    SamplePanel panel = new SamplePanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    Figure box = new Box(75, 275, 50);

}

}
</code>```

答:
Answer...

How to use Swing Timers

It is safe to use within the context of Swing as it won't block the Event Dispatching Thread while waiting and will generate notifications within the context of the Event Dispatching Thread, making it safe to update the UI from.

Observations...

Your basic design, while correct in concept, is implemented in correctly.  I'd would strongly discourage you from using JPanel in this way.  Components have a particular life cycle which you're not managing correctly, which could cause no end of issues.

Instead, go right back to basics.  What is it the shape should be able to?

```<code>public interface Figure {
    public void draw(Graphics2D g2d);
    public Rectangle getBounds();
    public void setBounds(Rectangle bounds);
}
</code>```

Here, it's capable of been painted and has a concept of size and position (yes, you can use an abstract class, but this removes all requirements on the base implementation, making it far more flexible)

Because I imagine most of the implementations are going to be basically the same, I can use an abstract class to implement the core functionality...

```<code>public abstract class AbstractFigure implements Figure {
    private Rectangle bounds;

    @Override
    public Rectangle getBounds() {
        return bounds;
    }

    @Override
    public void setBounds(Rectangle bounds) {
        this.bounds = bounds;
    }

}
</code>```

Based on your needs, you might be able to create a few abstract classes which implement the functionality different, but the basic idea is to see what functionality is common to all the implementations and reduce the amount of duplicate code you generate.

Then you can start implementing your concrete classes...

```<code>public class RectangleFigure extends AbstractFigure {

    public RectangleFigure(Rectangle bounds) {
        setBounds(bounds);
    }

    @Override
    public void draw(Graphics2D g2d) {
        g2d.setColor(Color.BLACK);
        g2d.fill(getBounds());
    }

}
</code>```

But where's the "erase" method you ask?  Well, erase is just the absence of painting, so, when you want to "erase" a shape, remove it from the painting process and repaint the container, shape is erased

This is suggests to me that you need to have a look at Painting in AWT and Swing and Performing Custom Painting to better understand how painting works in Swing.

"Where's the center method?" I hear you ask.  Okay, you "could" have a center method in the Figure, the problem is, Figure has no concept of the parent container, is you'd have to pass the size of the container to it.  Not difficult, I'd argue, however, this really isn't a function of the Figure, but a function of the container, so I'd have the center method implemented there, since you want to change the position of the Figures anyway, it makes sense (to me) to all that wrapped up in the container

Body:
I am taking an introductory java class and I have an inheritance related problem. I have to implement a system that has classes for various figures. the superclass is Figures and subclasses are Circle, Box and Rectangle and I am supposed to output the figures in the JPanel. I have designed all the classes and my code is below but I need to define the center() method on the figure class which when called on an object should draw and also erase the object. so within the main method of the JPanel class, I want to use the center() method to draw the three shapes and use the wait(long timeout) method to make the shapes change to random positions after 15 seconds.

import java.awt.Graphics;
import javax.swing.JPanel;

public abstract class Figure extends JPanel {

protected int xCoord;
protected int yCoord;

public Figure() {
}

public void erase() {

}

public void draw() {

}

public void center() {

}
}

the rectangle sub class is:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Rectangle extends Figure {
int width;
int height;

public Rectangle() {

    this.width = 0;
    this.height = 0;
}

public Rectangle(int xCoord, int yCoord, int width, int height)

{
    this.xCoord = xCoord;
    this.yCoord = yCoord;
    this.width = width;
    this.height = height;
}

public void draw(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(xCoord, yCoord, width, height);
}

public void erase(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, 0, 0);
}

}

the circle subclass:

public class Circle extends Figure {

private int radius;

 public Circle ()
  {
     this.radius = 0;
  }

 public Circle (int xCoord, int yCoord, int radius)
  {
     this.xCoord = xCoord;
     this.yCoord = yCoord;
     this.radius = radius;
  }

 public void draw(Graphics g){
      super.paintComponent(g);
      g.setColor(Color.BLACK);
      g.fillOval(xCoord, yCoord, radius, radius);
  }

 public void erase(Graphics g){
      super.paintComponent(g);
      g.setColor(Color.BLACK);
      g.fillOval(0,0,0,0);
  }

}

the box subclass:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Box extends Figure {

private int edgeLength;

public Box() {
    this.edgeLength = 0;
}

public Box(int xCoord, int yCoord, int edgeLength)// Creating Rectangle
                                                    // Class given width and
                                                    // height
{
    this.xCoord = xCoord;
    this.yCoord = yCoord;
    this.edgeLength = edgeLength;
}

public void draw(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(xCoord, yCoord, edgeLength, edgeLength);
}

public void erase(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, 0, 0);
}

}

the JPanel class

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Point;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SamplePanel extends JPanel {

private static final int PANEL_HEIGHT = 400;
private static final int PANEL_WIDTH = 400;
Rectangle rect = new Rectangle(75, 85, 50,30);
Circle circle = new Circle(275, 75, 50);
Box box = new Box (75, 275, 50);

public SamplePanel() {

    setPreferredSize(new Dimension(PANEL_HEIGHT, PANEL_WIDTH));
    setBackground(Color.WHITE);
    //Rectangle rect = new Rectangle(100, 100, 15,10);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    rect.draw(g);
    circle.draw(g);
    box.draw(g);
    g.drawLine(200, 0, 200, 400);
    g.drawLine(0, 200, 400, 200);

}

/**
 * @param layout
 */
public SamplePanel(LayoutManager layout) {
    super(layout);
}

/**
 * @param isDoubleBuffered
 */
public SamplePanel(boolean isDoubleBuffered) {
    super(isDoubleBuffered);
}

/**
 * @param layout
 * @param isDoubleBuffered
 */
public SamplePanel(LayoutManager layout, boolean isDoubleBuffered) {
    super(layout, isDoubleBuffered);
}

public static void main(String[] args) {
    JFrame frame = new JFrame("Window Title Here");
    SamplePanel panel = new SamplePanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    Figure box = new Box(75, 275, 50);

}

}

Body:
Answer...

How to use Swing Timers

It is safe to use within the context of Swing as it won't block the Event Dispatching Thread while waiting and will generate notifications within the context of the Event Dispatching Thread, making it safe to update the UI from.

Observations...

Your basic design, while correct in concept, is implemented in correctly.  I'd would strongly discourage you from using JPanel in this way.  Components have a particular life cycle which you're not managing correctly, which could cause no end of issues.

Instead, go right back to basics.  What is it the shape should be able to?

public interface Figure {
    public void draw(Graphics2D g2d);
    public Rectangle getBounds();
    public void setBounds(Rectangle bounds);
}

Here, it's capable of been painted and has a concept of size and position (yes, you can use an abstract class, but this removes all requirements on the base implementation, making it far more flexible)

Because I imagine most of the implementations are going to be basically the same, I can use an abstract class to implement the core functionality...

public abstract class AbstractFigure implements Figure {
    private Rectangle bounds;

    @Override
    public Rectangle getBounds() {
        return bounds;
    }

    @Override
    public void setBounds(Rectangle bounds) {
        this.bounds = bounds;
    }

}

Based on your needs, you might be able to create a few abstract classes which implement the functionality different, but the basic idea is to see what functionality is common to all the implementations and reduce the amount of duplicate code you generate.

Then you can start implementing your concrete classes...

public class RectangleFigure extends AbstractFigure {

    public RectangleFigure(Rectangle bounds) {
        setBounds(bounds);
    }

    @Override
    public void draw(Graphics2D g2d) {
        g2d.setColor(Color.BLACK);
        g2d.fill(getBounds());
    }

}

But where's the "erase" method you ask?  Well, erase is just the absence of painting, so, when you want to "erase" a shape, remove it from the painting process and repaint the container, shape is erased

This is suggests to me that you need to have a look at Painting in AWT and Swing and Performing Custom Painting to better understand how painting works in Swing.

"Where's the center method?" I hear you ask.  Okay, you "could" have a center method in the Figure, the problem is, Figure has no concept of the parent container, is you'd have to pass the size of the container to it.  Not difficult, I'd argue, however, this really isn't a function of the Figure, but a function of the container, so I'd have the center method implemented there, since you want to change the position of the Figures anyway, it makes sense (to me) to all that wrapped up in the container


来源: stackexchange

问:
Beautiful Soup - Finding first link in an article
I'm creating a python solution to this problem but I'm having trouble getting past some edge cases.

The problem I'm running into arises for a page like this where this link is the one that should be extracted since it is the first one outside of the parentheses. Conversely, some articles are like this where the link appears before the first parenthesis.

The way I'm handling these cases currently is by initially iterating through the elements and text in the first paragraph tag (stringified version) and checking to see which is found first between a '(' and an . If  is found first (meaning before a parenthesis has been reached), I just take that link. If a parenthesis is found first, I wait until the parentheses are closed and then take the following '

In effect, I am just getting the direct child of the first paragraph element which could be done with something like:

```<code>soup = BeautifulSoup(response.content, "lxml")
soup.select_one("#mw-content-text > p > a")
</code>```

What I think would work here is to use such a select statement to find the first link in the prefix from the beginning of th
 until the first parenthesis or (if there isn't a link in the prefix) find the link immediately following the close parenthesis using something similar to what I'm doing currently:

```<code>`findNext('a').attrs['href']`
</code>```

If such an approach is to be used, a multiple issues arise including:
1. How to actually get the prefix up until the first parenthesis with only the direct child elements of the '

Is there a streamlined way to do this? If there is a better approach, what would it be?

答:
This problem reminds me that popular algorithms&data structures problem when you need to check if parenthesis or other brackets are balanced. For these kind of problems, a stack data structure is convenient to use.

So, in this case, we'll push to stack if there is an opening parenthesis and pop from it if there is a closing one. The valid link for us would be the one when the stack is empty:

```<code>import requests
from bs4 import BeautifulSoup, NavigableString, Tag

urls = [
    "https://en.wikipedia.org/wiki/Modern_Greek",
    "https://en.wikipedia.org/wiki/Diglossia"
]

with requests.Session() as session:
    for url in urls:
        response = session.get(url)
        soup = BeautifulSoup(response.content, "html.parser")

        stack = []
        for child in soup.select_one("#mw-content-text > p").children:
            if isinstance(child, NavigableString):
                if "(" in child:
                    stack.append("(")
                if ")" in child:
                    stack.pop()

            if isinstance(child, Tag) and child.name == "a" and not stack:
                print(child.get_text())
                break
</code>```

It prints dialects for "Modern Greek" page and linguistics for "Diglossia". Both cases are handled.

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a python solution to this problem but I'm having trouble getting past some edge cases.

The problem I'm running into arises for a page like this where this link is the one that should be extracted since it is the first one outside of the parentheses. Conversely, some articles are like this where the link appears before the first parenthesis.

The way I'm handling these cases currently is by initially iterating through the elements and text in the first paragraph tag (stringified version) and checking to see which is found first between a '(' and an . If  is found first (meaning before a parenthesis has been reached), I just take that link. If a parenthesis is found first, I wait until the parentheses are closed and then take the following '

In effect, I am just getting the direct child of the first paragraph element which could be done with something like:

soup = BeautifulSoup(response.content, "lxml")
soup.select_one("#mw-content-text > p > a")

What I think would work here is to use such a select statement to find the first link in the prefix from the beginning of th
 until the first parenthesis or (if there isn't a link in the prefix) find the link immediately following the close parenthesis using something similar to what I'm doing currently:

`findNext('a').attrs['href']`

If such an approach is to be used, a multiple issues arise including:
1. How to actually get the prefix up until the first parenthesis with only the direct child elements of the '

Is there a streamlined way to do this? If there is a better approach, what would it be?

Body:
This problem reminds me that popular algorithms&data structures problem when you need to check if parenthesis or other brackets are balanced. For these kind of problems, a stack data structure is convenient to use.

So, in this case, we'll push to stack if there is an opening parenthesis and pop from it if there is a closing one. The valid link for us would be the one when the stack is empty:

import requests
from bs4 import BeautifulSoup, NavigableString, Tag

urls = [
    "https://en.wikipedia.org/wiki/Modern_Greek",
    "https://en.wikipedia.org/wiki/Diglossia"
]

with requests.Session() as session:
    for url in urls:
        response = session.get(url)
        soup = BeautifulSoup(response.content, "html.parser")

        stack = []
        for child in soup.select_one("#mw-content-text > p").children:
            if isinstance(child, NavigableString):
                if "(" in child:
                    stack.append("(")
                if ")" in child:
                    stack.pop()

            if isinstance(child, Tag) and child.name == "a" and not stack:
                print(child.get_text())
                break

It prints dialects for "Modern Greek" page and linguistics for "Diglossia". Both cases are handled.


问:
Project Reference Problem, Visual Studio 2010
I have a solution that has one class library project, and the others are WPF applications.   I have added class library's reference the but, but both of them cannot use its classes.

So, what is the problem?

NOTE: sorry for tags, it's safari's problem.

答:
Make sure that all your projects target same Framework.
It may be a case that your library class project targets full .Net Framework 4.0 while your wpf projects target .Net Framework 4.0 Client Profile.

To do that go to project properties of each project in a solution and check Application | Target Framework property. Alternatively you can download VSCommands 2010 extension and see all properties in one place via Solution Properties window.

ContentLicense: CC BY-SA 2.5


问:
Webpage displays differently on different screens
I'm trying to get my website to be display the way that it was designed. I have an iMac but when I view it on a MacBook Pro and my phone, the divs on one of my pages lose their proportions and it's not looking the way it should. Here's the link to my page:http://www.wintonbrownmusic.online/Music%20Site%20Beat%20Making.html

Here's the CSS for my page:

```<code>header, section, footer, aside, nav, main, article, figure {
display: block;
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}

a {
display: inline-block;
width: 90px;
text-align: center;
text-decoration: none;
font-family: Gagalin;
color: #404040;
font-size: 20px;
}

li {
width: 100px;
margin: auto;
display: inline;
}

p {
font-family: Arial;
padding-left: 10px;

}

a:hover, a:active {
padding-bottom:8px;
background: transparent;
border-bottom: 3px solid #FA8440;
}

a:active {
color: #FA8440;
}

.newspaper {
-webkit-columns: 100px 3; /* Chrome, Safari, Opera */
-moz-columns: 100px 3; /* Firefox */
columns: 100px 3;
font-family: Arial;
}

h2 {
font-family: Gagalin;
padding-left: 10px;
}

footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}

.blurb {
margin:5px 0 10px 10px;
width:425px;
height: 230px;
background:#1a1a1a;
border: 6px solid #4d4d4d;
padding: 30px;
float: right;
font-family: Arial;
color: White;
padding-right:50px;
}

.container-fluid {
margin: 0 auto;
margin-left: 0 auto;
width: 65%;
}
</code>```

I could use some assistance on what code I can use to make this page appear the same in all browsers, all pages and even phones.

答:
The problem is that the design is not responsive (does not naturally adjust to different screen sizes and formats).  Responsive design is a huge topic that can't really be covered in the contents of once conversation box, so I am adding some links for you to look at.

Responsive web design basics:
https://developers.google.com/web/fundamentals/design-and-ui/responsive/

Media queries:
https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Body:
I'm trying to get my website to be display the way that it was designed. I have an iMac but when I view it on a MacBook Pro and my phone, the divs on one of my pages lose their proportions and it's not looking the way it should. Here's the link to my page:http://www.wintonbrownmusic.online/Music%20Site%20Beat%20Making.html

Here's the CSS for my page:

header, section, footer, aside, nav, main, article, figure {
display: block;
}

ul {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}

a {
display: inline-block;
width: 90px;
text-align: center;
text-decoration: none;
font-family: Gagalin;
color: #404040;
font-size: 20px;
}

li {
width: 100px;
margin: auto;
display: inline;
}

p {
font-family: Arial;
padding-left: 10px;

}

a:hover, a:active {
padding-bottom:8px;
background: transparent;
border-bottom: 3px solid #FA8440;
}

a:active {
color: #FA8440;
}

.newspaper {
-webkit-columns: 100px 3; /* Chrome, Safari, Opera */
-moz-columns: 100px 3; /* Firefox */
columns: 100px 3;
font-family: Arial;
}

h2 {
font-family: Gagalin;
padding-left: 10px;
}

footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}

.blurb {
margin:5px 0 10px 10px;
width:425px;
height: 230px;
background:#1a1a1a;
border: 6px solid #4d4d4d;
padding: 30px;
float: right;
font-family: Arial;
color: White;
padding-right:50px;
}

.container-fluid {
margin: 0 auto;
margin-left: 0 auto;
width: 65%;
}

I could use some assistance on what code I can use to make this page appear the same in all browsers, all pages and even phones.


问:
conda install mingw for 64bit CentOS 7
I just installed Anaconda 2 on a linux machine with 64 bit CentOS 7. I tried:

```<code>conda install mingw libpython
</code>```

but it says:

conda install mingw libpython

Fetching package metadata .........

PackageNotFoundError: Package not found: Conda could not find '

答: Although the error message is extremely unhelpful, the error is that libpython is only available for Windows: https://anaconda.org/search?q=libpython

Title: conda install mingw for 64bit CentOS 7

Body:
I just installed Anaconda 2 on a linux machine with 64 bit CentOS 7. I tried:

conda install mingw libpython

but it says:

conda install mingw libpython

Fetching package metadata .........

PackageNotFoundError: Package not found: Conda could not find '


问:
Using the Reverse Method/ Arrays- How to Print out the Reverse
```<code>public static void main(String[] args) {
    int[] HwArray = new int[10];
    int count = 0;
    String separate = "";
    for (int i = 0; i < HwArray.length; i++) {
        System.out.print(separate);

        //Generate random numbers
        HwArray[i] = (int) (100 + Math.random() * 100);
        System.out.println("HwArray[" + i + "]=" + HwArray[i]);
    }

    int location = linearSearch(HwArray, 150);
    System.out.println("\nLinear Search Result: " + location);
}

// Reverse the order of all elements, then print HwArray.
public static int[] reverse(int[] list) {
    int[] result = new int[list.length];
    for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
        result[j] = list[i];
        System.out.println("HwArray[" + i + "]=" + result[j]);
    }

    return result;
}

public static int linearSearch(int[] list, int key) {
    for (int i = 0; i < list.length; i++) {
        if (list[i] == key)
            return i;  //return the index location

    }

    return -1;   //return if number is not found in the index
}
</code>```

<p>I'm trying to print out the elements in Reverse, but It will only print out the elements. I'm not sure what's wrong. </p>

答:
Please research a little more before asking questions, maybe google "java reverse array". That's what I did, and found that this person asked the same thing. Reversing an Array in Java

The solution is simple:

```<code>List<Integer> lst = Arrays.asList(list); //Converts the int "list" into a list.
Collections.reverse(lst); //Reverses the list.
result = list.toArray(lst);
</code>```

Body:
public static void main(String[] args) {
    int[] HwArray = new int[10];
    int count = 0;
    String separate = "";
    for (int i = 0; i < HwArray.length; i++) {
        System.out.print(separate);

        //Generate random numbers
        HwArray[i] = (int) (100 + Math.random() * 100);
        System.out.println("HwArray[" + i + "]=" + HwArray[i]);
    }

    int location = linearSearch(HwArray, 150);
    System.out.println("\nLinear Search Result: " + location);
}

// Reverse the order of all elements, then print HwArray.
public static int[] reverse(int[] list) {
    int[] result = new int[list.length];
    for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
        result[j] = list[i];
        System.out.println("HwArray[" + i + "]=" + result[j]);
    }

    return result;
}

public static int linearSearch(int[] list, int key) {
    for (int i = 0; i < list.length; i++) {
        if (list[i] == key)
            return i;  //return the index location

    }

    return -1;   //return if number is not found in the index
}

I'm trying to print out the elements in Reverse, but It will only print out the elements. I'm not sure what's wrong.

Body:
Please research a little more before asking questions, maybe google "java reverse array". That's what I did, and found that this person asked the same thing. Reversing an Array in Java

The solution is simple:

List<Integer> lst = Arrays.asList(list); //Converts the int "list" into a list.
Collections.reverse(lst); //Reverses the list.
result = list.toArray(lst);


问:
Nuke Viewer set framerange trouble
I'm writing a timeline synchronization script in Nuke10.
I should change global frame settings. Example:

```<code>nuke.root().knob('first_frame').setValue(1)
nuke.root().knob('last_frame').setValue(100)
</code>```

After that i should change viewer playback range. Example:

```<code>vv = nuke.activeViewer().node()
vv['frame_range_lock'].setValue(True)
vv['frame_range'].setValue('5-40')
</code>```

Separately it's worked. But together - not. At start i have global frame range 1-10. And when i run all that's lines - frame range set to 1-100 but playback range set to 5-10.

I add command in the middle of the script to check playback range:

```<code>nuke.root().knob('first_frame').setValue(1)
nuke.root().knob('last_frame').setValue(100)

x = vv.playbackRange()
print(x)

vv['frame_range_lock'].setValue(True)
vv['frame_range'].setValue('5-40')
</code>```

it's print:

```<code># Result: 1-10
</code>```

I think the problem is that the data in the viewer is not updated until the script finishes running.

How do I force a nuke to refresh the viewer?

Or there may be a command waiting to complete the update of previous commands?

Or it can be necessary to specify in a viewer a frame range?

答:
You just need to say viewer node to redraw then it will update range properly.

Here is a working example

```<code>vv = nuke.activeViewer().node()
nuke.root().knob('first_frame').setValue(1)
nuke.root().knob('last_frame').setValue(100)

vv.redraw()
vv['frame_range_lock'].setValue(True)
vv['frame_range'].setValue('25-40')
x = vv.playbackRange()
print(x)
</code>```

Title: Nuke Viewer set framerange trouble

Body:
I'm writing a timeline synchronization script in Nuke10.
I should change global frame settings. Example:

nuke.root().knob('first_frame').setValue(1)
nuke.root().knob('last_frame').setValue(100)

After that i should change viewer playback range. Example:

vv = nuke.activeViewer().node()
vv['frame_range_lock'].setValue(True)
vv['frame_range'].setValue('5-40')

Separately it's worked. But together - not. At start i have global frame range 1-10. And when i run all that's lines - frame range set to 1-100 but playback range set to 5-10.

I add command in the middle of the script to check playback range:

nuke.root().knob('first_frame').setValue(1)
nuke.root().knob('last_frame').setValue(100)

x = vv.playbackRange()
print(x)

vv['frame_range_lock'].setValue(True)
vv['frame_range'].setValue('5-40')

it's print:

# Result: 1-10

I think the problem is that the data in the viewer is not updated until the script finishes running.

How do I force a nuke to refresh the viewer?

Or there may be a command waiting to complete the update of previous commands?

Or it can be necessary to specify in a viewer a frame range?

Body:
You just need to say viewer node to redraw then it will update range properly.

Here is a working example

vv = nuke.activeViewer().node()
nuke.root().knob('first_frame').setValue(1)
nuke.root().knob('last_frame').setValue(100)

vv.redraw()
vv['frame_range_lock'].setValue(True)
vv['frame_range'].setValue('25-40')
x = vv.playbackRange()
print(x)


问:
beautifulsoup get images and google forms
I am trying to parse the following site using beautiful soup:
http://www.rishikumar.com/intern.html

I am then trying to send the entire webpage starting after the word "Subject" as the body of an email. I eventually want to automate the sending of an email for any message on this webpage.

I can successfully get the html text and styling but I am not sure how to extract the images as well as the google form at the bottom of the page. The images do not seem to have href's so I don't really know how to go about this.

Is this possible with beautiful soup/is there any other way to do what I am trying to achieve?

答:
Img url:

http://www.rishikumar.com/uploads/3/3/0/6/3306532/background-images/1586008872.png

Google form url:

https://docs.google.com/forms/d/e/1FAIpQLSep4Xbkgi5kk_MlupAFqUZuPDASWj95qMy8Y4M1-q2fKhudNw/viewform?embedded=true

I suggest you use F12 analysis page elements, take a look at beautifulsoup document


问:
Python Globalling to use and change in many functions
I have made a program where there is are many values that are accessed and changed in many classes and functions. I want to know is how to use and change a variable without using global or only using it once. I used global around 20 times all throughout my code and it looks ugly and is annoying.</p>

答: Two ideas that I have is either to pass a reference of all these variables through functions. The other idea is to define classes containing the variables. The all the functions of the class have access to the values defined in the class and you don't need to pass them. Or you are passing pack of variables.</p>


问:
Nested relationship ACF field not calling correct content
I have a repeater field for various properties. Inside that repeater field, I have a relationship subfield for references. When the "Open Modal" button is clicked, a modal pops up and should display the associated references for that property. Everything works except for the fact that no matter which property you click, it's only displaying the references for the first property. I have tried repositioning the endwhile; endif; wp_reset_postdata(); but have not been able to fix this issue.

Here is the link to the page.

Below is my PHP code:

```<code><?php if( have_rows('api_properties') ): ?>
            <ul>
            <?php while ( have_rows('api_properties') ) : the_row(); ?>

                <li>

                <?php

                    $name = get_sub_field('api_name');
                    $value = get_sub_field('api_value');
                    $posts = get_sub_field('api_references');
                ?>
                    <div class="w3-container">

                    <!-- Button trigger modal -->
                    <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>
                    <p><?php echo $name; ?></p>
                    <p><?php echo $value; ?></p>

                    <div id="id01" class="w3-modal">
                        <div class="w3-modal-content">
                          <header class="w3-container w3-teal">
                            <span onclick="document.getElementById('id01').style.display='none'"
                            class="w3-button w3-display-topright">×</span>
                            <h2>References</h2>
                            </header>

                        <div class="w3-container">
                        <ul>
                            <li class="header"><span>Title</span><span>Description</span><span class="number">Ref #</span><span>PDF</span></li>
                        </ul>
                        <?php if( $posts ): ?>
                                    <ul>
                                    <?php foreach( $posts as $p ): ?>
                                        <li>
                                            <span><a href="<?php echo get_permalink( $p->ID ); ?>">
                                                <?php echo get_the_title( $p->ID ); ?>
                                                </a></span>
                                            <span><?php echo get_field('reference_description', $p->ID); ?></span>
                                            <span class="number"><?php echo get_field('reference_number', $p->ID); ?></span>
                                            <span><?php echo get_field('reference_pdf', $p->ID); ?></span>
                                        </li>
                                    <?php endforeach; ?>
                                    </ul>

                                <?php endif; ?>

                          </div>
                          <footer class="w3-container w3-teal">
                            <p>Modal Footer</p>
                          </footer>
                      </div>
                     </div>
                    </div>

                    <p> </p>

            </li>

        <?php endwhile; ?>

            </ul>

        <?php endif; ?>
        <?php wp_reset_postdata(); ?>
</code>```

答:
The problem is in the button click action and the modal's id:

```<code><button onclick="document.getElementById('id01').style.display='block'" ...
// Then later,
<div id="id01" class="w3-modal">
</code>```

All buttons have the same onclick handler calling the div with the ID of id01, and all of the modal divs have an ID of id01; so, only the first one is showing. You need to increment the id as you're looping through. Something like (shortened for readability):

```<code><?php if( have_rows('api_properties') ): ?>
  <?php $id_increment = 0; ?>
  <ul>
    <?php while ( have_rows('api_properties') ) : the_row(); ?>
      // Your setup
      <button onclick="document.getElementById('id0<?php echo $id_increment; ?>').style.display='block'" class="w3-button w3-black">Open Modal</button>
      // More markup
      <div id="id0<?php echo $id_increment; ?>" class="w3-modal">
      // Rest of your modal and list markup
      <?php $id_increment++; ?>
    <?php endwhile; ?>
  </ul>
<?php endif; ?>
</code>```

Each time it loops through a "row" of the repeater, it will increase the $id_increment variable which will change the ID of the modal and the button used to open it.

Body:
I have a repeater field for various properties. Inside that repeater field, I have a relationship subfield for references. When the "Open Modal" button is clicked, a modal pops up and should display the associated references for that property. Everything works except for the fact that no matter which property you click, it's only displaying the references for the first property. I have tried repositioning the endwhile; endif; wp_reset_postdata(); but have not been able to fix this issue.

Here is the link to the page.

Below is my PHP code:

<?php if( have_rows('api_properties') ): ?>

            <?php while ( have_rows('api_properties') ) : the_row(); ?>

                <?php

                    $name = get_sub_field('api_name');
                    $value = get_sub_field('api_value');
                    $posts = get_sub_field('api_references');
                ?>

                    <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>

<?php echo $name; ?>

<?php echo $value; ?>

                            ×

References

TitleDescriptionRef #PDF

                        <?php if( $posts ): ?>

                                    <?php foreach( $posts as $p ): ?>

                                            <a href="<?php echo get_permalink( $p->ID ); ?>">
                                                <?php echo get_the_title( $p->ID ); ?>

                                            <?php echo get_field('reference_description', $p->ID); ?>
                                            <?php echo get_field('reference_number', $p->ID); ?>
                                            <?php echo get_field('reference_pdf', $p->ID); ?>

                                    <?php endforeach; ?>

                                <?php endif; ?>

Modal Footer

        <?php endwhile; ?>

        <?php endif; ?>
        <?php wp_reset_postdata(); ?>

Body:
The problem is in the button click action and the modal's id:

<button onclick="document.getElementById('id01').style.display='block'" ...
// Then later,
<div id="id01" class="w3-modal">

All buttons have the same onclick handler calling the div with the ID of id01, and all of the modal divs have an ID of id01; so, only the first one is showing. You need to increment the id as you're looping through. Something like (shortened for readability):

<?php if( have_rows('api_properties') ): ?>
  <?php $id_increment = 0; ?>
  <ul>
    <?php while ( have_rows('api_properties') ) : the_row(); ?>
      // Your setup
      <button onclick="document.getElementById('id0<?php echo $id_increment; ?>').style.display='block'" class="w3-button w3-black">Open Modal</button>
      // More markup
      <div id="id0<?php echo $id_increment; ?>" class="w3-modal">
      // Rest of your modal and list markup
      <?php $id_increment++; ?>
    <?php endwhile; ?>
  </ul>
<?php endif; ?>

Each time it loops through a "row" of the repeater, it will increase the $id_increment variable which will change the ID of the modal and the button used to open it.


问:
How do you make an Angular 2 component destroy itself?
I am creating multiple dropdown menu components with a button in the parent, but I want those components to have buttons which destroy themselves. I'm sure it's simple, but can't seem to find anything that will do it. I know how to destroy it from the parent, but can't seem to do it from within. Anyone know? And just before it's destroyed, how can I send a message to the parent letting it know? (I have instances of them in the parent, but there are other things in the parent that need a signal)

I'm creating them dynamically using viewContainerRef.createComponent. Template looks like this:

```<code><template item-host></template>
</code>```

I tried an @Output and got this:

```<code><template item-host [ERROR ->](destroyCheck)="someMethod($event)"></template>
</code>```

答:
Declare a output variable

```<code>@Output() destroyCheck:EventEmitter<string>=new EventEmitter<string>();

ngOnDestroy(){

          this.destroyCheck.emit('destroyed');

}
</code>```

In your parent component handle this way.

```<code><div>
     <child-comp (destroyCheck)="someMethod($event)"> </child-comp>
</div>
</code>```

Your method should be handled as

```<code>someMethod(something){
  console.log(something);
}
</code>```

Body:
I am creating multiple dropdown menu components with a button in the parent, but I want those components to have buttons which destroy themselves. I'm sure it's simple, but can't seem to find anything that will do it. I know how to destroy it from the parent, but can't seem to do it from within. Anyone know? And just before it's destroyed, how can I send a message to the parent letting it know? (I have instances of them in the parent, but there are other things in the parent that need a signal)

I'm creating them dynamically using viewContainerRef.createComponent. Template looks like this:

<template item-host></template>

I tried an @Output and got this:

<template item-host [ERROR ->](destroyCheck)="someMethod($event)"></template>

Body:
Declare a output variable

@Output() destroyCheck:EventEmitter<string>=new EventEmitter<string>();

ngOnDestroy(){

          this.destroyCheck.emit('destroyed');

}

In your parent component handle this way.

<div>
     <child-comp (destroyCheck)="someMethod($event)"> </child-comp>
</div>

Your method should be handled as

someMethod(something){
  console.log(something);
}


问:
Hide advanced custom fields items behind a checkbox
I have several advanced custom field items for different tasks on a post. I am looking for a way to group together fields for every separate task and hide them behind a checkbox so the user does not get confused between different fields.</p>

答: Add a checkbox, and then make your fields conditional based on whether the checkbox is checked. This is built-in ACF functionality. When you select "conditional" in ACF, it will show a dropdown for you to set when the field should be visible or not.</p>


问:
Web Server in IIS stops time after time
I have developed a web service in c# (ASP.NET), and published it in IIS 6.1 (Windows Server 2008). Web application takes data from this web service, but time after time it does not return anything. After I restart web service it works again normally. I don't understand why web service stops returning result time after time. What can cause this? Any help please?</p>

答: Hard to say without knowing any details. But an approach would be checking the event logs.</p>

Title: Web Server in IIS stops time after time


问:
Installing g++ 7.0.1 on Debian 8.7
I have been trying for quite some time to install g++ 7 on my Debian machine. I was able to install it quite easily on my mac (as homebrew had a formula for it). However I cannot seem to find a way to install it on Linux.

This individual had a thread on installing g++ 4.9, and changing the url he gave led me to this page, which seems to be in the right direction... But I imagine installing it this way might lead to a few potential problems down the road when I wish to update these packages.

Is there a source I'm missing? Or is there maybe a place where I can download and compile everything I need to get it running?

Thank you for your help.

Helpful Data:

My kernel is x86_64 Linux 3.16.0-4-amd64.

Edit: After following Dietrich's advice, I am now met with a new error:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gcc-7 : Depends: cpp-7 (= 7-20170316-1) but it is not going to be installed
         Depends: libcc1-0 (>= 7-20170316-1) but it is not going to be installed
         Depends: binutils (>= 2.28) but 2.25-5+deb8u1 is to be installed
         Depends: libgcc-7-dev (= 7-20170316-1) but it is not going to be installed
         Depends: libisl15 (>= 0.15) but it is not installable
         Depends: libmpfr4 (>= 3.1.3) but 3.1.2-2 is to be installed
         Depends: libstdc++6 (>= 5) but 4.9.2-10 is to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

This is how my sources.list is set up:

```<code>#------------------------------------------------------------------------------#
#                   OFFICIAL DEBIAN REPOS
#------------------------------------------------------------------------------#

###### Debian Main Repos
deb http://ftp.us.debian.org/debian/ jessie main contrib non-free
deb-src http://ftp.us.debian.org/debian/ jessie main contrib non-free

###### Debian Update Repos
deb http://security.debian.org/ jessie/updates main contrib non-free
deb http://ftp.us.debian.org/debian/ jessie-proposed-updates main contrib non-free
deb-src http://security.debian.org/ jessie/updates main contrib non-free
deb-src http://ftp.us.debian.org/debian/ jessie-proposed-updates main contrib non-free

###### For ffmpeg
deb http://www.deb-multimedia.org jessie main non-free

###### For gcc-7 (Experimental)
deb http://httpredir.debian.org/debian experimental main
</code>```

I'm guessing this is, as you said, a problem with me being on Debian stable? What would I need to do in order to fix this error, while remaining on stable?

Edit 2: Okay, so I figured out that last error. I just had to add go through for every individual dependency that gave my trouble and install it using apt-get install -t testing . Thank you to everyone who replied. You were all very helpful.

答:
From the page you must download the g++7 for amd64 deb file. Then, as root, run the following command.</p>

```<code>dpkg -i file.deb
</code>```

Title: Installing g++ 7.0.1 on Debian 8.7

Body:
I have been trying for quite some time to install g++ 7 on my Debian machine. I was able to install it quite easily on my mac (as homebrew had a formula for it). However I cannot seem to find a way to install it on Linux.

This individual had a thread on installing g++ 4.9, and changing the url he gave led me to this page, which seems to be in the right direction... But I imagine installing it this way might lead to a few potential problems down the road when I wish to update these packages.

Is there a source I'm missing? Or is there maybe a place where I can download and compile everything I need to get it running?

Thank you for your help.

Helpful Data:

My kernel is x86_64 Linux 3.16.0-4-amd64.

Edit: After following Dietrich's advice, I am now met with a new error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 gcc-7 : Depends: cpp-7 (= 7-20170316-1) but it is not going to be installed
         Depends: libcc1-0 (>= 7-20170316-1) but it is not going to be installed
         Depends: binutils (>= 2.28) but 2.25-5+deb8u1 is to be installed
         Depends: libgcc-7-dev (= 7-20170316-1) but it is not going to be installed
         Depends: libisl15 (>= 0.15) but it is not installable
         Depends: libmpfr4 (>= 3.1.3) but 3.1.2-2 is to be installed
         Depends: libstdc++6 (>= 5) but 4.9.2-10 is to be installed
E: Unable to correct problems, you have held broken packages.

This is how my sources.list is set up:

#------------------------------------------------------------------------------#
#                   OFFICIAL DEBIAN REPOS
#------------------------------------------------------------------------------#

###### Debian Main Repos
deb http://ftp.us.debian.org/debian/ jessie main contrib non-free
deb-src http://ftp.us.debian.org/debian/ jessie main contrib non-free

###### Debian Update Repos
deb http://security.debian.org/ jessie/updates main contrib non-free
deb http://ftp.us.debian.org/debian/ jessie-proposed-updates main contrib non-free
deb-src http://security.debian.org/ jessie/updates main contrib non-free
deb-src http://ftp.us.debian.org/debian/ jessie-proposed-updates main contrib non-free

###### For ffmpeg
deb http://www.deb-multimedia.org jessie main non-free

###### For gcc-7 (Experimental)
deb http://httpredir.debian.org/debian experimental main

I'm guessing this is, as you said, a problem with me being on Debian stable? What would I need to do in order to fix this error, while remaining on stable?

Edit 2: Okay, so I figured out that last error. I just had to add go through for every individual dependency that gave my trouble and install it using apt-get install -t testing . Thank you to everyone who replied. You were all very helpful.

Body:
From the page you must download the g++7 for amd64 deb file. Then, as root, run the following command.

dpkg -i file.deb


问:
Assigning avatars from URL string in JSQMessagesController
I couldn't find much of use in the docs, and the sample project in Swift only had hardcoded avatars so that wasn't much help either. I also saw this question but that example was also not applicable in my situation.

I have my user sign in with Facebook, and a graph request grabs their profile picture which is then stored in Firebase and a User object as a string (the URL path to the image I mean).

This is my cellForItem function

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
    let message = messages[indexPath.item]

    if message.senderId == senderId {
        cell.textView?.textColor = UIColor.white
    } else {
        cell.textView?.textColor = UIColor.black
    }
    return cell
}
</code>```

And this is where I should be setting the avatars:

```<code>override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {

    let message = messages[indexPath.item]

    if let messageID = message.senderId {
        let users = [User]()
        let userProfilePictures = users[indexPath.row].profilePicture
    }

    return ????
}
</code>```

Anyone know how I can get the profile pictures set to the correct avatars?

EDIT: This is my image caching code:

```<code>let imageCache = NSCache<NSString, UIImage>()
</code>```

extension UIImageView {

```<code>func loadImageUsingCacheWithUrlString(_ urlString: String) {

    self.image = nil

    // Check cache for image first
    if let cachedImage = imageCache.object(forKey: urlString as NSString) {
        self.image = cachedImage
        return
    }

    // Otherwise fire off a new download
    Alamofire.request(urlString)
        .responseImage { response in

            if let downloadedImage = response.result.value {
                // image is here.
                imageCache.setObject(downloadedImage, forKey: urlString as NSString)
                self.image = downloadedImage
            }
        }
}
</code>```

}

答:
Ya, What you are looking for is the 'JSQMessagesAvatarImageFactory' Documentation Link

Since you have your userProfilePicture Then you just need to get the image data for that url. You can do this a number of ways I personally love to use a framework that handles catching for you. SDWebImage or AlamofireImage or how ever else you want to get that data.

I like AlimofireImage so that is what I will demonstrate here. To make it so that I do not have to keep making downloading request for each cell I save them in a dictionary using the senderID as a key. If the dictionary entry is there I don't make the request. Define your dictionary.

```<code>var avatarDictionary: [String:UIImage] = [:]
</code>```

Then after retrieving all the messages for the conversation call getAllAvatars()

```<code>func getAllAvatars() {
    for message in messages {
        guard let key = message.senderID else { return }
        if avatarDictionary[key] == nil {
            try? _ = imageDownloader?.download(URLRequest(url: API.userPhoto(userID: key).asURL()), completion: { (response) in
                guard let image = response.result.value else { return }
                self.avatarDictionary[key] = image
                self.collectionView.reloadData()
            })
        }
    }
}
</code>```

API.userPhoto(userID: key).asURL() is the url to your image data source so this is what you will change for the url you have.

There are a few other methods you could also take a look into. I made my own function to give me a defaultAvatar for users with no image. It looks like this

```<code>func blankAvatar(message: Message) -> JSQMessageAvatarImageDataSource {
    return JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: initialsFrom(firstName: message.fistName, lastName: message.lastName), backgroundColor: UIColor.gray, textColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
}
</code>```

Then you can return a image if it is there or a blank avatar if not from the avatarImageDataForItemAt method

```<code>return avatarDictionary[id] == nil ? blankAvatar(message: message) : JSQMessagesAvatarImageFactory.avatarImage(with: avatarDictionary[id], diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
</code>```

Also don't forget to set the size of the avatars for the collectionView

```<code> collectionView?.collectionViewLayout.incomingAvatarViewSize = avatarSize
 collectionView?.collectionViewLayout.outgoingAvatarViewSize = avatarSize
</code>```

or they wont show at all.

Let me know if you need more help .

Body:
I couldn't find much of use in the docs, and the sample project in Swift only had hardcoded avatars so that wasn't much help either. I also saw this question but that example was also not applicable in my situation.

I have my user sign in with Facebook, and a graph request grabs their profile picture which is then stored in Firebase and a User object as a string (the URL path to the image I mean).

This is my cellForItem function

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
    let message = messages[indexPath.item]

    if message.senderId == senderId {
        cell.textView?.textColor = UIColor.white
    } else {
        cell.textView?.textColor = UIColor.black
    }
    return cell
}

And this is where I should be setting the avatars:

override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {

    let message = messages[indexPath.item]

    if let messageID = message.senderId {
        let users = [User]()
        let userProfilePictures = users[indexPath.row].profilePicture
    }

    return ????
}

Anyone know how I can get the profile pictures set to the correct avatars?

EDIT: This is my image caching code:

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

func loadImageUsingCacheWithUrlString(_ urlString: String) {

    self.image = nil

    // Check cache for image first
    if let cachedImage = imageCache.object(forKey: urlString as NSString) {
        self.image = cachedImage
        return
    }

    // Otherwise fire off a new download
    Alamofire.request(urlString)
        .responseImage { response in

            if let downloadedImage = response.result.value {
                // image is here.
                imageCache.setObject(downloadedImage, forKey: urlString as NSString)
                self.image = downloadedImage
            }
        }
}

}

Body:
Ya, What you are looking for is the 'JSQMessagesAvatarImageFactory' Documentation Link

Since you have your userProfilePicture Then you just need to get the image data for that url. You can do this a number of ways I personally love to use a framework that handles catching for you. SDWebImage or AlamofireImage or how ever else you want to get that data.

I like AlimofireImage so that is what I will demonstrate here. To make it so that I do not have to keep making downloading request for each cell I save them in a dictionary using the senderID as a key. If the dictionary entry is there I don't make the request. Define your dictionary.

var avatarDictionary: [String:UIImage] = [:]

Then after retrieving all the messages for the conversation call getAllAvatars()

func getAllAvatars() {
    for message in messages {
        guard let key = message.senderID else { return }
        if avatarDictionary[key] == nil {
            try? _ = imageDownloader?.download(URLRequest(url: API.userPhoto(userID: key).asURL()), completion: { (response) in
                guard let image = response.result.value else { return }
                self.avatarDictionary[key] = image
                self.collectionView.reloadData()
            })
        }
    }
}

API.userPhoto(userID: key).asURL() is the url to your image data source so this is what you will change for the url you have.

There are a few other methods you could also take a look into. I made my own function to give me a defaultAvatar for users with no image. It looks like this

func blankAvatar(message: Message) -> JSQMessageAvatarImageDataSource {
    return JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: initialsFrom(firstName: message.fistName, lastName: message.lastName), backgroundColor: UIColor.gray, textColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
}

Then you can return a image if it is there or a blank avatar if not from the avatarImageDataForItemAt method

return avatarDictionary[id] == nil ? blankAvatar(message: message) : JSQMessagesAvatarImageFactory.avatarImage(with: avatarDictionary[id], diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))

Also don't forget to set the size of the avatars for the collectionView

 collectionView?.collectionViewLayout.incomingAvatarViewSize = avatarSize
 collectionView?.collectionViewLayout.outgoingAvatarViewSize = avatarSize

or they wont show at all.

Let me know if you need more help .


问:
How to clip the gradient norm on the grad_and_var tuple in tensorflow-r1.0?
After getting the grad_and_var tuple with compute_gradient:

```<code>opt = tf.train.RMSPropOptimizer(learning_rate)
grad_and_var = opt.compute_gradients(losses, params)
</code>```

I'd like to clip the grad_and_var. But when I do:

```<code>clipped_gradients, _ = tf.clip_by_global_norm(grad_and_var, max_gradient_norm)
</code>```

directly, the resulting clipped_gradients is a list of tensor, that means, the gradient and the variables has been concatenated.

If I do

```<code>clipped_gradients = [tf.clip_by_global_norm(x[0], max_gradient_norm)[0] for x in grad_and_var]
</code>```

I got such an error:

```<code>TypeError: t_list should be a sequence
</code>```

Do you have any idea that how can I fix it? Thanks a lot!

答:
you can clip norm and add gradient noise like this:</p>

```<code>opt = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate)
gvs = opt.compute_gradients(self.loss)
gvs = [(tf.clip_by_norm(grad,self.config.max_grad), val) for grad,val in gvs]
gvs = [(tf.add(grad, tf.random_normal(tf.shape(grad),stddev=self.config.grad_noise)), val) for grad,val in gvs]
self.train_op = opt.apply_gradients(gvs)
</code>```

Body:
After getting the grad_and_var tuple with compute_gradient:

opt = tf.train.RMSPropOptimizer(learning_rate)
grad_and_var = opt.compute_gradients(losses, params)

I'd like to clip the grad_and_var. But when I do:

clipped_gradients, _ = tf.clip_by_global_norm(grad_and_var, max_gradient_norm)

directly, the resulting clipped_gradients is a list of tensor, that means, the gradient and the variables has been concatenated.

If I do

clipped_gradients = [tf.clip_by_global_norm(x[0], max_gradient_norm)[0] for x in grad_and_var]

I got such an error:

TypeError: t_list should be a sequence

Do you have any idea that how can I fix it? Thanks a lot!

Body:
you can clip norm and add gradient noise like this:

opt = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate)
gvs = opt.compute_gradients(self.loss)
gvs = [(tf.clip_by_norm(grad,self.config.max_grad), val) for grad,val in gvs]
gvs = [(tf.add(grad, tf.random_normal(tf.shape(grad),stddev=self.config.grad_noise)), val) for grad,val in gvs]
self.train_op = opt.apply_gradients(gvs)


问:
Why does Entity Framework Database First overrides on delete no action
I have an Entity Framework Project for a WinForms application and the approach that I'm using is Database First.
And here is my setup (I keep it as simple as possible):
Sql Database Model
Entity Framework Model

The problem is when I try to delete a department using the command:

```<code>context.Departamento.Remove(departamento)
</code>```

It deletes every record on DepartamentoComputadora table instead of throwing an exception for the "On Delete No Action" constraint in the database.

The weird thing is that if I try to delete that department on my database it actually does not let me delete it because of the constraint.

Is any configuration that I am missing on EF to enforce the on delete no action?

It is weirder that the actual configuration of EF shows the behavior that I expect to have on the table.

Thank you in advance!

答:
Actually, it was my fault with some issues with Git on Visual Studio. My model got broken when I committed staged changes and then even I was deleting, uninstalling EF, installing it again and recreating the model from scratch, some files were not deleted from my project folder and that was causing the problem.

The solution was pretty simple:

Creating a branch for the fix.

Deleting the Entity Data Model.

Uninstall EF and removed all left lines on app.config file referencing EF.

Installing EF again.

Creating the model again and committing changes.

Done.

Thank you very much!

Body:
I have an Entity Framework Project for a WinForms application and the approach that I'm using is Database First.
And here is my setup (I keep it as simple as possible):
Sql Database Model
Entity Framework Model

The problem is when I try to delete a department using the command:

context.Departamento.Remove(departamento)

It deletes every record on DepartamentoComputadora table instead of throwing an exception for the "On Delete No Action" constraint in the database.

The weird thing is that if I try to delete that department on my database it actually does not let me delete it because of the constraint.

Is any configuration that I am missing on EF to enforce the on delete no action?

It is weirder that the actual configuration of EF shows the behavior that I expect to have on the table.

Thank you in advance!


答:
You can find similar in the Stack Overflow Unix pages
To install the newest g++ from testing on debian, do the following:
Add debian testing repo to your apt sources by creating a file (with .list extension) on /etc/apt/sources.list.d folder containing the line

```<code>deb http://ftp.us.debian.org/debian testing main contrib non-free
</code>```

Instruct debian to use testing sources on certain packages by creating a file on /etc/apt/preferences.d containing the following:

```<code>Package: *
Pin: release a=testing
Pin-Priority: 100
</code>```

You should name the file something like preferences or testingpref,etc. If you have a preferences file, you can add it there. Remove the .unused or any . in the filename.

Update database:

```<code>sudo apt-get update
</code>```

Install g++:

```<code>sudo apt-get install -t testing g++
</code>```

This will give you the most recent version of g++ in the repo. Thus it will receive updates and more-easily reversable. You need to use -t testing to get most recent versions.
You may have dependency issues. It may be in experimental instead of testing for your architecture. See https://packages.debian.org/search?keywords=g%2B%2B

For experimental packages (7 is in there) add:

```<code>deb http://httpredir.debian.org/debian experimental main
</code>```

to /etc/apt/sources.list . Similar to above.. pinning should say a=experimental instead of a=testing and lastly,

```<code>sudo apt-get install -t experimental g++
</code>```

Good luck.

Title: Installing g++ 7.0.1 on Debian 8.7

Body:
You can find similar in the Stack Overflow Unix pages
To install the newest g++ from testing on debian, do the following:
Add debian testing repo to your apt sources by creating a file (with .list extension) on /etc/apt/sources.list.d folder containing the line

deb http://ftp.us.debian.org/debian testing main contrib non-free

Instruct debian to use testing sources on certain packages by creating a file on /etc/apt/preferences.d containing the following:

Package: *
Pin: release a=testing
Pin-Priority: 100

You should name the file something like preferences or testingpref,etc. If you have a preferences file, you can add it there. Remove the .unused or any . in the filename.

Update database:

sudo apt-get update

Install g++:

sudo apt-get install -t testing g++

This will give you the most recent version of g++ in the repo. Thus it will receive updates and more-easily reversable. You need to use -t testing to get most recent versions.
You may have dependency issues. It may be in experimental instead of testing for your architecture. See https://packages.debian.org/search?keywords=g%2B%2B

For experimental packages (7 is in there) add:

deb http://httpredir.debian.org/debian experimental main

to /etc/apt/sources.list . Similar to above.. pinning should say a=experimental instead of a=testing and lastly,

sudo apt-get install -t experimental g++

Good luck.

ContentLicense: CC BY-SA 4.0