问:
File gets corrupted in Socket Programming
I am trying to send file from client side to server side.  Here, WritableGUI is an interface which display the file name in a text area. File transferred to server but gets corrupted. Sometimes transferred file size is right but sometimes it shows file size 0 kb. whats wrong with my code?

Client Side:

```<code>public class FileClient {

    private Socket s;
    private String fileName;
    private long fileLength;

    public FileClient(String host, int port, String file, String fileName, long FileLength) {
        this.fileName = fileName;
        this.fileLength = FileLength;
        try {
            s = new Socket(host, port);
            sendFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendFile(String file) throws IOException {
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        dos.writeUTF(fileName);
        dos.writeLong(fileLength);
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
        fis.close();
        dos.close();
    }
}
</code>```

Server Side:

```<code>public class FileServer extends Thread {

    ServerSocket server;
    int port = 8877;
    WritableGUI gui;

    public FileServer(WritableGUI gui, int SOCKET_PORT) throws IOException {
        this.port = SOCKET_PORT;
        this.gui = gui;

        try {
            server = new ServerSocket(port);
        } catch (IOException ex) {
            Logger.getLogger(MessageListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        while (true) {
            try {
                Socket clientSock = server.accept();
                saveFile(clientSock);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void saveFile(Socket clientSock) throws IOException {
        DataInputStream dis = new DataInputStream(clientSock.getInputStream());
        FileOutputStream fos = new FileOutputStream(dis.readUTF());
        byte[] buffer = new byte[1024];

        gui.write("File Received: " + dis.readUTF());

        long filesize = dis.readLong(); // read file size in separate msg
        int read = 0;
        int totalRead = 0;
        int remaining = (int) filesize;
        while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 0) {
            totalRead += read;
            remaining -= read;
            System.out.println("read " + totalRead + " bytes.");
            fos.write(buffer, 0, read);
        }
        dis.close();
        fos.close();
    }
}
</code>```

答:
```<code>while (fis.read(buffer) > 0) {
        dos.write(buffer);
    }
</code>```

As usual. Wrong copy-loop. Try this:

```<code>int count;
while ((count = fis.read(buffer)) > 0) {
        dos.write(buffer, 0, count);
    }
</code>```

and have a good think about why.

Body:
I am trying to send file from client side to server side.  Here, WritableGUI is an interface which display the file name in a text area. File transferred to server but gets corrupted. Sometimes transferred file size is right but sometimes it shows file size 0 kb. whats wrong with my code?

Client Side:

public class FileClient {

    private Socket s;
    private String fileName;
    private long fileLength;

    public FileClient(String host, int port, String file, String fileName, long FileLength) {
        this.fileName = fileName;
        this.fileLength = FileLength;
        try {
            s = new Socket(host, port);
            sendFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendFile(String file) throws IOException {
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        dos.writeUTF(fileName);
        dos.writeLong(fileLength);
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
        fis.close();
        dos.close();
    }
}

Server Side:

public class FileServer extends Thread {

    ServerSocket server;
    int port = 8877;
    WritableGUI gui;

    public FileServer(WritableGUI gui, int SOCKET_PORT) throws IOException {
        this.port = SOCKET_PORT;
        this.gui = gui;

        try {
            server = new ServerSocket(port);
        } catch (IOException ex) {
            Logger.getLogger(MessageListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        while (true) {
            try {
                Socket clientSock = server.accept();
                saveFile(clientSock);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void saveFile(Socket clientSock) throws IOException {
        DataInputStream dis = new DataInputStream(clientSock.getInputStream());
        FileOutputStream fos = new FileOutputStream(dis.readUTF());
        byte[] buffer = new byte[1024];

        gui.write("File Received: " + dis.readUTF());

        long filesize = dis.readLong(); // read file size in separate msg
        int read = 0;
        int totalRead = 0;
        int remaining = (int) filesize;
        while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 0) {
            totalRead += read;
            remaining -= read;
            System.out.println("read " + totalRead + " bytes.");
            fos.write(buffer, 0, read);
        }
        dis.close();
        fos.close();
    }
}

Body:
while (fis.read(buffer) > 0) {
        dos.write(buffer);
    }

As usual. Wrong copy-loop. Try this:

int count;
while ((count = fis.read(buffer)) > 0) {
        dos.write(buffer, 0, count);
    }

and have a good think about why.


来源: stackexchange

问:
State of react app is not current with what I have in my database?
I am working on a small grocery list application. Whenever I submit a form, I perform an axios request to add the item to the database and update my "items" state to contain the new grocery item.

The issue is, unless I refresh the page, my state still shows an empty "items" array. The "items" array's initial state is pulled from the database, this works through using componentDidMount and setting the state of "items" in there.

Also, in my state, I have currentUser which is also pulled from the database. If I attempt to log this.state.currentUser.shoppingList after adding my first item, it will show an empty array even though I can see the server side log stating the array is not empty.

Here is my code:

```<code>**App Component**
import React from 'react';
import ListForm from './ListForm';
import * as helpers from '../helpers';

class App extends React.Component{
  state = {
    currentUser: {},
    items: []
  }

  componentDidMount() {
    console.log('Hello!');
    helpers.fetchUser()
      .then(data => {
        this.setState({
          currentUser: data,
          items: data.shoppingList
        }, () => {
          console.log(this.state)
        });
      });
  }

  // Handle adding new items
  onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);
  }

  // Handle deletion of items
  onDelete = (id, deleteItem) => {
    var shoppingList = this.state.currentUser.shoppingList;
    var index = shoppingList.findIndex(x => x.name === deleteItem);

    console.log(shoppingList);
    helpers.removeItem(id, deleteItem);
  }

  render() {
    return (
      <div className="container row offset-4">
        <div className="jumbotron col-sm-6">
          <ListForm
            currentUser={this.state.currentUser}
            items={this.state.items}
            onSubmit={this.onSubmit}
            onDelete={this.onDelete}
          />
        </div>
      </div>
    );
  }
};

export default App;
</code>```

Helpers.js

```<code>import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem =  (id, newItem) => {
  const resp = axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}

export const removeItem = (id, deleteItem) => {
  const resp = axios.delete("/api/" + id + "/removeItem", {data: {item: deleteItem}});

  return resp.data;
}
</code>```

ListForm Component

```<code>import React from 'react';
import ListItem from './ListItem';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  // Render content based on whether or not currentUser has been returned from
  // our API request.
  renderContent = () => {
    const shoppingList = this.props.currentUser.shoppingList;
    if(shoppingList === null || shoppingList === undefined) {
      return (<h5>Loading List</h5>);
    } else {
        return (
          <div>
            {this.props.items.map((item, index) =>
              <ListItem
                {...item}
                key={index}
                id={index}
                currentUser={this.props.currentUser}
                onDelete={this.props.onDelete}
              />
            )}
          </div>
        );
    }
  }

  // Handle the submission of a new item to database and state.
  handleSubmit = e => {
    e.preventDefault();

    this.props.onSubmit(this.props.currentUser._id, {name: this.state.value});
    this.setState(prevState => ({value: ''}));
  }

  // Handle any changes within the input.
  onChange = e => {
    this.setState({value: e.target.value});
  }

  render() {
    return (
      <div className="col-xs-9">
          <h3>Grocery List</h3>
        <form className="form-control" onSubmit={this.handleSubmit}>
          <input style={{display: "inline", width: "60%", height: "2em"}} className="form-control" type="text"
            value={this.state.value}
            onChange={this.onChange}
          />
          <button className="btn btn-success btn-sm float-right">Add item</button>
        </form>
        <div style={{marginTop: "10%"}}>
          {this.renderContent()}
        </div>
      </div>
    );
  }
}

export default ListForm;
</code>```

ListItem Component

```<code>import React from 'react';

const ListItem = props => {

  // Handle delete item requests
  const handleClick = event => {
    var delItem = document.getElementById("btn" + props.id).textContent;

    props.onDelete(props.currentUser._id, delItem);
  }

  return (
    <div>
      <li
        style={{display: "inline"}} id={"btn" + props.id} key={props.id}>{props.name}
      </li>
      <button
        style={{display: "inline"}} onClick={e => handleClick(e)} className="btn btn-danger btn-sm float-right">
          Remove
      </button>
      <hr />
    </div>
  );
}

export default ListItem;
</code>```

答:
Unlike render(), which is called every time the component's state is changed, componentDidMount()is called only once, after the component has been "mounted", that is, after its DOM nodes have been inserted in the DOM. For more details regarding the "mounted" term, you might want to check out the Component Lifecyle Reference.

In your code, adding an item will modify your client's state.items (not state.currentUser.shoppingList by the way), and your fetchUser function is called only once as being part of the componentDidMount client method (reference :
 https://reactjs.org/docs/react-component.html#componentdidmount).

In other words, when you add an item to the database using addItem, your component won't synchronize with your database update because your component's state is not updated to reflect the change that happened in the backend.

If you'd like to sync your user with what you have in the database, then you may call fetchUser after having added the item to the database like so :

```<code>  // Handle adding new items
  onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);

    helpers.fetchUser()
      .then(data => {
        this.setState({
          currentUser: data,
          items: data.shoppingList
        }, () => {
          console.log(this.state)
        });
      });
  }
</code>```

I did not test the code though, sorry. Maybe a cleaner way would be to "promisify" your addItem function just like you did for fetchUser.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I am working on a small grocery list application. Whenever I submit a form, I perform an axios request to add the item to the database and update my "items" state to contain the new grocery item.

The issue is, unless I refresh the page, my state still shows an empty "items" array. The "items" array's initial state is pulled from the database, this works through using componentDidMount and setting the state of "items" in there.

Also, in my state, I have currentUser which is also pulled from the database. If I attempt to log this.state.currentUser.shoppingList after adding my first item, it will show an empty array even though I can see the server side log stating the array is not empty.

Here is my code:

**App Component**
import React from 'react';
import ListForm from './ListForm';
import * as helpers from '../helpers';

class App extends React.Component{
  state = {
    currentUser: {},
    items: []
  }

  componentDidMount() {
    console.log('Hello!');
    helpers.fetchUser()
      .then(data => {
        this.setState({
          currentUser: data,
          items: data.shoppingList
        }, () => {
          console.log(this.state)
        });
      });
  }

  // Handle adding new items
  onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);
  }

  // Handle deletion of items
  onDelete = (id, deleteItem) => {
    var shoppingList = this.state.currentUser.shoppingList;
    var index = shoppingList.findIndex(x => x.name === deleteItem);

    console.log(shoppingList);
    helpers.removeItem(id, deleteItem);
  }

  render() {
    return (

          <ListForm
            currentUser={this.state.currentUser}
            items={this.state.items}
            onSubmit={this.onSubmit}
            onDelete={this.onDelete}
          />

    );
  }
};

export default App;

Helpers.js

import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem =  (id, newItem) => {
  const resp = axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}

export const removeItem = (id, deleteItem) => {
  const resp = axios.delete("/api/" + id + "/removeItem", {data: {item: deleteItem}});

  return resp.data;
}

ListForm Component

import React from 'react';
import ListItem from './ListItem';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  // Render content based on whether or not currentUser has been returned from
  // our API request.
  renderContent = () => {
    const shoppingList = this.props.currentUser.shoppingList;
    if(shoppingList === null || shoppingList === undefined) {
      return (
Loading List
);
    } else {
        return (

            {this.props.items.map((item, index) =>
              <ListItem
                {...item}
                key={index}
                id={index}
                currentUser={this.props.currentUser}
                onDelete={this.props.onDelete}
              />
            )}

        );
    }
  }

  // Handle the submission of a new item to database and state.
  handleSubmit = e => {
    e.preventDefault();

    this.props.onSubmit(this.props.currentUser._id, {name: this.state.value});
    this.setState(prevState => ({value: ''}));
  }

  // Handle any changes within the input.
  onChange = e => {
    this.setState({value: e.target.value});
  }

  render() {
    return (

Grocery List

        <form className="form-control" onSubmit={this.handleSubmit}>
          <input style={{display: "inline", width: "60%", height: "2em"}} className="form-control" type="text"
            value={this.state.value}
            onChange={this.onChange}
          />
          <button className="btn btn-success btn-sm float-right">Add item</button>
        </form>

          {this.renderContent()}

    );
  }
}

export default ListForm;

ListItem Component

import React from 'react';

const ListItem = props => {

  // Handle delete item requests
  const handleClick = event => {
    var delItem = document.getElementById("btn" + props.id).textContent;

    props.onDelete(props.currentUser._id, delItem);
  }

  return (

{props.name}

      <button
        style={{display: "inline"}} onClick={e => handleClick(e)} className="btn btn-danger btn-sm float-right">
          Remove
      </button>

  );
}

export default ListItem;

Body:
Unlike render(), which is called every time the component's state is changed, componentDidMount()is called only once, after the component has been "mounted", that is, after its DOM nodes have been inserted in the DOM. For more details regarding the "mounted" term, you might want to check out the Component Lifecyle Reference.

In your code, adding an item will modify your client's state.items (not state.currentUser.shoppingList by the way), and your fetchUser function is called only once as being part of the componentDidMount client method (reference :
 https://reactjs.org/docs/react-component.html#componentdidmount).

In other words, when you add an item to the database using addItem, your component won't synchronize with your database update because your component's state is not updated to reflect the change that happened in the backend.

If you'd like to sync your user with what you have in the database, then you may call fetchUser after having added the item to the database like so :

  // Handle adding new items
  onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);

    helpers.fetchUser()
      .then(data => {
        this.setState({
          currentUser: data,
          items: data.shoppingList
        }, () => {
          console.log(this.state)
        });
      });
  }

I did not test the code though, sorry. Maybe a cleaner way would be to "promisify" your addItem function just like you did for fetchUser.

Hope this helps!


问:
Changing a linked list of Ellipses to images in c#
I've made a simple snake game in c# wpf forms.The problem is that Iv'e made the food as Ellipses and I want to change that to an image of an apple.
This is the food class where I specified the type/shape of the food :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Controls;

namespace WpfApp1
{
class Food
{
    public double x, y;
    public Ellipse e = new Ellipse();
    public Food(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public void setFoodPosition()
    {
        Random r = new Random();
        if (Settings.size != 0)
            e.Width = e.Height = Settings.g.Size;
        else
            e.Width = e.Height = 10;
        e.Stroke = Brushes.Black;
        e.Fill = new SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255), (byte)r.Next(255))); ;
        Canvas.SetLeft(e, x);
        Canvas.SetTop(e, y);
    }
  }
 }
</code>```

does anyone have any idea how I do that?

答:
If you have an image of an apple in an image file, you should add that file to your Visual Studio project (e.g. in a project folder named Images) and set its Build Action to Resource.

You would then load the image by a Resource File Pack URI, and use it with an ImageBrush as Fill Brush of a Rectangle:

```<code>private Rectangle rect = new Rectangle();
...

rect.Fill = new ImageBrush(
    new BitmapImage(new Uri("pack://application:,,,/Images/Apple.png")));
</code>```

Or you use an Image element instead of a Rectangle:

```<code>private Image image = new Image();
...

image.Source = new BitmapImage(new Uri("pack://application:,,,/Images/Apple.png"));
</code>```

Body:
I've made a simple snake game in c# wpf forms.The problem is that Iv'e made the food as Ellipses and I want to change that to an image of an apple.
This is the food class where I specified the type/shape of the food :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Controls;

namespace WpfApp1
{
class Food
{
    public double x, y;
    public Ellipse e = new Ellipse();
    public Food(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public void setFoodPosition()
    {
        Random r = new Random();
        if (Settings.size != 0)
            e.Width = e.Height = Settings.g.Size;
        else
            e.Width = e.Height = 10;
        e.Stroke = Brushes.Black;
        e.Fill = new SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255), (byte)r.Next(255))); ;
        Canvas.SetLeft(e, x);
        Canvas.SetTop(e, y);
    }
  }
 }

does anyone have any idea how I do that?

Body:
If you have an image of an apple in an image file, you should add that file to your Visual Studio project (e.g. in a project folder named Images) and set its Build Action to Resource.

You would then load the image by a Resource File Pack URI, and use it with an ImageBrush as Fill Brush of a Rectangle:

private Rectangle rect = new Rectangle();
...

rect.Fill = new ImageBrush(
    new BitmapImage(new Uri("pack://application:,,,/Images/Apple.png")));

Or you use an Image element instead of a Rectangle:

private Image image = new Image();
...

image.Source = new BitmapImage(new Uri("pack://application:,,,/Images/Apple.png"));


问:
What is the application/utility of Foreign Key in MySQL?
Allow my to elaborate on the question with an example. I am writing from the
perspective that

(1) bytecodes should not be used to implement the logic already
implemented (hopefully more efficiently) in the database engine (e.g., if we
need to filter out 20 lines out of 500 coming out as the result of an SQL query,
we should be writing a better where clause), and that

(2) I have only a conceptual
understanding of foreign keys (e.g., they automatically create, manage and enforce
the constraints required to maintain data integrity across different tables).

Now, lets consider a simple schema with 4 tables and 15 columns in them
as follows (assume all columns are not null):

```<code>people
    pid bigint autoinc PK
    fname   varchar(32)
    lname   varchar(32)
    dob date
    sex char(1)
    addyID  bigint FK to address(aid)

relationship
    relof   bigint FK to people(pid)
    relto   bigint FK to people(pid)
    relis   tinyint

address
    aid bigint autoinc PK
    street  varchar(128)
    zipcode int FK to z2cs(zip)

z2cs
    zip int PK
    city    varchar(64)
    state   char(2)
</code>```

Expectations (Please answer True/False to the following 6)

It is possible to create the table relationship as above with foreign keys
pointing to different rows of the same table

Adding a row to relationship throws SQLException if either relof or relto
is missing in people

If we add a row to address, we do not need to check if the zipcode is there in z2cs -
missing zip throws an SQLException

Attempt to delete a row from address throws an exception if aid is used in people

Attempt to delete a row from people causes error if pid is used in relationship in
either of the columns relto or relof

An SQL statement exists that lets you find which columns in a table are foreign keys
and which table(column) do they refer to (I know "describe tablename" doesn't do it,
although I feel that it should)

If the answer to any of the above is false, can you please guide me to finding
what exactly is the contract for foreign keys in MySql. Thank you.

PS: If you answer True to [6], would you please share what is that statement.

Bonus question (unrelated to FK):

How would you write the create statement for the relationship table that satisfies the following constraints:

relof and relto cannot be the same

Combination of relof and relto is unique, i.e.,
if their is a row with [relof=584,relto=7823], you cannot insert another row with
either [relof=584,relto=7823] or [relof=7823,relto=584]

答:
1. It is possible to create the table relationship as above with foreign keys pointing to different rows of the same table

NO, a FK can only point to one row. But a row can be referenced by many other rows, like, an adress can be referenced by many people.

2. Adding a row to relationship throws SQLException if either relof or relto is missing in people

YES.

3. If we add a row to address, we do not need to check if the zipcode is there in z2cs - missing zip throws an SQLException

YES.

4. Attempt to delete a row from address throws an exception if aid is used in people

YES, if there is no Cascade Delete in the FK, which then automatically would delete the
entry in people instead of failing.

5. Attempt to delete a row from people causes error if pid is used in relationship in either of the columns relto or relof

YES, see 4.

6. An SQL statement exists that lets you find which columns in a table are foreign keys and which table(column) do they refer to (I know "describe tablename" doesn't do it, although I feel that it should)

AFAIK. There should be an information schema in MySQL where you can query the information from.

B1. relof and relto cannot be the same

Use a Trigger on update or insert to validate this. PostgreSQL knows CHECK constraints, which might ba also available in MySQL, but else a trigger is your choice.

B2. Combination of relof and relto is unique

A combined UNIQUE INDEX on both columns is your friend here.

ContentLicense: CC BY-SA 2.5

Body:
Allow my to elaborate on the question with an example. I am writing from the
perspective that

(1) bytecodes should not be used to implement the logic already
implemented (hopefully more efficiently) in the database engine (e.g., if we
need to filter out 20 lines out of 500 coming out as the result of an SQL query,
we should be writing a better where clause), and that

(2) I have only a conceptual
understanding of foreign keys (e.g., they automatically create, manage and enforce
the constraints required to maintain data integrity across different tables).

Now, lets consider a simple schema with 4 tables and 15 columns in them
as follows (assume all columns are not null):

people
    pid bigint autoinc PK
    fname   varchar(32)
    lname   varchar(32)
    dob date
    sex char(1)
    addyID  bigint FK to address(aid)

relationship
    relof   bigint FK to people(pid)
    relto   bigint FK to people(pid)
    relis   tinyint

address
    aid bigint autoinc PK
    street  varchar(128)
    zipcode int FK to z2cs(zip)

z2cs
    zip int PK
    city    varchar(64)
    state   char(2)

Expectations (Please answer True/False to the following 6)

It is possible to create the table relationship as above with foreign keys
pointing to different rows of the same table

Adding a row to relationship throws SQLException if either relof or relto
is missing in people

If we add a row to address, we do not need to check if the zipcode is there in z2cs -
missing zip throws an SQLException

Attempt to delete a row from address throws an exception if aid is used in people

Attempt to delete a row from people causes error if pid is used in relationship in
either of the columns relto or relof

An SQL statement exists that lets you find which columns in a table are foreign keys
and which table(column) do they refer to (I know "describe tablename" doesn't do it,
although I feel that it should)

If the answer to any of the above is false, can you please guide me to finding
what exactly is the contract for foreign keys in MySql. Thank you.

PS: If you answer True to [6], would you please share what is that statement.

Bonus question (unrelated to FK):

How would you write the create statement for the relationship table that satisfies the following constraints:

relof and relto cannot be the same

Combination of relof and relto is unique, i.e.,
if their is a row with [relof=584,relto=7823], you cannot insert another row with
either [relof=584,relto=7823] or [relof=7823,relto=584]


问:
How do you generate a function that warns about not enough arguments?
If you are dynamically generating functions with varying number of required arguments, how do you determine if the future number of supplied arguments to the function call are enough and/or how do you make sure your function warns for / about required, or missing number of arguments?

The anonymous function may have a structure body as simple as:

```<code>fucntion( x, y, z ) {
        /*test for the arguments supplied*/
    if( notEnoughArguments )
        /*exit the function and return a warning*/
        /*otherwise, say ...*/
     return x*y*x
    }
</code>```

The problem: you don't know beforehand how many arguments will a certain function require, and you're not sure how many arguments will be available/supplied at the time of the function call.

答: You can use arguments object inside the function. For e.g. arguments.length will provide number of arguments passed into the function. Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments for more details</p>

ContentLicense: CC BY-SA 4.0

Body:
If you are dynamically generating functions with varying number of required arguments, how do you determine if the future number of supplied arguments to the function call are enough and/or how do you make sure your function warns for / about required, or missing number of arguments?

The anonymous function may have a structure body as simple as:

fucntion( x, y, z ) {
        /*test for the arguments supplied*/
    if( notEnoughArguments )
        /*exit the function and return a warning*/
        /*otherwise, say ...*/
     return x*y*x
    }

The problem: you don't know beforehand how many arguments will a certain function require, and you're not sure how many arguments will be available/supplied at the time of the function call.


问:
python 3.6 sql database connection
I am trying to insert a row into my postgresql database with a table created from

```<code>    CREATE TABLE public.coinbase_btc_usd
(
  id bigserial primary key,
  price integer NOT NULL,
  buy integer NOT NULL,
  sell integer NOT NULL,
  "timestamp" timestamp with time zone
)
</code>```

However when my python 3.6 script runs and tries to add a row using psycopg2 like this it returns an error saying "no results to fetch" and nothing is added to my db.

```<code>        sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
                " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"

    print(sql_query)

    cur.execute(sql_query)
</code>```

I also printed the sql_query variable to see exactly what was getting attempted to execute and this was printed to the output

```<code>INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (16392.10, 16563.40, 16235.42, '2015-10-10 06:44:33.8672177')
</code>```

答:
change the

```<code>sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
            " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"
</code>```

to:

```<code>sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
            " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\') returning *"
</code>```

this should fix no results to fetch in my assumption.

If you see no row added, you most probably begin transaction and never commit it.

Title: python 3.6 sql database connection

Body:
I am trying to insert a row into my postgresql database with a table created from

    CREATE TABLE public.coinbase_btc_usd
(
  id bigserial primary key,
  price integer NOT NULL,
  buy integer NOT NULL,
  sell integer NOT NULL,
  "timestamp" timestamp with time zone
)

However when my python 3.6 script runs and tries to add a row using psycopg2 like this it returns an error saying "no results to fetch" and nothing is added to my db.

        sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
                " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"

    print(sql_query)

    cur.execute(sql_query)

I also printed the sql_query variable to see exactly what was getting attempted to execute and this was printed to the output

INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp) VALUES (16392.10, 16563.40, 16235.42, '2015-10-10 06:44:33.8672177')

Body:
change the

sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
            " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\')"

to:

sql_query = "INSERT INTO coinbase_btc_usd(price, buy, sell, timestamp)" \
            " VALUES (" + exchange_rate + ', ' + buy_rate + ', ' + sell_rate + ", \'2015-10-10 06:44:33.8672177\') returning *"

this should fix no results to fetch in my assumption.

If you see no row added, you most probably begin transaction and never commit it.


问:
How to apply an assumption to all nested tests in Junit5?
I have converted Junit4 suite to Junit5 nested classes:

```<code>class MadvocSuiteTest {
    @Nested
    class HelloActionTest extends HelloActionTestBase {}
    @Nested
    class SimpleTest extends SimpleTestBase {}
    ...
}
</code>```

I must skip the suite for Java9 (since MultiRelease-Jars are not working in the expanded mode).

How can I do that for the whole suite i.e. all nested classes, so not to add assumeTrue to every single test?

答:
Everytime you encounter functionality needed in more than a single JUnit Jupiter test class, think of the new Extension Model. In your case, the Conditional Test Execution extension point.

Here is an example of what you might want to do by Mike Kobit. Define your own extension DisabledOnJava9 like:

```<code>@ExtendWith(DisabledOnJava9Condition.class)
public @interface DisabledOnJava9 {}
</code>```

And the handler like his DisabledOnJava9Condition.java. Now you may use your DisabledOnJava9 annotation on any element you want to. This includes the entire test class or any nested class.

Find the source of all types by Mike here: https://github.com/mkobit/junit5-conditional-execution-extensions

Here is another example of implementing this extension point: https://blog.codefx.org/libraries/junit-5-conditions/

Body:
I have converted Junit4 suite to Junit5 nested classes:

class MadvocSuiteTest {
    @Nested
    class HelloActionTest extends HelloActionTestBase {}
    @Nested
    class SimpleTest extends SimpleTestBase {}
    ...
}

I must skip the suite for Java9 (since MultiRelease-Jars are not working in the expanded mode).

How can I do that for the whole suite i.e. all nested classes, so not to add assumeTrue to every single test?

Body:
Everytime you encounter functionality needed in more than a single JUnit Jupiter test class, think of the new Extension Model. In your case, the Conditional Test Execution extension point.

Here is an example of what you might want to do by Mike Kobit. Define your own extension DisabledOnJava9 like:

@ExtendWith(DisabledOnJava9Condition.class)
public @interface DisabledOnJava9 {}

And the handler like his DisabledOnJava9Condition.java. Now you may use your DisabledOnJava9 annotation on any element you want to. This includes the entire test class or any nested class.

Find the source of all types by Mike here: https://github.com/mkobit/junit5-conditional-execution-extensions

Here is another example of implementing this extension point: https://blog.codefx.org/libraries/junit-5-conditions/


问:
how to solve this error Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation:
I create a shopping cart using OOP PHP.When I return a single product information data from database through HTML form to perform edit operation,
I face this type of error

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\onlineShop\src\Product.php:100 Stack trace: #0 C:\xampp\htdocs\onlineShop\src\Product.php(100): PDO->query('SELECT * FROM t...') #1 C:\xampp\htdocs\onlineShop\views\Product\editProduct.php(18): App\Product->view() #2 {main} thrown in C:\xampp\htdocs\onlineShop\src\Product.php on line 100"

My editProduct file code below that

```<code><?php
  require_once("../../vendor/autoload.php");
  use App\Product;

  $product  = new Product();
  $product->setData($_GET);
  $allData = $product->view();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book Title Create Form</title>
</head>
<body>
<div class="container" align="center" id="body">
    <h3>Add Product Information</h3>
</div>
<div align="center" class="container">

    <form action="store.php" method="post" enctype="multipart/form-data" class="form-horizontal">
        <table class="table table-bordered table-responsive">
            <tr>
                <td><label class="control-label"> Product Name:</label></td>
                <td> <input type="text" class="form-control" name="productName" value=""<?php echo $allData->productName;?>""></td>
            </tr>

            <tr>
                <td><label class="control-label">Category :</label></td>
                <td><select name="categoryID" class="form-control">
                        <?php
                        $category = new App\Category();
                        $oneData= $category->index();
                        foreach($oneData as $singleData){

                            ?>
                            <option
                                <?php if($allData->categoryID==$singleData->categoryID){?>
                                      selected ="selected"
                           <?php } ?>
                                value="<?php echo $singleData->categoryID; ?>"><?php echo $singleData->categoryName;?></option>
                        <?php }?>
                    </select>
                </td>
            </tr>

            <tr>
                <td><label class="control-label">Brand :</label> </td>
                <td>
                    <select name="brandID" class="form-control">
                        <?php
                        $brand = new App\Brand();
                        $allData= $brand->index();
                        foreach($allData as $singleData){
                            ?>
                            <option
                                <?php if($allData->brandID==$singleData->brandID){?>
                                    selected ="selected"
                                <?php } ?> value="<?php echo $singleData->brandID;?>"><?php echo $singleData->brandName;?></option>
                        <?php } ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Description:</label></td>
                <td>
                    <textarea name="description" value="<?php echo $allData->description;?>" class="form-control" ></textarea>
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Price:</label></td>
                <td>
                    <input type="text" value="<?php echo $allData->price;?>" id="price" name="price" class="form-control">
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Upload Image :</label> </td>
                <td>
                    <input class="input-group" type="file"  value="<?php echo $allData->image;?>" id="image" name="image" >
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Product Type :</label></td>
                <td>
                    <select class="form-control" name="productType">
                        <option value="0">Featured</option>
                        <option value="1">General</option>
                    </select>
                </td>

            </tr>

        </table>

</div>
<div class="container">
    <input type="submit" value="EDIT" class="btn btn-success">
</div>

</form>
</body>
</html>
de here
</code>```

My view method below like that which is used for viewing single product information to perform edit operation.

```<code>                public function view()
            {

                $sql = "SELECT * FROM tbl_product WHERE productID=".$this->productID;
                $STH = $this->DBH->query($sql);
                $STH->setFetchMode(PDO::FETCH_OBJ);
                return $STH->fetch();
            }
</code>```

Pls  help me to provide solution this type of error.

答:
Please make sure that $this->productID is not coming as empty

update your function code like below and see:

```<code>public function view()
{

    if(!empty($this->productID)){
        $sql = "SELECT * FROM tbl_product WHERE productID=".$this->productID;
        $STH = $this->DBH->query($sql);
        $STH->setFetchMode(PDO::FETCH_OBJ);
        return $STH->fetch();
    }
        return [];
}
</code>```

Body:
I create a shopping cart using OOP PHP.When I return a single product information data from database through HTML form to perform edit operation,
I face this type of error

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\onlineShop\src\Product.php:100 Stack trace: #0 C:\xampp\htdocs\onlineShop\src\Product.php(100): PDO->query('SELECT * FROM t...') #1 C:\xampp\htdocs\onlineShop\views\Product\editProduct.php(18): App\Product->view() #2 {main} thrown in C:\xampp\htdocs\onlineShop\src\Product.php on line 100"

My editProduct file code below that

<?php
  require_once("../../vendor/autoload.php");
  use App\Product;

  $product  = new Product();
  $product->setData($_GET);
  $allData = $product->view();

?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Book Title Create Form</title>

Add Product Information

    <form action="store.php" method="post" enctype="multipart/form-data" class="form-horizontal">

                 Product Name:
                 <input type="text" class="form-control" name="productName" value=""<?php echo $allData->productName;?>"">

                Category :
                <select name="categoryID" class="form-control">
                        <?php
                        $category = new App\Category();
                        $oneData= $category->index();
                        foreach($oneData as $singleData){

                            ?>
                            <option
                                <?php if($allData->categoryID==$singleData->categoryID){?>
                                      selected ="selected"
                           <?php } ?>
                                value="<?php echo $singleData->categoryID; ?>"><?php echo $singleData->categoryName;?></option>
                        <?php }?>
                    </select>

                Brand :

                    <select name="brandID" class="form-control">
                        <?php
                        $brand = new App\Brand();
                        $allData= $brand->index();
                        foreach($allData as $singleData){
                            ?>
                            <option
                                <?php if($allData->brandID==$singleData->brandID){?>
                                    selected ="selected"
                                <?php } ?> value="<?php echo $singleData->brandID;?>"><?php echo $singleData->brandName;?></option>
                        <?php } ?>
                    </select>

                Description:

                    <textarea name="description" value="<?php echo $allData->description;?>" class="form-control" ></textarea>

                Price:

                    <input type="text" value="<?php echo $allData->price;?>" id="price" name="price" class="form-control">

                Upload Image :

                    <input class="input-group" type="file"  value="<?php echo $allData->image;?>" id="image" name="image" >

                Product Type :

                    <select class="form-control" name="productType">
                        <option value="0">Featured</option>
                        <option value="1">General</option>
                    </select>

    <input type="submit" value="EDIT" class="btn btn-success">

</form>

de here

My view method below like that which is used for viewing single product information to perform edit operation.

                public function view()
            {

                $sql = "SELECT * FROM tbl_product WHERE productID=".$this->productID;
                $STH = $this->DBH->query($sql);
                $STH->setFetchMode(PDO::FETCH_OBJ);
                return $STH->fetch();
            }

Pls  help me to provide solution this type of error.

Body:
Please make sure that $this->productID is not coming as empty

update your function code like below and see:

public function view()
{

    if(!empty($this->productID)){
        $sql = "SELECT * FROM tbl_product WHERE productID=".$this->productID;
        $STH = $this->DBH->query($sql);
        $STH->setFetchMode(PDO::FETCH_OBJ);
        return $STH->fetch();
    }
        return [];
}


答:
You can check the arguments length vs. the Function.length.

In functions...

The length property specifies the number of arguments expected by the
  function.

The arguments object is an array like object, that contains all arguments passed to the function.

function multi(x, y, z) {
  if(arguments.length < multi.length) {
    console.log('not enough arugments');
    return null;
  }

  return x * y * x
}

multi();

console.log(multi(1, 2, 3));```

Title: How do you generate a function that warns about not enough arguments?


问:
TFS 2017 missing process link
Our IT installed TFS 2017 (15.112.26307.0).  It's a clean installation.  It currently has few startup projects, just to see and explorer features.  But the projects are missing "Process" link under Project Template page, to configure Agile/Scrum/CMMI.  I don't see link for "Configure Features" either.  My account has Project Administrator and Project Collection Administrators privileges.  Ultimately we would like to explorer Agile process.  Any help appreciated.</p>

答:
The Process tab is something that Microsoft has been building for VSTS and which is likely to come to on-prem in the near future. But for now TFS still uses the old XML based work item templates which offer a higher level of customizability, but which are also much harder to maintain.

For specific guidance on using witadmin.exe check out:

TFS Process Template Customisation Guide

Practical guidance for Work Item Tracking (WIT) and Process Template customizations.

Title: TFS 2017 missing process link


问:
Compiling device drivers to the kernel
I'm trying to compile a device driver, but i get the following error,
and the same one for all following header

```<code>ddd@ddd:~/Desktop$ make
make -C /lib/modules/4.13.0-19-generic/build  M=/home/ddd/Desktop  modules
make[1]: Entering directory '/usr/src/linux-headers-4.13.0-19-generic'
  CC [M]  /home/ddd/Desktop/message_slot.o
/home/ddd/Desktop/message_slot.c:23:10: fatal error: stdio.h: No such file or directory
 #include <stdio.h>
          ^~~~~~~~~
compilation terminated.
scripts/Makefile.build:309: recipe for target '/home/ddd/Desktop/message_slot.o' failed
make[2]: *** [/home/ddd/Desktop/message_slot.o] Error 1
Makefile:1546: recipe for target '_module_/home/ddd/Desktop' failed
make[1]: *** [_module_/home/ddd/Desktop] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.13.0-19-generic'
Makefile:5: recipe for target 'all' failed
make: *** [all] Error 2
ddd@ddd:~/Desktop$
</code>```

I compiler the program using the following makefile:

```<code>obj-m := message_slot.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
    $(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
    $(MAKE) -C $(KDIR) M=$(PWD) clean
</code>```

The thing is, that by running the small .c code:

```<code>#include <stdio.h>
#include <stdli.h>

int main(){
  printf("test");
 }
</code>```

with the command

gcc test.c -o test

everything compiles.
I suspect it's something with the kernel headers, but i've downloaded all headers as specified. I'm running lubuntu 17.10

am i missing something?

Thanks a lot

答:
stdio.h is user space header file not kernel space, that's why your make fails.
In driver program why we are including all headers because bcz its not having main() function, Right ?

when you will do make, observe your makefile

```<code> obj-m := message_slot.o
 KDIR := /lib/modules/$(shell uname -r)/build
</code>```

that means you are compiling as a modules and your source code will be in /usr/src/linux-4(some version).

for e.g

```<code>   #include <linux/stat.h>
</code>```

not

```<code>#include <stat.h>
</code>```

and

```<code>xyz@xyz-PC:/usr/src/linux-4.1.39/include/linux$ ls -l stdio.h
        ls: cannot access stdio.h: No such file or directory
</code>```

In your driver program why are you including stdio.h because you are not going to use printf, instead printk() ?

Yes in application program you can include stdio.h because you compiling using gcc compiler as a file not as a module.

I hope it helps.

Title: Compiling device drivers to the kernel

Body:
I'm trying to compile a device driver, but i get the following error,
and the same one for all following header

ddd@ddd:~/Desktop$ make
make -C /lib/modules/4.13.0-19-generic/build  M=/home/ddd/Desktop  modules
make[1]: Entering directory '/usr/src/linux-headers-4.13.0-19-generic'
  CC [M]  /home/ddd/Desktop/message_slot.o
/home/ddd/Desktop/message_slot.c:23:10: fatal error: stdio.h: No such file or directory
 #include <stdio.h>
          ^~~~~~~~~
compilation terminated.
scripts/Makefile.build:309: recipe for target '/home/ddd/Desktop/message_slot.o' failed
make[2]: *** [/home/ddd/Desktop/message_slot.o] Error 1
Makefile:1546: recipe for target '_module_/home/ddd/Desktop' failed
make[1]: *** [_module_/home/ddd/Desktop] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.13.0-19-generic'
Makefile:5: recipe for target 'all' failed
make: *** [all] Error 2
ddd@ddd:~/Desktop$

I compiler the program using the following makefile:

obj-m := message_slot.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
    $(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
    $(MAKE) -C $(KDIR) M=$(PWD) clean

The thing is, that by running the small .c code:

#include <stdio.h>
#include <stdli.h>

int main(){
  printf("test");
 }

with the command

gcc test.c -o test

everything compiles.
I suspect it's something with the kernel headers, but i've downloaded all headers as specified. I'm running lubuntu 17.10

am i missing something?

Thanks a lot

Body:
stdio.h is user space header file not kernel space, that's why your make fails.
In driver program why we are including all headers because bcz its not having main() function, Right ?

when you will do make, observe your makefile

 obj-m := message_slot.o
 KDIR := /lib/modules/$(shell uname -r)/build

that means you are compiling as a modules and your source code will be in /usr/src/linux-4(some version).

for e.g

   #include <linux/stat.h>

not

#include <stat.h>

and

xyz@xyz-PC:/usr/src/linux-4.1.39/include/linux$ ls -l stdio.h
        ls: cannot access stdio.h: No such file or directory

In your driver program why are you including stdio.h because you are not going to use printf, instead printk() ?

Yes in application program you can include stdio.h because you compiling using gcc compiler as a file not as a module.

I hope it helps.


问:
Easy_install or pip with NTLM auth
In my working environment, internet access is managed by NTLM authentication and is associated with Windows user account, and easy_install or pip doesn't work:

```<code>C:\>easy_install django
install_dir D:\Python26\Lib\site-packages\
Searching for django
Reading http://pypi.python.org/simple/django/
Download error: timed out -- Some packages may not be found!
....

C:\>pip install django
Downloading/unpacking django
  Cannot fetch index base URL http://pypi.python.org/simple/
  Could not find any downloads that satisfy the requirement django
No distributions at all found for django
</code>```

Is it possible to get them working in such an environment?

答: Use NTLMAPS, and point pip to the local proxy.</p>

Title: Easy_install or pip with NTLM auth

Body:
In my working environment, internet access is managed by NTLM authentication and is associated with Windows user account, and easy_install or pip doesn't work:

C:\>easy_install django
install_dir D:\Python26\Lib\site-packages\
Searching for django
Reading http://pypi.python.org/simple/django/
Download error: timed out -- Some packages may not be found!
....

C:\>pip install django
Downloading/unpacking django
  Cannot fetch index base URL http://pypi.python.org/simple/
  Could not find any downloads that satisfy the requirement django
No distributions at all found for django

Is it possible to get them working in such an environment?


问:
best pattern design for my project
I create a solution in asp.net web form and database first entity and want to create web application at first but in the future, I need create web service for using in android app.

so I need a design pattern for my project that my web service project doesn't have a dependency on my web project.

I know probably should use n tier but I need someone explain it.

i need someone say which and why use pattern for compare

答:
I suggest for webservice part you make use of WebApi as its easy to create and later on you can use with you android mobile app also.

WEBAPI is helpuful for Rest implementation and you cna use it very easily.

your project structure needs to be like

Asp.NEt -- fornt end

in this you can make use of MVP(model-view-Prsenter) or MVC(model-view-controller)

Business layer consist of Business classes (Modle classes) and encapsulate you full business logic and business rules

Data Layer - here you make call to WebAPI functions which will do work of database interaction ...in WebAPI you can again implemnt three layer
or
You can create DataLayer library whih you can make use in WebProject as well as in you WebAPI project ...

Title: best pattern design for my project


问:
Call method from Main Activity into Fragment Adapter
How to call a method from my activity in to my fragment adapter? I use a RecyclerView on my fragment and there is intent inside this fragment adapter. I already make a method in my Main Activity but I'm unable to call it from my Fragment Adapter.

Method in Main Activity

```<code>public void showInterstitial() {
  if(interstitialAd != null && interstitialAd.isLoaded()) {
     interstitialAd.show();
     loadingIklan=true;
  }
}
</code>```

and I want put that method inside intent switch case on fragment adapter

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

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView homeTitle;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            ((MainActivity) getActivity()).showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }
    }

    public List<HomeData> homeList;

    public HomeAdapter(List<HomeData> homeList) {

        this.homeList = homeList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.homeTitle.setText(homeList.get(position).getHomeTitle());
    }

    @Override
    public int getItemCount() {
        return homeList.size();
    }
}
</code>```

my main fragment

```<code>public class Home extends Fragment {

    public Home() {
        // Required empty public constructor
    }

    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.home, container, false);

        recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        homeAdapter = new HomeAdapter(homeDataList());
        recyclerView.setAdapter(homeAdapter);

        return view;
    }
}
</code>```

anyone can help me with a right code? Thank you.

答:
interfacesample.java

```<code>public interface sample{
      function onclick();
}
</code>```

activity.java

```<code>class activity extends appcombatactivity implements sample{
         override onclick(){
//do whatever you want to do
}

}
</code>```

//adapter.java

```<code>switch (getAdapterPosition()) {
                            case 0:
                            //getActivity show red code//
                               (context as activity).onclick()

                                break;
                            default:
                                intent = new Intent(context, AllBlock.class);
                                break;
                        }
</code>```

something like that. Hope you able to understand. Let me know if have any doubt.

Body:
How to call a method from my activity in to my fragment adapter? I use a RecyclerView on my fragment and there is intent inside this fragment adapter. I already make a method in my Main Activity but I'm unable to call it from my Fragment Adapter.

Method in Main Activity

public void showInterstitial() {
  if(interstitialAd != null && interstitialAd.isLoaded()) {
     interstitialAd.show();
     loadingIklan=true;
  }
}

and I want put that method inside intent switch case on fragment adapter

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

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView homeTitle;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            ((MainActivity) getActivity()).showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }
    }

    public List<HomeData> homeList;

    public HomeAdapter(List<HomeData> homeList) {

        this.homeList = homeList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.homeTitle.setText(homeList.get(position).getHomeTitle());
    }

    @Override
    public int getItemCount() {
        return homeList.size();
    }
}

my main fragment

public class Home extends Fragment {

    public Home() {
        // Required empty public constructor
    }

    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.home, container, false);

        recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        homeAdapter = new HomeAdapter(homeDataList());
        recyclerView.setAdapter(homeAdapter);

        return view;
    }
}

anyone can help me with a right code? Thank you.

Body:
interfacesample.java

public interface sample{
      function onclick();
}

activity.java

class activity extends appcombatactivity implements sample{
         override onclick(){
//do whatever you want to do
}

}

//adapter.java

switch (getAdapterPosition()) {
                            case 0:
                            //getActivity show red code//
                               (context as activity).onclick()

                                break;
                            default:
                                intent = new Intent(context, AllBlock.class);
                                break;
                        }

something like that. Hope you able to understand. Let me know if have any doubt.


问:
Finding included or non-included points
I am writing for Python 3.5.2. I have a list named coordinate_list:

```<code>[
    ['x1', '120;40', '100;0;60;40'],
    ['x2', '200;50', '80;10;30;5'],
    ['x3', '150;15', '120;0;25;10'],
    ['x4', '240;60', '100;10;0;40'],
    ['x5', '260;45', '70;0;10;25'],
    ['x6', '225;15', '75;10;5;10'],
    ['x7', '273;20', '75;0;0;0'],
    ['x8', '221;5', '0;0;0;0'],
    ['x9', '345;20', '0;0;0;0'],
]
</code>```

Firstly, I want to explain the meaning of the list elements. Each row in the list identifies a point. The first element, like

"x1" , "x2" ," x3",...

is the name of the point. The next element is the point's coordinates, separated by ;. The final element is the point's range. For example, x1's coordinates are (120, 40). And it reaches to (120 + 100) on the east, (120 - 0) on the west, (40 + 60) on the north, and (40 - 40) on the south.

If any other point is in this range, I must put it in a dictionary or a list. For instance, x1's range is (220, 120, 100, 0) (east, west, north, south) so x1 includes x2 and x3.

How can I do that? I wrote something but it is very unpythonic. I created lots of list, and it is not readable. Also, I got stuck finding the included possible points.

答:
As timgeb mentions, storing your data in a class makes it easier to develop and maintain your code than trying to do everything with lists.

Here is a simple class structure that does the job.

```<code>data = [
    ['x1', '120;40', '100;0;60;40'],
    ['x2', '200;50', '80;10;30;5'],
    ['x3', '150;15', '120;0;25;10'],
    ['x4', '240;60', '100;10;0;40'],
    ['x5', '260;45', '70;0;10;25'],
    ['x6', '225;15', '75;10;5;10'],
    ['x7', '273;20', '75;0;0;0'],
    ['x8', '221;5', '0;0;0;0'],
    ['x9', '345;20', '0;0;0;0'],
]

class Point:
    def __init__(self, name, xy, extent):
        ''' Extract the point's coordinates and compute its bounds '''
        self.name = name
        self.x, self.y = [int(u) for u in xy.split(';')]
        east, west, north, south = [int(u) for u in extent.split(';')]
        self.east = self.x + east
        self.west = self.x - west
        self.north = self.y + north
        self.south = self.y - south

    def __repr__(self):
        ''' Create a simple string representation of the Point '''
        fmt = "('{name}', ({x}, {y}), ({east}, {west}, {north}, {south}))"
        return fmt.format(**self.__dict__)

    def includes(self, other):
        ''' Test if `other` is in the bounds of `self` '''
        return (self.west <= other.x <= self.east and
            self.south <= other.y <= self.north)

# Convert the original data to a list of Points
coords = [Point(*row) for row in data]
for p in coords:
    print(p)
print()

#Find which points p2 are in the bounds of each point p1
for p1 in coords:
    print(p1.name, [p2.name for p2 in coords if p2 != p1 and p1.includes(p2)])
</code>```

output

```<code>('x1', (120, 40), (220, 120, 100, 0))
('x2', (200, 50), (280, 190, 80, 45))
('x3', (150, 15), (270, 150, 40, 5))
('x4', (240, 60), (340, 230, 60, 20))
('x5', (260, 45), (330, 260, 55, 20))
('x6', (225, 15), (300, 215, 20, 5))
('x7', (273, 20), (348, 273, 20, 20))
('x8', (221, 5), (221, 221, 5, 5))
('x9', (345, 20), (345, 345, 20, 20))

x1 ['x2', 'x3']
x2 ['x4', 'x5']
x3 ['x6', 'x8']
x4 ['x5', 'x7']
x5 ['x7']
x6 ['x7', 'x8']
x7 ['x9']
x8 []
x9 []
</code>```

Title: Finding included or non-included points

Body:
I am writing for Python 3.5.2. I have a list named coordinate_list:

[
    ['x1', '120;40', '100;0;60;40'],
    ['x2', '200;50', '80;10;30;5'],
    ['x3', '150;15', '120;0;25;10'],
    ['x4', '240;60', '100;10;0;40'],
    ['x5', '260;45', '70;0;10;25'],
    ['x6', '225;15', '75;10;5;10'],
    ['x7', '273;20', '75;0;0;0'],
    ['x8', '221;5', '0;0;0;0'],
    ['x9', '345;20', '0;0;0;0'],
]

Firstly, I want to explain the meaning of the list elements. Each row in the list identifies a point. The first element, like

"x1" , "x2" ," x3",...

is the name of the point. The next element is the point's coordinates, separated by ;. The final element is the point's range. For example, x1's coordinates are (120, 40). And it reaches to (120 + 100) on the east, (120 - 0) on the west, (40 + 60) on the north, and (40 - 40) on the south.

If any other point is in this range, I must put it in a dictionary or a list. For instance, x1's range is (220, 120, 100, 0) (east, west, north, south) so x1 includes x2 and x3.

How can I do that? I wrote something but it is very unpythonic. I created lots of list, and it is not readable. Also, I got stuck finding the included possible points.

Body:
As timgeb mentions, storing your data in a class makes it easier to develop and maintain your code than trying to do everything with lists.

Here is a simple class structure that does the job.

data = [
    ['x1', '120;40', '100;0;60;40'],
    ['x2', '200;50', '80;10;30;5'],
    ['x3', '150;15', '120;0;25;10'],
    ['x4', '240;60', '100;10;0;40'],
    ['x5', '260;45', '70;0;10;25'],
    ['x6', '225;15', '75;10;5;10'],
    ['x7', '273;20', '75;0;0;0'],
    ['x8', '221;5', '0;0;0;0'],
    ['x9', '345;20', '0;0;0;0'],
]

class Point:
    def __init__(self, name, xy, extent):
        ''' Extract the point's coordinates and compute its bounds '''
        self.name = name
        self.x, self.y = [int(u) for u in xy.split(';')]
        east, west, north, south = [int(u) for u in extent.split(';')]
        self.east = self.x + east
        self.west = self.x - west
        self.north = self.y + north
        self.south = self.y - south

    def __repr__(self):
        ''' Create a simple string representation of the Point '''
        fmt = "('{name}', ({x}, {y}), ({east}, {west}, {north}, {south}))"
        return fmt.format(**self.__dict__)

    def includes(self, other):
        ''' Test if `other` is in the bounds of `self` '''
        return (self.west <= other.x <= self.east and
            self.south <= other.y <= self.north)

# Convert the original data to a list of Points
coords = [Point(*row) for row in data]
for p in coords:
    print(p)
print()

#Find which points p2 are in the bounds of each point p1
for p1 in coords:
    print(p1.name, [p2.name for p2 in coords if p2 != p1 and p1.includes(p2)])

output

('x1', (120, 40), (220, 120, 100, 0))
('x2', (200, 50), (280, 190, 80, 45))
('x3', (150, 15), (270, 150, 40, 5))
('x4', (240, 60), (340, 230, 60, 20))
('x5', (260, 45), (330, 260, 55, 20))
('x6', (225, 15), (300, 215, 20, 5))
('x7', (273, 20), (348, 273, 20, 20))
('x8', (221, 5), (221, 221, 5, 5))
('x9', (345, 20), (345, 345, 20, 20))

x1 ['x2', 'x3']
x2 ['x4', 'x5']
x3 ['x6', 'x8']
x4 ['x5', 'x7']
x5 ['x7']
x6 ['x7', 'x8']
x7 ['x9']
x8 []
x9 []


问:
How to display items from redux store in angular5 app?
I have an angular5 component that I am trying to hookup with a reduxstore, it looks like this:

```<code>import { Component } from '@angular/core';
import { NgRedux, select, DevToolsExtension } from '@angular-redux/store';
import { TodoActions } from './actions';
import { AppState, INITIAL_STATE, rootReducer } from './store';
import {Observable} from "rxjs/Observable";

@Component({
  selector: 'app-root',
  template: `
    <input type="text" #edit />
    <button (click)="actions.add({data:edit,action:'ADD'})">add</button>
    <p>The list is:</p>
    <ul>
      <li *ngFor="let item of (items | async)">
        {{item}}
      </li>
    </ul>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  @select() readonly items$: Observable<string[]>;

  constructor(
    ngRedux: NgRedux<AppState>,
    devTools: DevToolsExtension,
    private actions: TodoActions) {

    ngRedux.configureStore(
      rootReducer,
      INITIAL_STATE,
      null,
      devTools.isEnabled() ? [ devTools.enhancer() ] : []);
  }
}
</code>```

The issue is that I cannot display items in the list. Here is the rootreducer:

```<code>import {Action} from 'redux';
import {TodoActions} from './actions';

export interface AppState {
  items: string[];
}
export const INITIAL_STATE: AppState = {items: []};

export function rootReducer(state: AppState, action: Action): AppState {
  switch (action.type) {
    case TodoActions.ADD:
      var newstate = state;
      newstate.items.push(action.data.data.value);
      return newstate;
  }
  ;

default:
  return state;
}
}
</code>```

How can I display the items? it looks like the first item gets added to the state from the redux-console. Here is also a githublink

答:
This doesn't look quite right:

  var newstate = state;
  newstate.items.push(action.data.data.value);
  return newstate;
```

<p>You're not actually creating a new array or a copy: both <code>newstate</code> and <code>state</code> are the same array, so you're probably better off returning a new array shallow-cloned:</p>

<pre class="lang-ts prettyprint-override"><code>export function rootReducer(state: AppState, action): AppState {
  switch (action.type) {
    case TodoActions.ADD:
      return {
        ...state,
        items: [
          ...state.items,
          action.data.value
        ]
      }

    default:
      return state;
  }
}
</code>```

You might notice I've pulled the type specifier off action. I'm not sure it makes sense to specify Action as the type for action, in most sample code I've seen that passed untyped so:

export function rootReducer(state: AppState, action): AppState {
```

<p>This will avoid TS complaining about lack of <code>data</code> on type <code>Action</code>. Alternatively, you could define a custom action type for each reducer you write.</p>

<p>Once you get past that, I think the reason you're not seeing any items is because you name the array <code>items$</code> in the <code>@select</code> decorator. So:</p>

<pre class="lang-ts prettyprint-override"><code>@Component({
  selector: 'app-root',
  template: `
    <input type="text" #edit />
    <button (click)="actions.add({value:edit.value,action:'ADD'})">add</button>
    <p>The list is:</p>
    <ul>
      <li *ngFor="let item of (items$ | async)">
        {{item}}
      </li>
    </ul>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  @select() readonly items$: Observable<string[]>;
</code>```

works better. Note I tweaked the button definition a bit to avoid passing the entire input through, since you only need the value.

Body:
I have an angular5 component that I am trying to hookup with a reduxstore, it looks like this:

import { Component } from '@angular/core';
import { NgRedux, select, DevToolsExtension } from '@angular-redux/store';
import { TodoActions } from './actions';
import { AppState, INITIAL_STATE, rootReducer } from './store';
import {Observable} from "rxjs/Observable";

@Component({
  selector: 'app-root',
  template: `
    <input type="text" #edit />
    <button (click)="actions.add({data:edit,action:'ADD'})">add</button>

The list is:

        {{item}}

  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  @select() readonly items$: Observable<string[]>;

  constructor(
    ngRedux: NgRedux<AppState>,
    devTools: DevToolsExtension,
    private actions: TodoActions) {

    ngRedux.configureStore(
      rootReducer,
      INITIAL_STATE,
      null,
      devTools.isEnabled() ? [ devTools.enhancer() ] : []);
  }
}

The issue is that I cannot display items in the list. Here is the rootreducer:

import {Action} from 'redux';
import {TodoActions} from './actions';

export interface AppState {
  items: string[];
}
export const INITIAL_STATE: AppState = {items: []};

export function rootReducer(state: AppState, action: Action): AppState {
  switch (action.type) {
    case TodoActions.ADD:
      var newstate = state;
      newstate.items.push(action.data.data.value);
      return newstate;
  }
  ;

default:
  return state;
}
}

How can I display the items? it looks like the first item gets added to the state from the redux-console. Here is also a githublink

Body:
This doesn't look quite right:

  var newstate = state;
  newstate.items.push(action.data.data.value);
  return newstate;

You're not actually creating a new array or a copy: both newstate and state are the same array, so you're probably better off returning a new array shallow-cloned:

export function rootReducer(state: AppState, action): AppState {
  switch (action.type) {
    case TodoActions.ADD:
      return {
        ...state,
        items: [
          ...state.items,
          action.data.value
        ]
      }

    default:
      return state;
  }
}

You might notice I've pulled the type specifier off action. I'm not sure it makes sense to specify Action as the type for action, in most sample code I've seen that passed untyped so:

export function rootReducer(state: AppState, action): AppState {

This will avoid TS complaining about lack of data on type Action. Alternatively, you could define a custom action type for each reducer you write.

Once you get past that, I think the reason you're not seeing any items is because you name the array items$ in the @select decorator. So:

@Component({
  selector: 'app-root',
  template: `
    <input type="text" #edit />
    <button (click)="actions.add({value:edit.value,action:'ADD'})">add</button>
    <p>The list is:</p>
    <ul>
      <li *ngFor="let item of (items$ | async)">
        {{item}}
      </li>
    </ul>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  @select() readonly items$: Observable<string[]>;

works better. Note I tweaked the button definition a bit to avoid passing the entire input through, since you only need the value.


问:
Xamarin Carousel View - Binding not succesfull
I'm not sure but i spent already 1 day with this problem.

I try to bind a Collection to the Xamarin Forms Carousel.

XAML Code:

```<code><cv:CarouselView ItemsSource="{Binding MainSlider}"  x:Name="carousel"   >
       <cv:CarouselView.ItemTemplate>
           <DataTemplate>
                  <Label Text="{Binding Name}" />
           </DataTemplate>
       </cv:CarouselView.ItemTemplate>
   </cv:CarouselView>
</code>```

Xamarin Forms

```<code>public class SliderItem
     {
        public string ImageUrl { get; set; }
        public string Name { get; set; }
    }
</code>```

...

```<code>public ObservableCollection<SliderItem> MainSlider { get; set; }

...

 InitializeComponent();

        MainSlider = new ObservableCollection<SliderItem> {
            new SliderItem
            {
                ImageUrl = "1.jpg",
                Name = "Test 1"
             },
            new SliderItem
            {
                 ImageUrl = "2.jpg",
                Name="Test 2"
            }
        };

        this.BindingContext = this;
</code>```

The Label will keep empty and i cannot find the problem.

Anyone an idea?

答: Try to populate the list before  InitializeComponent()</p>

Body:
I'm not sure but i spent already 1 day with this problem.

I try to bind a Collection to the Xamarin Forms Carousel.

XAML Code:

<cv:CarouselView ItemsSource="{Binding MainSlider}"  x:Name="carousel"   >
       <cv:CarouselView.ItemTemplate>
           <DataTemplate>

           </DataTemplate>
       </cv:CarouselView.ItemTemplate>
   </cv:CarouselView>

Xamarin Forms

public class SliderItem
     {
        public string ImageUrl { get; set; }
        public string Name { get; set; }
    }

...

public ObservableCollection<SliderItem> MainSlider { get; set; }

...

 InitializeComponent();

        MainSlider = new ObservableCollection<SliderItem> {
            new SliderItem
            {
                ImageUrl = "1.jpg",
                Name = "Test 1"
             },
            new SliderItem
            {
                 ImageUrl = "2.jpg",
                Name="Test 2"
            }
        };

        this.BindingContext = this;

The Label will keep empty and i cannot find the problem.

Anyone an idea?


问:
Are dynamic exception specifications invalid in c++17?
Are dynamic exception specifications invalid in c++17? Like this</p>

```<code>void f() throw(int);
</code>```

答:
General C++ guidelines discourages to use of exception specifications with any version of C++ and new standard has removed this feature.

E.30: Don't use exception specifications

Reason

Exception specifications make error handling brittle, impose a
run-time cost, and have been removed from the C++ standard.

Example

```<code>int use(int arg)
    throw(X, Y)
{
    // ...
    auto x = f(arg);
    // ...
}
</code>```

If f() throws an exception different from X and Y the unexpected
handler is invoked, which by default terminates. That's OK, but say
that we have checked that this cannot happen and f is changed to
throw a new exception Z, we now have a crash on our hands unless we
change use() (and re-test everything). The snag is that f() may be
in a library we do not control and the new exception is not anything
that use() can do anything about or is in any way interested in. We
can change use() to pass Z through, but now use()'s callers
probably needs to be modified. This quickly becomes unmanageable.
Alternatively, we can add a try-catch to use() to map Z into
an acceptable exception. This too, quickly becomes unmanageable. Note
that changes to the set of exceptions often happens at the lowest
level of a system (e.g., because of changes to a network library or
some middleware), so changes "bubble up" through long call chains. In
a large code base, this could mean that nobody could update to a new
version of a library until the last user was modified. If use() is
part of a library, it may not be possible to update it because a
change could affect unknown clients.

The policy of letting exceptions propagate until they reach a function
that potentially can handle it has proven itself over the years.

Note

No. This would not be any better had exception specifications been
statically enforced. For example, see Stroustrup94.

Note

If no exception may be thrown, use
noexcept
or its equivalent throw().

Body:
Are dynamic exception specifications invalid in c++17? Like this

void f() throw(int);

Body:
General C++ guidelines discourages to use of exception specifications with any version of C++ and new standard has removed this feature.

E.30: Don't use exception specifications

Reason

Exception specifications make error handling brittle, impose a
run-time cost, and have been removed from the C++ standard.

Example

int use(int arg)
    throw(X, Y)
{
    // ...
    auto x = f(arg);
    // ...
}

If f() throws an exception different from X and Y the unexpected
handler is invoked, which by default terminates. That's OK, but say
that we have checked that this cannot happen and f is changed to
throw a new exception Z, we now have a crash on our hands unless we
change use() (and re-test everything). The snag is that f() may be
in a library we do not control and the new exception is not anything
that use() can do anything about or is in any way interested in. We
can change use() to pass Z through, but now use()'s callers
probably needs to be modified. This quickly becomes unmanageable.
Alternatively, we can add a try-catch to use() to map Z into
an acceptable exception. This too, quickly becomes unmanageable. Note
that changes to the set of exceptions often happens at the lowest
level of a system (e.g., because of changes to a network library or
some middleware), so changes "bubble up" through long call chains. In
a large code base, this could mean that nobody could update to a new
version of a library until the last user was modified. If use() is
part of a library, it may not be possible to update it because a
change could affect unknown clients.

The policy of letting exceptions propagate until they reach a function
that potentially can handle it has proven itself over the years.

Note

No. This would not be any better had exception specifications been
statically enforced. For example, see Stroustrup94.

Note

If no exception may be thrown, use
noexcept
or its equivalent throw().


问:
Woocommerce - rename product tab according to the product category selected
I was hoping to rename the default product DESCRIPTION TAB on single product page to a different name according to the product category selected.

I was initially coming out of the following WC function to rename the default description tab:

```<code>add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {

    $tabs['description']['title'] = __( 'More Information' );   // Rename the description tab

    return $tabs;

}
</code>```

Now what I would like to achieve is that if the product is assigned to category "Books", then the name of the description tab would change to "About this book".
Then If the product is assigned to category "Videos", then the tab would change to "About this video" and if the product is assigned to any other category, the tab name would change to "More Information"

I tried to amend the code and this is what I came up with:

```<code>add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {

    global $product, $woocommerce;

    if ( is_product_category() ) {

        if ( is_product_category( 'books' ) ) {
           $tabs['description']['title'] = __( 'About this book' );
        } elseif ( is_product_category( 'videos' ) ) {
           $tabs['description']['title'] = __( 'About this video' );
        } else {
           $tabs['description']['title'] = __( 'More Information' );
        }
    }

    return $tabs;
}
</code>```

But unfortunately it doesn't seem to be working as the tab name is still "Description"

What am I doing wrong?

答:
Change:

```<code> is_product_category( 'books' ) to has_term( 'books', 'product_cat' )
 is_product_category( 'videos' ) to has_term( 'videos', 'product_cat' )
</code>```

, and it should work.

Function is_product_category returns true only when viewing a product category page. But you are on single product page, that's why it returns FALSE.

Body:
I was hoping to rename the default product DESCRIPTION TAB on single product page to a different name according to the product category selected.

I was initially coming out of the following WC function to rename the default description tab:

add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {

    $tabs['description']['title'] = __( 'More Information' );   // Rename the description tab

    return $tabs;

}

Now what I would like to achieve is that if the product is assigned to category "Books", then the name of the description tab would change to "About this book".
Then If the product is assigned to category "Videos", then the tab would change to "About this video" and if the product is assigned to any other category, the tab name would change to "More Information"

I tried to amend the code and this is what I came up with:

add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {

    global $product, $woocommerce;

    if ( is_product_category() ) {

        if ( is_product_category( 'books' ) ) {
           $tabs['description']['title'] = __( 'About this book' );
        } elseif ( is_product_category( 'videos' ) ) {
           $tabs['description']['title'] = __( 'About this video' );
        } else {
           $tabs['description']['title'] = __( 'More Information' );
        }
    }

    return $tabs;
}

But unfortunately it doesn't seem to be working as the tab name is still "Description"

What am I doing wrong?

Body:
Change:

 is_product_category( 'books' ) to has_term( 'books', 'product_cat' )
 is_product_category( 'videos' ) to has_term( 'videos', 'product_cat' )

, and it should work.

Function is_product_category returns true only when viewing a product category page. But you are on single product page, that's why it returns FALSE.


问:
c# fetching database into SQL Server datatable
I have a problem with this code... I don't have the slightest clue for what is happening...

When I run this code in Visual Studio, I get an error saying:

System.InvalidCastException: 'Object cannot be cast from DBNull to other types.'

And here's the code:

```<code>conn.Open();

SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);

SqlDataAdapter da = new SqlDataAdapter("Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd", conn);

DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow DR in dt.Rows)
{
    int date;
    date = Convert.ToInt32(DR["timepassedd"]);

    if (date > 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='"+comboBox1.Text+"'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'",conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You Returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
    else if (date <= 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='" + comboBox1.Text + "'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
}

conn.Close();
</code>```

Thanks in advance

答:
Run code below the answer will be obvious :</p>

```<code>                string sql1 = "update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'";
                Console.WriteLine(sql1);
                Console.ReadLine();
                SqlCommand com = new SqlCommand(sql1, conn);
                string sql2 = "Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd"
                Console.ReadLine();
                SqlDataAdapter da = new SqlDataAdapter(sql2, conn);
</code>```

Body:
I have a problem with this code... I don't have the slightest clue for what is happening...

When I run this code in Visual Studio, I get an error saying:

System.InvalidCastException: 'Object cannot be cast from DBNull to other types.'

And here's the code:

conn.Open();

SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);

SqlDataAdapter da = new SqlDataAdapter("Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd", conn);

DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow DR in dt.Rows)
{
    int date;
    date = Convert.ToInt32(DR["timepassedd"]);

    if (date > 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='"+comboBox1.Text+"'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'",conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You Returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
    else if (date <= 0)
    {
        com = new SqlCommand("DELETE lend WHERE client_name ='" + comboBox1.Text + "'" +
                             "UPDATE book_list set book_stock = book_stock  1 WHERE book_name ='" + comboBox1.Text + "'", conn);
        com.ExecuteNonQuery();

        MessageBox.Show("You returned the book " + date + " Days Late!" +
                            "please pay the fee to the front desk");

        UserPanel u = new UserPanel();
        u.Show();

        this.Hide();
    }
}

conn.Close();

Thanks in advance

Body:
Run code below the answer will be obvious :

                string sql1 = "update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'";
                Console.WriteLine(sql1);
                Console.ReadLine();
                SqlCommand com = new SqlCommand(sql1, conn);
                string sql2 = "Declare @startdate smalldatetime declare @enddate smalldatetime set @startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set @enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, @startdate+2, @enddate)as timepassedd"
                Console.ReadLine();
                SqlDataAdapter da = new SqlDataAdapter(sql2, conn);


问:
php reference versus value
```<code>  class Test {
      private $arr;
      function __construct() {
          $this->arr = array('test');
      }

      function getArr() {
          return $this->arr;
      }
  }
  $a = new Test();
  $b = $a->getArr();
  $b[0][0] = 'a';
  $s = $a->getArr();
  echo $s[0]
</code>```

Why does this echo test instead of aest? Does PHP copy the array and the contents of the array when returning it? How do I get an array in which I can change the strings and have it reflected in the object?

答:
By returning and assigning by reference:

```<code>class Test {
    //...
    function &getArr() {
        return $this->arr;
    }
}
$a = new Test();
$b =& $a->getArr();
$b[0][0] = 'a';
$s = $a->getArr();
echo $s[0];
</code>```

Does PHP copy the array and the contents of the array when returning it?

From the point of view of the programmer, it works as if returning would copy the value, except when returning by reference. In terms of implementation, there are optimizations that avoid this happens, as long as it has no impact in the behavior of the script.

Title: php reference versus value

Body:
  class Test {
      private $arr;
      function __construct() {
          $this->arr = array('test');
      }

      function getArr() {
          return $this->arr;
      }
  }
  $a = new Test();
  $b = $a->getArr();
  $b[0][0] = 'a';
  $s = $a->getArr();
  echo $s[0]

Why does this echo test instead of aest? Does PHP copy the array and the contents of the array when returning it? How do I get an array in which I can change the strings and have it reflected in the object?

Body:
By returning and assigning by reference:

class Test {
    //...
    function &getArr() {
        return $this->arr;
    }
}
$a = new Test();
$b =& $a->getArr();
$b[0][0] = 'a';
$s = $a->getArr();
echo $s[0];

Does PHP copy the array and the contents of the array when returning it?

From the point of view of the programmer, it works as if returning would copy the value, except when returning by reference. In terms of implementation, there are optimizations that avoid this happens, as long as it has no impact in the behavior of the script.