问:
promise gives undefined result in callback
fileUpload.js

```<code>var Uploader = require('s3-image-uploader');
var express = require('express');
var config = require('./../config.js');
var Promise = require('promise');

var uploader = new Uploader({
    aws: {
        key: config.awsKey,
        secret: config.awsSecret
    },
    websockets: false
});

exports.fileUpload = function(fileName) {

    new Promise(function(resolve, reject) {

        uploader.upload({
                fileId: 'someUniqueIdentifier',
                bucket: 'quflip',
                source: './public/images/' + fileName,
                name: fileName
            },
            function(data) { // success
                console.log('upload success:', resolve);
                resolve(data);
            },
            function(errMsg, errObject) { //error
                reject(false);
            });
    });
};
</code>```

logintest.js

```<code>var awsUpload = require('./../config/fileUpload.js');

var userData = function(req, res) {
console.log("true/false" + awsUpload.fileUpload(profile_image));
</code>```

Here what is happening is, I am getting undefined value in console.log. So it means that callback is not passing the data. How can I pass the data effectively for further purpose

答:
If you want your function to actually return the promise then change this:

```<code>exports.fileUpload = function (fileName) {
    new Promise(function(resolve, reject) {
        // ...
    });
};
</code>```

to this:

```<code>exports.fileUpload = function (fileName) {
    return new Promise(function(resolve, reject) {
        // ...
    });
};
</code>```

Without the return statement the promise that you're creating is not going to get returned by your function.

But even then you won't be able to use it like this:

```<code>console.log("true/false" + awsUpload.fileUpload(profile_image));
</code>```

You will have to use something like this:

```<code>awsUpload.fileUpload(profile_image).then(result => {
  console.log("true/false" + result);
});
</code>```

Or this, if you're using async/await and you're inside async function:

```<code>console.log("true/false" + await awsUpload.fileUpload(profile_image));
</code>```

Body:
fileUpload.js

var Uploader = require('s3-image-uploader');
var express = require('express');
var config = require('./../config.js');
var Promise = require('promise');

var uploader = new Uploader({
    aws: {
        key: config.awsKey,
        secret: config.awsSecret
    },
    websockets: false
});

exports.fileUpload = function(fileName) {

    new Promise(function(resolve, reject) {

        uploader.upload({
                fileId: 'someUniqueIdentifier',
                bucket: 'quflip',
                source: './public/images/' + fileName,
                name: fileName
            },
            function(data) { // success
                console.log('upload success:', resolve);
                resolve(data);
            },
            function(errMsg, errObject) { //error
                reject(false);
            });
    });
};

logintest.js

var awsUpload = require('./../config/fileUpload.js');

var userData = function(req, res) {
console.log("true/false" + awsUpload.fileUpload(profile_image));

Here what is happening is, I am getting undefined value in console.log. So it means that callback is not passing the data. How can I pass the data effectively for further purpose

Body:
If you want your function to actually return the promise then change this:

exports.fileUpload = function (fileName) {
    new Promise(function(resolve, reject) {
        // ...
    });
};

to this:

exports.fileUpload = function (fileName) {
    return new Promise(function(resolve, reject) {
        // ...
    });
};

Without the return statement the promise that you're creating is not going to get returned by your function.

But even then you won't be able to use it like this:

console.log("true/false" + awsUpload.fileUpload(profile_image));

You will have to use something like this:

awsUpload.fileUpload(profile_image).then(result => {
  console.log("true/false" + result);
});

Or this, if you're using async/await and you're inside async function:

console.log("true/false" + await awsUpload.fileUpload(profile_image));


来源: stackexchange

问:
CSS overlay with scrolling content
I am trying to get a content panel inside a fixed-position overlay to scroll vertically, but it does not scroll, it is forced into its container.

Can you spot the mistake?
fiddle

Only the green bottom should scroll the header should stay where it is.

```<code><html>
<head>
    <style>
        * {
            box-sizing: border-box;
        }
    </style>
</head>
<body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%;">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height: 10000px; width: 100%; background-color: green; overflow: scroll;">Bottom</div>
    </div>

</body>
</html>
</code>```

答:
You just need to add the maximum height of the container like this

```<code>max-height:100%;
</code>```

and add the scroll property

```<code>overflow-y:auto;
</code>```

And your code will look like this

```<code><style>
    * {
        box-sizing: border-box;
    }
</style>

<body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%; max-height:100%; overflow-y:auto;">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height: 10000px; width: 100%; background-color: green; overflow: scroll;">Bottom</div>
    </div>

</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Title: CSS overlay with scrolling content

Body:
I am trying to get a content panel inside a fixed-position overlay to scroll vertically, but it does not scroll, it is forced into its container.

Can you spot the mistake?
fiddle

Only the green bottom should scroll the header should stay where it is.

Top

Bottom

Body:
You just need to add the maximum height of the container like this

max-height:100%;

and add the scroll property

overflow-y:auto;

And your code will look like this

<style>
    * {
        box-sizing: border-box;
    }
</style>

<body style="background-color: #502074;">
    <div style="position: fixed; width:100%; height: 100%; max-height:100%; overflow-y:auto;">
        <div style="height: 80px; width: 100%; background-color: yellow;">Top</div>
        <div style="height: 10000px; width: 100%; background-color: green; overflow: scroll;">Bottom</div>
    </div>

</body>
</html>


问:
How a function can be automatically called upon a variable change?
I have a class consisting of variable members and a function member. The variable member occasionally changes. I want the function to be called automatically upon the variable changes. In other words, how can I tie the variables inside a class?

```<code>class line
{
   double x, y; // The poition of the lind end. The line starts at the origin (0,0)
   double l; // The length of the line
   void length()
   {
      l = Math.sqrt(x*x+y*y);
   }
}
</code>```

In example above, I need the length to be updated when x and y change.

答:
Make your variables into properties, then put your functions in the set accesors.</p>

```<code>class line
{
    double _x, _y;

    double x
    {
        get { return _x; }
        set
        {
            _x = value;
            length();
        }
    }

    double y
    {
        get { return _y; }
        set
        {
            _y = value;
            length();
        }
    }

    double l; // The length of the line

    void length()
    {
        l = Math.Sqrt(_x * _x + _y * _y);
    }
}
</code>```

Body:
I have a class consisting of variable members and a function member. The variable member occasionally changes. I want the function to be called automatically upon the variable changes. In other words, how can I tie the variables inside a class?

class line
{
   double x, y; // The poition of the lind end. The line starts at the origin (0,0)
   double l; // The length of the line
   void length()
   {
      l = Math.sqrt(x*x+y*y);
   }
}

In example above, I need the length to be updated when x and y change.

Body:
Make your variables into properties, then put your functions in the set accesors.

class line
{
    double _x, _y;

    double x
    {
        get { return _x; }
        set
        {
            _x = value;
            length();
        }
    }

    double y
    {
        get { return _y; }
        set
        {
            _y = value;
            length();
        }
    }

    double l; // The length of the line

    void length()
    {
        l = Math.Sqrt(_x * _x + _y * _y);
    }
}


问:
Is there an open source C visual debugger for windows?
Is there an open source C visual debugger for windows?
I have heard about the visual C++ express free edition, but does it have a visual debugger?

Thanks.

答:
It's not open source (but then does it really need to be?) Visual C++ 2008 Express Edition is an IDE with an integrated debugger.

You can create a C++ project, delete the .cpp files and create/include your .c files.

OwnerDisplayName: linkedlist

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: splattne

OwnerDisplayName: Mitch Wheat


问:
Try loading data from JSON using JsGrid MVC
I have a problem loading data from JSON, when i assign the JSON to property "data" of JsGrid there are not data found in the table. I am retriving the data using Ajax.

```<code>$.ajax({
            url: '@Url.Action("consulta_Unidades")',
            async: false,
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                //console.log(response.value);
                datos = JSON.stringify(response);
                alert(datos);
            }
        });
</code>```

The JsGrid code is next.

```<code>$("#table_div").jsGrid({

            width: "100%",
            height: "auto",

            editing: true,

            data: datos,

            fields: [
                { name: "id_almacen", type: "text", width: 150 },
                { name: "idunidad", type: "text", width: 150 },
                { name: "tipo_unidad", type: "text", width: 150 },
                { name: "nomenclatura ", type: "text", width: 150 },
                { name: "capacidad_tarimas", type: "text", width: 150 },
                { name: "altura", type: "text", width: 150 },
                { type: "control" }

            ]
        });
</code>```

Any idea for resolve this problem?

答:
In your ajax success "response" its a json object, only check

```<code>if(response){
 datos=response
}
</code>```

Another scenario:

The property "data" should be a "object" like json.

Change

```<code>datos = JSON.stringify(response);
</code>```

For

```<code>datos = JSON.parse(response);
</code>```

Use

```<code>datos = JSON.parse(JSON.stringify(response));
</code>```

Only if it required for object "response"

Body:
I have a problem loading data from JSON, when i assign the JSON to property "data" of JsGrid there are not data found in the table. I am retriving the data using Ajax.

$.ajax({
            url: '@Url.Action("consulta_Unidades")',
            async: false,
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                //console.log(response.value);
                datos = JSON.stringify(response);
                alert(datos);
            }
        });

The JsGrid code is next.

$("#table_div").jsGrid({

            width: "100%",
            height: "auto",

            editing: true,

            data: datos,

            fields: [
                { name: "id_almacen", type: "text", width: 150 },
                { name: "idunidad", type: "text", width: 150 },
                { name: "tipo_unidad", type: "text", width: 150 },
                { name: "nomenclatura ", type: "text", width: 150 },
                { name: "capacidad_tarimas", type: "text", width: 150 },
                { name: "altura", type: "text", width: 150 },
                { type: "control" }

            ]
        });

Any idea for resolve this problem?

Body:
In your ajax success "response" its a json object, only check

if(response){
 datos=response
}

Another scenario:

The property "data" should be a "object" like json.

Change

datos = JSON.stringify(response);

For

datos = JSON.parse(response);

Use

datos = JSON.parse(JSON.stringify(response));

Only if it required for object "response"


问:
Regex in python to get values from multiple lines
I have string in following format and needs regex to get address values. example lines are following,

```<code>var address = 'Uhartia, 64220 Gamarthe, France';
var address = 'Eaux Chaudes
Place de l\'Eglise, 64440 Laruns, France';
</code>```

I need regex in Python.

答:
This will get the quoted text (in capture group 1)

address\s*=\s*'([^'\\]*(?:\\[\S\s][^'\\]*)*)'

Expanded

```<code> address \s* = \s*
 '
 (                             # (1 start), Single quoted text
      [^'\\]*
      (?: \\ [\S\s] [^'\\]* )*
 )                             # (1 end)
 '
</code>```

Body:
I have string in following format and needs regex to get address values. example lines are following,

var address = 'Uhartia, 64220 Gamarthe, France';
var address = 'Eaux Chaudes
Place de l\'Eglise, 64440 Laruns, France';

I need regex in Python.

Body:
This will get the quoted text (in capture group 1)

address\s*=\s*'([^'\\]*(?:\\[\S\s][^'\\]*)*)'

Expanded

 address \s* = \s*
 '
 (                             # (1 start), Single quoted text
      [^'\\]*
      (?: \\ [\S\s] [^'\\]* )*
 )                             # (1 end)
 '


问:
Remove duplicated elements List<Vector3> Mono / C# - Unity3D
I need to remove the duplicates of elements in my Vector3 list.
For Example, here is a list:

```<code>List<Vector3> PointsToGo = new List<Vector3>();

PointsToGo.Add(new Vector3(1, 1, 1));
PointsToGo.Add(new Vector3(2, 2, 2));
PointsToGo.Add(new Vector3(1, 1, 1)); // Get this one or the first one out
PointsToGo.Add(new Vector3(4, 4, 4));
</code>```

Do you know how to solve this problem ? Maybe Linq can help me ?

Thanks for your answer!

答:
Here is your solution

```<code>PointsToGo = PointsToGo.Distinct().ToList();
</code>```

Note that you have add using System.Linq; to the top your code.

Body:
I need to remove the duplicates of elements in my Vector3 list.
For Example, here is a list:

List<Vector3> PointsToGo = new List<Vector3>();

PointsToGo.Add(new Vector3(1, 1, 1));
PointsToGo.Add(new Vector3(2, 2, 2));
PointsToGo.Add(new Vector3(1, 1, 1)); // Get this one or the first one out
PointsToGo.Add(new Vector3(4, 4, 4));

Do you know how to solve this problem ? Maybe Linq can help me ?

Thanks for your answer!

Body:
Here is your solution

PointsToGo = PointsToGo.Distinct().ToList();

Note that you have add using System.Linq; to the top your code.


问:
Transform Angular 2 Observable Into a non observable
I am using 6.3 of NGX Data Table which cannot bind to an observable collection.  How do I transform an Angular Observable Collection into a regular non-observable Array?

Here is what I have for the service:

```<code>private _productUrl = '../../api/todos/todos.json';

constructor(private _http: Http) { }

getToDos(): Observable<IToDo[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IToDo[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}
</code>```

Here is what I have for the component.ts.  It gives me an error on the foreach loop: Cannot read property 'length' of undefined

```<code>ngOnInit() {
    this._toDoService.getToDos()
        .subscribe(
          toDos => this.toDos = toDos,
          error => this.errorMessage = <any>error);

    this.rows = this.transform(this.toDos);
}

transform(source: IToDo[]): IToDo[] {
    let dest: IToDo[] = [];

    for (let sourceItem of source)
    {
      let destItem: IToDo = {
        toDoId: sourceItem.toDoId,
        name: sourceItem.name,
        priority: sourceItem.priority,
        dueDate: sourceItem.dueDate,
        completed: sourceItem.completed
      };
      dest.push(destItem);
    }

    return dest;
}
</code>```

答:
Observables can be asynchronous, so you cant simply manipulate todos right after the subscription call you make. Instead, manipulate todos inside of the subscription:

```<code>ngOnInit() {
  this._toDoService.getToDos()
    .subscribe(
      toDos => {
        this.toDos = toDos
        this.rows = this.transform(this.toDos);
      },
      error => this.errorMessage = <any>error);
}
</code>```

Your this.transform call was being called synchronously, meaning your call stack is just a linear progression of calls.

Body:
I am using 6.3 of NGX Data Table which cannot bind to an observable collection.  How do I transform an Angular Observable Collection into a regular non-observable Array?

Here is what I have for the service:

private _productUrl = '../../api/todos/todos.json';

constructor(private _http: Http) { }

getToDos(): Observable<IToDo[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IToDo[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

Here is what I have for the component.ts.  It gives me an error on the foreach loop: Cannot read property 'length' of undefined

ngOnInit() {
    this._toDoService.getToDos()
        .subscribe(
          toDos => this.toDos = toDos,
          error => this.errorMessage = <any>error);

    this.rows = this.transform(this.toDos);
}

transform(source: IToDo[]): IToDo[] {
    let dest: IToDo[] = [];

    for (let sourceItem of source)
    {
      let destItem: IToDo = {
        toDoId: sourceItem.toDoId,
        name: sourceItem.name,
        priority: sourceItem.priority,
        dueDate: sourceItem.dueDate,
        completed: sourceItem.completed
      };
      dest.push(destItem);
    }

    return dest;
}

Body:
Observables can be asynchronous, so you cant simply manipulate todos right after the subscription call you make. Instead, manipulate todos inside of the subscription:

ngOnInit() {
  this._toDoService.getToDos()
    .subscribe(
      toDos => {
        this.toDos = toDos
        this.rows = this.transform(this.toDos);
      },
      error => this.errorMessage = <any>error);
}

Your this.transform call was being called synchronously, meaning your call stack is just a linear progression of calls.

ContentLicense: CC BY-SA 4.0


问:
How to setup LXD containers that communicate over the LAN
I have a set of servers rung up to a LAN. I am able to install and work with LXD containers on a machine, but for the life of me I can't get the containers visible on the network. I have attempted to follow these urls, to no avail :

https://www.simpleprecision.com/ubuntu-16-04-lxd-networking-simple-bridge/

https://www.stgraber.org/2016/10/27/network-management-with-lxd-2-3/

https://www.simpleprecision.com/ubuntu-16-04-lxd-networking-simple-bridge/

My servers are setup as follows:

eth0 - Hardware NIC connected to the Internet

eth1 - Hardware NIC connected to the LAN

If i try to setup a bridge on the eth1 device via lxdbr0, the containers are not visible on the LAN. If i try to setup a bridged br0 device manually, bridged to eth1 and using DHCP, the device fails to start.

My /etc/network/interfaces looks like this:

```<code>iface lo inet loopback

# The primary network interface
iface eth0 inet static
    address x.x.x.x
    netmask 255.255.255.224
    gateway x.x.x.x

iface eth1 inet static
    address 192.168.0.61/23

iface br0 inet dhcp
    bridge_ports eth1
    bridge-ifaces eth1
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

auto lo eth0 eth1 br0
</code>```

Is it possible to create containers that are visible on the LAN and can connect to the internet?

LXD v2.7 on Ubuntu 16.04

答:
Yes, this is very possible. I haven't played around with all the new networking features introduced in LXD 2.3, so I can't speak to any of that, but it looks like you are wanting a pretty simple network layout, so those features may not even come into play. I do something somewhat similar to your network layout. I have 4 NIC's in all my servers. The first two I put in a bond and put on my management network, and the second two I put in a LAG (another bond) and use for all LXD traffic. I have multiple VLAN's so my LAG is setup as an trunk port and I create VLAN devices for each VLAN I want to be able to connect to. I then put those VLAN devices into a bridge that the actual container uses.

Take away all the bonding, and raw VLAN devices and you have essentially the same setup: one NIC for management of the LXD host, one bridge for LXD container traffic. I don't use the default lxcbr0 device, but all the concepts should be the same.

A simple example

First define the NIC or NIC's that will be part of your bridge. In your case it looks like you are just using one NIC (eth1). You need to set the NIC to manual. Do not assign an address to it.

```<code>auto eth1
iface eth1 inet manual
</code>```

Next define your bridge, again I would not define an IP address here. I prefer to assign all my containers IP's inside the container. Set the bridge to manual as well. When the container starts it will bring up the device.

```<code>auto br0
iface br0 inet manual
  bridge_ports eth1
  bridge_stp off
  bridge_fd 0
  bridge_maxwait 0
</code>```

Now all you have to do is use this bridge in your container's profile.

```<code>lxduser@lxdhost:~$ lxc profile show default
name: default
config: {}
description: ""
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: br0
</code>```

Now start your container and edit the network configuration. For example in Debian based systems you would edit /etc/network/interfaces (in the container). In Red Hat based systems you would edit /etc/sysconfig/network-scripts/ifcfg-eth0 (in the container). Here is the Debian example.

```<code>auto eth0
iface eth0 inet dhcp
</code>```

As long as DHCP is working on the network that eth1 (on your LXD host) is plugged into then the container should get an address and be routable on that network. In order to get internet access then eth1 has to be plugged into a subnet that has internet access, it is not dependent on the container.

More complex networking

If you want to put containers on different VLAN's, want fault tolerance on your host, or both, then this requires a bit more setup. I use the configuration file below on my LXD host.

```<code>############################
# PHYSICAL NETWORK DEVICES #
############################

# Management network interface
auto enp2s0f0
iface enp2s0f0 inet static
    address 10.1.31.36/24
    gateway 10.1.31.1
    dns-nameserver 10.1.30.2 10.1.30.3 75.75.75.75
    dns-search harmonywave.com

#iface enp2s0f0 inet6 dhcp

# Second network interface
auto enp2s0f1
iface enp2s0f1 inet manual

# LXD slave interface (1)
auto enp3s0f0
iface enp3s0f0 inet manual
    bond-master bond1

# LXD slave interface (2)
auto enp3s0f1
iface enp3s0f1 inet manual
    bond-master bond1

##########################
# BONDED NETWORK DEVICES #
##########################

# Bond network device
auto bond1
iface bond1 inet manual
    bond-mode 4
    bond-miimon 100
    bond-lacp-rate 1
    bond-slaves enp3s0f0 enp3s0f1
    bond-downdelay 400
    bond-updelay 800

####################
# RAW VLAN DEVICES #
####################

# Tagged traffic on bond1 for VLAN 10
iface bond1.10 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 20
iface bond1.20 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 30
iface bond1.30 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 31
iface bond1.31 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 42
iface bond1.42 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 50
iface bond1.50 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 90
iface bond1.90 inet manual
    vlan-raw-device bond1

##########################
# BRIDGE NETWORK DEVICES #
##########################

# Bridged interface for VLAN 10
auto br0-10
iface br0-10 inet manual
    bridge_ports bond1.10
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 20
auto br0-20
iface br0-20 inet manual
    bridge_ports bond1.20
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 30
auto br0-30
iface br0-30 inet manual
    bridge_ports bond1.30
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 31
auto br0-31
iface br0-31 inet manual
    bridge_ports bond1.31
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 42
auto br0-42
iface br0-42 inet manual
    bridge_ports bond1.42
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 50
auto br0-50
iface br0-50 inet manual
    bridge_ports bond1.50
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 90
auto br0-90
iface br0-90 inet manual
    bridge_ports bond1.90
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0
</code>```

Let's break this down. First I define the physical NIC's. That's the PHYSICAL NETWORK DEVICES section. Nothing different between mine and yours for this first NIC (eth0 for you enp2s0f0 for me). I just define it statically and give it an address. I assign an address on my management network for this NIC. The third and fourth NIC's I use for container traffic. I wanted to use LACP in a LAG so I defined the devices as manual and made them a slave to "bond1".

Next I define my bond devices. That's the BONDED NETWORK DEVICES section. In this case just the one bond for container traffic. Again, I set it to manual and define the bond mode as 4 (LACP). Could have just as easily setup a different type of bond (active-passive, active-active, etc).

Next, because I have the third and fourth NIC physically connected to a trunk port on the switch I have to specify dot1Q so that traffic is actually tagged. I create a raw VLAN device for each VLAN that a container could possibly be in. I append a .XX where "XX" is the VLAN ID. This isn't necessary anymore, I just do this for easy identification. Then tag the device with the "vlan-raw-device" stanza. This is the RAW VLAN DEVICES section.

Finally, in the BRIDGE NETWORK DEVICES section I create bridges for each VLAN device. This is what the container will actually use. Again, I set this to manual and do not define an IP address, that is defined inside the container.

Now all I have to do is assign whatever bridge is on the VLAN I want to a container. For simplicity and to avoid configuring every container, I just create a profile for each bridge/VLAN. For example here is my profile for VLAN 31.

```<code>lxduser@lxdhost:~$ lxc profile show 31_vlan_int_server
name: 31_vlan_int_server
config: {}
description: ""
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: br0-31
    type: nic
</code>```

Then I just assign this profile to any container I want on VLAN 31. At this point I can either setup my container's /etc/network/interfaces file as dhcp (if DHCP is enabled on that VLAN) or give it a static IP address that is part of that VLAN.

The Entire network layout looks something like this.

The container uses the veth device inside the bridge (which LXD creates). The host adds the raw vlan device to the bridge as well and they both use the actual bond device, which in turn uses the physical NICs.

Concerning issues with connectivity

Finally, concerning your issues of not being able to connect to the internet, make sure that the bridge your containers is using has internet access. I like to take a step-by-step troubleshooting approach.

Make sure that eth1 has internet access. Temporarily remove any bond and bridge configuration and use eth1 directly on the host. Change it from manual to static and give it an IP address.

On the host can you ping the NIC's IP address?

Yes? NIC is working, continue troubleshooting. No? NIC is not setup properly, everything else will fail.

On the host can you ping another host on the same subnet?

Yes? Switching is setup correctly, continue troubleshooting. No? Issue connecting to the network. Possible static routing issue on the box itself, possible issue with the switch.

On the host can you ping a machine on a different subnet (try ping 8.8.8.8)?

Yes? Routing is working properly, continue troubleshooting. No? Possible gateway misconfiguration on the host. Possible issue with the router. Possible issue with static routing on the box (check gateway of last resort).

Can you resolve a DNS address (try ping www.google.com)?

Yes? DNS resolution is setup correctly, continue troubleshooting. No? Issue with DNS resolution. Check /etc/resolv.conf or resolvconf setup.

If everything is working on eth1 when it is setup statically then you know that NIC is functioning properly. The next step would be to change eth1 back to manual, remove the static IP from it, and recreate your bridge. Now assign the static IP address on the bridge itself and repeat all the sub-steps from step 1.

If everything works successfully then you should be able to connect with your container (after setting your bridge back to manual and removing the static IP). If not, then get an address on the container (static or DHCP) and repeat the sub-steps from step 1.

Body:
I have a set of servers rung up to a LAN. I am able to install and work with LXD containers on a machine, but for the life of me I can't get the containers visible on the network. I have attempted to follow these urls, to no avail :

https://www.simpleprecision.com/ubuntu-16-04-lxd-networking-simple-bridge/

https://www.stgraber.org/2016/10/27/network-management-with-lxd-2-3/

https://www.simpleprecision.com/ubuntu-16-04-lxd-networking-simple-bridge/

My servers are setup as follows:

eth0 - Hardware NIC connected to the Internet

eth1 - Hardware NIC connected to the LAN

If i try to setup a bridge on the eth1 device via lxdbr0, the containers are not visible on the LAN. If i try to setup a bridged br0 device manually, bridged to eth1 and using DHCP, the device fails to start.

My /etc/network/interfaces looks like this:

iface lo inet loopback

# The primary network interface
iface eth0 inet static
    address x.x.x.x
    netmask 255.255.255.224
    gateway x.x.x.x

iface eth1 inet static
    address 192.168.0.61/23

iface br0 inet dhcp
    bridge_ports eth1
    bridge-ifaces eth1
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

auto lo eth0 eth1 br0

Is it possible to create containers that are visible on the LAN and can connect to the internet?

LXD v2.7 on Ubuntu 16.04

Body:
Yes, this is very possible. I haven't played around with all the new networking features introduced in LXD 2.3, so I can't speak to any of that, but it looks like you are wanting a pretty simple network layout, so those features may not even come into play. I do something somewhat similar to your network layout. I have 4 NIC's in all my servers. The first two I put in a bond and put on my management network, and the second two I put in a LAG (another bond) and use for all LXD traffic. I have multiple VLAN's so my LAG is setup as an trunk port and I create VLAN devices for each VLAN I want to be able to connect to. I then put those VLAN devices into a bridge that the actual container uses.

Take away all the bonding, and raw VLAN devices and you have essentially the same setup: one NIC for management of the LXD host, one bridge for LXD container traffic. I don't use the default lxcbr0 device, but all the concepts should be the same.

A simple example

First define the NIC or NIC's that will be part of your bridge. In your case it looks like you are just using one NIC (eth1). You need to set the NIC to manual. Do not assign an address to it.

auto eth1
iface eth1 inet manual

Next define your bridge, again I would not define an IP address here. I prefer to assign all my containers IP's inside the container. Set the bridge to manual as well. When the container starts it will bring up the device.

auto br0
iface br0 inet manual
  bridge_ports eth1
  bridge_stp off
  bridge_fd 0
  bridge_maxwait 0

Now all you have to do is use this bridge in your container's profile.

lxduser@lxdhost:~$ lxc profile show default
name: default
config: {}
description: ""
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: br0

Now start your container and edit the network configuration. For example in Debian based systems you would edit /etc/network/interfaces (in the container). In Red Hat based systems you would edit /etc/sysconfig/network-scripts/ifcfg-eth0 (in the container). Here is the Debian example.

auto eth0
iface eth0 inet dhcp

As long as DHCP is working on the network that eth1 (on your LXD host) is plugged into then the container should get an address and be routable on that network. In order to get internet access then eth1 has to be plugged into a subnet that has internet access, it is not dependent on the container.

More complex networking

If you want to put containers on different VLAN's, want fault tolerance on your host, or both, then this requires a bit more setup. I use the configuration file below on my LXD host.

############################
# PHYSICAL NETWORK DEVICES #
############################

# Management network interface
auto enp2s0f0
iface enp2s0f0 inet static
    address 10.1.31.36/24
    gateway 10.1.31.1
    dns-nameserver 10.1.30.2 10.1.30.3 75.75.75.75
    dns-search harmonywave.com

#iface enp2s0f0 inet6 dhcp

# Second network interface
auto enp2s0f1
iface enp2s0f1 inet manual

# LXD slave interface (1)
auto enp3s0f0
iface enp3s0f0 inet manual
    bond-master bond1

# LXD slave interface (2)
auto enp3s0f1
iface enp3s0f1 inet manual
    bond-master bond1

##########################
# BONDED NETWORK DEVICES #
##########################

# Bond network device
auto bond1
iface bond1 inet manual
    bond-mode 4
    bond-miimon 100
    bond-lacp-rate 1
    bond-slaves enp3s0f0 enp3s0f1
    bond-downdelay 400
    bond-updelay 800

####################
# RAW VLAN DEVICES #
####################

# Tagged traffic on bond1 for VLAN 10
iface bond1.10 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 20
iface bond1.20 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 30
iface bond1.30 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 31
iface bond1.31 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 42
iface bond1.42 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 50
iface bond1.50 inet manual
    vlan-raw-device bond1

# Tagged traffic on bond1 for VLAN 90
iface bond1.90 inet manual
    vlan-raw-device bond1

##########################
# BRIDGE NETWORK DEVICES #
##########################

# Bridged interface for VLAN 10
auto br0-10
iface br0-10 inet manual
    bridge_ports bond1.10
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 20
auto br0-20
iface br0-20 inet manual
    bridge_ports bond1.20
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 30
auto br0-30
iface br0-30 inet manual
    bridge_ports bond1.30
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 31
auto br0-31
iface br0-31 inet manual
    bridge_ports bond1.31
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 42
auto br0-42
iface br0-42 inet manual
    bridge_ports bond1.42
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 50
auto br0-50
iface br0-50 inet manual
    bridge_ports bond1.50
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

# Bridged interface for VLAN 90
auto br0-90
iface br0-90 inet manual
    bridge_ports bond1.90
    bridge_stp off
    bridge_fd 0
    bridge_maxwait 0

Let's break this down. First I define the physical NIC's. That's the PHYSICAL NETWORK DEVICES section. Nothing different between mine and yours for this first NIC (eth0 for you enp2s0f0 for me). I just define it statically and give it an address. I assign an address on my management network for this NIC. The third and fourth NIC's I use for container traffic. I wanted to use LACP in a LAG so I defined the devices as manual and made them a slave to "bond1".

Next I define my bond devices. That's the BONDED NETWORK DEVICES section. In this case just the one bond for container traffic. Again, I set it to manual and define the bond mode as 4 (LACP). Could have just as easily setup a different type of bond (active-passive, active-active, etc).

Next, because I have the third and fourth NIC physically connected to a trunk port on the switch I have to specify dot1Q so that traffic is actually tagged. I create a raw VLAN device for each VLAN that a container could possibly be in. I append a .XX where "XX" is the VLAN ID. This isn't necessary anymore, I just do this for easy identification. Then tag the device with the "vlan-raw-device" stanza. This is the RAW VLAN DEVICES section.

Finally, in the BRIDGE NETWORK DEVICES section I create bridges for each VLAN device. This is what the container will actually use. Again, I set this to manual and do not define an IP address, that is defined inside the container.

Now all I have to do is assign whatever bridge is on the VLAN I want to a container. For simplicity and to avoid configuring every container, I just create a profile for each bridge/VLAN. For example here is my profile for VLAN 31.

lxduser@lxdhost:~$ lxc profile show 31_vlan_int_server
name: 31_vlan_int_server
config: {}
description: ""
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: br0-31
    type: nic

Then I just assign this profile to any container I want on VLAN 31. At this point I can either setup my container's /etc/network/interfaces file as dhcp (if DHCP is enabled on that VLAN) or give it a static IP address that is part of that VLAN.

The Entire network layout looks something like this.

The container uses the veth device inside the bridge (which LXD creates). The host adds the raw vlan device to the bridge as well and they both use the actual bond device, which in turn uses the physical NICs.

Concerning issues with connectivity

Finally, concerning your issues of not being able to connect to the internet, make sure that the bridge your containers is using has internet access. I like to take a step-by-step troubleshooting approach.

Make sure that eth1 has internet access. Temporarily remove any bond and bridge configuration and use eth1 directly on the host. Change it from manual to static and give it an IP address.

On the host can you ping the NIC's IP address?

Yes? NIC is working, continue troubleshooting. No? NIC is not setup properly, everything else will fail.

On the host can you ping another host on the same subnet?

Yes? Switching is setup correctly, continue troubleshooting. No? Issue connecting to the network. Possible static routing issue on the box itself, possible issue with the switch.

On the host can you ping a machine on a different subnet (try ping 8.8.8.8)?

Yes? Routing is working properly, continue troubleshooting. No? Possible gateway misconfiguration on the host. Possible issue with the router. Possible issue with static routing on the box (check gateway of last resort).

Can you resolve a DNS address (try ping www.google.com)?

Yes? DNS resolution is setup correctly, continue troubleshooting. No? Issue with DNS resolution. Check /etc/resolv.conf or resolvconf setup.

If everything is working on eth1 when it is setup statically then you know that NIC is functioning properly. The next step would be to change eth1 back to manual, remove the static IP from it, and recreate your bridge. Now assign the static IP address on the bridge itself and repeat all the sub-steps from step 1.

If everything works successfully then you should be able to connect with your container (after setting your bridge back to manual and removing the static IP). If not, then get an address on the container (static or DHCP) and repeat the sub-steps from step 1.


问:
Wordpress set value from input field as comment author for logged in users
I have a shared account, lets call it "marketing".
Now I have three people using this account named Anna, Ben and Max.

When someone logs into this account and wants to type a comment with their name, it always shows the name "marketing" as author. How can I change this so that I put a name in my input field and I get the value from this as my comment author. In my comments.php I do not check if the user is logged on and call it here:

```<code><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="2"/>
</code>```

I tried to make following in my functions.php:

```<code>function change_author( $commentdata ) {
    if ( $commentdata['user_ID'] == 2 ) {  // User ID for Marketing

    $commentdata['user_ID'] = 0;
    $commentdata['comment_author'] = '';

  }

  return $commentdata;
}
add_filter( 'preprocess_comment' , 'change_author' );
</code>```

In this case my comment_author will always be Anonymous and also if I set it to NULL.

When i give the variable a value $commentdata['comment_author'] = 'test';
I get "test" as my comment_author but as I said, I would like to have the value I set in my input field. It works for not logged in users very well so I thought there might be a trick for logged in users as well.

In phpMyAdmin I checked for the entries in the database and it is giving me the right values for ID etc. But it also empties the comment_author field which results in an anonymous author.

I really hope that somebody can give me the right hint to accomplish this task.

答: https://wordpress.org/plugins/allow-multiple-accounts/ this plugin might help you, you can have multiple accounts under one account.</p>

Body:
I have a shared account, lets call it "marketing".
Now I have three people using this account named Anna, Ben and Max.

When someone logs into this account and wants to type a comment with their name, it always shows the name "marketing" as author. How can I change this so that I put a name in my input field and I get the value from this as my comment author. In my comments.php I do not check if the user is logged on and call it here:

<input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="2"/>

I tried to make following in my functions.php:

function change_author( $commentdata ) {
    if ( $commentdata['user_ID'] == 2 ) {  // User ID for Marketing

    $commentdata['user_ID'] = 0;
    $commentdata['comment_author'] = '';

  }

  return $commentdata;
}
add_filter( 'preprocess_comment' , 'change_author' );

In this case my comment_author will always be Anonymous and also if I set it to NULL.

When i give the variable a value $commentdata['comment_author'] = 'test';
I get "test" as my comment_author but as I said, I would like to have the value I set in my input field. It works for not logged in users very well so I thought there might be a trick for logged in users as well.

In phpMyAdmin I checked for the entries in the database and it is giving me the right values for ID etc. But it also empties the comment_author field which results in an anonymous author.

I really hope that somebody can give me the right hint to accomplish this task.


问:
Practical application of SKI calculus and BCKW
I can understand how to create and think about the SKI and BCKW calculus, but I am never able to find practical uses.  Maybe I am not looking deeply enough?  That is, I wonder if (an example only please, I am not implying this is true) Java Servlets use S extensively and Python generators are an example of BCW and I am just unable to see through the forest of trees?</p>

答: Although lambda and SKI calculus don't reflect the input and output systems of most programming languages (such as graphics, network connections, or arguably even standard input and output), the way practical computer programming is structured corresponds to Lambda (and therefore SKI and BCKW), such as the idea of recursion and somewhat the way functions are called. A lot of these programming languages have lambda abstractions for use as functions. </p>


问:
Visual Studio macro for penter and pexit
I'm making a profiler in a project, and I want to make it easy to integrate into my projects. I'm using penter and pexit with the /GH /Gh compiler flags so those functions are called every time a function is called or returned from. Right now, basically all I have to do in my projects is copy over the penter and pexit function anywhere in the global scope and that works, but I want to make a macro so it just basically inserts the function in. I defined the macro in my Profiler.h file and included that in my other project. the errors i'm getting are

```<code>error C2598: linkage specification must be at global scope
error C2601: '_pexit' : local function definitions are illegal
error C1075: end of file found before the left brace '{' at 'path/main.cpp' was matched
</code>```

note that 'path/main.cpp' is a long path to my project (non-profiler project) and main is where i'm 'calling' the macros

here are my macros, I must be understanding these wrong. I figured it'd just insert the function where it was 'called'

```<code>#define PENTER                                           \
extern "C" void __declspec(naked) _cdecl _penter(void)   \
{                                                        \
  _asm push ebp;                                         \
  _asm mov ebp, esp;                                     \
  _asm pushad;                                           \
  Profiler::GetInstance().Enter();                       \
  _asm popad;                                            \
  _asm mov esp, ebp;                                     \
  _asm pop ebp;                                          \
  _asm ret;                                              \
}                                                        \

#define PEXIT                                            \
extern "C" void __declspec(naked) _cdecl _pexit(void)    \
{                                                        \
  _asm push ebp;                                         \
  _asm mov ebp, esp;                                     \
  _asm pushad;                                           \
  Profiler::GetInstance().Exit();                        \
  _asm popad;                                            \
  _asm mov esp, ebp;                                     \
  _asm pop ebp;                                          \
  _asm ret;                                              \
}                                                        \
</code>```

Thanks for any help!

答:
You can try micro-profiler to do the task. Or take it's source for collection from here: hooks.asm
The good thing about it is that it works for x64 as well (you cannot inject assembly instructions in x64 cpp).</p>

Body:
I'm making a profiler in a project, and I want to make it easy to integrate into my projects. I'm using penter and pexit with the /GH /Gh compiler flags so those functions are called every time a function is called or returned from. Right now, basically all I have to do in my projects is copy over the penter and pexit function anywhere in the global scope and that works, but I want to make a macro so it just basically inserts the function in. I defined the macro in my Profiler.h file and included that in my other project. the errors i'm getting are

error C2598: linkage specification must be at global scope
error C2601: '_pexit' : local function definitions are illegal
error C1075: end of file found before the left brace '{' at 'path/main.cpp' was matched

note that 'path/main.cpp' is a long path to my project (non-profiler project) and main is where i'm 'calling' the macros

here are my macros, I must be understanding these wrong. I figured it'd just insert the function where it was 'called'

#define PENTER                                           \
extern "C" void __declspec(naked) _cdecl _penter(void)   \
{                                                        \
  _asm push ebp;                                         \
  _asm mov ebp, esp;                                     \
  _asm pushad;                                           \
  Profiler::GetInstance().Enter();                       \
  _asm popad;                                            \
  _asm mov esp, ebp;                                     \
  _asm pop ebp;                                          \
  _asm ret;                                              \
}                                                        \

#define PEXIT                                            \
extern "C" void __declspec(naked) _cdecl _pexit(void)    \
{                                                        \
  _asm push ebp;                                         \
  _asm mov ebp, esp;                                     \
  _asm pushad;                                           \
  Profiler::GetInstance().Exit();                        \
  _asm popad;                                            \
  _asm mov esp, ebp;                                     \
  _asm pop ebp;                                          \
  _asm ret;                                              \
}                                                        \

Thanks for any help!


问:
Tensorflow Variables are Not Initialized using Between-graph Replication
I have Python code test.py as below, which uses "Between-graph Replication" for Distributed Tensorflow:

```<code>import argparse
import logging

import tensorflow as tf

log = logging.getLogger(__name__)

# Job Names
PARAMETER_SERVER = "ps"
WORKER_SERVER = "worker"

# Cluster Details
CLUSTER_SPEC = {
    PARAMETER_SERVER: ["localhost:2222"],
    WORKER_SERVER: ["localhost:1111", "localhost:1112"]}

def parse_command_arguments():
    """ Set up and parse the command line arguments passed for experiment. """
    parser = argparse.ArgumentParser(
        description="Parameters and Arguments for the Test.")
    parser.add_argument(
        "--job_name",
        type=str,
        default="",
        help="One of 'ps', 'worker'"
    )
    # Flags for defining the tf.train.Server
    parser.add_argument(
        "--task_index",
        type=int,
        default=0,
        help="Index of task within the job"
    )

    return parser.parse_args()

def start_server(job_name, task_index):
    """ Create a server based on a cluster spec. """
    cluster = tf.train.ClusterSpec(CLUSTER_SPEC)
    server = tf.train.Server(
        cluster, job_name=job_name, task_index=task_index)

    return server, cluster

def model():
    """ Build up a simple estimator model. """
    # Build a linear model and predict values
    W = tf.Variable([.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    x = tf.placeholder(tf.float32)
    linear_model = W * x + b
    y = tf.placeholder(tf.float32)
    global_step = tf.get_variable('global_step', [],
                                  initializer=tf.constant_initializer(0),
                                  trainable=False)

    # Loss sub-graph
    loss = tf.reduce_sum(tf.square(linear_model - y))

    # optimizer
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(loss, global_step=global_step)

    init_op = tf.global_variables_initializer()
    log.info("Variables initialized ...")

    return W, b, loss, x, y, train, global_step, init_op

if __name__ == "__main__":
    # Initializing logging with level "INFO".
    logging.basicConfig(level=logging.INFO)

    # Parse arguments from command line.
    arguments = parse_command_arguments()
    job_name = arguments.job_name
    task_index = arguments.task_index

    # Start a server.
    server, cluster = start_server(job_name, task_index)

    if job_name == "ps":
        server.join()
    else:
        with tf.device(tf.train.replica_device_setter(
                worker_device="/job:worker/task:%d" % task_index,
                cluster=cluster)):
            W, b, loss, x, y, train, global_step, init_op = model()
        with tf.train.MonitoredTrainingSession(
                master=server.target,
                is_chief=(arguments.task_index == 0 and (
                            arguments.job_name == 'worker'))) as sess:
            step = 0
            # training data
            x_train = [1, 2, 3, 4]
            y_train = [0, -1, -2, -3]
            while not sess.should_stop() and step < 1000:
                _, step = sess.run(
                    [train, global_step], {x: x_train, y: y_train})

            # evaluate training accuracy
            curr_W, curr_b, curr_loss = sess.run(
                [W, b, loss], {x: x_train, y: y_train})
            print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))
</code>```

I ran the code with 3 different processes in a single machine (MacPro with only CPUs) following the order below:

Parameter Server: $ python test.py  --task_index 0 --job_name ps

Worker 1: $ python test.py  --task_index 0 --job_name worker

Worker 2: $ python test.py  --task_index 1 --job_name worker

and I found that the process for "Worker 2" hit an error:

```<code>$ python test.py --task_index 1 --job_name worker
I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:197] Initialize GrpcChannelCache for job ps -> {0 -> localhost:2222}
I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:197] Initialize GrpcChannelCache for job worker -> {0 -> localhost:1111, 1 -> localhost:1112}
I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:211] Started server with target: grpc://localhost:1112
INFO:__main__:Variables initialized ...
I tensorflow/core/distributed_runtime/master_session.cc:993] Start master session 9912c75f2921fe13 with config:

INFO:tensorflow:Waiting for model to be ready.  Ready_for_local_init_op:  None, ready: Variables not initialized: Variable, Variable_1, global_step
INFO:tensorflow:Waiting for model to be ready.  Ready_for_local_init_op:  None, ready: Variables not initialized: Variable, Variable_1, global_step
</code>```

and that process for "Worker 2" was just frozen there. The error shows Tensorflow variables for "Worker 2" are unsuccessfully initialized, so I wonder if there is a bug for MonitoredTrainingSession in terms of coordinating variable initializations across Tensorflow Sessions or somewhere else, or I missed things in my code.

NOTE: The code was running with Tensorflow 0.12

答:
I think this is "intended behavior" for the tf.train.MonitoredTrainingSession coordination protocol. In a recent answer, I explained how this protocol is geared towards long-running training jobs, so a worker will sleep for 30 seconds between checking to see if the variables have been initialized.

There is a race condition between Worker 1 running the initialization op and Worker 2 checking the variables, and if Worker 2 "wins" the race, it will observe that some variables are uninitialized, and it will enter a 30-second sleep before checking again.

However, the overall amount of computation in your program is very small, so in this 30-second period Worker 1 will be able to complete its work and terminate. When Worker 2 checks to see if the variables are initialized, it will create a new tf.Session that tries to connect to the other tasks, but Worker 1 is no longer running, so you will see a log message like this (repeating every 10 seconds or so):

```<code>I tensorflow/core/distributed_runtime/master.cc:193] CreateSession still waiting for response from worker: /job:worker/replica:0/task:0
</code>```

When the training job is substantially longer than 30 seconds, this would not be a problem.

One workaround is to remove the interdependency between the workers, by setting a "device filter". Since in a typical between-graph configuration the individual workers do not communicate, you can tell TensorFlow to ignore the absence of another worker at session-creation time, using tf. ConfigProto:

```<code># Each worker only needs to contact the PS task(s) and the local worker task.
config = tf.ConfigProto(device_filters=[
    '/job:ps', '/job:worker/task:%d' % arguments.task_index])

with tf.train.MonitoredTrainingSession(
    master=server.target,
    config=config,
    is_chief=(arguments.task_index == 0 and (
              arguments.job_name == 'worker'))) as sess:
  # ...
</code>```

Body:
I have Python code test.py as below, which uses "Between-graph Replication" for Distributed Tensorflow:

import argparse
import logging

import tensorflow as tf

log = logging.getLogger(__name__)

# Job Names
PARAMETER_SERVER = "ps"
WORKER_SERVER = "worker"

# Cluster Details
CLUSTER_SPEC = {
    PARAMETER_SERVER: ["localhost:2222"],
    WORKER_SERVER: ["localhost:1111", "localhost:1112"]}

def parse_command_arguments():
    """ Set up and parse the command line arguments passed for experiment. """
    parser = argparse.ArgumentParser(
        description="Parameters and Arguments for the Test.")
    parser.add_argument(
        "--job_name",
        type=str,
        default="",
        help="One of 'ps', 'worker'"
    )
    # Flags for defining the tf.train.Server
    parser.add_argument(
        "--task_index",
        type=int,
        default=0,
        help="Index of task within the job"
    )

    return parser.parse_args()

def start_server(job_name, task_index):
    """ Create a server based on a cluster spec. """
    cluster = tf.train.ClusterSpec(CLUSTER_SPEC)
    server = tf.train.Server(
        cluster, job_name=job_name, task_index=task_index)

    return server, cluster

def model():
    """ Build up a simple estimator model. """
    # Build a linear model and predict values
    W = tf.Variable([.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    x = tf.placeholder(tf.float32)
    linear_model = W * x + b
    y = tf.placeholder(tf.float32)
    global_step = tf.get_variable('global_step', [],
                                  initializer=tf.constant_initializer(0),
                                  trainable=False)

    # Loss sub-graph
    loss = tf.reduce_sum(tf.square(linear_model - y))

    # optimizer
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(loss, global_step=global_step)

    init_op = tf.global_variables_initializer()
    log.info("Variables initialized ...")

    return W, b, loss, x, y, train, global_step, init_op

if __name__ == "__main__":
    # Initializing logging with level "INFO".
    logging.basicConfig(level=logging.INFO)

    # Parse arguments from command line.
    arguments = parse_command_arguments()
    job_name = arguments.job_name
    task_index = arguments.task_index

    # Start a server.
    server, cluster = start_server(job_name, task_index)

    if job_name == "ps":
        server.join()
    else:
        with tf.device(tf.train.replica_device_setter(
                worker_device="/job:worker/task:%d" % task_index,
                cluster=cluster)):
            W, b, loss, x, y, train, global_step, init_op = model()
        with tf.train.MonitoredTrainingSession(
                master=server.target,
                is_chief=(arguments.task_index == 0 and (
                            arguments.job_name == 'worker'))) as sess:
            step = 0
            # training data
            x_train = [1, 2, 3, 4]
            y_train = [0, -1, -2, -3]
            while not sess.should_stop() and step < 1000:
                _, step = sess.run(
                    [train, global_step], {x: x_train, y: y_train})

            # evaluate training accuracy
            curr_W, curr_b, curr_loss = sess.run(
                [W, b, loss], {x: x_train, y: y_train})
            print("W: %s b: %s loss: %s" % (curr_W, curr_b, curr_loss))

I ran the code with 3 different processes in a single machine (MacPro with only CPUs) following the order below:

Parameter Server: $ python test.py  --task_index 0 --job_name ps

Worker 1: $ python test.py  --task_index 0 --job_name worker

Worker 2: $ python test.py  --task_index 1 --job_name worker

and I found that the process for "Worker 2" hit an error:

$ python test.py --task_index 1 --job_name worker
I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:197] Initialize GrpcChannelCache for job ps -> {0 -> localhost:2222}
I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:197] Initialize GrpcChannelCache for job worker -> {0 -> localhost:1111, 1 -> localhost:1112}
I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:211] Started server with target: grpc://localhost:1112
INFO:__main__:Variables initialized ...
I tensorflow/core/distributed_runtime/master_session.cc:993] Start master session 9912c75f2921fe13 with config:

INFO:tensorflow:Waiting for model to be ready.  Ready_for_local_init_op:  None, ready: Variables not initialized: Variable, Variable_1, global_step
INFO:tensorflow:Waiting for model to be ready.  Ready_for_local_init_op:  None, ready: Variables not initialized: Variable, Variable_1, global_step

and that process for "Worker 2" was just frozen there. The error shows Tensorflow variables for "Worker 2" are unsuccessfully initialized, so I wonder if there is a bug for MonitoredTrainingSession in terms of coordinating variable initializations across Tensorflow Sessions or somewhere else, or I missed things in my code.

NOTE: The code was running with Tensorflow 0.12

Body:
I think this is "intended behavior" for the tf.train.MonitoredTrainingSession coordination protocol. In a recent answer, I explained how this protocol is geared towards long-running training jobs, so a worker will sleep for 30 seconds between checking to see if the variables have been initialized.

There is a race condition between Worker 1 running the initialization op and Worker 2 checking the variables, and if Worker 2 "wins" the race, it will observe that some variables are uninitialized, and it will enter a 30-second sleep before checking again.

However, the overall amount of computation in your program is very small, so in this 30-second period Worker 1 will be able to complete its work and terminate. When Worker 2 checks to see if the variables are initialized, it will create a new tf.Session that tries to connect to the other tasks, but Worker 1 is no longer running, so you will see a log message like this (repeating every 10 seconds or so):

I tensorflow/core/distributed_runtime/master.cc:193] CreateSession still waiting for response from worker: /job:worker/replica:0/task:0

When the training job is substantially longer than 30 seconds, this would not be a problem.

One workaround is to remove the interdependency between the workers, by setting a "device filter". Since in a typical between-graph configuration the individual workers do not communicate, you can tell TensorFlow to ignore the absence of another worker at session-creation time, using tf. ConfigProto:

# Each worker only needs to contact the PS task(s) and the local worker task.
config = tf.ConfigProto(device_filters=[
    '/job:ps', '/job:worker/task:%d' % arguments.task_index])

with tf.train.MonitoredTrainingSession(
    master=server.target,
    config=config,
    is_chief=(arguments.task_index == 0 and (
              arguments.job_name == 'worker'))) as sess:
  # ...


问:
What's wrong with my Scanner java code?
```<code>import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}
</code>```

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

```<code>Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)
</code>```

How can I fix my code?

答:
"5" in in.nextInt(5); means radix. Do you need it? Does the program work if you use nextInt() method with no parameters?

Also, for some reason both of versions work for me with no error:

```<code>// output of nextInt(radix) version
java Excercise5
Input first number: 32
Input second number: 23
17 x 53 = 901

// output of nextInt() version
java Excercise5
Input first number: 5
Input second number: 25
5 x 25 = 125
</code>```

Title: What's wrong with my Scanner java code?

Body:
import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)

How can I fix my code?

Body:
"5" in in.nextInt(5); means radix. Do you need it? Does the program work if you use nextInt() method with no parameters?

Also, for some reason both of versions work for me with no error:

// output of nextInt(radix) version
java Excercise5
Input first number: 32
Input second number: 23
17 x 53 = 901

// output of nextInt() version
java Excercise5
Input first number: 5
Input second number: 25
5 x 25 = 125


问:
ERROR :Execution failed for task ':app:processDebugResources'
When I try to build my project, the Messages Gradle Build reports these messages:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugResources'.

java.lang.IllegalArgumentException (no error message)

Gradle file

```<code>android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
    applicationId "com.example.bolt.skola"
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.roughike:bottom-bar:1.3.9'

compile 'com.google.android.gms:play-services-identity:10.2.0'
compile 'com.google.android.gms:play-services-plus:10.2.0'
compile 'com.google.android.gms:play-services-gcm:10.2.0'

testCompile 'junit:junit:4.12'
}
</code>```

答: I edited my package name to solve the problem.</p>

Body:
When I try to build my project, the Messages Gradle Build reports these messages:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:processDebugResources'.

java.lang.IllegalArgumentException (no error message)

Gradle file

android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
    applicationId "com.example.bolt.skola"
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.roughike:bottom-bar:1.3.9'

compile 'com.google.android.gms:play-services-identity:10.2.0'
compile 'com.google.android.gms:play-services-plus:10.2.0'
compile 'com.google.android.gms:play-services-gcm:10.2.0'

testCompile 'junit:junit:4.12'
}


问:
MPI_Recv() invalid buffer pointer
I have a dynamically allocated array that is sent by rank 0 to other ranks using MPI_Send()
On the receiving side, a dynamic array is allocated memory using malloc()
MPI_Recv() happens on the other ranks. At this receive function, I get invalid Buffer Pointer error.

Code is conceptually similar to this:

```<code>    struct graph{
    int count;
    int * array;
} a_graph;

int x = 10;
MPI_Status status;

//ONLY 2 RANKS ARE PRESENT. RANK 0 SENDS MSG TO RANK 1

if (rank == 0){
    a_graph * my_graph = malloc(sizeof(my_graph))
    my_graph->count = x;
    my_graph->array = malloc(sizeof(int)*my_graph->count);
    for(int i =0; i < my_graph->count; i++)
        my_graph->array[i] = i;
    MPI_Send(my_graph->array,my_graph->count,int,1,0,MPI_COMM_WORLD);
    free(my_graph->array);
    free(my_graph);
    }
else if (rank == 1){
    a_graph * my_graph = malloc(sizeof(my_graph))
    my_graph->count = x;
    my_graph->array = malloc(sizeof(int)*my_graph->count);
    MPI_Recv(my_graph->array,my_graph->count,int,0,0,MPI_COMM_WORLD,&status)  // MPI INVALID BUFFER POINTER ERROR HAPPENS AT THIS RECV
}
</code>```

I dont understand why this happens since memory is allocated in both sender and receiver ranks

答:
Below is a minimal, working, and verifiable (MWVE) example which Zulan suggested you to make. Please provide MWVE in your future questions. Anyway, you need to use MPI datatype MPI_INT instead of int for sending and receiving.

```<code>#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct graph{
    int count;
    int * array;
} a_graph;

int main()
{
    MPI_Init(NULL, NULL);
    int rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    int x = 10;
    MPI_Status status;

    //ONLY 2 RANKS ARE PRESENT. RANK 0 SENDS MSG TO RANK 1

    if (rank == 0){
        a_graph * my_graph = malloc(sizeof(a_graph));
        my_graph->count = x;
        my_graph->array = malloc(sizeof(int)*my_graph->count);
        for(int i =0; i < my_graph->count; i++)
            my_graph->array[i] = i;
        MPI_Send(my_graph->array,my_graph->count,MPI_INT,1,0,MPI_COMM_WORLD);
        free(my_graph->array);
        free(my_graph);
    }
    else if (rank == 1){
        a_graph * my_graph = malloc(sizeof(a_graph));
        my_graph->count = x;
        my_graph->array = malloc(sizeof(int)*my_graph->count);
        MPI_Recv(my_graph->array,my_graph->count,MPI_INT,0,0,MPI_COMM_WORLD,&status);
        for (int i=0; i<my_graph->count; ++i)
        {
            printf("%i\n", my_graph->array[i]);
        }
    }

    MPI_Finalize();

    return 0;
}
</code>```

Title: MPI_Recv() invalid buffer pointer

Body:
I have a dynamically allocated array that is sent by rank 0 to other ranks using MPI_Send()
On the receiving side, a dynamic array is allocated memory using malloc()
MPI_Recv() happens on the other ranks. At this receive function, I get invalid Buffer Pointer error.

Code is conceptually similar to this:

    struct graph{
    int count;
    int * array;
} a_graph;

int x = 10;
MPI_Status status;

//ONLY 2 RANKS ARE PRESENT. RANK 0 SENDS MSG TO RANK 1

if (rank == 0){
    a_graph * my_graph = malloc(sizeof(my_graph))
    my_graph->count = x;
    my_graph->array = malloc(sizeof(int)*my_graph->count);
    for(int i =0; i < my_graph->count; i++)
        my_graph->array[i] = i;
    MPI_Send(my_graph->array,my_graph->count,int,1,0,MPI_COMM_WORLD);
    free(my_graph->array);
    free(my_graph);
    }
else if (rank == 1){
    a_graph * my_graph = malloc(sizeof(my_graph))
    my_graph->count = x;
    my_graph->array = malloc(sizeof(int)*my_graph->count);
    MPI_Recv(my_graph->array,my_graph->count,int,0,0,MPI_COMM_WORLD,&status)  // MPI INVALID BUFFER POINTER ERROR HAPPENS AT THIS RECV
}

I dont understand why this happens since memory is allocated in both sender and receiver ranks

Body:
Below is a minimal, working, and verifiable (MWVE) example which Zulan suggested you to make. Please provide MWVE in your future questions. Anyway, you need to use MPI datatype MPI_INT instead of int for sending and receiving.

#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct graph{
    int count;
    int * array;
} a_graph;

int main()
{
    MPI_Init(NULL, NULL);
    int rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    int x = 10;
    MPI_Status status;

    //ONLY 2 RANKS ARE PRESENT. RANK 0 SENDS MSG TO RANK 1

    if (rank == 0){
        a_graph * my_graph = malloc(sizeof(a_graph));
        my_graph->count = x;
        my_graph->array = malloc(sizeof(int)*my_graph->count);
        for(int i =0; i < my_graph->count; i++)
            my_graph->array[i] = i;
        MPI_Send(my_graph->array,my_graph->count,MPI_INT,1,0,MPI_COMM_WORLD);
        free(my_graph->array);
        free(my_graph);
    }
    else if (rank == 1){
        a_graph * my_graph = malloc(sizeof(a_graph));
        my_graph->count = x;
        my_graph->array = malloc(sizeof(int)*my_graph->count);
        MPI_Recv(my_graph->array,my_graph->count,MPI_INT,0,0,MPI_COMM_WORLD,&status);
        for (int i=0; i<my_graph->count; ++i)
        {
            printf("%i\n", my_graph->array[i]);
        }
    }

    MPI_Finalize();

    return 0;
}


问:
Append/concatenate two files using spark/scala
I have multiple files stored in HDFS, and I need to merge them into one file using spark. However, because this operation is done frequently (every hour). I need to append those multiple files to the source file.

I found that there is the FileUtil that gives the 'copymerge' function. but it doesn't allow to append two files.

Thank you for your help

答:
You can do this with two methods:

```<code> sc.textFile("path/source", "path/file1", "path/file2").coalesce(1).saveAsTextFile("path/newSource")
</code>```

Or as @Pushkr has proposed

```<code> new UnionRDD(sc, Seq(sc.textFile("path/source"), sc.textFile("path/file1"),..)).coalesce(1).saveAsTextFile("path/newSource")
</code>```

If you don't want to create a new source and overwrite the same source every hour, you can use dataframe with save mode overwrite ( How to overwrite the output directory in spark)

Body:
You can do this with two methods:

 sc.textFile("path/source", "path/file1", "path/file2").coalesce(1).saveAsTextFile("path/newSource")

Or as @Pushkr has proposed

 new UnionRDD(sc, Seq(sc.textFile("path/source"), sc.textFile("path/file1"),..)).coalesce(1).saveAsTextFile("path/newSource")

If you don't want to create a new source and overwrite the same source every hour, you can use dataframe with save mode overwrite ( How to overwrite the output directory in spark)


问:
promise gives undefined result in callback
fileUpload.js

```<code>var Uploader = require('s3-image-uploader');
var express = require('express');
var config = require('./../config.js');
var Promise = require('promise');

var uploader = new Uploader({
    aws: {
        key: config.awsKey,
        secret: config.awsSecret
    },
    websockets: false
});

exports.fileUpload = function(fileName) {

    new Promise(function(resolve, reject) {

        uploader.upload({
                fileId: 'someUniqueIdentifier',
                bucket: 'quflip',
                source: './public/images/' + fileName,
                name: fileName
            },
            function(data) { // success
                console.log('upload success:', resolve);
                resolve(data);
            },
            function(errMsg, errObject) { //error
                reject(false);
            });
    });
};
</code>```

logintest.js

```<code>var awsUpload = require('./../config/fileUpload.js');

var userData = function(req, res) {
console.log("true/false" + awsUpload.fileUpload(profile_image));
</code>```

Here what is happening is, I am getting undefined value in console.log. So it means that callback is not passing the data. How can I pass the data effectively for further purpose

答:
You need to chain to the promise with .then and do the log there. First, make sure you return the promise

```<code>return new Promise(function(resolve, reject) {
</code>```

Then, you can do:

```<code>var userData = function (req, res) {
  awsUpload.fileUpload(profile_image).then(data => {
    console.log("true/false" + data);
  });
}
</code>```

If you are working in an environment that supports async/await, you can do this a bit more simply:

```<code>var userData = async function (req, res) {
  console.log("true/false" + await awsUpload.fileUpload(profile_image));
};
</code>```

Keep in mind that this will return a Promise.

I don't see where profile_image gets set, though.

Body:
fileUpload.js

var Uploader = require('s3-image-uploader');
var express = require('express');
var config = require('./../config.js');
var Promise = require('promise');

var uploader = new Uploader({
    aws: {
        key: config.awsKey,
        secret: config.awsSecret
    },
    websockets: false
});

exports.fileUpload = function(fileName) {

    new Promise(function(resolve, reject) {

        uploader.upload({
                fileId: 'someUniqueIdentifier',
                bucket: 'quflip',
                source: './public/images/' + fileName,
                name: fileName
            },
            function(data) { // success
                console.log('upload success:', resolve);
                resolve(data);
            },
            function(errMsg, errObject) { //error
                reject(false);
            });
    });
};

logintest.js

var awsUpload = require('./../config/fileUpload.js');

var userData = function(req, res) {
console.log("true/false" + awsUpload.fileUpload(profile_image));

Here what is happening is, I am getting undefined value in console.log. So it means that callback is not passing the data. How can I pass the data effectively for further purpose

Body:
You need to chain to the promise with .then and do the log there. First, make sure you return the promise

return new Promise(function(resolve, reject) {

Then, you can do:

var userData = function (req, res) {
  awsUpload.fileUpload(profile_image).then(data => {
    console.log("true/false" + data);
  });
}

If you are working in an environment that supports async/await, you can do this a bit more simply:

var userData = async function (req, res) {
  console.log("true/false" + await awsUpload.fileUpload(profile_image));
};

Keep in mind that this will return a Promise.

I don't see where profile_image gets set, though.


问:
didReceiveMemoryWarning: what type of memory?
I have a base cordova app, with some objective-c code around cordova's framework. Sometimes I've didReceiveMemoryWarning notification, but I don't understand if the problem is the javascript inside the UIWebView or other.
The documentation says:

Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low.

But my question is: what type of memory?
RAM? Heap allocations? Something else?

答: You should profile your app with Instruments and you'll get a better picture of what's consuming memory.</p>


问:
Radio button for each entry

    NAME
    CLASS
    ROLL NO.
    ATTENDENCE

  <?php
               $stream=$_SESSION['stream'];
               $year=$_SESSION['year'];
               $rs=mysql_query("SELECT * FROM student WHERE stream='$stream' AND year='$year' ORDER BY roll",$connect);
               while($row=mysql_fetch_array($rs))
               {
          ?>

      <?=$row[0]?>

      <?=$row[3]?>
        <?=$row[4]?>

      <?=$row[5]?>

      <input type="radio" name="r1" value="p" class="attendence">
      <input type="radio" name="r1" value="a" class="attendence">

  <?php
                    }
          ?>

```

------------------
here is the code I am currently working on. I am making online attendance system where I am making the page where teacher will give the attendance to student. I have successfully retrive the name of the student but I am unable to make the radio button for which teacher will give the attendance.. Here 2 radio button appears but among all of these only 1 is working

答:
my understanding is for different students only one radio value is working and applicable to all.

You need an array which specify per row.
so use brackets in name r1[] as i mention.

If not this is the requirement then explain more

Title: Radio button for each entry

Body:
    NAME
    CLASS
    ROLL NO.
    ATTENDENCE

  <?php
               $stream=$_SESSION['stream'];
               $year=$_SESSION['year'];
               $rs=mysql_query("SELECT * FROM student WHERE stream='$stream' AND year='$year' ORDER BY roll",$connect);
               while($row=mysql_fetch_array($rs))
               {
          ?>

      <?=$row[0]?>

      <?=$row[3]?>
        <?=$row[4]?>

      <?=$row[5]?>

      <input type="radio" name="r1" value="p" class="attendence">
      <input type="radio" name="r1" value="a" class="attendence">

  <?php
                    }
          ?>

------------------
here is the code I am currently working on. I am making online attendance system where I am making the page where teacher will give the attendance to student. I have successfully retrive the name of the student but I am unable to make the radio button for which teacher will give the attendance.. Here 2 radio button appears but among all of these only 1 is working


问:
Populating JTextField based on latest KeyStroke
The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox populate jTextField1 if the checkbox is selected, and populate the other if it is not selected or vice versa which is working perfectly.

But I would like to explore if this can be done without the checkbox.

As in, if I type something in jtextfield1 and double click the item in list to complete the text, the item clicked should be appended to jtextfield1 based on fetching the latest KeyStroke I used.

Is there are any way to do this?

答:
The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.

Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.

Check out List Action for a simple class that allows you to implement this functionality by using an Action.

Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.

The basic code for the custom Action would be:

```<code>JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );
</code>```

Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.

To use the FocusListener approach you would need to define an instance variable in your class:

```<code>private JTextField lastFocusedTextField = null;
</code>```

Then in the constructor of your class where you create the text fields you would create the listener:

```<code>FocusListener fl = new FocusAdapter()
{
    @Override
    public void focusGained(FocusEvent e)
    {
        lastFocusedTextField = (JTextField)e.getSource();
    }
};

JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field
</code>```

Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:

```<code>JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );
</code>```

So you need:

an instance variable

a FocusListener

a MouseListener

Body:
The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.

Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.

Check out List Action for a simple class that allows you to implement this functionality by using an Action.

Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.

The basic code for the custom Action would be:

JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );

Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.

To use the FocusListener approach you would need to define an instance variable in your class:

private JTextField lastFocusedTextField = null;

Then in the constructor of your class where you create the text fields you would create the listener:

FocusListener fl = new FocusAdapter()
{
    @Override
    public void focusGained(FocusEvent e)
    {
        lastFocusedTextField = (JTextField)e.getSource();
    }
};

JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field

Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:

JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );

So you need:

an instance variable

a FocusListener

a MouseListener