问:
React - Redux App: "Invalid attempt to spread non-iterable instance" Issue

At the beginning, that sample app was working properly. I could see
  data that I inputted over browser page and database. At now, I can see
  the data only via the database, the browser doesn't show data and getting this
  error additionally: "Invalid attempt to spread non-iterable
  instance".

There is the sample code :

projectActions.js

```<code>import {FETCH_BOOK, CREATE_BOOK, DELETE_BOOK} from '../actions/projectTypes';
import axios from 'axios';

const apiUrl = 'http://api/books';

export const createBookSuccess =  (data) => {
  return {
    type: CREATE_BOOK,
    payload: {
      _id: data._id,
      author: data.author,
      publication: data.publication,
      publisher: data.publisher
    }
  }
};

export const deleteBookSuccess = _id => {
  return {
    type: DELETE_BOOK,
    payload: {
      _id
    }
  }
};

export const fetchBook = (books) => {
  return {
    type: FETCH_BOOK,
    books
  }
};

export const createBook = ({ author, publication, publisher }) => {
  return (dispatch) => {
    return axios.post(`${apiUrl}`, {author, publication, publisher})
      .then(response => {
        dispatch(createBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const deleteBook = _id => {
  return (dispatch) => {
    return axios.delete(`${apiUrl}/${_id}`)
      .then(response => {
        dispatch(deleteBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const fetchAllBooks = () => {
  return (dispatch) => {
    return axios.get(apiUrl)
      .then(response => {
        dispatch(fetchBook(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};
</code>```

projectReducer.js

```<code>import {CREATE_BOOK, DELETE_BOOK, FETCH_BOOK} from '../actions/projectTypes';

const projectReducer = (state = [], action) => {
  switch (action.types) {
    case CREATE_BOOK:
      return [...state, action.payload];
    case DELETE_BOOK:
      let afterDelete = state.filter(book => {
        return book._id !== action.payload._id
      });
      return {
        ...state,
        state: afterDelete
      }
    case FETCH_BOOK:
      return action.books;
    default:
      return state;
  }
}

export default projectReducer;
</code>```

rootReducer.js

```<code>import books from './projectReducer';
import {combineReducers} from 'redux';

const rootReducer = combineReducers({
    books: books
});

export default rootReducer;
</code>```

BookListElement.js

```<code>import React from 'react';
import {connect} from 'react-redux';
import BookList from '../components/bookList';
import {deleteBook} from '../store/actions/projectActions';

const BookListElement= ({books, deleteBook}) => {
  if(!books.length) {
    return (
      <div>
        No Books
      </div>
    )
  }
  return (
    <div>
      {books.map(book => {
        return (
          <BookList book={book} deleteBook={deleteBook} key={book._id} />
        );
      })}
    </div>
  );
}

const mapStateToProps = state => {
  return {
    books: state.books
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deleteBook: _id => {
      dispatch(deleteBook(_id));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement);
</code>```

bookList.js

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

const styles = {
  borderBottom: '2px solid #eee',
  background: '#fafafa',
  margin: '.75rem auto',
  padding: '.6rem 1rem',
  maxWidth: '500px',
  borderRadius: '7px'
};

const BookList =  ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  return (
    <div style={styles} key={_id}>
      <h2>{author}</h2>
      <p>{publication}</p>
      <p>{publisher}</p>
      <button className="btn waves-effect waves-light" type="submit" name="action" onClick={() => {deleteBook(_id)}}>
        <i className="large material-icons">delete_forever</i>
      </button>
    </div>
  );
};

export default BookList;
</code>```

bookCreate.js

```<code>import React, {Component} from 'react';

class BookCreate extends Component {
  state= {
    author: '',
    publication: '',
    publisher: ''
  }

  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.createBook(this.state)
  }

  render() {
    return (
      <div className="container">
        <form onSubmit={this.handleSubmit} className="white" autoComplete="off">
          <h5 className="grey-text text-darken-3">Create New Book</h5>
          <div className="input-field">
            <label htmlFor="author">Author</label>
            <input type="text" id="author" onChange={this.handleChange}/>
          </div>

          <div className="input-field">
            <label htmlFor="publication">Publication</label>
            <input type="text" id="publication" onChange={this.handleChange}/>
          </div>

          <div className="input-field">
            <label htmlFor="publisher">Publisher</label>
            <input type="text" id="publisher" onChange={this.handleChange}/>
          </div>

          <div className="input-field">
            <button className="btn pink lighten-1 z-depth-0">Create</button>
          </div>
        </form>
      </div>
    )
  }
}

export default BookCreate;
</code>```

I checked the code a few times and read an older post about this issue
  but I didn't find any solution as a junior. That would be great if you
  say what did I miss.

EDIT: Added view.js file as bookList.js .

答:
I think you should return your fetch response to reducer state and you can filter your deleted books in one line. maybe this would work.

//projectReducer.js
import {CREATE_BOOK, DELETE_BOOK, FETCH_BOOK} from '../actions/projectTypes';

const projectReducer = (state = [], action) => {
  switch (action.types) {
    case CREATE_BOOK:
      return [...state, action.payload];
    case DELETE_BOOK:
      return state = state.filter(book => book._id !== action.payload._id)
    case FETCH_BOOK:
      return state = action.books;
    default:
      return state;
  }
}

export default projectReducer;
```

Body:
At the beginning, that sample app was working properly. I could see
  data that I inputted over browser page and database. At now, I can see
  the data only via the database, the browser doesn't show data and getting this
  error additionally: "Invalid attempt to spread non-iterable
  instance".

There is the sample code :

projectActions.js

import {FETCH_BOOK, CREATE_BOOK, DELETE_BOOK} from '../actions/projectTypes';
import axios from 'axios';

const apiUrl = 'http://api/books';

export const createBookSuccess =  (data) => {
  return {
    type: CREATE_BOOK,
    payload: {
      _id: data._id,
      author: data.author,
      publication: data.publication,
      publisher: data.publisher
    }
  }
};

export const deleteBookSuccess = _id => {
  return {
    type: DELETE_BOOK,
    payload: {
      _id
    }
  }
};

export const fetchBook = (books) => {
  return {
    type: FETCH_BOOK,
    books
  }
};

export const createBook = ({ author, publication, publisher }) => {
  return (dispatch) => {
    return axios.post(`${apiUrl}`, {author, publication, publisher})
      .then(response => {
        dispatch(createBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const deleteBook = _id => {
  return (dispatch) => {
    return axios.delete(`${apiUrl}/${_id}`)
      .then(response => {
        dispatch(deleteBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const fetchAllBooks = () => {
  return (dispatch) => {
    return axios.get(apiUrl)
      .then(response => {
        dispatch(fetchBook(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

projectReducer.js

import {CREATE_BOOK, DELETE_BOOK, FETCH_BOOK} from '../actions/projectTypes';

const projectReducer = (state = [], action) => {
  switch (action.types) {
    case CREATE_BOOK:
      return [...state, action.payload];
    case DELETE_BOOK:
      let afterDelete = state.filter(book => {
        return book._id !== action.payload._id
      });
      return {
        ...state,
        state: afterDelete
      }
    case FETCH_BOOK:
      return action.books;
    default:
      return state;
  }
}

export default projectReducer;

rootReducer.js

import books from './projectReducer';
import {combineReducers} from 'redux';

const rootReducer = combineReducers({
    books: books
});

export default rootReducer;

BookListElement.js

import React from 'react';
import {connect} from 'react-redux';
import BookList from '../components/bookList';
import {deleteBook} from '../store/actions/projectActions';

const BookListElement= ({books, deleteBook}) => {
  if(!books.length) {
    return (

        No Books

    )
  }
  return (

      {books.map(book => {
        return (
          <BookList book={book} deleteBook={deleteBook} key={book._id} />
        );
      })}

  );
}

const mapStateToProps = state => {
  return {
    books: state.books
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deleteBook: _id => {
      dispatch(deleteBook(_id));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement);

bookList.js

import React from 'react';

const styles = {
  borderBottom: '2px solid #eee',
  background: '#fafafa',
  margin: '.75rem auto',
  padding: '.6rem 1rem',
  maxWidth: '500px',
  borderRadius: '7px'
};

const BookList =  ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  return (

{author}

{publication}

{publisher}

      <button className="btn waves-effect waves-light" type="submit" name="action" onClick={() => {deleteBook(_id)}}>
        delete_forever
      </button>

  );
};

export default BookList;

bookCreate.js

import React, {Component} from 'react';

class BookCreate extends Component {
  state= {
    author: '',
    publication: '',
    publisher: ''
  }

  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.createBook(this.state)
  }

  render() {
    return (

        <form onSubmit={this.handleSubmit} className="white" autoComplete="off">

Create New Book

            Author
            <input type="text" id="author" onChange={this.handleChange}/>

            Publication
            <input type="text" id="publication" onChange={this.handleChange}/>

            Publisher
            <input type="text" id="publisher" onChange={this.handleChange}/>

            <button className="btn pink lighten-1 z-depth-0">Create</button>

        </form>

    )
  }
}

export default BookCreate;

I checked the code a few times and read an older post about this issue
  but I didn't find any solution as a junior. That would be great if you
  say what did I miss.

EDIT: Added view.js file as bookList.js .


来源: stackexchange

问:
product/1 instead of product.php?id=1
This is not really a problem but a question.

I have this file that shows the product information when you go to URL/product.php?id=1 How can I make it show the same when going to URL/product/1. id is a variable that changes.

Sorry, I have no clue how htaccess works, and how to rewrite..

答:
You need to internally rewrite the request from /product/1 to /product.php?id=1. On Apache, you need to do this with mod_rewrite. In .htaccess this would take the form of:

```<code># We must enable the rewrite engine before using mod_rewrite
RewriteEngine On

# Internally rewrite a request from "/product/1"
RewriteRule ^product/1$ /product.php?id=1 [L]
</code>```

Note that this literally rewrites from /product/1 to /product.php?id=1 (as stated in the question) nothing else. And is internal to the server - the URL in the browser's address bar does not change.

The arguments to Apache directives are space separated:

^product/1$ - The first argument (pattern) to the RewriteRule directive is a regular expression (regex) that matches against the URL-path (only) of the request. Note that in .htaccess this URL-path does not start with a slash, so the URL-path that is matched is product/1 not /product/1, even though you are requesting example.com/product/1.

/product.php?id=1 - The second argument (substitution) is the string that is substituted for the requested URL. ie. the target URL. This is an "ordinary" string, not a regex.

[L] - The third argument (flags) are additional options that can change how the RewriteRule directive behaves. The argument must be surrounded in square brackets and contains a comma separated list of flags. The L (or last) flag signifies this is the last directive in this round of processing. If this is the last directive in the file then the L flag is not required. If you omit the L flag then processing continues and the request could be further rewritten (if you have more directives). Another common flag is the R (or redirect) flag. This changes the internal rewrite into an external redirect (which sends a Location HTTP response header back to the client and results in the browser being externally redirected to the new URL - the URL in the browser's address bar changes).

Additional Note: In this instance, since you are requesting "product" and a file with that basename exists (in fact, that is the file you are rewriting to) you also need to make sure that MultiViews is disabled (it is by default). If MultiViews is enabled (some shared hosts enable this for some reason) then mod_negotiation will trigger an internal subrequest for product.php before your mod_rewrite directive gets to rewrite the request and this will be missing the id URL parameter. (Numerous rewriting issues on SO are caused by conflicts with MultiViews.) To disable MultiViews, you can include this at the top of your .htaccess file:

```<code>Options -MultiViews
</code>```

More generic

To make this more generic and rewrite /product/<number> to /product.php?id=<number>, where <number> is 1 or more digits, you can modify the regex (first argument) and create a backreference that you use in the substitution string (second argument). For example:

```<code># Internally rewrite a request from "/product/<number>"
RewriteRule ^product/(\d+)$ /product.php?id=$1 [L]
</code>```

This would rewrite a URL of the form /product/123 to /product.php?id=123. Where 123 is 1 or more digits, denoted by the regex subpattern \d+. (\d is a shorthand character class and is the same as the marginally more verbose [0-9]. + is a quantifier that indicates 1 or more of the preceding pattern - in this case digits.) By surrounding this in parentheses, we create a capturing group, which we can refer to in the substitution. That's what the $1 backreference is. $1 is essentially a variable that contains whatever value the regex captured.

In summary:

```<code># Disable MultiViews
Options -MultiViews

# We must enable the rewrite engine before using mod_rewrite
RewriteEngine On

# Internally rewrite a request to "/product/<number>"
RewriteRule ^product/(\d+)$ /product.php?id=$1 [L]
</code>```

Reference:

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule

ContentLicense: CC BY-SA 4.0

Title: product/1 instead of product.php?id=1

Body:
You need to internally rewrite the request from /product/1 to /product.php?id=1. On Apache, you need to do this with mod_rewrite. In .htaccess this would take the form of:

# We must enable the rewrite engine before using mod_rewrite
RewriteEngine On

# Internally rewrite a request from "/product/1"
RewriteRule ^product/1$ /product.php?id=1 [L]

Note that this literally rewrites from /product/1 to /product.php?id=1 (as stated in the question) nothing else. And is internal to the server - the URL in the browser's address bar does not change.

The arguments to Apache directives are space separated:

^product/1$ - The first argument (pattern) to the RewriteRule directive is a regular expression (regex) that matches against the URL-path (only) of the request. Note that in .htaccess this URL-path does not start with a slash, so the URL-path that is matched is product/1 not /product/1, even though you are requesting example.com/product/1.

/product.php?id=1 - The second argument (substitution) is the string that is substituted for the requested URL. ie. the target URL. This is an "ordinary" string, not a regex.

[L] - The third argument (flags) are additional options that can change how the RewriteRule directive behaves. The argument must be surrounded in square brackets and contains a comma separated list of flags. The L (or last) flag signifies this is the last directive in this round of processing. If this is the last directive in the file then the L flag is not required. If you omit the L flag then processing continues and the request could be further rewritten (if you have more directives). Another common flag is the R (or redirect) flag. This changes the internal rewrite into an external redirect (which sends a Location HTTP response header back to the client and results in the browser being externally redirected to the new URL - the URL in the browser's address bar changes).

Additional Note: In this instance, since you are requesting "product" and a file with that basename exists (in fact, that is the file you are rewriting to) you also need to make sure that MultiViews is disabled (it is by default). If MultiViews is enabled (some shared hosts enable this for some reason) then mod_negotiation will trigger an internal subrequest for product.php before your mod_rewrite directive gets to rewrite the request and this will be missing the id URL parameter. (Numerous rewriting issues on SO are caused by conflicts with MultiViews.) To disable MultiViews, you can include this at the top of your .htaccess file:

Options -MultiViews

More generic

To make this more generic and rewrite /product/<number> to /product.php?id=<number>, where <number> is 1 or more digits, you can modify the regex (first argument) and create a backreference that you use in the substitution string (second argument). For example:

# Internally rewrite a request from "/product/<number>"
RewriteRule ^product/(\d+)$ /product.php?id=$1 [L]

This would rewrite a URL of the form /product/123 to /product.php?id=123. Where 123 is 1 or more digits, denoted by the regex subpattern \d+. (\d is a shorthand character class and is the same as the marginally more verbose [0-9]. + is a quantifier that indicates 1 or more of the preceding pattern - in this case digits.) By surrounding this in parentheses, we create a capturing group, which we can refer to in the substitution. That's what the $1 backreference is. $1 is essentially a variable that contains whatever value the regex captured.

In summary:

# Disable MultiViews
Options -MultiViews

# We must enable the rewrite engine before using mod_rewrite
RewriteEngine On

# Internally rewrite a request to "/product/<number>"
RewriteRule ^product/(\d+)$ /product.php?id=$1 [L]

Reference:

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule


问:
Filter data using group by
I have this data

I want to filter this table to get another table contain quantity of each item which driver have.
I tried to use group by driver_id but it count all items with the driver. I don't need that I need quantity of each item with the driver.
I need a result table like this

答:
You need to GROUP BY item_id and then by driver_id
and COUNT function to count the number of records for each group.

Something like this should work:

```<code>SELECT item_id,COUNT(*) AS quantity,driver_id FROM `table`
GROUP BY item_id,driver_id
</code>```

Title: Filter data using group by

Body:
You need to GROUP BY item_id and then by driver_id
and COUNT function to count the number of records for each group.

Something like this should work:

SELECT item_id,COUNT(*) AS quantity,driver_id FROM `table`
GROUP BY item_id,driver_id


问:
Passing self and returning it in a closure without retain cycle
I'm tired of using the [weak self] capture in closures, so I would like to pass self and return that in the closure like this:

```<code>alertManager.askToConfirm(from: self) { vc, confirmed in
        if confirmed {
            vc.model.confirm()
        } else {
            vc.model.reject()
        }
    }
</code>```

inside AlertManager my code would be like this:

```<code>func askToConfirm<T>(from vc: T, completion: @escaping (T) -> ()) {
    let invitation = pageItemFactory.createConfirmationPageItem() { [weak self] accepted in
        self?.dismissAlert()
        completion(vc, accepted)
    }
    present(invitation)
}
</code>```

Will this create a retain cycle?

答:
No, from what I can see, this will not result in a retain cycle.

For example, this will result in a retain cycle. When myFunction executes, the Foo instance will hold a strong reference to the completion block. In turn, the completion block holds a strong reference to the Foo instance. This will a retain cycle, and in this case you need to add a capture list.

```<code>class Foo<T> {
  var completion: (T) -> ()

  func myFunction(_ vc: T, completion: @escaping (T) -> ()) {
    self.completion = completion // This will create a retain cycle
    completion(vc)
  }

  func doSomething() {
    myFunction(self) { vc in
      print(vc)
    }
  }
}
</code>```

Body:
I'm tired of using the [weak self] capture in closures, so I would like to pass self and return that in the closure like this:

alertManager.askToConfirm(from: self) { vc, confirmed in
        if confirmed {
            vc.model.confirm()
        } else {
            vc.model.reject()
        }
    }

inside AlertManager my code would be like this:

func askToConfirm<T>(from vc: T, completion: @escaping (T) -> ()) {
    let invitation = pageItemFactory.createConfirmationPageItem() { [weak self] accepted in
        self?.dismissAlert()
        completion(vc, accepted)
    }
    present(invitation)
}

Will this create a retain cycle?

Body:
No, from what I can see, this will not result in a retain cycle.

For example, this will result in a retain cycle. When myFunction executes, the Foo instance will hold a strong reference to the completion block. In turn, the completion block holds a strong reference to the Foo instance. This will a retain cycle, and in this case you need to add a capture list.

class Foo<T> {
  var completion: (T) -> ()

  func myFunction(_ vc: T, completion: @escaping (T) -> ()) {
    self.completion = completion // This will create a retain cycle
    completion(vc)
  }

  func doSomething() {
    myFunction(self) { vc in
      print(vc)
    }
  }
}


问:
DNS: .ly domain - in google cloud dns
my company has acquired a .ly domain (managed by the Libyan government), which we'd like to use for our brand. In order to manage this domain there's a very basic management panel allowing me to insert some "DNS Servers". Together with a cryptic message about when it's required to not only use domain names for these servers but also specify their IP Address. Due to bad translation, I can't make any sense of that.

Ultimately, I would like to manage the DNS configuration via google cloud DNS, where I've created a DNS A record for the domain pointing to our website's IP Address.

This looks like this:

(sorry for the german, can't make google cloud console translate to english; Type is "Public" and DNS Peering is "Deactivated".)

I've set this up and waited for some hours with nothing happening. Dig offer any information helpful to me either

```<code>$ dig homeful.ly

; <<>> DiG 9.10.6 <<>> homeful.ly
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 42243
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;homeful.ly.            IN  A

;; Query time: 899 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Wed May 29 16:47:37 CEST 2019
;; MSG SIZE  rcvd: 39
</code>```

My question would be: What am I doing wrong? (I have generally only basic understanding of DNS)

答:
The Cloud DNS configuration seems correct and using $ curl and $ traceroute commands it's possible to know more information about the issue. Making a traceroute and curl to your domain you have the following messages:

$ traceroute homeful.ly
homeful.ly: No address associated with hostname

$ curl -i homeful.ly
curl: (6) Could not resolve host: homeful.ly

In a web browser the IP associate in your A register 35.244.164.50 is showing the message 'default backend - 404'. With these data you can have two different type of issue:

1.- You doesn't have the correct configuration in your Domain registrar. This isn't in Cloud DNS it's where you have your domain registered (Google domains, Godaddy, domain.com...). In Cloud DNS documentation you have the following sentence:

'Now that you have the list of Cloud DNS name servers hosting your
  managed zone, update the NS records for your domain with your domain
  registrar. Your domain registrar might be Google Domains or a
  third-party registrar.'

The domain registrar configuration must has the NS records that you have configured in your Cloud DNS zone. How you can make this? In the same document of above you have the next paragraph:

'The process will differ by domain registrar provider and you should
  consult the documentation for your provider to determine how to make
  the name server change.'

Without know what domain registrar are you using this is my best tip.

2.- GCP Load balancer configuration. If your domain is working or not, your GCP project configuration is showing an issue. If it's not for testing purpose you can check how is configured your backend service, forwarding rules, healtchecks, firewall rules in your LB.

Check your domain registrar configuration and if you have issue with the GCP project configuration you can open another question.

Title: DNS: .ly domain - in google cloud dns

Body:
my company has acquired a .ly domain (managed by the Libyan government), which we'd like to use for our brand. In order to manage this domain there's a very basic management panel allowing me to insert some "DNS Servers". Together with a cryptic message about when it's required to not only use domain names for these servers but also specify their IP Address. Due to bad translation, I can't make any sense of that.

Ultimately, I would like to manage the DNS configuration via google cloud DNS, where I've created a DNS A record for the domain pointing to our website's IP Address.

This looks like this:

(sorry for the german, can't make google cloud console translate to english; Type is "Public" and DNS Peering is "Deactivated".)

I've set this up and waited for some hours with nothing happening. Dig offer any information helpful to me either

$ dig homeful.ly

; <<>> DiG 9.10.6 <<>> homeful.ly
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 42243
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;homeful.ly.            IN  A

;; Query time: 899 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Wed May 29 16:47:37 CEST 2019
;; MSG SIZE  rcvd: 39

My question would be: What am I doing wrong? (I have generally only basic understanding of DNS)


问:
Why image upload is not displaying the image preview text?
I have customized my form upload button and hide the input field via css display:none but when I select an image the input is not showing the preview text!

I want to display the selected image preview text so that user know he has selected an image!

HTML:

```<code><div class="form-group">
    <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
    <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
    <span>No file chosen</span>
</div>
</code>```

CSS:

```<code>.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}
input[type=file] {
    display: none;
}
</code>```

 input[type=file]{
    display:none;
}
 .custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
 <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
 <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">                        <span>No file chosen</span>
</div></code>```

UPDATE: I tried all these solutions (How to display file name for custom styled input file using jquery?) but none worked for me. In my scenario I have two upload buttons one is before image upload and second is after image upload as shown in video.

Still I can't display the preview text in front of the upload buttons.

答:
It does not work because your No file chosen is static.

Try:

```<code><div class="form-group">
    <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
    <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
    <span id="images"></span>
</div>

<script type="text/javascript">
var field = document.getElementById('before_image');
var span = document.getElementById('images');

field.addEventListener('change', function() {
    var img = document.createElement('img');
    img.src = field.files[0].getAsDataURL();
    span.appendChild(img);
});
</script>
</code>```

Body:
I have customized my form upload button and hide the input field via css display:none but when I select an image the input is not showing the preview text!

I want to display the selected image preview text so that user know he has selected an image!

HTML:

     Before Image*
    <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
    No file chosen

CSS:

.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}
input[type=file] {
    display: none;
}

 input[type=file]{
    display:none;
}
 .custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

  Before Image*
 <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">                        No file chosen

UPDATE: I tried all these solutions (How to display file name for custom styled input file using jquery?) but none worked for me. In my scenario I have two upload buttons one is before image upload and second is after image upload as shown in video.

Still I can't display the preview text in front of the upload buttons.

Body:
It does not work because your <span>No file chosen</span> is static.

Try:

<div class="form-group">
    <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
    <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
    <span id="images"></span>
</div>

<script type="text/javascript">
var field = document.getElementById('before_image');
var span = document.getElementById('images');

field.addEventListener('change', function() {
    var img = document.createElement('img');
    img.src = field.files[0].getAsDataURL();
    span.appendChild(img);
});
</script>


问:
Variables are suddenly null in Flutter
I've implemented a date selection in my flutter app. The selected date then gets displayed, but as soon as the focus changes, the selected DateTime object becomes null without any reason.

To store the DateTime and some other variables I've created an object which is stored as a final variable in the StatefulWidget class. This object also includes Strings which don't change when the DateTime becomes null.

```<code>import 'package:flutter/material.dart';
import 'package:smartyne/core/assignment.dart';

class AssignmentPage extends StatefulWidget {

  final bool editMode;
  final Assignment assignment;

  AssignmentPage(this.assignment, this.editMode);

  @override
  _AssignmentPageState createState() => _AssignmentPageState();
}

class _AssignmentPageState extends State<AssignmentPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        ...
        body: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: "Title"),
                onChanged: (value) {
                  widget.assignment.title = value;
                  setState(() {});
                },
              ),

              ...

              SizedBox(
                height: 16.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  MaterialButton(
                    child: Text(widget.assignment.deadlineAsString),
                    onPressed: () {
                      _showDatePicker();
                    },
                  ),

                  ...

                ],
              )
            ],
          ),
        ));
  }

  void _showDatePicker() async {
    final DateTime newDeadline = await showDatePicker(
        context: context,
        initialDate: widget.assignment.deadline == null ? DateTime.now() : widget.assignment.deadline,
        firstDate: DateTime(1900),
        lastDate: DateTime(2099)
    );

    if (newDeadline != null && newDeadline != widget.assignment.deadline) {
      setState(() {
        widget.assignment.deadline = newDeadline;
      });
    }
  }
}

</code>```

As shown above, the DateTime gets selected by a DatePicker and the result is then stored in the assignment object. But when you click on the TextField for the title, it suddenly turns null.

Example gif: https://gph.is/g/aKn7yqq

答:
Use the declared variable inside state class like below</p>

```<code>import 'package:flutter/material.dart';
import 'package:smartyne/core/assignment.dart';

class AssignmentPage extends StatefulWidget {

  @override
  _AssignmentPageState createState() => _AssignmentPageState();
}

class _AssignmentPageState extends State<AssignmentPage> {
  final bool editMode;
  final Assignment assignment;
 @override
  Widget build(BuildContext context) {
return new Container();

//access it like
//Text(assignment.deadlineAsString),
//instead of
//Text(widget.assignment.deadlineAsString),

}
</code>```

Title: Variables are suddenly null in Flutter

Body:
I've implemented a date selection in my flutter app. The selected date then gets displayed, but as soon as the focus changes, the selected DateTime object becomes null without any reason.

To store the DateTime and some other variables I've created an object which is stored as a final variable in the StatefulWidget class. This object also includes Strings which don't change when the DateTime becomes null.

import 'package:flutter/material.dart';
import 'package:smartyne/core/assignment.dart';

class AssignmentPage extends StatefulWidget {

  final bool editMode;
  final Assignment assignment;

  AssignmentPage(this.assignment, this.editMode);

  @override
  _AssignmentPageState createState() => _AssignmentPageState();
}

class _AssignmentPageState extends State<AssignmentPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        ...
        body: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: "Title"),
                onChanged: (value) {
                  widget.assignment.title = value;
                  setState(() {});
                },
              ),

              ...

              SizedBox(
                height: 16.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  MaterialButton(
                    child: Text(widget.assignment.deadlineAsString),
                    onPressed: () {
                      _showDatePicker();
                    },
                  ),

                  ...

                ],
              )
            ],
          ),
        ));
  }

  void _showDatePicker() async {
    final DateTime newDeadline = await showDatePicker(
        context: context,
        initialDate: widget.assignment.deadline == null ? DateTime.now() : widget.assignment.deadline,
        firstDate: DateTime(1900),
        lastDate: DateTime(2099)
    );

    if (newDeadline != null && newDeadline != widget.assignment.deadline) {
      setState(() {
        widget.assignment.deadline = newDeadline;
      });
    }
  }
}

As shown above, the DateTime gets selected by a DatePicker and the result is then stored in the assignment object. But when you click on the TextField for the title, it suddenly turns null.

Example gif: https://gph.is/g/aKn7yqq

Body:
Use the declared variable inside state class like below

import 'package:flutter/material.dart';
import 'package:smartyne/core/assignment.dart';

class AssignmentPage extends StatefulWidget {

  @override
  _AssignmentPageState createState() => _AssignmentPageState();
}

class _AssignmentPageState extends State<AssignmentPage> {
  final bool editMode;
  final Assignment assignment;
 @override
  Widget build(BuildContext context) {
return new Container();

//access it like
//Text(assignment.deadlineAsString),
//instead of
//Text(widget.assignment.deadlineAsString),

}


问:
Calculate driving distances Google Maps API
For a website where a user enters his address, I'm trying to find the location closest to him where the user can collect the ordered goods.

Based on the user's address I can narrow down the possible pick up locations to between 2 and 5. So I'd like to calculate the distance between user's address (point A) and the possible pick up locations.

The demo here works fine with just two addresses. I've adapted the code as much as I can to work with more than two addresses. I posted my JS code here since I can't seem to properly format it in SO.

In the code are two alerts. The first alert correctly shows the different pick up locations. But the second alert always shows the LAST pickup location.

Can anyone explain why?

HTML:

```<code><p id="hello">Hello World</p>
</code>```

JavaScript:

```<code>var geocoder, location1, location2, gDir;

function initialize(counter) {
    if( counter == 0 ){
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
    }
    GEvent.addListener(gDir, "load", function() {
        var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        $("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');
    });
}

function getDistance(agency_add, counter) {
    initialize(counter);
    geocoder.getLocations(agency_add, function (response) {
        if (!response || response.Status.code != 200) {
            alert("Sorry, we were unable to geocode the address" + agency_add);
        }
        else {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
            //alert("ONE: "+location1.address);
            geocoder.getLocations(document.forms[0].address1.value, function (response) {
                //alert("TWO: "+location1.address);
                if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}
                else {
                    location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}

$(document).ready(function(){
    //put each agency address in an array
    var agencies = [];
    $(".agency_field").each(function(index) {
        agencies.push($(this).val());
    });

    for (var i = 0; i < agencies.length; i++){
        var res = getDistance(agencies[i], i);
    }
});
</code>```

答:
you are calling geocoder.getLocations inside a loop. geocoder.getLocations runs asynchronously. when it receives the 2nd request while still processing the first, it cancels the first request.

If you want to multi-thread geocoder.getLocations you need to create multiple instances of it.

ContentLicense: CC BY-SA 3.0

Body:
For a website where a user enters his address, I'm trying to find the location closest to him where the user can collect the ordered goods.

Based on the user's address I can narrow down the possible pick up locations to between 2 and 5. So I'd like to calculate the distance between user's address (point A) and the possible pick up locations.

The demo here works fine with just two addresses. I've adapted the code as much as I can to work with more than two addresses. I posted my JS code here since I can't seem to properly format it in SO.

In the code are two alerts. The first alert correctly shows the different pick up locations. But the second alert always shows the LAST pickup location.

Can anyone explain why?

HTML:

Hello World

JavaScript:

var geocoder, location1, location2, gDir;

function initialize(counter) {
    if( counter == 0 ){
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
    }
    GEvent.addListener(gDir, "load", function() {
        var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        $("#results").append('Driving Distance: ' + drivingDistanceKilometers + ' kilometers

');
    });
}

function getDistance(agency_add, counter) {
    initialize(counter);
    geocoder.getLocations(agency_add, function (response) {
        if (!response || response.Status.code != 200) {
            alert("Sorry, we were unable to geocode the address" + agency_add);
        }
        else {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
            //alert("ONE: "+location1.address);
            geocoder.getLocations(document.forms[0].address1.value, function (response) {
                //alert("TWO: "+location1.address);
                if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}
                else {
                    location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}

$(document).ready(function(){
    //put each agency address in an array
    var agencies = [];
    $(".agency_field").each(function(index) {
        agencies.push($(this).val());
    });

    for (var i = 0; i < agencies.length; i++){
        var res = getDistance(agencies[i], i);
    }
});


问:
Direct show capture pin configure run time live gamer portable 2 plus
I am trying to configure the output pin of live gamer portable 2 plus for lower frame rates.  Through GraphStudioNext I can access the configuration through the capture pin and change the frame rate.

However when I try IAMStreamConfig on the capture pin through the API, it will only allow me to select the default settings and not use the same frame rates I can do through GraphStudioNext.

Is there a different interface I should be using to get the output pin stream config seen in GraphStudioNext?

Below is the default Delphi routine to send the standard formats, I modified this so I changed the frame rate and kept all the other parameters and it worked.

```<code>      if (Format.Width = MediaHeader.bmiHeader.biWidth) and
        (Format.Height = MediaHeader.bmiHeader.biHeight) and
        (Format.AvgTimePerFrame = MediaHeader.AvgTimePerFrame) and
        (Format.BitsPerPixel = MediaHeader.bmiHeader.biBitCount) then
      begin
        MediaHeader.AvgTimePerFrame := NewRate;
        CheckNull(AMStreamConfig, 'IAMStreamConfig');
        CheckError(AMStreamConfig.SetFormat(MediaType));
        Exit;
      end;
</code>```

答:
This is a bit complicated because some cameras might support rates flexibly from within certain range and other might have fixed set of supported rates. Generally speaking you should be able to build a media type with desired frame rate and the device would capture as many as it can within the requested amount (or some would just ignore your setting).

However the canonical behavior is to enumerate formats with IAMStreamConfig so that you have MinFrameInterval and MaxFrameInterval range for a format of interest. Then (optionally) also use IAMVideoControl::GetFrameRateList to retrieve set of supported/suggested rates, the one that you see in GraphEdit/GraphStudio.

Then you can update a media type and instruct the camera to use a media type with specific frame rate via IAMStreamConfig::SetFormat.

Body:
I am trying to configure the output pin of live gamer portable 2 plus for lower frame rates.  Through GraphStudioNext I can access the configuration through the capture pin and change the frame rate.

However when I try IAMStreamConfig on the capture pin through the API, it will only allow me to select the default settings and not use the same frame rates I can do through GraphStudioNext.

Is there a different interface I should be using to get the output pin stream config seen in GraphStudioNext?

Below is the default Delphi routine to send the standard formats, I modified this so I changed the frame rate and kept all the other parameters and it worked.

      if (Format.Width = MediaHeader.bmiHeader.biWidth) and
        (Format.Height = MediaHeader.bmiHeader.biHeight) and
        (Format.AvgTimePerFrame = MediaHeader.AvgTimePerFrame) and
        (Format.BitsPerPixel = MediaHeader.bmiHeader.biBitCount) then
      begin
        MediaHeader.AvgTimePerFrame := NewRate;
        CheckNull(AMStreamConfig, 'IAMStreamConfig');
        CheckError(AMStreamConfig.SetFormat(MediaType));
        Exit;
      end;


问:
Require image with space in image name throws error
I'm currently working on a soundboard app, and I'm using ListItem for creating buttons. It allows me to create buttons with little avatars. I'm keeping monster data in an array.

I've already tried to replace('%20', '') method after the path to image but it didn't work for me.

Here is some code:

```<code>{
  "name": "Smoczy zębacz",

  "image": {source: require('./assets/img/Smoczy zębacz.jpg')},

  "sound": require('./assets/sounds/Smoczy zębacz.mp3')
}
</code>```

It works well when image and sound name don't contain space.

I want this code to find image with space in it's name but I'am getting this error:

```<code>Error: Asset not found: C:\Users\user\Soundboard\assets\img\Smoczy%20zębacz.jpg for platform: android
at C:\Users\user\Soundboard\node_modules\metro\src\Assets.js:147:13
at Generator.next (<anonymous>)
at step (C:\Users\user\Soundboard\node_modules\metro\src\Assets.js:326:347)
at C:\Users\user\Soundboard\node_modules\metro\src\Assets.js:326:507
</code>```

When I click on it I also get the same error with mp3 file.

答:
I think your wrongly use the url

your are using image url

C:\Users\user\Soundboard\assets\sounds\Smoczy%20zębacz.jpg

instead of mp3 url

C:\Users\user\Soundboard\assets\sounds\Smoczy%20zębacz.mp3

Body:
I'm currently working on a soundboard app, and I'm using ListItem for creating buttons. It allows me to create buttons with little avatars. I'm keeping monster data in an array.

I've already tried to replace('%20', '') method after the path to image but it didn't work for me.

Here is some code:

{
  "name": "Smoczy zębacz",

  "image": {source: require('./assets/img/Smoczy zębacz.jpg')},

  "sound": require('./assets/sounds/Smoczy zębacz.mp3')
}

It works well when image and sound name don't contain space.

I want this code to find image with space in it's name but I'am getting this error:

Error: Asset not found: C:\Users\user\Soundboard\assets\img\Smoczy%20zębacz.jpg for platform: android
at C:\Users\user\Soundboard\node_modules\metro\src\Assets.js:147:13
at Generator.next (<anonymous>)
at step (C:\Users\user\Soundboard\node_modules\metro\src\Assets.js:326:347)
at C:\Users\user\Soundboard\node_modules\metro\src\Assets.js:326:507

When I click on it I also get the same error with mp3 file.


问:
Multiple conditions in regex - how to replace both colon and space with dash
How to replace both colon and space with dash in regex?
Here's what I've managed to do:
to replace space: replace(/\s+/g, '-'),
to replace colon: replace(/:\s+/g, '-').
How do I merge these expressions?

答:
Use an alternation [ :]

var input = "Hello World:Goodbye";
console.log(input);
input = input.replace(/[ :]+/g, '-');
console.log(input);```

Note that this replaces actual spaces, not all whitespace characters, which your original version using \s does.

Body:
Use an alternation [ :]

var input = "Hello World:Goodbye";
console.log(input);
input = input.replace(/[ :]+/g, '-');
console.log(input);

Note that this replaces actual spaces, not all whitespace characters, which your original version using \s does.


问:
Launching Squirrel SQL client on Mac OS
I am Launching SQuirrel SQL on Mac OS X(El Capitan) that has JDK1.8 on it produces an error message saying the JDK-version should be at least 1.6. It then quits. SQL client version is 3.7. How do I resolve this?</p>

答:
The shell script now comes with Alternative solutions ready. Alternative 2 works for me. Just commented out Alternative 1 and uncommented the 2.

```<code>#Alternative 1
#SQUIRREL_SQL_HOME=`dirname "$0"`/Contents/Resources/Java

#Alternative 2
SQUIRREL_SQL_HOME=$(echo $ABSPATH | grep -o '^/.*/Contents/')Resources/Java

#Alternative 3
#SQUIRREL_SQL_HOME=`/Applications/SQuirreLSQL.app/Contents/Resources/Java'
</code>```

Open the script file as in @vijay answer.

Title: Launching Squirrel SQL client on Mac OS

Body:
The shell script now comes with Alternative solutions ready. Alternative 2 works for me. Just commented out Alternative 1 and uncommented the 2.

#Alternative 1
#SQUIRREL_SQL_HOME=`dirname "$0"`/Contents/Resources/Java

#Alternative 2
SQUIRREL_SQL_HOME=$(echo $ABSPATH | grep -o '^/.*/Contents/')Resources/Java

#Alternative 3
#SQUIRREL_SQL_HOME=`/Applications/SQuirreLSQL.app/Contents/Resources/Java'

Open the script file as in @vijay answer.


问:
Remove a big list of of special characters
I want to remove each of the following special characters from my documents:

```<code>symbols = {`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/}
</code>```

The reason why I am not simply doing something like this:

```<code>document = re.sub(r'([^\s\w]|_)+', '', document)
</code>```

is that in this way I remove also many (accented/special) letters in the case of documents written in languages such as Polish etc.

How can I remove each of the special characters above in one expression?

答:
If you have a list of the symbols you want to remove, you can construct this simple regex:

```<code>rgx = '|'.join(map(re.escape, symbols))
</code>```

Example:

```<code># example symbols list
symbols = ['"', '<', '+', '*']

document = '<div prop="+*+">'

rgx = '|'.join(map(re.escape, symbols))

document = re.sub(rgx, '', document)

print(document)
</code>```

Output:

```<code>div prop=>
</code>```

The code '|'.join(map(re.escape, symbols)) will construct the following regex:

```<code>\"|\<|\+|\*
</code>```

which means match any one of the symbols ", <, +, or *.

Body:
I want to remove each of the following special characters from my documents:

symbols = {`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/}

The reason why I am not simply doing something like this:

document = re.sub(r'([^\s\w]|_)+', '', document)

is that in this way I remove also many (accented/special) letters in the case of documents written in languages such as Polish etc.

How can I remove each of the special characters above in one expression?

Body:
If you have a list of the symbols you want to remove, you can construct this simple regex:

rgx = '|'.join(map(re.escape, symbols))

Example:

# example symbols list
symbols = ['"', '<', '+', '*']

document = '<div prop="+*+">'

rgx = '|'.join(map(re.escape, symbols))

document = re.sub(rgx, '', document)

print(document)

Output:

div prop=>

The code '|'.join(map(re.escape, symbols)) will construct the following regex:

\"|\<|\+|\*

which means match any one of the symbols ", <, +, or *.


问:
How to check if element in list matches with another element in a list of strings?

Input lists

```<code>list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
</code>```

Output list

```<code>output=['Google','AU-KBC Research Centre']
</code>```

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

答:
For an efficient solution you might want to use sets here. Define exclusion_list as a set, and use a list comprehension to check membership on each of the words in list1:

```<code>list1 = ['Google', 'Stanford University',
         'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)',
         'AU-KBC Research Centre']

# define a set from the exclusion_list
exclusion_list = set(['university','institute','school','University','Institute','School'])

[i for i in list1 if not set(i.split()).intersection(exclusion_list)]
# ['Google', 'AU-KBC Research Centre']
</code>```

Body:
Input lists

list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']

Output list

output=['Google','AU-KBC Research Centre']

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

Body:
For an efficient solution you might want to use sets here. Define exclusion_list as a set, and use a list comprehension to check membership on each of the words in list1:

list1 = ['Google', 'Stanford University',
         'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)',
         'AU-KBC Research Centre']

# define a set from the exclusion_list
exclusion_list = set(['university','institute','school','University','Institute','School'])

[i for i in list1 if not set(i.split()).intersection(exclusion_list)]
# ['Google', 'AU-KBC Research Centre']


问:
Spring Boot 2.0.0.M6 and file upload more than 10 MB
To my Spring Boot 2.0.0.M6 application.properties I have added the following lines:

```<code>spring.http.multipart.max-file-size=100MB
spring.http.multipart.max-request-size=100MB
</code>```

but when I try to upload to my RestController the 21MB file it fails with the following exception:

```<code>Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (21112803) exceeds the configured maximum (10485760)
</code>```

I run my application on Embedded Tomcat packaged with Spring Boot.

How to properly configure my application in order to allow file upload up to 100MB?

答:
For SpringBoot 1.5.7 till or before 2.1.2 the property need to set in application.properties file are:

```<code>spring.http.multipart.max-file-size=100MB
spring.http.multipart.max-request-size=100MB
</code>```

Also make sure you have application.properties file in "resources" folder. In case you are not sure with the size then "-1" is the value.

Body:
To my Spring Boot 2.0.0.M6 application.properties I have added the following lines:

spring.http.multipart.max-file-size=100MB
spring.http.multipart.max-request-size=100MB

but when I try to upload to my RestController the 21MB file it fails with the following exception:

Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (21112803) exceeds the configured maximum (10485760)

I run my application on Embedded Tomcat packaged with Spring Boot.

How to properly configure my application in order to allow file upload up to 100MB?

Body:
For SpringBoot 1.5.7 till or before 2.1.2 the property need to set in application.properties file are:

spring.http.multipart.max-file-size=100MB
spring.http.multipart.max-request-size=100MB

Also make sure you have application.properties file in "resources" folder. In case you are not sure with the size then "-1" is the value.


问:
Size of child class with diamond inheritance structure seems strange
I have 4 classes A, B, C, D.
B and C inherit A, and D inherit B and C.

If A, B, C, D doesn't have any member variable, sizeof(D) returns 1(which is expected).
But when B has one integer as member variable, sizeof(D) suddenly changes to 8.

Since sizeof(int) is 4, shouldn't sizeof(D) return 4 as well?

class A
{
};

class B : public A
{
    int data;
};

class C : public A
{
};

class D : public B, public C
{
};

int main()
{
    sizeof(A); // 1
    sizeof(B); // 4
    sizeof(C); // 1
    sizeof(D); // 8?
}
```

答:
You have 2 A subobjects in D, and they must have distinct representations. The lower bound on sizeof(D) is therefore 1 + sizeof(int).

The implementation you used chose to size D such that (sizeof(D) % alignof(D)) == 0.

Your implementation is non-conforming in the entirely empty case, as it has put two distinct As in the same storage.


Title: Remove a big list of of special characters

Body:
You can solve this without regular expressions by using str.replace():

symbols = {"`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"}

for c in symbols:
    document = document.replace(c, "")


问:
AWS IAM User with access to a folder in an Amazon EC2 instance
I have created an ubuntu instance in Amazon EC2. The instance has 3 project folders in the root directory:

```<code>/var/www/html/project_1
/var/www/html/project_2
/var/www/html/project_3
</code>```

I would like to add an IAM user for a developer with access to only project_1 folder and not the others. The developer can connect to the folder in the instance from ssh or sftp through Filezilla or ssh client but get access to only project_1 folder.

答:
You should create separate users with permission for,

whoever that needs access to your AWS EC2 instance.

And you'll need to give permissions to your folder as to which user or user group can access those folders.

Ref -

https://www.digitalocean.com/community/tutorials/how-to-create-a-sudo-user-on-ubuntu-quickstart

Body:
I have created an ubuntu instance in Amazon EC2. The instance has 3 project folders in the root directory:

/var/www/html/project_1
/var/www/html/project_2
/var/www/html/project_3

I would like to add an IAM user for a developer with access to only project_1 folder and not the others. The developer can connect to the folder in the instance from ssh or sftp through Filezilla or ssh client but get access to only project_1 folder.


问:
Is there a Tree Search function in Python to get all the parent for a given node based on Data, not by Node Id
Need to search a Tree based on Data.

Tried converting a Tree to Dict and search but did not work as expected. Requirement is to get all the related parent details of a node based on data.

tree = Tree()
tree.create_node(tag="Eatables",identifier="Food",data="Eatables")  # root node
......
tree.create_node(tag="Apple",identifier="Apple1",parent="RF_01",data="Apple")
..............
tree.create_node(tag="Apple",identifier="Apple2",parent="AppJu1",data="Apple")
..............
tree.create_node(tag="Apple",identifier="Apple3",parent="Salad1",data="Apple")
............
tree.show()

Eatables
├── Ingredients
│   ├── Milk
│   ├── Sugar
│   └── Water
├── Processed_Food
│   ├── Apple_Juice
│   │   ├── Apple
│   │   └── Milk
│   └── Salad
│       ├── Apple
│       ├── Banana
│       ├── Beetroot
│       ├── Carrot
│       ├── JackFruit
│       └── Mango
├── Raw_Food
│   ├── Apple
│   ├── Banana
│   ├── Jack_Fruit
│   └── Mango
└── Vegetables
    ├── Beet_root
    └── Carrot
```

Expected output is Node, Parent & grand_parent.
[ [Apple, Raw_food, Eatables],[Apple,Salad,Processed_Food],[Apple,Apple_Juice,Processed_Food] ]

答: By taking nodeid it is possible to get all the required data, fpointer and bpointer are very useful. Starting a search in a Tree data structure without nodeid is not an efficient way.</p>

Body:
Need to search a Tree based on Data.

Tried converting a Tree to Dict and search but did not work as expected. Requirement is to get all the related parent details of a node based on data.

tree = Tree()
tree.create_node(tag="Eatables",identifier="Food",data="Eatables")  # root node
......
tree.create_node(tag="Apple",identifier="Apple1",parent="RF_01",data="Apple")
..............
tree.create_node(tag="Apple",identifier="Apple2",parent="AppJu1",data="Apple")
..............
tree.create_node(tag="Apple",identifier="Apple3",parent="Salad1",data="Apple")
............
tree.show()

Eatables
├── Ingredients
│   ├── Milk
│   ├── Sugar
│   └── Water
├── Processed_Food
│   ├── Apple_Juice
│   │   ├── Apple
│   │   └── Milk
│   └── Salad
│       ├── Apple
│       ├── Banana
│       ├── Beetroot
│       ├── Carrot
│       ├── JackFruit
│       └── Mango
├── Raw_Food
│   ├── Apple
│   ├── Banana
│   ├── Jack_Fruit
│   └── Mango
└── Vegetables
    ├── Beet_root
    └── Carrot

Expected output is Node, Parent & grand_parent.
[ [Apple, Raw_food, Eatables],[Apple,Salad,Processed_Food],[Apple,Apple_Juice,Processed_Food] ]


问:
I got an error when i selected CORS of my api gate way
I select "Enable CORS" in my AWS Lambda API Gateway and checked the checkbox "Default 4XX" but the operation fails with an "Unknown Error".

What is wrong with my steps?

aws-image

error-image

答: You need to set a default Status Code for 4XX responses. Afterwards, you can add the CORS headers using the "Enable CORS" functionality.


问:
How to query a stored procedure to parent and child tables?
I have a table of jobs and a stored procedure to show that jobs per user.
But now, I need to use a different query for the same column.

For now I got this:

```<code>SELECT
    extrajobs.ExtraJobsID, prof.ProfileName,
    functscope.Name AS functionscope1,
    functscope.Name AS functionscope2,
    extrajobs.FunctionScopeID,
    users.UserID, extrajobs.CreateDate,
    users.Username, extrajobs.LastUpdate,
    prof.ProfileName,
    extrajobs.Description, extrajobs.Day, extrajobs.Hours,
    extrajobs.Remaining, extrajobs.Coordinator,
    extrajobs.Feedback__On_Coordinator, extrajobs.Status_Coordinator,
    extrajobs.Director, extrajobs.Status_Director,
    extrajobs.Feedback__On_Director
    --SELECT DISTINCT(users.Username), prof.ProfileName
FROM
    TBL_User AS users
JOIN
    TBL_ExtraJobs AS extrajobs ON extrajobs.UserID = users.UserID
JOIN
    TBL_UserFunctionScope AS functscope ON extrajobs.FunctionScopeID= functscope.FunctionScopeID
JOIN
    REL_ProfileUser AS relprofileuser ON users.UserID = relprofileuser.UserID
JOIN
    TBL_Profile AS prof ON prof.ProfileID = relprofileuser.ProfileID
JOIN
    TBL_UserFunction AS funct ON funct.FunctionID = relprofileuser.FunctionID
WHERE
    funct.Name = 'Extra-jobs'
</code>```

Stored procedure result set

and this is table of jobs:

TBL_FunctionScope

And now, in the result from the stored procedure, I want to put int functioscope1 the parent of funtionscope2 like the TBL_FunctionScope.

How can I do this ?

答:
You need is to include JOINs with the TBL_FunctionScope and TBL_UserFunctionScope, like this:</p>

```<code>SELECT
    extrajobs.ExtraJobsID, prof.ProfileName,
    functscope.Name AS functionscope1,
    functscope.Name AS functionscope2,
    parentfunctscope.Name as parentfunction,
    extrajobs.FunctionScopeID,
    users.UserID, extrajobs.CreateDate,
    users.Username, extrajobs.LastUpdate,
    prof.ProfileName,
    extrajobs.Description, extrajobs.Day, extrajobs.Hours,
    extrajobs.Remaining, extrajobs.Coordinator,
    extrajobs.Feedback__On_Coordinator, extrajobs.Status_Coordinator,
    extrajobs.Director, extrajobs.Status_Director,
    extrajobs.Feedback__On_Director
    --SELECT DISTINCT(users.Username), prof.ProfileName
FROM
    TBL_User AS users
JOIN
    TBL_ExtraJobs AS extrajobs ON extrajobs.UserID = users.UserID
JOIN
    TBL_UserFunctionScope AS functscope ON extrajobs.FunctionScopeID= functscope.FunctionScopeID
JOIN
    TBL_FunctionScope as func ON extrajobs.FunctionScopeID= func.FunctionScopeID
LEFT JOIN
    TBL_UserFunctionScope AS parentfunctscope ON func.ParentScopeID = parentfunctscope.FunctionScopeID
JOIN
    REL_ProfileUser AS relprofileuser ON users.UserID = relprofileuser.UserID
JOIN
    TBL_Profile AS prof ON prof.ProfileID = relprofileuser.ProfileID
JOIN
    TBL_UserFunction AS funct ON funct.FunctionID = relprofileuser.FunctionID
WHERE
    funct.Name = 'Extra-jobs'
</code>```

Body:
I have a table of jobs and a stored procedure to show that jobs per user.
But now, I need to use a different query for the same column.

For now I got this:

SELECT
    extrajobs.ExtraJobsID, prof.ProfileName,
    functscope.Name AS functionscope1,
    functscope.Name AS functionscope2,
    extrajobs.FunctionScopeID,
    users.UserID, extrajobs.CreateDate,
    users.Username, extrajobs.LastUpdate,
    prof.ProfileName,
    extrajobs.Description, extrajobs.Day, extrajobs.Hours,
    extrajobs.Remaining, extrajobs.Coordinator,
    extrajobs.Feedback__On_Coordinator, extrajobs.Status_Coordinator,
    extrajobs.Director, extrajobs.Status_Director,
    extrajobs.Feedback__On_Director
    --SELECT DISTINCT(users.Username), prof.ProfileName
FROM
    TBL_User AS users
JOIN
    TBL_ExtraJobs AS extrajobs ON extrajobs.UserID = users.UserID
JOIN
    TBL_UserFunctionScope AS functscope ON extrajobs.FunctionScopeID= functscope.FunctionScopeID
JOIN
    REL_ProfileUser AS relprofileuser ON users.UserID = relprofileuser.UserID
JOIN
    TBL_Profile AS prof ON prof.ProfileID = relprofileuser.ProfileID
JOIN
    TBL_UserFunction AS funct ON funct.FunctionID = relprofileuser.FunctionID
WHERE
    funct.Name = 'Extra-jobs'

Stored procedure result set

and this is table of jobs:

TBL_FunctionScope

And now, in the result from the stored procedure, I want to put int functioscope1 the parent of funtionscope2 like the TBL_FunctionScope.

How can I do this ?

Body:
You need is to include JOINs with the TBL_FunctionScope and TBL_UserFunctionScope, like this:

SELECT
    extrajobs.ExtraJobsID, prof.ProfileName,
    functscope.Name AS functionscope1,
    functscope.Name AS functionscope2,
    parentfunctscope.Name as parentfunction,
    extrajobs.FunctionScopeID,
    users.UserID, extrajobs.CreateDate,
    users.Username, extrajobs.LastUpdate,
    prof.ProfileName,
    extrajobs.Description, extrajobs.Day, extrajobs.Hours,
    extrajobs.Remaining, extrajobs.Coordinator,
    extrajobs.Feedback__On_Coordinator, extrajobs.Status_Coordinator,
    extrajobs.Director, extrajobs.Status_Director,
    extrajobs.Feedback__On_Director
    --SELECT DISTINCT(users.Username), prof.ProfileName
FROM
    TBL_User AS users
JOIN
    TBL_ExtraJobs AS extrajobs ON extrajobs.UserID = users.UserID
JOIN
    TBL_UserFunctionScope AS functscope ON extrajobs.FunctionScopeID= functscope.FunctionScopeID
JOIN
    TBL_FunctionScope as func ON extrajobs.FunctionScopeID= func.FunctionScopeID
LEFT JOIN
    TBL_UserFunctionScope AS parentfunctscope ON func.ParentScopeID = parentfunctscope.FunctionScopeID
JOIN
    REL_ProfileUser AS relprofileuser ON users.UserID = relprofileuser.UserID
JOIN
    TBL_Profile AS prof ON prof.ProfileID = relprofileuser.ProfileID
JOIN
    TBL_UserFunction AS funct ON funct.FunctionID = relprofileuser.FunctionID
WHERE
    funct.Name = 'Extra-jobs'


问:
How to set default value on select in a dynamic select component angular
I am trying to create a dynamic select component for my application. This component would be used in various forms throughout my application. In some cases, there may be some predefined value that may be provided to the select, in which case the value would be selected as default by the drop-down. In order to achieve this functionality I have looked over SO and found various questions that answer this problem, but are using NgModule as a directive for adding default value, whereas I am using formControlName for my component. I have tried a solution myself (code added below) but it doesn't seem to be working. I am reluctant to use ngModule with formControlName because the feature is deprecated in Angular 6 (the version I am using). How do I achieve the functionality?

component.html

```<code><div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [ngValue]="item.id">{{item.name}}</option>
  </select>
</div>
</code>```

component.ts

```<code>import { Component, ViewEncapsulation, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  encapsulation: ViewEncapsulation.None
})
/**
* This class is used to create a generic dropdown component. Population is done on runtime
*/
export class DropdownComponent{
  /**
  * Define FormGroup
  */
  @Input() group: FormGroup;

  /**
  * Define formControlName
  */
  @Input() formControlName: string;

  /**
  * Define id
  */
  @Input() id: string;

  /**
  * Define data
  */
  @Input() data: any;

  /**
  * Define placeholder
  */
  @Input() placeholder: string;

  /**
  * For any predefined value being passed
  */
  @Input() predefined: string;

  constructor() { }

}
</code>```

what I tried (ts file remained the same)

```<code><div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
    <ng-template *ngIf="predefined !== undefined; else default">
      <option *ngFor="let item of data" [selected]="item.id === predefined">{{item.name}}</option>
    </ng-template>
    <ng-template #default>
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [ngValue]="item.id">{{item.name}}</option>
    </ng-template>
  </select>
</div>
</code>```

答:
In order to cater the problem, the solution was to define a method in the OnInit lifecycle hook, which extracted the entire object an inserted into the template. The lifecycle hook sets a particular variable called selection and sets to the formControl:

```<code>selection: any

ngOnInit() {
    if (this.predefined !== undefined) {
      let index = Object.keys(this.data);
      var self = this;
      index.forEach(function(i) {
        Object.keys(self.data[i]).some(function(k) {
          if (self.data[i][k] === self.predefined) {
            self.selection = self.data[i];
            return self.data[i][k];
          }
        }
        )
      });
      this.group.controls[this.formControlName].setValue(this.selection.id, { onlySelf: true });
    }
  }
</code>```

The template didn't need any modification like I did in the question's update, so reverted to the previous:

```<code><div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [(ngValue)]="item.id">{{item.name}}</option>
  </select>
</div>
</code>```

Body:
I am trying to create a dynamic select component for my application. This component would be used in various forms throughout my application. In some cases, there may be some predefined value that may be provided to the select, in which case the value would be selected as default by the drop-down. In order to achieve this functionality I have looked over SO and found various questions that answer this problem, but are using NgModule as a directive for adding default value, whereas I am using formControlName for my component. I have tried a solution myself (code added below) but it doesn't seem to be working. I am reluctant to use ngModule with formControlName because the feature is deprecated in Angular 6 (the version I am using). How do I achieve the functionality?

component.html

  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [ngValue]="item.id">{{item.name}}</option>
  </select>

component.ts

import { Component, ViewEncapsulation, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  encapsulation: ViewEncapsulation.None
})
/**
* This class is used to create a generic dropdown component. Population is done on runtime
*/
export class DropdownComponent{
  /**
  * Define FormGroup
  */
  @Input() group: FormGroup;

  /**
  * Define formControlName
  */
  @Input() formControlName: string;

  /**
  * Define id
  */
  @Input() id: string;

  /**
  * Define data
  */
  @Input() data: any;

  /**
  * Define placeholder
  */
  @Input() placeholder: string;

  /**
  * For any predefined value being passed
  */
  @Input() predefined: string;

  constructor() { }

}

what I tried (ts file remained the same)

  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
    <ng-template *ngIf="predefined !== undefined; else default">
      <option *ngFor="let item of data" [selected]="item.id === predefined">{{item.name}}</option>
    </ng-template>
    <ng-template #default>
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [ngValue]="item.id">{{item.name}}</option>
    </ng-template>
  </select>

Body:
In order to cater the problem, the solution was to define a method in the OnInit lifecycle hook, which extracted the entire object an inserted into the template. The lifecycle hook sets a particular variable called selection and sets to the formControl:

selection: any

ngOnInit() {
    if (this.predefined !== undefined) {
      let index = Object.keys(this.data);
      var self = this;
      index.forEach(function(i) {
        Object.keys(self.data[i]).some(function(k) {
          if (self.data[i][k] === self.predefined) {
            self.selection = self.data[i];
            return self.data[i][k];
          }
        }
        )
      });
      this.group.controls[this.formControlName].setValue(this.selection.id, { onlySelf: true });
    }
  }

The template didn't need any modification like I did in the question's update, so reverted to the previous:

<div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [(ngValue)]="item.id">{{item.name}}</option>
  </select>
</div>


问:
MVC 5 Remote Validation
I need to validate an input field value from user before the form is submitted.

I have created an action in my custom controller and decorated the field with it:

action name:      CheckValue
   controller name:  Validate

```<code>[Remote("CheckValue", "Validate"), ErrorMessage="Value is not valid"]
public string Value { get; set; }
</code>```

The problem is when I press submit, the form is being submitted and then the message Value is not valid is shown if the value entered by the user is not valid.

How can I validate the value entered by user and prevent the form to be submitted if value is not valid, and display the error message?

If I try in JavaScript to check if the form is valid $("#formId").valid() that returns true, that means no matter what is the status of the value (valid or not) the form is valid.

In the other hand if I decorate another field with the [Required] attribute the form is not submitted and the error is shown for that field that is required. However the validation doesn't occur behind the scene for the remote validation field.

答:
I got the same problem i was copying and pasting script links >
problem solved when I drag and drop jquery files from script folder to view page
I hope this help. </p>

Title: MVC 5 Remote Validation

Body:
I need to validate an input field value from user before the form is submitted.

I have created an action in my custom controller and decorated the field with it:

action name:      CheckValue
   controller name:  Validate

[Remote("CheckValue", "Validate"), ErrorMessage="Value is not valid"]
public string Value { get; set; }

The problem is when I press submit, the form is being submitted and then the message Value is not valid is shown if the value entered by the user is not valid.

How can I validate the value entered by user and prevent the form to be submitted if value is not valid, and display the error message?

If I try in JavaScript to check if the form is valid $("#formId").valid() that returns true, that means no matter what is the status of the value (valid or not) the form is valid.

In the other hand if I decorate another field with the [Required] attribute the form is not submitted and the error is shown for that field that is required. However the validation doesn't occur behind the scene for the remote validation field.


答:
symbols = ['a', 'b', '|']
document = document.translate({ord(c):None for c in symbols})
```


问:
How to get string and two integers as an input in the same line
I want my input in this format    string N M

where N, M are integer value . I want this input in same line.

I have tried input().split() but it doesn't work.

```<code>alphabets  = input().split()   # what to do next
</code>```

My input format is (str, int, int).

答:
I Believe what you are trying to do is, take a string, and two integers as an input on the same line in console:-

```<code>string, N, M = input().split(" ")

N = int(N)
M = int(M)

print(string, type(string))
print(N, type(N))
print(M, type(M))
</code>```

The above code prompts for input, here the string and the two integers are separated by " " between them, i.e there should be a space between the string and each integers. I also printed out their datatypes so that it becomes a lot more intuitive for you to understand.

OUTPUT:-

```<code>apple 10 5
apple <class 'str'>
10 <class 'int'>
5 <class 'int'>
</code>```

NOTE:- There should be whitespace between each inputs, otherwise unwanted results may arise.

Examples of legal inputs:-

```<code>Hesoyam 100 20
AppleBabyCare 34 1215
</code>```

Body:
I want my input in this format    string N M

where N, M are integer value . I want this input in same line.

I have tried input().split() but it doesn't work.

alphabets  = input().split()   # what to do next

My input format is (str, int, int).

Body:
I Believe what you are trying to do is, take a string, and two integers as an input on the same line in console:-

string, N, M = input().split(" ")

N = int(N)
M = int(M)

print(string, type(string))
print(N, type(N))
print(M, type(M))

The above code prompts for input, here the string and the two integers are separated by " " between them, i.e there should be a space between the string and each integers. I also printed out their datatypes so that it becomes a lot more intuitive for you to understand.

OUTPUT:-

apple 10 5
apple <class 'str'>
10 <class 'int'>
5 <class 'int'>

NOTE:- There should be whitespace between each inputs, otherwise unwanted results may arise.

Examples of legal inputs:-

Hesoyam 100 20
AppleBabyCare 34 1215


问:
Need help with hashMap with expiry time constraints
I need a thread-safe Map with a time limited expiry policy. I tried looking for an existing library, but could not find one. Jboss cache is going to be a heavy alternative for my requirement. I have a first cut draft in place. Please have a look at the code posted on pastebin

I need constructive comments and enhancement suggestions. Thanks in advance.

答:
Take a look at Guava MapMaker:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html

It does exactly what you are looking for.


答:
If you want to remove literally each character, you can use str.replace and string module:

```<code>a = '345l,we.gm34mf,]-='

for char in string.punctuation:
    a = a.replace(char, '')
a
</code>```

'345lwegm34mf'

If you need more symbols to replace (string.punctuation equals to '!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~'), you can add them to ain` string.

Body:
If you want to remove literally each character, you can use str.replace and string module:

a = '345l,we.gm34mf,]-='

for char in string.punctuation:
    a = a.replace(char, '')
a

'345lwegm34mf'

If you need more symbols to replace (string.punctuation equals to '!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~'), you can add them to ain` string.


问:
trying to rebuild the itoa function
my program on only outputs none zero numbers ...eg input = 16076, output = 1676 ... can anyone please help with the maths</p>

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

char        *ft_itoa(int n)
{

    int count;
    int i;
    int j = 0;
    int temp;
    int allocated = 0;
    char *val;
    int zero;
    while (n > 0)
    {
        count = n;
        i = 0;
        temp = 1;

        while (count > 0)
        {
            i++;
            count /= 10;
            printf("works %d\n", i);
        }
        if (allocated == 0)
        {
            printf("alocated\n");
            allocated = 1;
            val = (char *)malloc((i + 1) * sizeof(char));
        }

        while (i > 1)
        {
            temp *= 10;
            i--;
            //printf("temp = %d\n", temp);
        }
        val[j] =  n / (temp) + '0';
        n = n - ((temp) * (n / temp));
        //val++;
</code>```

答:
There are several problems in your code, independently of the fact you do not mimic the usual atoi (which get the string in argument, more the basis, and also works on negative numbers)

you do not change the value of j so you only modify val[0], and because the end of the loop is not visible we do not know if you put the final null character somewhere

your code is very complicated for nothing, for instance why do you compute the number of digit and the power of ten each turn ?

visibly you do not know the modulo operator '%' exists

zero is useless

my program on only outputs none zero numbers

this is because of your way to count the number of digits each turn, after you removed the two higher digits from 16076 you get 076 so in fact 76 and you bypass the 0

The right way after you computed one time the number of digits is to write the number in the reverse order, starting by the lower digit

For instance if like you I allocate the string and only manages positive numbers a solution can be :

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

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage: %s <positive number>\n", *argv);
  else {
    int n;

    if ((sscanf(argv[1], "%d", &n) != 1)  || (n < 0))
      fprintf(stderr, "invalid number '%s'\n", argv[1]);
    else {
      int v;
      size_t ndigits;

      if (n == 0)
        ndigits = 1;
      else
        for (v = n, ndigits = 0; v != 0; v /= 10, ++ndigits)
          ; /* empty body */

      char * s = malloc(ndigits + 1);

      s[ndigits] = 0;

      do {
        s[--ndigits] = n % 10 + '0';
        n /= 10;
      } while (ndigits != 0);

      puts(s);
      free(s);
    }
  }

  return 0;
}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall i.c
pi@raspberrypi:/tmp $ ./a.out 16076
16076
pi@raspberrypi:/tmp $
</code>```

Execution under valgrind :

```<code>pi@raspberrypi:/tmp $ valgrind ./a.out 16076
==6822== Memcheck, a memory error detector
==6822== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6822== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==6822== Command: ./a.out 16076
==6822==
16076
==6822==
==6822== HEAP SUMMARY:
==6822==     in use at exit: 0 bytes in 0 blocks
==6822==   total heap usage: 2 allocs, 2 frees, 1,030 bytes allocated
==6822==
==6822== All heap blocks were freed -- no leaks are possible
==6822==
==6822== For counts of detected and suppressed errors, rerun with: -v
==6822== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $
</code>```

Title: trying to rebuild the itoa function

Body:
my program on only outputs none zero numbers ...eg input = 16076, output = 1676 ... can anyone please help with the maths

#include <stdio.h>

char        *ft_itoa(int n)
{

    int count;
    int i;
    int j = 0;
    int temp;
    int allocated = 0;
    char *val;
    int zero;
    while (n > 0)
    {
        count = n;
        i = 0;
        temp = 1;

        while (count > 0)
        {
            i++;
            count /= 10;
            printf("works %d\n", i);
        }
        if (allocated == 0)
        {
            printf("alocated\n");
            allocated = 1;
            val = (char *)malloc((i + 1) * sizeof(char));
        }

        while (i > 1)
        {
            temp *= 10;
            i--;
            //printf("temp = %d\n", temp);
        }
        val[j] =  n / (temp) + '0';
        n = n - ((temp) * (n / temp));
        //val++;

Body:
There are several problems in your code, independently of the fact you do not mimic the usual atoi (which get the string in argument, more the basis, and also works on negative numbers)

you do not change the value of j so you only modify val[0], and because the end of the loop is not visible we do not know if you put the final null character somewhere

your code is very complicated for nothing, for instance why do you compute the number of digit and the power of ten each turn ?

visibly you do not know the modulo operator '%' exists

zero is useless

my program on only outputs none zero numbers

this is because of your way to count the number of digits each turn, after you removed the two higher digits from 16076 you get 076 so in fact 76 and you bypass the 0

The right way after you computed one time the number of digits is to write the number in the reverse order, starting by the lower digit

For instance if like you I allocate the string and only manages positive numbers a solution can be :

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

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage: %s <positive number>\n", *argv);
  else {
    int n;

    if ((sscanf(argv[1], "%d", &n) != 1)  || (n < 0))
      fprintf(stderr, "invalid number '%s'\n", argv[1]);
    else {
      int v;
      size_t ndigits;

      if (n == 0)
        ndigits = 1;
      else
        for (v = n, ndigits = 0; v != 0; v /= 10, ++ndigits)
          ; /* empty body */

      char * s = malloc(ndigits + 1);

      s[ndigits] = 0;

      do {
        s[--ndigits] = n % 10 + '0';
        n /= 10;
      } while (ndigits != 0);

      puts(s);
      free(s);
    }
  }

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall i.c
pi@raspberrypi:/tmp $ ./a.out 16076
16076
pi@raspberrypi:/tmp $

Execution under valgrind :

pi@raspberrypi:/tmp $ valgrind ./a.out 16076
==6822== Memcheck, a memory error detector
==6822== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6822== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==6822== Command: ./a.out 16076
==6822==
16076
==6822==
==6822== HEAP SUMMARY:
==6822==     in use at exit: 0 bytes in 0 blocks
==6822==   total heap usage: 2 allocs, 2 frees, 1,030 bytes allocated
==6822==
==6822== All heap blocks were freed -- no leaks are possible
==6822==
==6822== For counts of detected and suppressed errors, rerun with: -v
==6822== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $


问:
How to take a pathname string with wildcards and resolve the glob with pathlib?
If I'm given a path as a string, such as "~/pythoncode/*.py" what is the best way to glob it in pathlib?

Using pathlib, there is a way of appending to a path using a glob:

```<code>p = pathlib.Path('~/pythoncode/').expanduser().glob('*.py')
</code>```

but this, for example, does not work because the user isn't expanded:

```<code>p = pathlib.Path().glob('~/pythoncode/*.py')
</code>```

and this is generates an exception because I'm providing no arguments to glob():

```<code>p = pathlib.Path('~/pythoncode/*.py').expanduser().glob()
</code>```

Is there a way to do this in pathlib, or must I parse the string first?

答:
pathlib.Path.glob does not support absolute (non-relative) path patterns, but glob.glob does:

```<code>from glob import glob
from pathlib import Path

paths = [Path(p) for p in glob('/foo/*/bar')]
</code>```

Or in connection with Path.expanduser:

```<code>paths = [Path(p) for p in glob(str(Path('~/.bash*').expanduser()))]
</code>```

Body:
If I'm given a path as a string, such as "~/pythoncode/*.py" what is the best way to glob it in pathlib?

Using pathlib, there is a way of appending to a path using a glob:

p = pathlib.Path('~/pythoncode/').expanduser().glob('*.py')

but this, for example, does not work because the user isn't expanded:

p = pathlib.Path().glob('~/pythoncode/*.py')

and this is generates an exception because I'm providing no arguments to glob():

p = pathlib.Path('~/pythoncode/*.py').expanduser().glob()

Is there a way to do this in pathlib, or must I parse the string first?

Body:
pathlib.Path.glob does not support absolute (non-relative) path patterns, but glob.glob does:

from glob import glob
from pathlib import Path

paths = [Path(p) for p in glob('/foo/*/bar')]

Or in connection with Path.expanduser:

paths = [Path(p) for p in glob(str(Path('~/.bash*').expanduser()))]


问:
How to change dictionary keys only? Without change values swift
I have array like this.

```<code>var Array = [Int:[String:Any]]()
</code>```

I just update the values

```<code> let updateValue = ["Name":tripName!,"date":firstDate,"year":year,"startData":startDateValue,"endDate":endDateValue,"countryName":countrname!,"totelBudjet":totelBudjet,"backgroundImage":arrImages[randomItem],"code":getAddtripeAttibutes.code,"countryIcon":countryIcon] as [String : Any]

 Array.updateValue(updateValue, forKey: tripId)

 tripId = tripId + 1
</code>```

We have more Array data as mentioned below

trip keys like :

[0] [1] [2]

```<code>[0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 1: ["date": "May 30 - May 31", "backgroundImage": "Europe_Trip", "endDate": 2019-05-31 10:14:43 +0000, "code": "DZD", "countryName": "Algeria", "tripName": "Gg", "countryIcon": "dz", "totelBudjet": "500 DZD", "startData": 2019-05-30 10:14:43 +0000, "year": "2019"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]
</code>```

I have updated tableview with above data

after i delete one array [1] it look like:
  this

[0] [2]

```<code> [0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]
</code>```

But I want to update the keys as [0][1] not as [0][2]

Can any one please help me with this?

答:
Why are you trying to mimic an array using a dictionary?

If you have an array like this.

```<code>var array: [[String: Any]] = [["year": "2019"], ["year": "2020"], ["year": "2021"]] // Minimalistic example array
</code>```

You can delete values at that particular location and it'll give you what you need currently.

```<code>array.remove(at: 1)
print(array[1])
</code>```

["year": "2021"]

Note - Your data looks like JSON response. So, you could use @Kamran's suggestion in the comments and use a struct Trip conforming Decodable and directly get your data as an array of Trips. However, if your JSON is formatted with keys 0, 1, 2... then your JSON is really bad and you should get it changed if you can. If you can't, you'll have to change the dictionary of dictionaries to an array of dictionary or better yet array of structs.

Body:
I have array like this.

var Array = [Int:[String:Any]]()

I just update the values

 let updateValue = ["Name":tripName!,"date":firstDate,"year":year,"startData":startDateValue,"endDate":endDateValue,"countryName":countrname!,"totelBudjet":totelBudjet,"backgroundImage":arrImages[randomItem],"code":getAddtripeAttibutes.code,"countryIcon":countryIcon] as [String : Any]

 Array.updateValue(updateValue, forKey: tripId)

 tripId = tripId + 1

We have more Array data as mentioned below

trip keys like :

[0] [1] [2]

[0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 1: ["date": "May 30 - May 31", "backgroundImage": "Europe_Trip", "endDate": 2019-05-31 10:14:43 +0000, "code": "DZD", "countryName": "Algeria", "tripName": "Gg", "countryIcon": "dz", "totelBudjet": "500 DZD", "startData": 2019-05-30 10:14:43 +0000, "year": "2019"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]

I have updated tableview with above data

after i delete one array [1] it look like:
  this

[0] [2]

 [0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]

But I want to update the keys as [0][1] not as [0][2]

Can any one please help me with this?

Body:
Why are you trying to mimic an array using a dictionary?

If you have an array like this.

var array: [[String: Any]] = [["year": "2019"], ["year": "2020"], ["year": "2021"]] // Minimalistic example array

You can delete values at that particular location and it'll give you what you need currently.

array.remove(at: 1)
print(array[1])

["year": "2021"]

Note - Your data looks like JSON response. So, you could use @Kamran's suggestion in the comments and use a struct Trip conforming Decodable and directly get your data as an array of Trips. However, if your JSON is formatted with keys 0, 1, 2... then your JSON is really bad and you should get it changed if you can. If you can't, you'll have to change the dictionary of dictionaries to an array of dictionary or better yet array of structs.