问:
Change the background color of a div using Javascript and a json file
I am trying to dynamically create and color divs based on a .json file i have created. I have been able to create each individual div but adding the colors from the file is what I can't seem to do, i have been able to print out the color names but being able to change each div is giving me issues any assistance would be greatly appreciated.

My code is below.

index.html

```<code> <!DOCTYPE html>
<meta charset="utf-8">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link rel="stylesheet" type="css/text" href="">
   <title>Json and Ajax</title>
</head>
<style>

    h1
    {
        margin-bottom: 60px;
    }

    .boxvalue
    {
        width:150px;
        height: 150px;
        border: 2px solid rgb(199, 91, 91);
        display: inline-block;
        margin: 20px;
    }

    .Colorname
    {
        font-size: 18px;
        font-weight: 600;
        margin: 20px;
        display: inline-block;
        text-align: center;
    }
</style>
<body>
<div class="container-fluid">
    <header>
      <h1>Colors</h1>
    </header>
   <div id="ColorArea">

   </div>
</div>
    <script src="colorequest.js"></script>
 </body>
</code>```

js File

```<code>var ColorContainer = document.getElementById('ColorArea');

var NewRequest = new XMLHttpRequest();
NewRequest.open('GET', 'colors.json', true);

NewRequest.onload = function()
{
    var ColorData = JSON.parse(NewRequest.responseText);
    renderHTML(ColorData);
};
NewRequest.send();

/* Function used to render the Color Data */
function renderHTML(data){
 var ColorInfo = " ";
 var Colordiv

 for (i = 0; i<data.length; i++)
    {
        ColorInfo += data[i].code.hex + " " + data[i].color + "<br>";
        Colordiv = document.createElement('div');
        Colordiv.classList.add('boxvalue');
        ColorContainer.appendChild(Colordiv);
    }

}
</code>```

json File

```<code>[
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]
</code>```

答:
You can set the background color of the div with CSS:

```<code>Colordiv.style.backgroundColor = data[i].code.hex;
</code>```

The for loop becomes

```<code>for (i = 0; i<data.length; i++) {
  ColorInfo += data[i].code.hex + " " + data[i].color + "<br>";
  Colordiv = document.createElement('div');
  Colordiv.classList.add('boxvalue');
  Colordiv.style.backgroundColor = data[i].code.hex;
  ColorContainer.appendChild(Colordiv);
}
</code>```

var ColorContainer = document.getElementById('ColorArea');

var ColorData = [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]

/* Function used to render the Color Data */
function renderHTML(data){
 var ColorInfo = " ";
 var Colordiv

 for (i = 0; i<data.length; i++)
    {
        ColorInfo += data[i].code.hex + " " + data[i].color + "
";
        Colordiv = document.createElement('div');
        Colordiv.classList.add('boxvalue');
        Colordiv.style.backgroundColor = data[i].code.hex;
        ColorContainer.appendChild(Colordiv);
    }

}

renderHTML(ColorData)```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
<meta charset="utf-8">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link rel="stylesheet" type="css/text" href="">
   <title>Json and Ajax</title>
</head>
<style>

    h1
    {
        margin-bottom: 60px;
    }

    .boxvalue
    {
        width:150px;
        height: 150px;
        border: 2px solid rgb(199, 91, 91);
        display: inline-block;
        margin: 20px;
    }

    .Colorname
    {
        font-size: 18px;
        font-weight: 600;
        margin: 20px;
        display: inline-block;
        text-align: center;
    }
</style>
<body>
<div class="container-fluid">
    <header>
      <h1>Colors</h1>
    </header>
   <div id="ColorArea">

   </div>
</div>
    <script src="colorequest.js"></script>
 </body></code>```

Body:
I am trying to dynamically create and color divs based on a .json file i have created. I have been able to create each individual div but adding the colors from the file is what I can't seem to do, i have been able to print out the color names but being able to change each div is giving me issues any assistance would be greatly appreciated.

My code is below.

index.html

 <!DOCTYPE html>
<meta charset="utf-8">

   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link rel="stylesheet" type="css/text" href="">
   <title>Json and Ajax</title>

Colors

js File

var ColorContainer = document.getElementById('ColorArea');

var NewRequest = new XMLHttpRequest();
NewRequest.open('GET', 'colors.json', true);

NewRequest.onload = function()
{
    var ColorData = JSON.parse(NewRequest.responseText);
    renderHTML(ColorData);
};
NewRequest.send();

/* Function used to render the Color Data */
function renderHTML(data){
 var ColorInfo = " ";
 var Colordiv

 for (i = 0; i<data.length; i++)
    {
        ColorInfo += data[i].code.hex + " " + data[i].color + "
";
        Colordiv = document.createElement('div');
        Colordiv.classList.add('boxvalue');
        ColorContainer.appendChild(Colordiv);
    }

}

json File

[
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]

Body:
You can set the background color of the div with CSS:

Colordiv.style.backgroundColor = data[i].code.hex;

The for loop becomes

for (i = 0; i<data.length; i++) {
  ColorInfo += data[i].code.hex + " " + data[i].color + "<br>";
  Colordiv = document.createElement('div');
  Colordiv.classList.add('boxvalue');
  Colordiv.style.backgroundColor = data[i].code.hex;
  ColorContainer.appendChild(Colordiv);
}

var ColorContainer = document.getElementById('ColorArea');

var ColorData = [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]

/* Function used to render the Color Data */
function renderHTML(data){
 var ColorInfo = " ";
 var Colordiv

 for (i = 0; i<data.length; i++)
    {
        ColorInfo += data[i].code.hex + " " + data[i].color + "<br>";
        Colordiv = document.createElement('div');
        Colordiv.classList.add('boxvalue');
        Colordiv.style.backgroundColor = data[i].code.hex;
        ColorContainer.appendChild(Colordiv);
    }

}

renderHTML(ColorData)

 <!DOCTYPE html>
<meta charset="utf-8">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link rel="stylesheet" type="css/text" href="">
   <title>Json and Ajax</title>
</head>
<style>

    h1
    {
        margin-bottom: 60px;
    }

    .boxvalue
    {
        width:150px;
        height: 150px;
        border: 2px solid rgb(199, 91, 91);
        display: inline-block;
        margin: 20px;
    }

    .Colorname
    {
        font-size: 18px;
        font-weight: 600;
        margin: 20px;
        display: inline-block;
        text-align: center;
    }
</style>
<body>
<div class="container-fluid">
    <header>
      <h1>Colors</h1>
    </header>
   <div id="ColorArea">

   </div>
</div>
    <script src="colorequest.js"></script>
 </body>


来源: stackexchange

问:
Tkinter error: Couldn't recognize data in image file
I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn't recognize data in image file

I use the code from the documentation:

```<code>canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)
</code>```

Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?

I am using Python 3 on Mac. Python file and image are in the same folder.

答:
Your code seems right, this is running for me on Windows 7 (Python 3.6):

```<code>from tkinter import *
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

mainloop()
</code>```

resulting in this tkinter GUI:

 with this image as bll.jpg:

(imgur converted it to bll.png but this is working for me as well.)

More options:

This answer mentions, tkinter is working only with gif images. Try using a .gif image.

If this is not working, use PIL as stated in this answer.

Update: Solution with PIL:

```<code>from tkinter import *
from PIL import ImageTk, Image
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = ImageTk.PhotoImage(Image.open("bll.jpg"))  # PIL solution
canv.create_image(20, 20, anchor=NW, image=img)

mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn't recognize data in image file

I use the code from the documentation:

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?

I am using Python 3 on Mac. Python file and image are in the same folder.

Body:
Your code seems right, this is running for me on Windows 7 (Python 3.6):

from tkinter import *
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

mainloop()

resulting in this tkinter GUI:

 with this image as bll.jpg:

(imgur converted it to bll.png but this is working for me as well.)

More options:

This answer mentions, tkinter is working only with gif images. Try using a .gif image.

If this is not working, use PIL as stated in this answer.

Update: Solution with PIL:

from tkinter import *
from PIL import ImageTk, Image
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = ImageTk.PhotoImage(Image.open("bll.jpg"))  # PIL solution
canv.create_image(20, 20, anchor=NW, image=img)

mainloop()


问:
Square Point of Sale API - Error code "amount_too_small", but card is charged?
i'm making calls to the square pos ios web api with charges of $1.00 for system integration testing.

the calls are successful, in that they switch control to the square app, the card gets charged $1.00, transactions show up in the dashboard, i can refund them, etc. so obviously i'm sending the minimum amount suggested in the documentation to test the api (https://docs.connect.squareup.com/articles/web-api-ios) due to the lack of a point of sale api sandbox?

why does the response return a status of "error" with an error_code of "amount_too_small" when it was processed successfully?

答:
Make sure you are using an amount of at least 100 to represent $1 (or 100 cents). You should only get this error if you try to charge an amount lower than 100.

My guess is that you are seeing transactions that you made previously, or you are getting replayed responses by reusing idempotency keys. If you are in fact getting an error in response while a transaction is being created, it seems like there is something wrong with our system. Could you record a video of what you are doing, or some detailed logs of requests & responses with headers?


问:
Nested Vue.Draggable list breaks when dragging cross-level
I want to have a draggable, nested list with Vue and used the Vue.Draggable component for it. I'm however stuck with updating nested lists.

The rendering is fine, the dragging is fine when you stay inside the same level. But dragging cross-level doesn't seem to do it (error in VueComponent.onDragStart).

html

```<code><template>
  <div class="fluid container">

    <div  class="col-md-6">
        <draggable class="list-group" element="ul" v-model="list" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false">
          <transition-group type="transition" :name="'flip-list'">
            <li class="list-group-item" v-for="element in list" :key="element.order">

              <i :class="element.fixed? 'fa fa-anchor' : 'glyphicon glyphicon-pushpin'" @click=" element.fixed=! element.fixed" aria-hidden="true"></i>
              {{element.name}}
              <span class="badge">{{element.order}}</span>

              <draggable v-if="element.notes" class="list-group" element="ul" :options="dragOptions" :move="onMove">
                 <transition-group class="list-group" :name="'flip-list'">
                   <li class="list-group-item" v-for="elementDeep in element.notes" :key="elementDeep.order">
                      {{elementDeep.name}} <span class="badge">{{ elementDeep.order }}</span>
                  </li>
                </transition-group>
              </draggable>

            </li>
          </transition-group>
      </draggable>
    </div>

    <div  class="list-group col-md-6">
      ```{{listString}}```
    </div>

  </div>
</template>
</code>```

Vue js

```<code><script>
import draggable from 'vuedraggable'

var folderOneReady = [
   {
      "name":"LOREM IPSUM",
      "order":1,
      "fixed":false
   },
   {
      "name":"MAGNA ALIQUA",
      "order":2,
      "fixed":false
   },
    {
      "name": "DOLOREM LAUDANTIUM",
      "notes": [
         {
           "name": "Note level deep One",
            "order":31,
            "fixed":false
         },
          {
           "name": "Note level deep two",
            "order":32,
            "fixed":false
         },
         {
           "name": "Note level deep deep three",
            "order":33,
            "fixed":false
         }
       ],
       "order":3,
       "fixed":false
    },
   {
      "name":"SIT AMET",
      "order":4,
      "fixed":false
   },
   {
      "name":"NEMO",
      "order":5,
      "fixed":false
   },
   {
      "name":"ACCUSANTIUM",
      "order":6,
      "fixed":false
   },
   {
      "name":"ESSE",
      "order":7,
      "fixed":false
   },
   {
      "name":"DOLORES",
      "order":8,
      "fixed":false
   }
];

export default {
  name: 'hello',
  components: {
    draggable,
  },
  data () {
    return {
      list: folderOneReady,
      editable:true,
      isDragging: false,
      delayedDragging:false
    }
  },
  methods:{
    onMove ({relatedContext, draggedContext}) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      return (!relatedElement || !relatedElement.fixed) && !draggedElement.fixed;
    }
  },
  computed: {
    dragOptions () {
      return  {
        animation: 1,
        group: 'description',
        disabled: !this.editable,
        ghostClass: 'ghost'
      };
    },
    listString(){
      return JSON.stringify(this.list, null, 2);
    }
  },
  watch: {
    isDragging (newValue) {
      if (newValue){
        this.delayedDragging= true
        return
      }
      this.$nextTick( () =>{
           this.delayedDragging =false
      })
    }
  }
}
</script>
</code>```

Anyone can direct me in the right direction?

答:
It may not be the only problem but you need to set the list prop or use v-model for the nested draggable
Try something like:</p>

```<code><draggable v-if="element.notes" class="list-group" element="ul" :options="dragOptions" :move="onMove" :list="element.notes">
</code>```

Body:
I want to have a draggable, nested list with Vue and used the Vue.Draggable component for it. I'm however stuck with updating nested lists.

The rendering is fine, the dragging is fine when you stay inside the same level. But dragging cross-level doesn't seem to do it (error in VueComponent.onDragStart).

html

<template>

        <draggable class="list-group" element="ul" v-model="list" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false">
          <transition-group type="transition" :name="'flip-list'">

              {{element.name}}
              {{element.order}}

              <draggable v-if="element.notes" class="list-group" element="ul" :options="dragOptions" :move="onMove">
                 <transition-group class="list-group" :name="'flip-list'">

                      {{elementDeep.name}} {{ elementDeep.order }}

                </transition-group>
              </draggable>

          </transition-group>
      </draggable>

{{listString}}

</template>

Vue js

Anyone can direct me in the right direction?

Body:
It may not be the only problem but you need to set the list prop or use v-model for the nested draggable
Try something like:

<draggable v-if="element.notes" class="list-group" element="ul" :options="dragOptions" :move="onMove" :list="element.notes">


问:
Add UIView to ContentView in a TableViewCell using constraints
I am trying to add cells to UITableView using Constraints. Do you know how. The following just gives:

And says: Height is ambiguous for UIView

Do you know how to add a UIView to ContextView using constraints - note the fixed height in the constraints.

```<code>import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintHeight = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.height,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: nil,
                                                  attribute: NSLayoutAttribute.height,
                                                  multiplier: 1, constant: 50) // << Note fixed height

        view.translatesAutoresizingMaskIntoConstraints = false

        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintHeight])

        return cell!
    }

}
</code>```

Tried to change constraints to include bottom of the contentView:

```<code>import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintBottom = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: view,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  multiplier: 1, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintBottom])

        return cell!
    }

}
</code>```

答:
You're doing a couple things wrong.

First, you are setting the constraints backward. You want to constrain your new view to the contentView:

```<code>let constraintTop = NSLayoutConstraint(item: view,  // constrain this view
                           attribute: NSLayoutAttribute.top,
                           relatedBy: NSLayoutRelation.equal,
                           toItem: cell?.contentView,  // to this view
                           attribute: NSLayoutAttribute.top,
                           multiplier: 1,
                           constant: 0)
</code>```

Second, don't do this:

```<code>cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
</code>```

Third, your code is (well, will be) adding a new "orange view" every time the cell is reused. Much better to add subviews in the init portion of a custom cell class, but if you're going to do it in cellForRow, check if it's already there first:

```<code>    if cell.contentView.subviews.count == 0 {
        // no, so add it here

        let view = UIView()

        // continue with view setup
</code>```

Fourth, you may find it easier / more logical / cleaner / etc to add constraints this way:

```<code>cell.contentView.addSubview(view)

view.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 0.0).isActive = true
view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 0.0).isActive = true
view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 0.0).isActive = true
view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: 0.0).isActive = true
</code>```

And... since you have registered a cell class for reuse, this format will give you a valid cell:

```<code>    // instead of this
    //var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    //if cell == nil {
    //  cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
    //}

    // better method
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
</code>```

So, here is the full function:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    // have we already added the subview?
    if cell.contentView.subviews.count == 0 {
        // no, so add it here

        let view = UIView()

        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        cell.contentView.addSubview(view)

        view.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 0.0).isActive = true
        view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 0.0).isActive = true
        view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 0.0).isActive = true
        view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: 0.0).isActive = true

    }

    return cell
}
</code>```

Body:
I am trying to add cells to UITableView using Constraints. Do you know how. The following just gives:

And says: Height is ambiguous for UIView

Do you know how to add a UIView to ContextView using constraints - note the fixed height in the constraints.

import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintHeight = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.height,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: nil,
                                                  attribute: NSLayoutAttribute.height,
                                                  multiplier: 1, constant: 50) // << Note fixed height

        view.translatesAutoresizingMaskIntoConstraints = false

        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintHeight])

        return cell!
    }

}

Tried to change constraints to include bottom of the contentView:

import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintBottom = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: view,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  multiplier: 1, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintBottom])

        return cell!
    }

}

Body:
You're doing a couple things wrong.

First, you are setting the constraints backward. You want to constrain your new view to the contentView:

let constraintTop = NSLayoutConstraint(item: view,  // constrain this view
                           attribute: NSLayoutAttribute.top,
                           relatedBy: NSLayoutRelation.equal,
                           toItem: cell?.contentView,  // to this view
                           attribute: NSLayoutAttribute.top,
                           multiplier: 1,
                           constant: 0)

Second, don't do this:

cell?.contentView.translatesAutoresizingMaskIntoConstraints = false

Third, your code is (well, will be) adding a new "orange view" every time the cell is reused. Much better to add subviews in the init portion of a custom cell class, but if you're going to do it in cellForRow, check if it's already there first:

    if cell.contentView.subviews.count == 0 {
        // no, so add it here

        let view = UIView()

        // continue with view setup

Fourth, you may find it easier / more logical / cleaner / etc to add constraints this way:

cell.contentView.addSubview(view)

view.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 0.0).isActive = true
view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 0.0).isActive = true
view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 0.0).isActive = true
view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: 0.0).isActive = true

And... since you have registered a cell class for reuse, this format will give you a valid cell:

    // instead of this
    //var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    //if cell == nil {
    //  cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
    //}

    // better method
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

So, here is the full function:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    // have we already added the subview?
    if cell.contentView.subviews.count == 0 {
        // no, so add it here

        let view = UIView()

        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        cell.contentView.addSubview(view)

        view.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 0.0).isActive = true
        view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 0.0).isActive = true
        view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 0.0).isActive = true
        view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: 0.0).isActive = true

    }

    return cell
}


问:
(C#) DataGridView: How to get Selected Count with cells AND rows?
So I have this DataGridView

And This code:

```<code>if(dataGridView1.SelectedRows.Count > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }
</code>```

It counts correctly to 2 if I have 2 completly selected rows.
But I want to check if any cells from 2 different rows or more are selected.

In other words:
in my picture my current selection is returning 1 at the moment but i want it to return 2.

Thank you.

Edit after fix: Working code:

```<code>if(dataGridView1.SelectedCells.Cast<DataGridViewCell>().Select(c => c.RowIndex).Distinct().Count() > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }
</code>```

答:
If you have a fairly standard setup where each column is bound to a property of your backing data object, and each row represents one object, the following should work:

```<code>dataGridView1.SelectedCells.Select(c => c.Item).Distinct().Count()
</code>```

This will return the number of items the different cells are bound to. Since each item has one row that binds to it, it will return the count of every row with at least one selected cell.

Body:
So I have this DataGridView

And This code:

if(dataGridView1.SelectedRows.Count > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }

It counts correctly to 2 if I have 2 completly selected rows.
But I want to check if any cells from 2 different rows or more are selected.

In other words:
in my picture my current selection is returning 1 at the moment but i want it to return 2.

Thank you.

Edit after fix: Working code:

if(dataGridView1.SelectedCells.Cast<DataGridViewCell>().Select(c => c.RowIndex).Distinct().Count() > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }

Body:
If you have a fairly standard setup where each column is bound to a property of your backing data object, and each row represents one object, the following should work:

dataGridView1.SelectedCells.Select(c => c.Item).Distinct().Count()

This will return the number of items the different cells are bound to. Since each item has one row that binds to it, it will return the count of every row with at least one selected cell.


问:
Ordering a list of lists by lists len
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

```<code> orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else:
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1

 return orderedpaths
</code>```

the error I'm getting is:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax
</code>```

I have no idea why.

答:
Your problem was the number of brackets in:

```<code>smallest=(len(paths[c])
</code>```

and in:

```<code>if(len[paths[c])<smallest):
</code>```

and also in:

```<code>if(len[paths[c])<smallest):
</code>```

To sort paths according to their length, you can try this:

```<code>orderedpaths = sorted(paths, key=len)
</code>```

Here's the documentation for sorted.

ContentLicense: CC BY-SA 2.5

Title: Ordering a list of lists by lists len

Body:
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

 orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else:
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1

 return orderedpaths

the error I'm getting is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax

I have no idea why.

Body:
Your problem was the number of brackets in:

smallest=(len(paths[c])

and in:

if(len[paths[c])<smallest):

and also in:

if(len[paths[c])<smallest):

To sort paths according to their length, you can try this:

orderedpaths = sorted(paths, key=len)

Here's the documentation for sorted.


问:
How do I create a dynamic variable name in React?
In React, I am trying to dynamically create my state variable name using a variable and static text. 'level2' will be created by 'level' text plus a variable indicating what level (selectedItem.Level+1).

```<code>this.state={
  level1:[""], // city
  level2:[""]  // township
  level3:[""]  // neighborhood
  level4:[""]  // street
}
</code>```

When a user clicks on a city, I populate an array of all townships within the city and so on. Through props I know what level was clicked. I would like to dynamically create what state variable to update.

'FilteredListFromClick' is a array of children based on what parent was clicked.

```<code>this.setState({level2: FilteredListFromClick}) // hard coding name works, level2 is populated with a list of townships in clicked city.

var levelName = "level" + selectedItem.Level+1; // column1, column2, etc
this.setState({levelName: FilteredListFromClick}) // does not work, state is not updated, results are an empty list

this.setState({"level"{selectedItem.Level+1}: FilteredListFromClick}) // syntax errors - I've tried playing around with different combos of (), {}, "", and so on. Ideally I would like to set my state in one line like this.
</code>```

答:
Use [] brackets like this

```<code>this.setState({["level" + (selectedItem.Level+1)]: FilteredListFromClick})
</code>```

Body:
In React, I am trying to dynamically create my state variable name using a variable and static text. 'level2' will be created by 'level' text plus a variable indicating what level (selectedItem.Level+1).

this.state={
  level1:[""], // city
  level2:[""]  // township
  level3:[""]  // neighborhood
  level4:[""]  // street
}

When a user clicks on a city, I populate an array of all townships within the city and so on. Through props I know what level was clicked. I would like to dynamically create what state variable to update.

'FilteredListFromClick' is a array of children based on what parent was clicked.

this.setState({level2: FilteredListFromClick}) // hard coding name works, level2 is populated with a list of townships in clicked city.

var levelName = "level" + selectedItem.Level+1; // column1, column2, etc
this.setState({levelName: FilteredListFromClick}) // does not work, state is not updated, results are an empty list

this.setState({"level"{selectedItem.Level+1}: FilteredListFromClick}) // syntax errors - I've tried playing around with different combos of (), {}, "", and so on. Ideally I would like to set my state in one line like this.

Body:
Use [] brackets like this

this.setState({["level" + (selectedItem.Level+1)]: FilteredListFromClick})


问:
Send Packets to another subnet/network using Sockets
I am trying to find out whether the machines in a network are running a certain app. More like, I am trying to resolve addresses of nodes in a network.

I built a small code based on ARP, but it works only on a local network(same subnet). What I want to do is resolve addresses out of the subnet i.e. all other nodes.

I read these answers: UDP broadcast packets across subnets
and Broadcast on different subnets

But they all talk about changing router setting or creating a multicast network.

From what I read for multicasting to work, I need to create a multitask network beforehand. Is it really necessary?

And for changing router setting, does it really have to be a "special" router?

This is all for a college assignment and would be demonstrating it probably on an ad-hoc network or something like that.
I am open to ideas to solve the original problem.

PS:
1. I am a beginner in networking so do excuse me for any fault or misinterpretation.

I am using sockets and C(No other option).

Edit 1:
I am well aware ARP is useless outside the subnet. I mentioned it because I used it and it helped explaining the problem.

Edit 2:

The original problem is:

Building a chat application, nothing fancy sending messages from one point to another, without using a  central server of any kind. Not even a hybrid network with a central store is allowed.

i.e. if A and B are two clients, A should directly connect to B and vice versa.
I did some research and decided to use P2P architecture. And now I am stuck to how will A discover address of B. If I know the subnet of B, I can brute force and locate B but since I don't have such information what do I do?

答:
Adding to what other answers have provided:

ARP is not useful for a system in another subnet. Even if you were able to send an ARP request to a system in the other subnet, and receive its response somehow -- providing you with that system's MAC address -- you could not use it to send a packet to that system because Ethernet does not provide a routing mechanism, and so the system will never see any Ethernet packet you address to it.

If you are simply trying to identify which systems within another IP subnet are live, you can probably do this by other means. Take a look at the nmap command, for example. It supports a wide variety of IP communications methods that will be routed to the other subnet and can often detect what machines are present and which services are available on the machines found.

And you can of course duplicate what nmap does yourself. For example, if you want to find out which systems in subnet 192.168.10.0/24 are listening on TCP port 80, one way is to simply attempt to connect to port 80 on each system in that subnet. In general, there are four answers you may receive back:

Connection success (No error: the machine is present and there is a program listening to that port)

Connection refused (errno ECONNREFUSED: the machine is present but there
is no program listening to that port)

No route to host (EHOSTUNREACH: there is no machine answering to
that IP address)

No response (ETIMEDOUT: several reasons why this can happen; for example, the system could have firewall settings causing it to simply ignore the request)

(And there are other less likely possibilities as well.) Using other IP access methods (ICMP/ping, UDP packets) will have a different matrix of possible results.

As others have explained, multicast mechanisms would only be helpful for discovering a set of cooperating machines that are pre-configured to join a multicast group.


问:
how to make a dictionary using two lists
so I have this code and I am trying to create a lastnames to firstnames dictionary. I have created two lists out of my original dictionary which is:

```<code>person_to_friends = {
    'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
    'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
    'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
    'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
    'Alex Dunphy': ['Luke Dunphy'],
    'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
    'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
    'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
    'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
    'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
    'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}

family_dictionary = []
friends_dictionary = []
last_names = []
for person in person_to_friends:
    family_dictionary.append(person)
    for name in person_to_friends[person]:
        friends_dictionary.append(name)
</code>```

The above code gives me two lists, and I'm trying to use these to create a lastnames_to_firstnames dictionary where the keys are the lastnames of the people and the values should be all the names of the people with this lastname. I'm not sure how to proceed from here.

答:
You can try this;

```<code>from collections import defaultdict
import itertools
d = defaultdict(list)
person_to_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
'Alex Dunphy': ['Luke Dunphy'],
'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}
new_people = list(itertools.chain.from_iterable([[i.split() for i in [a]+b] for a, b in person_to_friends.items()]))
for i in new_people:
   d[i[-1]].append(i[0])

final_list = {a:list(set(b)) for a, b in d.items()}
</code>```

Output:

```<code>{'Dunphy': ['Alex', 'Luke', 'Claire', 'Phil', 'Haley'], 'D-Money': ['Dylan'], 'Tucker': ['Cameron'], 'D-Cat': ['Gilbert', 'Chairman'], 'Delgado': ['Manny'], 'Pritchett': ['Mitchell', 'Gloria', 'Jay']}
</code>```

Without importing anything:

```<code>d = {}
new_people = [[i.split() for i in [a]+b] for a, b in person_to_friends.items()]
for listing in new_people:
    for i in listing:
        if i[-1] in d:
           d[i[-1]].append(i[0])
        else:
           d[i[-1]] = [i[0]]

d = {a:list(set(b)) for a, b in d.items()}
</code>```

Output:

```<code>{'Dunphy': ['Alex', 'Luke', 'Claire', 'Phil', 'Haley'], 'D-Money': ['Dylan'], 'Tucker': ['Cameron'], 'D-Cat': ['Gilbert', 'Chairman'], 'Delgado': ['Manny'], 'Pritchett': ['Mitchell', 'Gloria', 'Jay']}
</code>```

Body:
so I have this code and I am trying to create a lastnames to firstnames dictionary. I have created two lists out of my original dictionary which is:

person_to_friends = {
    'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
    'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
    'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
    'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
    'Alex Dunphy': ['Luke Dunphy'],
    'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
    'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
    'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
    'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
    'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
    'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}

family_dictionary = []
friends_dictionary = []
last_names = []
for person in person_to_friends:
    family_dictionary.append(person)
    for name in person_to_friends[person]:
        friends_dictionary.append(name)

The above code gives me two lists, and I'm trying to use these to create a lastnames_to_firstnames dictionary where the keys are the lastnames of the people and the values should be all the names of the people with this lastname. I'm not sure how to proceed from here.

Body:
You can try this;

from collections import defaultdict
import itertools
d = defaultdict(list)
person_to_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
'Alex Dunphy': ['Luke Dunphy'],
'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}
new_people = list(itertools.chain.from_iterable([[i.split() for i in [a]+b] for a, b in person_to_friends.items()]))
for i in new_people:
   d[i[-1]].append(i[0])

final_list = {a:list(set(b)) for a, b in d.items()}

Output:

{'Dunphy': ['Alex', 'Luke', 'Claire', 'Phil', 'Haley'], 'D-Money': ['Dylan'], 'Tucker': ['Cameron'], 'D-Cat': ['Gilbert', 'Chairman'], 'Delgado': ['Manny'], 'Pritchett': ['Mitchell', 'Gloria', 'Jay']}

Without importing anything:

d = {}
new_people = [[i.split() for i in [a]+b] for a, b in person_to_friends.items()]
for listing in new_people:
    for i in listing:
        if i[-1] in d:
           d[i[-1]].append(i[0])
        else:
           d[i[-1]] = [i[0]]

d = {a:list(set(b)) for a, b in d.items()}

Output:

{'Dunphy': ['Alex', 'Luke', 'Claire', 'Phil', 'Haley'], 'D-Money': ['Dylan'], 'Tucker': ['Cameron'], 'D-Cat': ['Gilbert', 'Chairman'], 'Delgado': ['Manny'], 'Pritchett': ['Mitchell', 'Gloria', 'Jay']}


问:
Displaying All Tables Created By a User PL SQL Procedure
I am trying to create a procedure that displays all of the tables created by a specified user. Here is what I have so far:

```<code>CREATE OR REPLACE PROCEDURE user_tables
@username VARCHAR(50),
@result  varchar(100000)  OUTPUT
AS
BEGIN
   -- Execution section
   Set result = SELECT * FROM ALL_TABLES WHERE OWNER = @username;

EXCEPTION
  -- Exception section
     WHEN no_data_found THEN
      dbms_output.put_line('User does not exist');
   WHEN others THEN
      dbms_output.put_line('Error!');

END;
</code>```

I was wondering if this is the right path, and how I should go about completing this task

答:
Here is a hint</p>

```<code>BEGIN
    FOR tn IN (SELECT table_name FROM all_tables /*WHERE owner = vc_User_Name*/)
    LOOP
        -- Display some stuff
        DBMS_OUTPUT.PUT_LINE(tn.table_name);
    END LOOP;
END;
/
</code>```

Body:
I am trying to create a procedure that displays all of the tables created by a specified user. Here is what I have so far:

CREATE OR REPLACE PROCEDURE user_tables
@username VARCHAR(50),
@result  varchar(100000)  OUTPUT
AS
BEGIN
   -- Execution section
   Set result = SELECT * FROM ALL_TABLES WHERE OWNER = @username;

EXCEPTION
  -- Exception section
     WHEN no_data_found THEN
      dbms_output.put_line('User does not exist');
   WHEN others THEN
      dbms_output.put_line('Error!');

END;

I was wondering if this is the right path, and how I should go about completing this task

Body:
Here is a hint

BEGIN
    FOR tn IN (SELECT table_name FROM all_tables /*WHERE owner = vc_User_Name*/)
    LOOP
        -- Display some stuff
        DBMS_OUTPUT.PUT_LINE(tn.table_name);
    END LOOP;
END;
/


问:
How to change pointer variables within a struct?
So I am trying to implement a linked list and I have this struct for each of the nodes:

```<code>    typedef struct listNode {
        struct listNode *next;
        void *data;
    } NODE;
</code>```

Previously, I had made a game where the spacecraft struct looked like this:

```<code>   typedef struct {
       int height;
       int width;
   } SPACECRAFT;
</code>```

and I could make a new spacecraft by doing

```<code>  SPACECRAFT plyrShip = {
      .width = //someInt;
      .height = //someInt;
  };
</code>```

Though with the nodes, the variables are pointers and it isn't allowing me to create a new node by doing

```<code>  NODE newNode = {
      .*next = null;
      .*data = *data //function has *data as parameter so I can pass it
                     //into the node
  }
</code>```

What am I doing wrong?

答:
You have conflated the pointer declaration syntax and the designated initializer syntax. A member field may be declared to be a pointer type. When using designated initializers, just name the field. Also note they are comma separated.</p>

```<code>  NODE newNode = {
      .next = null,
      .data = data
  };
</code>```

Body:
So I am trying to implement a linked list and I have this struct for each of the nodes:

    typedef struct listNode {
        struct listNode *next;
        void *data;
    } NODE;

Previously, I had made a game where the spacecraft struct looked like this:

   typedef struct {
       int height;
       int width;
   } SPACECRAFT;

and I could make a new spacecraft by doing

  SPACECRAFT plyrShip = {
      .width = //someInt;
      .height = //someInt;
  };

Though with the nodes, the variables are pointers and it isn't allowing me to create a new node by doing

  NODE newNode = {
      .*next = null;
      .*data = *data //function has *data as parameter so I can pass it
                     //into the node
  }

What am I doing wrong?

Body:
You have conflated the pointer declaration syntax and the designated initializer syntax. A member field may be declared to be a pointer type. When using designated initializers, just name the field. Also note they are comma separated.

  NODE newNode = {
      .next = null,
      .data = data
  };


问:
Rails: Where to define a helper method that will be available to several controllers?
I would like to define a helper method, my_method, that will be available inside BuyersController methods (like index, create, e.t.c.).

I tried to define it in app/helpers/application_helper.rb but it didn't work:

```<code>undefined method `my_method' for #<BuyersController:0x26df468>
</code>```

It should be in some shared place because I want to use it in other controllers also. This is why I tried app/helpers/application_helper.rb.

What is the right place to define it ?

答:
You should include the application helper module in your application controller so that its methods will be available everywhere (all controllers and views) during a request.

```<code>class ApplicationController < ActionController::Base
  helper ApplicationHelper
  …
end
</code>```

See the API docs for the helper method

Body:
I would like to define a helper method, my_method, that will be available inside BuyersController methods (like index, create, e.t.c.).

I tried to define it in app/helpers/application_helper.rb but it didn't work:

undefined method `my_method' for #<BuyersController:0x26df468>

It should be in some shared place because I want to use it in other controllers also. This is why I tried app/helpers/application_helper.rb.

What is the right place to define it ?

Body:
You should include the application helper module in your application controller so that its methods will be available everywhere (all controllers and views) during a request.

class ApplicationController < ActionController::Base
  helper ApplicationHelper
  …
end

See the API docs for the helper method


问:
Sorting an array using oop
The following is a sample array:

```<code>array(11, -2, 4, 35, 0, 8, -9)
</code>```

I would like to use oop to sort it and generate this result:

Output :

```<code>Array ( [0] => -9 [1] => -2 [2] => 0 [3] => 4 [4] => 8 [5] => 11 [6] => 35 )
</code>```

I was provided the solution far below, which works. What I don't understand is what the __construct is doing. I have a beginner's understanding of how constructors work, but what specifically is the purpose of this constructor?:

```<code> public function __construct(array $asort)
 {
    $this->_asort = $asort;
</code>```

Is it turning the input into an array?

```<code><?php
class array_sort
{
    protected $_asort;

    public function __construct(array $asort)
     {
        $this->_asort = $asort;
     }
    public function alhsort()
     {
        $sorted = $this->_asort;
        sort($sorted);
        return $sorted;
      }
}
$sortarray = new array_sort(array(11, -2, 4, 35, 0, 8, -9));
print_r($sortarray->alhsort());
?>
</code>```

答:
```<code><?php
class array_sort
{
    public $temp;
    public function alhsort(array $sorted)
     {
        for($i=0; $i<count($sorted)-1; $i++){
            for($j=$i+1; $j<count($sorted); $j++){
                if($sorted[$i] > $sorted[$j]){
                    $temp =  $sorted[$i];
                    $sorted[$i] = $sorted[$j];
                    $sorted[$j] = $temp;
                }
            }
        }
        return $sorted;
      }
}
$sortarray = new array_sort();
print_r($sortarray->alhsort(array(11, -2, 4, 35, 0, 8, -9)));
?>
</code>```

Title: Sorting an array using oop

Body:
The following is a sample array:

array(11, -2, 4, 35, 0, 8, -9)

I would like to use oop to sort it and generate this result:

Output :

Array ( [0] => -9 [1] => -2 [2] => 0 [3] => 4 [4] => 8 [5] => 11 [6] => 35 )

I was provided the solution far below, which works. What I don't understand is what the __construct is doing. I have a beginner's understanding of how constructors work, but what specifically is the purpose of this constructor?:

 public function __construct(array $asort)
 {
    $this->_asort = $asort;

Is it turning the input into an array?

<?php
class array_sort
{
    protected $_asort;

    public function __construct(array $asort)
     {
        $this->_asort = $asort;
     }
    public function alhsort()
     {
        $sorted = $this->_asort;
        sort($sorted);
        return $sorted;
      }
}
$sortarray = new array_sort(array(11, -2, 4, 35, 0, 8, -9));
print_r($sortarray->alhsort());
?>


问:
New element in the context menu of a contenteditable

How to add a new element in the context menu of a contenteditable
?

I'd like to add an option "Show HTML" that would display the raw HTML that is inside the div.

document.getElementById("a").oncontextmenu = function() {
  alert("How to add a new element in the Context menu?");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="a" contenteditable="true">Hello you, <strong>right-click</strong> here and see the new option <i>"Show HTML"</i></div></code>```

Note: Unlike this question or this one I don't want to override the normal context menu and build a new one, but add a new element to the existing context menu:

答:
You can not use this in all browsers. Method  of defining a context menu item, now deprecated and removed from the HTML specification. https://www.w3.org/TR/2016/REC-html51-20161101/interactive-elements.html#context-menus,

https://caniuse.com/#search=contextmenu

Title: New element in the context menu of a contenteditable <div>

Body:
How to add a new element in the context menu of a contenteditable
?

I'd like to add an option "Show HTML" that would display the raw HTML that is inside the div.

document.getElementById("a").oncontextmenu = function() {
  alert("How to add a new element in the Context menu?");
}

Hello you, right-click here and see the new option "Show HTML"

Note: Unlike this question or this one I don't want to override the normal context menu and build a new one, but add a new element to the existing context menu:


问:
Ramda: replace NULL values in json array
We have a json array that has the form:

```<code>[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]
</code>```

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

答:
You can use lensProp with set.

```<code>arr.map(o => R.set(R.lensProp('symbol'), o.symbol || '', o))
</code>```

Body:
We have a json array that has the form:

[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

Body:
You can use lensProp with set.

arr.map(o => R.set(R.lensProp('symbol'), o.symbol || '', o))


问:
Google Chrome 62.0.3202.94 gapi.auth2.getAuthInstance().signIn popup_closed_by_user
Try sample from documentation
https://developers.google.com/identity/protocols/OAuth2UserAgent#example
We could select an account from popup dialog,
but
SignIn don't autorize in Google Chrome version 62.0.3202.94

In my example bilding by this documentation I got the error message with code "popup_closed_by_user"

In Google Chrome version 62.0.3202.94
method
`

```<code>gapi.auth2.getAuthInstance().signIn(options).then(
    function(resp) {
     var auth_code = resp.code;
    },
function(resp) {
     var auth_code = resp.code;
});
</code>```

`

got error response "popup_closed_by_user" and don't autorize user
the same code works fine in oldest chrome version and in other browsers

答:
answer was found
Go to chrome://settings/content/cookies, the "Block third-party cookies" setting.
https://github.com/google/google-api-javascript-client/issues/357</p>

Body:
Try sample from documentation
https://developers.google.com/identity/protocols/OAuth2UserAgent#example
We could select an account from popup dialog,
but
SignIn don't autorize in Google Chrome version 62.0.3202.94

In my example bilding by this documentation I got the error message with code "popup_closed_by_user"

In Google Chrome version 62.0.3202.94
method
`

gapi.auth2.getAuthInstance().signIn(options).then(
    function(resp) {
     var auth_code = resp.code;
    },
function(resp) {
     var auth_code = resp.code;
});

`

got error response "popup_closed_by_user" and don't autorize user
the same code works fine in oldest chrome version and in other browsers


问:
How can I merge overlapping strings in python?
I have some strings,

```<code>['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
</code>```

These strings partially overlap each other. If you manually overlapped them you would get:

```<code>SGALWDVPSPV
</code>```

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

答:
My proposed solution with a more challenging test list:

```<code>#strFrag = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
strFrag = ['ALWDVPS', 'SGALWDV', 'LWDVPSP', 'WDVPSPV', 'GALWDVP', 'LWDVPSP', 'ALWDVPS']

for repeat in range(0, len(strFrag)-1):
    bestMatch = [2, '', ''] #overlap score (minimum value 3), otherStr index, assembled str portion
    for otherStr in strFrag[1:]:
        for x in range(0,len(otherStr)):
            if otherStr[x:] == strFrag[0][:len(otherStr[x:])]:
                if len(otherStr)-x > bestMatch[0]:
                    bestMatch = [len(otherStr)-x, strFrag.index(otherStr), otherStr[:x]+strFrag[0]]
            if otherStr[:-x] == strFrag[0][-len(otherStr[x:]):]:
                if x > bestMatch[0]:
                    bestMatch = [x, strFrag.index(otherStr), strFrag[0]+otherStr[-x:]]
    if bestMatch[0] > 2:
        strFrag[0] = bestMatch[2]
        strFrag = strFrag[:bestMatch[1]]+strFrag[bestMatch[1]+1:]

print(strFrag)
print(strFrag[0])
</code>```

Basically the code compares every string/fragment to the first in list and finds the best match (most overlap). It consolidates the list progressively, merging the best matches and removing the individual strings. Code assumes that there are no unfillable gaps between strings/fragments (Otherwise answer may not result in longest possible assembly. Can be solved by randomizing the starting string/fragment). Also assumes that the reverse complement is not present (poor assumption with contig assembly), which would result in nonsense/unmatchable strings/fragments. I've included a way to restrict the minimum match requirements (changing bestMatch[0] value) to prevent false matches. Last assumption is that all matches are exact. To enable flexibility in permitting mismatches when assembling the sequence makes the problem considerably more complex. I can provide a solution for assembling with mismatches upon request.

Body:
I have some strings,

['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']

These strings partially overlap each other. If you manually overlapped them you would get:

SGALWDVPSPV

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

Body:
My proposed solution with a more challenging test list:

#strFrag = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
strFrag = ['ALWDVPS', 'SGALWDV', 'LWDVPSP', 'WDVPSPV', 'GALWDVP', 'LWDVPSP', 'ALWDVPS']

for repeat in range(0, len(strFrag)-1):
    bestMatch = [2, '', ''] #overlap score (minimum value 3), otherStr index, assembled str portion
    for otherStr in strFrag[1:]:
        for x in range(0,len(otherStr)):
            if otherStr[x:] == strFrag[0][:len(otherStr[x:])]:
                if len(otherStr)-x > bestMatch[0]:
                    bestMatch = [len(otherStr)-x, strFrag.index(otherStr), otherStr[:x]+strFrag[0]]
            if otherStr[:-x] == strFrag[0][-len(otherStr[x:]):]:
                if x > bestMatch[0]:
                    bestMatch = [x, strFrag.index(otherStr), strFrag[0]+otherStr[-x:]]
    if bestMatch[0] > 2:
        strFrag[0] = bestMatch[2]
        strFrag = strFrag[:bestMatch[1]]+strFrag[bestMatch[1]+1:]

print(strFrag)
print(strFrag[0])

Basically the code compares every string/fragment to the first in list and finds the best match (most overlap). It consolidates the list progressively, merging the best matches and removing the individual strings. Code assumes that there are no unfillable gaps between strings/fragments (Otherwise answer may not result in longest possible assembly. Can be solved by randomizing the starting string/fragment). Also assumes that the reverse complement is not present (poor assumption with contig assembly), which would result in nonsense/unmatchable strings/fragments. I've included a way to restrict the minimum match requirements (changing bestMatch[0] value) to prevent false matches. Last assumption is that all matches are exact. To enable flexibility in permitting mismatches when assembling the sequence makes the problem considerably more complex. I can provide a solution for assembling with mismatches upon request.


问:
Why does a HashMap sometimes print in natural order
I was going through the introduction of Hash Map in Java and I came across that Hash Maps are unordered and unsorted. So we should get the mappings in an arbitrary order of the keys when printing the using System.out.println(HM). For example, the following code

```<code>HashMap<Integer,String> HM = new HashMap<>();
HM.put(16,"hello16");
HM.put(6, "hello6");
HM.put(1, "hello1");
</code>```

prints {16=hello16, 1=hello1, 6=hello6} which is an apparently random order of keys. But when I replace the HM.put(16,"hello16"); with HM.put(15,"hello15");, it prints the mappings in the natural order of the keys, which is surprising and seems unlikely by chance:

```<code>{1=hello1, 6=hello6, 15=hello15}
</code>```

I asked a friend and he said that it's related to the initial capacity (=16) of the HashMap but he couldn't explain it clearly. Can anyone explain this difference in the output with this particular example.

答:
The code prints {16=hello16, 1=hello1, 6=hello6} which is random order of keys

The order may appear arbitrary, but it is deterministic. The order is based on three factors:

The values of hash codes for the keys,

The number of buckets in the hash table, and

The order the keys are inserted (for deciding the order of items with identical hash keys)

Enumerating hash table entries goes by hash bucket. Since the number of hash buckets is lower than the range of possible hash codes, the value of hash code translates into the index of hash bucket indirectly. Java implementation applies a supplemental hash function on top of the hash key, and then uses bitwise & to get the actual index:

```<code>static int hash(int h) {
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}
...
static int indexFor(int h, int length) {
    return h & (length-1);
}
</code>```

You can see from the indexFor code that length is expected to be a power of two (that's why they can use & (length-1) instead of % length expression). In your case this is important, because hash codes for integers match values of the corresponding integers. Assuming a capacity of 16 buckets, 16 would translate to bucket zero, while 15 would translate to bucket 15 (buckets are numbered from zero).

That's why the value for 15 moves from the front to the back in your example.

Body:
I was going through the introduction of Hash Map in Java and I came across that Hash Maps are unordered and unsorted. So we should get the mappings in an arbitrary order of the keys when printing the using System.out.println(HM). For example, the following code

HashMap<Integer,String> HM = new HashMap<>();
HM.put(16,"hello16");
HM.put(6, "hello6");
HM.put(1, "hello1");

prints {16=hello16, 1=hello1, 6=hello6} which is an apparently random order of keys. But when I replace the HM.put(16,"hello16"); with HM.put(15,"hello15");, it prints the mappings in the natural order of the keys, which is surprising and seems unlikely by chance:

{1=hello1, 6=hello6, 15=hello15}

I asked a friend and he said that it's related to the initial capacity (=16) of the HashMap but he couldn't explain it clearly. Can anyone explain this difference in the output with this particular example.

Body:
The code prints {16=hello16, 1=hello1, 6=hello6} which is random order of keys

The order may appear arbitrary, but it is deterministic. The order is based on three factors:

The values of hash codes for the keys,

The number of buckets in the hash table, and

The order the keys are inserted (for deciding the order of items with identical hash keys)

Enumerating hash table entries goes by hash bucket. Since the number of hash buckets is lower than the range of possible hash codes, the value of hash code translates into the index of hash bucket indirectly. Java implementation applies a supplemental hash function on top of the hash key, and then uses bitwise & to get the actual index:

static int hash(int h) {
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}
...
static int indexFor(int h, int length) {
    return h & (length-1);
}

You can see from the indexFor code that length is expected to be a power of two (that's why they can use & (length-1) instead of % length expression). In your case this is important, because hash codes for integers match values of the corresponding integers. Assuming a capacity of 16 buckets, 16 would translate to bucket zero, while 15 would translate to bucket 15 (buckets are numbered from zero).

That's why the value for 15 moves from the front to the back in your example.


问:
Prompt a local file like Open SaveAs from browser
I have a file in my local system. I would like to know how to take it to browser and prompting open, save as, cancel dialog as similar while downloading a file.</p>

答:
Thank god. I fixed it using the below code. "filename" is the name of the  file and "filepath" is the physical location of the file.</p>

```<code>System.Web.HttpContext.Current.Response.ContentType = "application/x-7z-compressed";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".zip");
System.Web.HttpContext.Current.Response.TransmitFile(filepath);
System.Web.HttpContext.Current.Response.End();
</code>```

Body:
Thank god. I fixed it using the below code. "filename" is the name of the  file and "filepath" is the physical location of the file.

System.Web.HttpContext.Current.Response.ContentType = "application/x-7z-compressed";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".zip");
System.Web.HttpContext.Current.Response.TransmitFile(filepath);
System.Web.HttpContext.Current.Response.End();


问:
React App : Start API server with React server
I'm working on a pretty simple react App (my first), but I can't figure out how to get both the API and the react server to start...

I'm using react-router for client routes and I've used express on another project so I've started my React project with it to setup the API.

But I was wondering if there was a way to use react-router to handle API routes and return some data...

I've googled and looked around but I can seem to find anything about that (nor confirming nor refuting).

Does anyone have any input about that?

(I know it isn't a proper SO question but I can't seem to find any info to close the nagging wonder)

答:
I'm working on a pretty simple react App (my first), but I can't
  figure out how to get both the API and the react server to start...

There is an npm module that I use for my React/Express app called concurrently that I use to start my client and backend servers at the same time.

I installed that globally:

```<code>npm install concurrently
</code>```

In my app's main package.json, I have the scripts setup like this:

```<code>"scripts":{
  "start": "concurrently \"npm run server\" \"npm run client\"",
  "server": "node bin/www",
  "client": "node start-client.js"
}
</code>```

That setup allows me to run npm start and it starts up my server and client scripts.

In start-client.js, I have this:

```<code>const args = ["start"];
const opts = { stdio: "inherit", cwd: "client", shell: true };
require("child_process").spawn("npm", args, opts);
</code>```

start-client.js is located at the root of my app.

My file structure looks like this:

```<code>|--bin
|--client
|--routes
|--app.js
|--package.json
|--start-client.js
</code>```

But I was wondering if there was a way to use react-router to handle
  API routes and return some data...

To fetch data from the API server, I use the native fetch() method inside my React components.

Since I'm using Express, I will create a route and export it to my app.js file like so:

```<code>/* myRoute.js */
var express = require('express')
var router = express.Router()

router.get('/', function(req, res, next) {
  res.send('index', {title: 'Express'})
})

module.exports = router

/* app.js */

var myRoute = require('./routes/myRoute')
var app = express()
//will fetch data from this endpoint
app.use('/myRoute', myRoute)
</code>```

Now in my React component, I will fetch data from /myRoute like so:

```<code>fetch('/myRoute')
  .then(res => JSON.parse(res))
  .then(res => console.log(res))
</code>```

Body:
I'm working on a pretty simple react App (my first), but I can't
  figure out how to get both the API and the react server to start...

There is an npm module that I use for my React/Express app called concurrently that I use to start my client and backend servers at the same time.

I installed that globally:

npm install concurrently

In my app's main package.json, I have the scripts setup like this:

"scripts":{
  "start": "concurrently \"npm run server\" \"npm run client\"",
  "server": "node bin/www",
  "client": "node start-client.js"
}

That setup allows me to run npm start and it starts up my server and client scripts.

In start-client.js, I have this:

const args = ["start"];
const opts = { stdio: "inherit", cwd: "client", shell: true };
require("child_process").spawn("npm", args, opts);

start-client.js is located at the root of my app.

My file structure looks like this:

|--bin
|--client
|--routes
|--app.js
|--package.json
|--start-client.js

But I was wondering if there was a way to use react-router to handle
  API routes and return some data...

To fetch data from the API server, I use the native fetch() method inside my React components.

Since I'm using Express, I will create a route and export it to my app.js file like so:

/* myRoute.js */
var express = require('express')
var router = express.Router()

router.get('/', function(req, res, next) {
  res.send('index', {title: 'Express'})
})

module.exports = router

/* app.js */

var myRoute = require('./routes/myRoute')
var app = express()
//will fetch data from this endpoint
app.use('/myRoute', myRoute)

Now in my React component, I will fetch data from /myRoute like so:

fetch('/myRoute')
  .then(res => JSON.parse(res))
  .then(res => console.log(res))


问:
Jade/Pug set value for input field
```<code> input(type="text", name="Q1VolTarget", value="#{value.Q1TargetVolume}")
                    td  #{value.Q1TargetGP}
</code>```

Instead of de-referencing #{value.Q1TargetVolume} and displaying value, this code is displaying this #{value.Q1TargetVolume} as text

What is the correct syntax please?

答:
ok I used this syntax:

```<code>input(type="text", name="Q1VolTarget", value=value.Q1TargetVolume)
</code>```

I am using  "pug": "^2.0.0-rc.4",

Title: Jade/Pug set value for input field

Body:
 input(type="text", name="Q1VolTarget", value="#{value.Q1TargetVolume}")
                    td  #{value.Q1TargetGP}

Instead of de-referencing #{value.Q1TargetVolume} and displaying value, this code is displaying this #{value.Q1TargetVolume} as text

What is the correct syntax please?

Body:
ok I used this syntax:

input(type="text", name="Q1VolTarget", value=value.Q1TargetVolume)

I am using  "pug": "^2.0.0-rc.4",


问:
ng-valid and ng-invalid classes in angular dart forms are no more exposed
Dart: 1.24.2;
Angular: 4.0.0;
I created some CSS rules based on .ng-valid and .ng-invalid classes in angular forms. But, in last releases, it seems that ng-valid and ng-invalid classes are no more exposed, so my CSS rules are no more working.
Is it correct?
if yes, how can I by-pass this change?

Edit1: Test case
I simply generated a brand new project with angular and angular-material in my IDE (WebStorm). It generates a simple todo application. I took the todo_list_component.html and wrapped the whole content with a <form> </form> tag. In the todo_list_component.dart I have added an import for angular_forms and added formDirectives to the directives list.
Inspecting the form in dartium no ng-valid class has been added. The only class added, in my case is: class="_ngcontent-umj-2"

Edit2: Shortcut
Not very elegant, but working:

```<code><form #form="ngForm" [class.ng-valid]="form.valid" [class.ng-invalid]="!form.valid">
</code>```

答:
Yes, this behavior changed in a recent release of angular_forms.

Previously, the NgControlStatus directive was included in list of formDirectives. However, this caused every component that used forms to pay the price for these host bindings.

Now, if you want the behavior, you need to include NgControlStatus explicitly in the directives list of the @Component.

https://github.com/dart-lang/angular/blob/master/angular_forms/lib/src/directives/ng_control_status.dart#L15

Body:
Dart: 1.24.2;
Angular: 4.0.0;
I created some CSS rules based on .ng-valid and .ng-invalid classes in angular forms. But, in last releases, it seems that ng-valid and ng-invalid classes are no more exposed, so my CSS rules are no more working.
Is it correct?
if yes, how can I by-pass this change?

Edit1: Test case
I simply generated a brand new project with angular and angular-material in my IDE (WebStorm). It generates a simple todo application. I took the todo_list_component.html and wrapped the whole content with a <form> </form> tag. In the todo_list_component.dart I have added an import for angular_forms and added formDirectives to the directives list.
Inspecting the form in dartium no ng-valid class has been added. The only class added, in my case is: class="_ngcontent-umj-2"

Edit2: Shortcut
Not very elegant, but working:

<form #form="ngForm" [class.ng-valid]="form.valid" [class.ng-invalid]="!form.valid">


问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
```<code>BinaryFormatter bf = new BinaryFormatter();
byte[] bytes;
MemoryStream ms = new MemoryStream();

string orig = "喂 Hello 谢谢 Thank You";
bf.Serialize(ms, orig);
ms.Seek(0, 0);
bytes = ms.ToArray();

MessageBox.Show("Original bytes Length: " + bytes.Length.ToString());

MessageBox.Show("Original string Length: " + orig.Length.ToString());

for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo encrypt
for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo decrypt

BinaryFormatter bfx = new BinaryFormatter();
MemoryStream msx = new MemoryStream();
msx.Write(bytes, 0, bytes.Length);
msx.Seek(0, 0);
string sx = (string)bfx.Deserialize(msx);

MessageBox.Show("Still intact :" + sx);

MessageBox.Show("Deserialize string Length(still intact): "
    + sx.Length.ToString());

BinaryFormatter bfy = new BinaryFormatter();
MemoryStream msy = new MemoryStream();
bfy.Serialize(msy, sx);
msy.Seek(0, 0);
byte[] bytesy = msy.ToArray();

MessageBox.Show("Deserialize bytes Length(still intact): "
   + bytesy.Length.ToString());
</code>```

OwnerDisplayName: Vulcan Eager

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Dale Ragan

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Michael Buen


问:
Concatenate ByteArrayOutputStream
```<code>public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

```<code>public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
</code>```

答:
I don't know what the API of ByteArrayOutputStream on J2ME is like but try:

```<code>ByteArrayOutputStream realOutput = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(realOutput);
dout.writeUTF(recordid);
dout.flush();

ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
objectStream.writeTo(realOutput);

return realOutput.toByteArray();
</code>```

Title: Concatenate ByteArrayOutputStream

Body:
public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Body:
I don't know what the API of ByteArrayOutputStream on J2ME is like but try:

ByteArrayOutputStream realOutput = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(realOutput);
dout.writeUTF(recordid);
dout.flush();

ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
objectStream.writeTo(realOutput);

return realOutput.toByteArray();