问:
Flutter animations: how to keep position of parent widget
I'm having some trouble with an animation in Flutter.
There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position?

I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller:

```<code>    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _animation = Tween(begin: 0.25, end: 0.35).animate(
        CurvedAnimation(parent: _animationController, curve: Curves.elasticIn))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        }
      });
</code>```

These are the circles:

```<code>Column(
        children: <Widget>[
Container(
            margin: EdgeInsets.only(top: 16.0),
            child: Center(
              child: Text(
                'Circles',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
Container(
            margin: EdgeInsets.only(top: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                ),
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return GestureDetector(
                      onTap: () {
                        _animationController.forward();
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width *
                            _animation.value,
                        height: MediaQuery.of(context).size.height *
                            _animation.value,
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: Center(child: Text('Circle')),
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: AppColors.primaryBlue)),
                      ),
                    );
                  },
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                )
              ],
            ),
          ),
</code>```

You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks!

答: first i suggest you delete mainAxisSize: MainAxisSize.min, if that didn't work, try to wrap the animated builder with a container and give it the same proprities as those

Body:
I'm having some trouble with an animation in Flutter.
There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position?

I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller:

    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _animation = Tween(begin: 0.25, end: 0.35).animate(
        CurvedAnimation(parent: _animationController, curve: Curves.elasticIn))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        }
      });

These are the circles:

Column(
        children: <Widget>[
Container(
            margin: EdgeInsets.only(top: 16.0),
            child: Center(
              child: Text(
                'Circles',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
Container(
            margin: EdgeInsets.only(top: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                ),
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return GestureDetector(
                      onTap: () {
                        _animationController.forward();
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width *
                            _animation.value,
                        height: MediaQuery.of(context).size.height *
                            _animation.value,
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: Center(child: Text('Circle')),
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: AppColors.primaryBlue)),
                      ),
                    );
                  },
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                )
              ],
            ),
          ),

You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks!


来源: stackexchange

问:
Constantly getting undefined when iterating through an array
So I'm just practising my react redux skills. Im a beginner. I have created an action, reducer and several components. I'm basically making a todo app. I am fetching the data from an API which I have successfully done but the problem is arising when I'm trying to loop through the data and have it surrounded with
 tags. I am getting Cannot read property 'map' of undefined which i dont understand why because in the console i can clearly see the array.

Action:

```<code>export function getLists(){
return function (dispatch) {
    return fetch ("https://reqres.in/api/users?page=1")
    .then( response => response.json())
    .then (json => {console.log('sdsd'); console.log(json);
        dispatch({  type: "ADD_ITEMS", payload: { json, loading: false}  });
    });
}
}
</code>```

Reducer:

```<code>const initialState = {
todothings: [],
loading: true
};
function rootReducer (state = initialState, action) {
    if( action.type === "ADD_ITEMS"){
        console.dir("In the ADD_ITEMS reducer" + action.payload);
        return Object.assign({}, state, {
            todothings: state.todothings.concat(action.payload.json),
            loading: action.payload.loading,
          });
    } else if ( action.type === "DELETE_ITEM") {
    } else {
        return state;
    }
}
export default rootReducer;
</code>```

ToDo Components:

```<code>import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';

class TodosComponent extends Component {
    componentDidMount(){
        console.log('in the Todos comp -> componentDidMount()');
        this.props.getList();
    }
    render(){
        const {todothings , loading} = this.props;
        if(!loading){
            return(
                <div>
                    <p>dfd</p>
                    {console.log(todothings)}
                    <TodoItems list={todothings}></TodoItems>
                </div>
            )
        } else {
            return (
                <p>Fetching from upstream.</p>
            )
        }
    }
}

function mapStateToProps(state){
    return {
        todothings: state.todothings,
        loading: state.loading,
    }
}
function mapDispatchToProps(dispatch){
    return {
        getList: () => dispatch(getLists())
      };
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;
</code>```

TodoItem Component:

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

function TodoItems (props) {
    return(
        <div>
            <ul>
            {console.log('In the todoitems')}
            {console.log(props)}

            {props.list.map( element => (
               <p>{element.data}</p>
            ))}
            </ul>
        </div>
    );
}

export default TodoItems;
</code>```

EDIT:

This is what I have so far now:

ToDoItems:

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

const TodoItems = ({ list = [] }) => {
    if (list.length === 0) return null;
    return (
      <ul>
        {list.map(item => (
          <li key={item.id} {...item}>
            <p>{item.first_name}</p>
          </li>
        ))}
      </ul>
    );
  };
export default TodoItems;
</code>```

ToDo Component:

```<code>import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';

class TodosComponent extends Component {
    componentDidMount(){
        console.log('in the Todos comp -> componentDidMount()');
        this.props.getList();
    }
    render(){
        const {todothings , loading} = this.props;
        if(!loading){
            return(
                <div>
                    <p>dfd</p>
                    {console.log('in the todo comp')}
                    {console.log(todothings)}
                    <TodoItems list={todothings.data}></TodoItems>
                </div>
            )
        } else {
            return (
                <p>Fetching from upstream.</p>
            )
        }
    }
}

function mapStateToProps(state){
    return {
        todothings: state.todothings,
        loading: state.loading,
    }
}
function mapDispatchToProps(dispatch){
    return {
        getList: () => dispatch(getLists())
      };
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;
</code>```

Reducer:

```<code>const initialState = {
todothings: [],
loading: true
};

function rootReducer (state = initialState, action) {
    if( action.type === "ADD_ITEMS"){
        console.dir("In the ADD_ITEMS reducer" + action.payload);
        return Object.assign({}, state, {
            todothings: state.todothings.concat(action.payload.json.data),
            loading: action.payload.loading,
          });
    } else if ( action.type === "DELETE_ITEM") {
    } else {
        return state;
    }
}
export default rootReducer;
</code>```

Action:

```<code>export function getLists(){
return function (dispatch) {
    return fetch ("https://reqres.in/api/users?page=1")
    .then( response => response.json())
    .then (json => {console.log('sdsd'); console.log(json);
        dispatch({  type: "ADD_ITEMS", payload: { json, loading: false}

});
        });
    }
}
</code>```

There are now no errors yet nothing is getting displayed:

```<code>(3) [{…}, {…}, {…}]
0: {id: 1, email: "george.bluth@reqres.in", first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}
1: {id: 2, email: "janet.weaver@reqres.in", first_name: "Janet", last_name: "Weaver", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"}
2: {id: 3, email: "emma.wong@reqres.in", first_name: "Emma", last_name: "Wong", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
length: 3
__proto__: Array(0)
</code>```

答:
Afternoon,

I think the data you want is from prop.list.data not props.list within <TodoItems />

In your component <TodDo /> try:

```<code><TodoItems list={todothings.data}></TodoItems>

</code>```

Then tidy up your stateless component <TodoItems /> (to cover an empty array):

```<code>const TodoItems = ({ list = [] }) => {
  if (list.length === 0) return null;

  return (
    <ul>
      {list.map(item => (
        <li key={item.id} {...item}>
          <ul>
            {Object.keys(item).map((data, key) => (
              <li {...{ key }}>{data}</li>
            ))}
          </ul>
        </li>
      ))}
    </ul>
  );
};
</code>```

Note:

Your array has an object, with this shape:

```<code>{
    id: 1,
    email: "g.buth@reqres.in",
    first_name: "George",
    last_name: "Bluth"
}
</code>```

What do you want to return in your
?

Update to loop through object.

ContentLicense: CC BY-SA 4.0

Body:
So I'm just practising my react redux skills. Im a beginner. I have created an action, reducer and several components. I'm basically making a todo app. I am fetching the data from an API which I have successfully done but the problem is arising when I'm trying to loop through the data and have it surrounded with
 tags. I am getting Cannot read property 'map' of undefined which i dont understand why because in the console i can clearly see the array.

Action:

export function getLists(){
return function (dispatch) {
    return fetch ("https://reqres.in/api/users?page=1")
    .then( response => response.json())
    .then (json => {console.log('sdsd'); console.log(json);
        dispatch({  type: "ADD_ITEMS", payload: { json, loading: false}  });
    });
}
}

Reducer:

const initialState = {
todothings: [],
loading: true
};
function rootReducer (state = initialState, action) {
    if( action.type === "ADD_ITEMS"){
        console.dir("In the ADD_ITEMS reducer" + action.payload);
        return Object.assign({}, state, {
            todothings: state.todothings.concat(action.payload.json),
            loading: action.payload.loading,
          });
    } else if ( action.type === "DELETE_ITEM") {
    } else {
        return state;
    }
}
export default rootReducer;

ToDo Components:

import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';

class TodosComponent extends Component {
    componentDidMount(){
        console.log('in the Todos comp -> componentDidMount()');
        this.props.getList();
    }
    render(){
        const {todothings , loading} = this.props;
        if(!loading){
            return(

dfd

                    {console.log(todothings)}
                    <TodoItems list={todothings}></TodoItems>

            )
        } else {
            return (

Fetching from upstream.

            )
        }
    }
}

function mapStateToProps(state){
    return {
        todothings: state.todothings,
        loading: state.loading,
    }
}
function mapDispatchToProps(dispatch){
    return {
        getList: () => dispatch(getLists())
      };
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;

TodoItem Component:

import React from 'react';

function TodoItems (props) {
    return(

            {console.log('In the todoitems')}
            {console.log(props)}

            {props.list.map( element => (

{element.data}

            ))}

    );
}

export default TodoItems;

EDIT:

This is what I have so far now:

ToDoItems:

import React from 'react';

const TodoItems = ({ list = [] }) => {
    if (list.length === 0) return null;
    return (

        {list.map(item => (

{item.first_name}

        ))}

    );
  };
export default TodoItems;

ToDo Component:

import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';

class TodosComponent extends Component {
    componentDidMount(){
        console.log('in the Todos comp -> componentDidMount()');
        this.props.getList();
    }
    render(){
        const {todothings , loading} = this.props;
        if(!loading){
            return(

dfd

                    {console.log('in the todo comp')}
                    {console.log(todothings)}
                    <TodoItems list={todothings.data}></TodoItems>

            )
        } else {
            return (

Fetching from upstream.

            )
        }
    }
}

function mapStateToProps(state){
    return {
        todothings: state.todothings,
        loading: state.loading,
    }
}
function mapDispatchToProps(dispatch){
    return {
        getList: () => dispatch(getLists())
      };
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;

Reducer:

const initialState = {
todothings: [],
loading: true
};

function rootReducer (state = initialState, action) {
    if( action.type === "ADD_ITEMS"){
        console.dir("In the ADD_ITEMS reducer" + action.payload);
        return Object.assign({}, state, {
            todothings: state.todothings.concat(action.payload.json.data),
            loading: action.payload.loading,
          });
    } else if ( action.type === "DELETE_ITEM") {
    } else {
        return state;
    }
}
export default rootReducer;

Action:

export function getLists(){
return function (dispatch) {
    return fetch ("https://reqres.in/api/users?page=1")
    .then( response => response.json())
    .then (json => {console.log('sdsd'); console.log(json);
        dispatch({  type: "ADD_ITEMS", payload: { json, loading: false}

});
        });
    }
}

There are now no errors yet nothing is getting displayed:

(3) [{…}, {…}, {…}]
0: {id: 1, email: "george.bluth@reqres.in", first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}
1: {id: 2, email: "janet.weaver@reqres.in", first_name: "Janet", last_name: "Weaver", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"}
2: {id: 3, email: "emma.wong@reqres.in", first_name: "Emma", last_name: "Wong", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
length: 3
__proto__: Array(0)

Body:
Afternoon,

I think the data you want is from prop.list.data not props.list within <TodoItems />

In your component <TodDo /> try:

<TodoItems list={todothings.data}></TodoItems>

Then tidy up your stateless component <TodoItems /> (to cover an empty array):

const TodoItems = ({ list = [] }) => {
  if (list.length === 0) return null;

  return (
    <ul>
      {list.map(item => (
        <li key={item.id} {...item}>
          <ul>
            {Object.keys(item).map((data, key) => (
              <li {...{ key }}>{data}</li>
            ))}
          </ul>
        </li>
      ))}
    </ul>
  );
};

Note:

Your array has an object, with this shape:

{
    id: 1,
    email: "g.buth@reqres.in",
    first_name: "George",
    last_name: "Bluth"
}

What do you want to return in your <li>?

Update to loop through object.


问:
How can I merge two files in Pentaho Data Integration (Kettle)
I'm working with Pentaho Data Integration (Kettle) and I have a question.

I have two input files file1.txt and file2.txt with the same header:

file1.txt

```<code>NAME;AGE
alberto;22
angela;22
madelaine;23
</code>```

file2.txt

```<code>NAME;AGE
carlos;56
fernando;30
ana;16
</code>```

and I want to merge both files into one, files_together.txt

```<code>NAME;AGE
alberto;22
angela;22
madelaine;23
carlos;56
fernando;30
ana;16
</code>```

I've tried all (I think) and I don't know how to do it. I've been searching in Google, Youtube... with no positive match.

Thank you very much.

答: You must "Select Values" step. The name of the fields must be the same.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm working with Pentaho Data Integration (Kettle) and I have a question.

I have two input files file1.txt and file2.txt with the same header:

file1.txt

NAME;AGE
alberto;22
angela;22
madelaine;23

file2.txt

NAME;AGE
carlos;56
fernando;30
ana;16

and I want to merge both files into one, files_together.txt

NAME;AGE
alberto;22
angela;22
madelaine;23
carlos;56
fernando;30
ana;16

I've tried all (I think) and I don't know how to do it. I've been searching in Google, Youtube... with no positive match.

Thank you very much.


问:
Upload image to Firebase Storage and show as Profile Image
I need help with uploading image to Firebase Storage. I have a profile menu in my app. When user tap on this menu he/she can see profile with their info and Profile Image. So I made it so you can select a photo from the gallery. But I need to save photo to Firebase Storage and add ref to Firebase Database by uid.
In addition, the user may not have a photo, so it will be nill because nothing in Database. Look at photo and you will understand everything

```<code>extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    var selectedImage: UIImage?
    if let editedImage = info[.editedImage] as? UIImage {
        selectedImage = editedImage
        self.profileImage.image = selectedImage!
        self.savedImage = selectedImage
        picker.dismiss(animated: true, completion: nil)
    } else if let originalImage = info[.originalImage] as? UIImage {
        selectedImage = originalImage
        self.profileImage.image = selectedImage!
        self.savedImage = selectedImage
        picker.dismiss(animated: true, completion: nil)
    }

}

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView) )
        profileImage.addGestureRecognizer(tapGesture)
        profileImage.isUserInteractionEnabled = true

@objc func handleSelectProfileImageView () {
    print("Tapped")

    let pickerController = UIImagePickerController()
    pickerController.delegate = self
    present(pickerController, animated: true, completion: nil)

}
</code>```

So, how to upload and dowload image.
If the user does not have a photo (ref in Database). He will see image from assets.
If the user have photo he will see image from FB.
image

答:
For Uploading to Firebase storage

```<code>let imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.img_Photo?.image)!, 0.5)!)
let _:NSData = NSData(data:UIImagePNGRepresentation(((self.img_Photo?.image)!))!)
self.uploadProfileImageToFirebase(data: imgData)
</code>```

Function for uploading

```<code>func uploadProfileImageToFirebase(data:NSData){
    let randomPic = randomString(length: 10)
    let storageRef = Storage.storage().reference().child("Pictures").child("\(value(forKey: "UserUID") ?? randomPic).jpg")
    if data != nil {
        storageRef.putData(data as Data, metadata: nil, completion: { (metadata, error) in
            if(error != nil){
                print(error)
                return
            }
            guard let userID = Auth.auth().currentUser?.uid else {
                return
            }
            // Fetch the download URL
            storageRef.downloadURL { url, error in
                if let error = error {
                    // Handle any errors
                    if(error != nil){
                        print(error)
                        return
                    }
                } else {
                    // Get the download URL for 'images/stars.jpg'

                    let urlStr:String = (url?.absoluteString) ?? ""
                    let values = ["photo_url": urlStr]
                    self.registerUserIntoDatabaseWithUID(uid: userID, values: values as [String : AnyObject])
                }
            }
        })
    }

}

func registerUserIntoDatabaseWithUID(uid:String, values:[String:AnyObject]){
    let ref = Database.database().reference(fromURL: "https://domain.firebaseio.com/")
    let usersReference = ref.child("users").child((Auth.auth().currentUser?.uid)!)

    usersReference.updateChildValues(values) { (error, ref) in
        if(error != nil){
            print(error)
            return
        }
        self.parentVC?.dismiss(animated: true, completion: nil)
    }

}
</code>```

Body:
I need help with uploading image to Firebase Storage. I have a profile menu in my app. When user tap on this menu he/she can see profile with their info and Profile Image. So I made it so you can select a photo from the gallery. But I need to save photo to Firebase Storage and add ref to Firebase Database by uid.
In addition, the user may not have a photo, so it will be nill because nothing in Database. Look at photo and you will understand everything

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    var selectedImage: UIImage?
    if let editedImage = info[.editedImage] as? UIImage {
        selectedImage = editedImage
        self.profileImage.image = selectedImage!
        self.savedImage = selectedImage
        picker.dismiss(animated: true, completion: nil)
    } else if let originalImage = info[.originalImage] as? UIImage {
        selectedImage = originalImage
        self.profileImage.image = selectedImage!
        self.savedImage = selectedImage
        picker.dismiss(animated: true, completion: nil)
    }

}

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView) )
        profileImage.addGestureRecognizer(tapGesture)
        profileImage.isUserInteractionEnabled = true

@objc func handleSelectProfileImageView () {
    print("Tapped")

    let pickerController = UIImagePickerController()
    pickerController.delegate = self
    present(pickerController, animated: true, completion: nil)

}

So, how to upload and dowload image.
If the user does not have a photo (ref in Database). He will see image from assets.
If the user have photo he will see image from FB.
image

Body:
For Uploading to Firebase storage

let imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.img_Photo?.image)!, 0.5)!)
let _:NSData = NSData(data:UIImagePNGRepresentation(((self.img_Photo?.image)!))!)
self.uploadProfileImageToFirebase(data: imgData)

Function for uploading

func uploadProfileImageToFirebase(data:NSData){
    let randomPic = randomString(length: 10)
    let storageRef = Storage.storage().reference().child("Pictures").child("\(value(forKey: "UserUID") ?? randomPic).jpg")
    if data != nil {
        storageRef.putData(data as Data, metadata: nil, completion: { (metadata, error) in
            if(error != nil){
                print(error)
                return
            }
            guard let userID = Auth.auth().currentUser?.uid else {
                return
            }
            // Fetch the download URL
            storageRef.downloadURL { url, error in
                if let error = error {
                    // Handle any errors
                    if(error != nil){
                        print(error)
                        return
                    }
                } else {
                    // Get the download URL for 'images/stars.jpg'

                    let urlStr:String = (url?.absoluteString) ?? ""
                    let values = ["photo_url": urlStr]
                    self.registerUserIntoDatabaseWithUID(uid: userID, values: values as [String : AnyObject])
                }
            }
        })
    }

}

func registerUserIntoDatabaseWithUID(uid:String, values:[String:AnyObject]){
    let ref = Database.database().reference(fromURL: "https://domain.firebaseio.com/")
    let usersReference = ref.child("users").child((Auth.auth().currentUser?.uid)!)

    usersReference.updateChildValues(values) { (error, ref) in
        if(error != nil){
            print(error)
            return
        }
        self.parentVC?.dismiss(animated: true, completion: nil)
    }

}


问:
String manipulation using list comprehension
I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.

```<code>def myfunc(*args):
    return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
</code>```

How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?

答:
The above answers are correct but they ask you to modify the current syntax. In general you should try to understand how *args works.

In python, *args in a function definition is used to receive variable number of arguments. Such cases arise when we don't know in advance how many arguments will be passed.

For example :

```<code>def myFun(*argv):
    for arg in argv:
        print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
</code>```

Now coming back to your code, you can make it run by selecting the first argument from the args list. See below :

```<code>def myfunc(*args):
    return ''.join([args[0][i].upper() if i%2==0 else args[0][i].lower() for i in range(len(args[0]))])
print(myfunc("input"))
</code>```

Help the community by selecting the best answer for this question.

Body:
I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.

def myfunc(*args):
    return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])

How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?

Body:
The above answers are correct but they ask you to modify the current syntax. In general you should try to understand how *args works.

In python, *args in a function definition is used to receive variable number of arguments. Such cases arise when we don't know in advance how many arguments will be passed.

For example :

def myFun(*argv):
    for arg in argv:
        print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Now coming back to your code, you can make it run by selecting the first argument from the args list. See below :

def myfunc(*args):
    return ''.join([args[0][i].upper() if i%2==0 else args[0][i].lower() for i in range(len(args[0]))])
print(myfunc("input"))

Help the community by selecting the best answer for this question.


问:
add background image in laravel 5
I am trying to add a background image for my website in Laravel 5.

I've used this in my css file.

```<code>html {
        background-image: url("images/background.jpg");
    }
</code>```

the image is in the public folder of my Laravel project folder. I tried all the paths but it just doesn't load.

I keep getting this error:

```<code>http://Laravelproject.app:8000/background.jpg 404 (Not Found)
</code>```

Any help would be appreciated. Thanks.

答:
I use

```<code>background-image: {{asset("/images/background.jpg")}};
</code>```

and my image is in public/images

Title: add background image in laravel 5

Body:
I am trying to add a background image for my website in Laravel 5.

I've used this in my css file.

html {
        background-image: url("images/background.jpg");
    }

the image is in the public folder of my Laravel project folder. I tried all the paths but it just doesn't load.

I keep getting this error:

http://Laravelproject.app:8000/background.jpg 404 (Not Found)

Any help would be appreciated. Thanks.

Body:
I use

background-image: {{asset("/images/background.jpg")}};

and my image is in public/images


问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

答:
If the order is not important, you should use set.difference. However, if you want to retain order, a simple list comprehension is all it takes.

```<code>result = [a for a in A if a not in subset_of_A]
</code>```

EDIT: As delnan says, performance will be substantially improved if subset_of_A is an actual set, since checking for membership in a set is O(1) as compared to O(n) for a list.

```<code>A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]
</code>```

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
If the order is not important, you should use set.difference. However, if you want to retain order, a simple list comprehension is all it takes.

result = [a for a in A if a not in subset_of_A]

EDIT: As delnan says, performance will be substantially improved if subset_of_A is an actual set, since checking for membership in a set is O(1) as compared to O(n) for a list.

A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]


问:
calculate array values by key
i have a array  problem can i calculate same integer value.
my example arrays on the bottom please

```<code>int = -21;
</code>```

my first array

```<code>Array
(
    [580] => 13.000000
    [582] => 8.000000
    [485] => 7.000000
)
</code>```

and i need is algoritm

```<code>Array
(
    [580] => 13.000000+int // sum -8
    [582] => 8.000000+(-8) // 0
    [485] => 7.000000
)
</code>```

after result

```<code>Array
(
    [580] => 8
    [582] => 0
    [485] => 7.000000
)
</code>```

答:
If I understand the question correctly:

```<code>$array = [
    580 => 13.000000,
    582 => 8.000000,
    485 => 7.000000,
];

// The initial number to sum
$int = -21;

foreach ($array as $key => $val) {
    // Add the int number to the current element.
    $array[$key] = $val + $int;

    // Now replace $int with the new sum so we'll use that
    // in the next iteration instead
    $int = $array[$key];
}
</code>```

A shorter version would be:

```<code>foreach ($array as $key => $val) {
    $int = $array[$key] = $val + $int;
}
</code>```

That will give you:

```<code>Array
(
    [580] => -8
    [582] => 0
    [485] => 7
)
</code>```

(and the first value is -8 as you stated in your comments)

Here's a demo

Title: calculate array values by key

Body:
i have a array  problem can i calculate same integer value.
my example arrays on the bottom please

int = -21;

my first array

Array
(
    [580] => 13.000000
    [582] => 8.000000
    [485] => 7.000000
)

and i need is algoritm

Array
(
    [580] => 13.000000+int // sum -8
    [582] => 8.000000+(-8) // 0
    [485] => 7.000000
)

after result

Array
(
    [580] => 8
    [582] => 0
    [485] => 7.000000
)

Body:
If I understand the question correctly:

$array = [
    580 => 13.000000,
    582 => 8.000000,
    485 => 7.000000,
];

// The initial number to sum
$int = -21;

foreach ($array as $key => $val) {
    // Add the int number to the current element.
    $array[$key] = $val + $int;

    // Now replace $int with the new sum so we'll use that
    // in the next iteration instead
    $int = $array[$key];
}

A shorter version would be:

foreach ($array as $key => $val) {
    $int = $array[$key] = $val + $int;
}

That will give you:

Array
(
    [580] => -8
    [582] => 0
    [485] => 7
)

(and the first value is -8 as you stated in your comments)

Here's a demo


问:
getSymbols() from quantmod in R doesn't work
I tried running getSymbols() from the famous library quantmod in R, but it didn't work. So I want to ask how to solve this problem.

The codes that I tried was the following :

```<code>library(quantmod)
</code>```

```<code>getSymbols("AAPL")
</code>```

```<code>Error in download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  :
  cannot open URL 'http://ichart.finance.yahoo.com/table.csv?s=AAPL&a=0&b=01&c=2007&d=4&e=30&f=2019&g=d&q=q&y=0&z=AAPL&x=.csv'
In addition: Warning message:
In download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  :
  InternetOpenUrl failed: '서버 이름이나 주소를 확인할 수 없습니다.'
</code>```

```<code>getSymbols("AAPL", src="google")
</code>```

```<code>Error in download.file(paste(google.URL, "q=", Symbols.name, "&startdate=",  :
  cannot open URL 'http://finance.google.com/finance/historical?q=AAPL&startdate=Jan+01,+2007&enddate=May+30,+2019&output=csv'
In addition: Warning message:
In download.file(paste(google.URL, "q=", Symbols.name, "&startdate=",  :
  cannot open URL 'http://finance.google.com/finance/historical?q=AAPL&startdate=Jan+01,+2007&enddate=May+30,+2019&output=csv': HTTP status was '403 Forbidden'
</code>```

I have ever run this function on the same desktop(OS : Windows 8.1K, x64).

Thank you for telling me about the right lastest version, so I tried upgrading the package like the below, but to fail.

```<code>install.packages("quantmod")
</code>```

It answered that it still calls v0.4-7.

```<code>Installing package into ‘C:/Users/fya/Documents/R/win-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://mran.revolutionanalytics.com/snapshot/2016-11-01/bin/windows/contrib/3.3/quantmod_0.4-7.zip'
Content type 'application/zip' length 472947 bytes (461 KB)
downloaded 461 KB

package ‘quantmod’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\***\AppData\Local\Temp\RtmpozsYvx\downloaded_packages
</code>```

Is there more effective way for solving this problem?

I referred to another stackoverflow page about upgrading packages in R :
https://stackoverflow.com/questions/21461649/how-to-update-a-package-in-r

答:
The latest version of quantmod on CRAN is 0.4-14, so you need to upgrade. Also note that Google Finance no longer provides any data.

You're using MRAN and R-3.3.x. MRAN may have quantmod_0.4-14, but they apparently do not for older R versions. And CRAN only provides Windows binaries for the latest minor version of R (currently 3.6.x).

You can install the latest quantmod from CRAN on R-3.3.x, but you will have to do some of the steps manually. Download quantmod_0.4-14 from CRAN then call:

```<code>install.packages("quantmod_0.4-14.tar.gz", repos = NULL, type = "source")
</code>```

I think that should work. Comment if you still have issues.

Body:
I tried running getSymbols() from the famous library quantmod in R, but it didn't work. So I want to ask how to solve this problem.

The codes that I tried was the following :

library(quantmod)

getSymbols("AAPL")

Error in download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  :
  cannot open URL 'http://ichart.finance.yahoo.com/table.csv?s=AAPL&a=0&b=01&c=2007&d=4&e=30&f=2019&g=d&q=q&y=0&z=AAPL&x=.csv'
In addition: Warning message:
In download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  :
  InternetOpenUrl failed: '서버 이름이나 주소를 확인할 수 없습니다.'

getSymbols("AAPL", src="google")

Error in download.file(paste(google.URL, "q=", Symbols.name, "&startdate=",  :
  cannot open URL 'http://finance.google.com/finance/historical?q=AAPL&startdate=Jan+01,+2007&enddate=May+30,+2019&output=csv'
In addition: Warning message:
In download.file(paste(google.URL, "q=", Symbols.name, "&startdate=",  :
  cannot open URL 'http://finance.google.com/finance/historical?q=AAPL&startdate=Jan+01,+2007&enddate=May+30,+2019&output=csv': HTTP status was '403 Forbidden'

I have ever run this function on the same desktop(OS : Windows 8.1K, x64).

Thank you for telling me about the right lastest version, so I tried upgrading the package like the below, but to fail.

install.packages("quantmod")

It answered that it still calls v0.4-7.

Installing package into ‘C:/Users/fya/Documents/R/win-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://mran.revolutionanalytics.com/snapshot/2016-11-01/bin/windows/contrib/3.3/quantmod_0.4-7.zip'
Content type 'application/zip' length 472947 bytes (461 KB)
downloaded 461 KB

package ‘quantmod’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\***\AppData\Local\Temp\RtmpozsYvx\downloaded_packages

Is there more effective way for solving this problem?

I referred to another stackoverflow page about upgrading packages in R :
https://stackoverflow.com/questions/21461649/how-to-update-a-package-in-r

Body:
The latest version of quantmod on CRAN is 0.4-14, so you need to upgrade. Also note that Google Finance no longer provides any data.

You're using MRAN and R-3.3.x. MRAN may have quantmod_0.4-14, but they apparently do not for older R versions. And CRAN only provides Windows binaries for the latest minor version of R (currently 3.6.x).

You can install the latest quantmod from CRAN on R-3.3.x, but you will have to do some of the steps manually. Download quantmod_0.4-14 from CRAN then call:

install.packages("quantmod_0.4-14.tar.gz", repos = NULL, type = "source")

I think that should work. Comment if you still have issues.


问:
How to store paytm API response information in mysql database using php
I am new in php and payment gateway integration. I have successfully integrated the payment system but the problem is that I am facing to store those information in database. Here is my response.php code.
Right now there are no errors but those information is not storing data in to my database.

```<code><?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");

// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");

$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";

$paramList = $_POST;
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] :
""; //Sent by Paytm pg

//Verify all parameters received from Paytm pg to your application. Like MID
received from paytm pg is same as your application’s MID, TXN_AMOUNT and
ORDER_ID are same as what was sent by you to Paytm PG for initiating
transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY,
$paytmChecksum); //will return TRUE or FALSE string.

if($isValidChecksum == "TRUE") {
echo "<b>Checksum matched and following are the transaction details:</b>" .
"<br/>";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
    echo "<b>Transaction status is success</b>" . "<br/>";
    //Process your transaction here as success transaction.

    //Verify amount & order id received from Payment gateway with your
 application's order id and amount.
 }
 else {
    echo "<b>Transaction status is failure</b>" . "<br/>";
    header("Location: ../wallet.php?wallet");
 }
 if (isset($_POST) && count($_POST)>0 )
 {
 var_dump($_POST);
include("db.php");
$TRANS_DATE_TIME= date('Y-m-d H:i:s');
#$ORDERID = $_POST["ORDERID"];
#$TXNID= $_POST["TXNID"];

$GETTING_INFO="INSERT INTO `wallet_transaction`
(`ORDERID`,`TXNID`,`TRANS_DATE_TIME`) VALUES ('".$_POST['ORDERID']."',
'".$_POST['TXNID']."','$TRANS_DATE_TIME')";
$dbsuccess=$conn->query($GETTING_INFO);

if($dbsuccess){
     header("Location: ../wallet.php?wallet");
 }
}

}
else {
echo "<b>Checksum mismatched.</b>";
//Process transaction as suspicious.
header("Location: ../wallet.php?wallet");
}
?>
</code>```

Redirect page

```<code><?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");

$checkSum = "";
$paramList = array();

$ORDER_ID = $_POST["ORDER_ID"];
$CUST_ID = $_POST["CUST_ID"];
$INDUSTRY_TYPE_ID = $_POST["INDUSTRY_TYPE_ID"];
$CHANNEL_ID = $_POST["CHANNEL_ID"];
$TXN_AMOUNT = $_POST["TXN_AMOUNT"];
$MSISDN = $_POST["MSISDN"];
$EMAIL = $_POST["EMAIL"];

// Create an array having all required parameters for creating checksum.
$paramList["MID"] = PAYTM_MERCHANT_MID;
$paramList["ORDER_ID"] = $ORDER_ID;
$paramList["CUST_ID"] = $CUST_ID;
$paramList["INDUSTRY_TYPE_ID"] = $INDUSTRY_TYPE_ID;
$paramList["CHANNEL_ID"] = $CHANNEL_ID;
$paramList["TXN_AMOUNT"] = $TXN_AMOUNT;
$paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;

$paramList["CALLBACK_URL"] =
"https://shareworld.com/PaytmKit/pgResponse.php";
$paramList["MSISDN"] = $MSISDN; //Mobile number of customer
$paramList["EMAIL"] = $EMAIL; //Email ID of customer
$paramList["VERIFIED_BY"] = "EMAIL"; //
$paramList["IS_USER_VERIFIED"] = "YES"; //

 //Here checksum string will return by getChecksumFromArray() function.
 $checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
?>
<html>
<head>
<title>Merchant Check Out Page</title>
</head>
<body>
<center><h1>Please do not refresh this page...</h1></center>
    <form method="post" action="<?php echo PAYTM_TXN_URL ?>" name="f1">
    <table border="1">
        <tbody>
        <?php
        foreach($paramList as $name => $value) {
            echo '<input type="hidden" name="' . $name .'" value="' . $value
 . '">';
 //Database connection will be there

        }
        ?>
        <input type="hidden" name="CHECKSUMHASH" value="<?php echo $checkSum
 ?>">
        </tbody>
    </table>
    <script type="text/javascript">
        document.f1.submit();
    </script>
</form>
</body>
</html>
</code>```

答:
```<code>if($isValidChecksum == "TRUE") {
echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
    echo "<b>Transaction status is success</b>" . "<br/>";
    //Process your transaction here as success transaction.
    //Verify amount & order id received from Payment gateway with your application's order id and amount.
}
else {
    echo "<b>Transaction status is failure</b>" . "<br/>";
}

if (isset($_POST) && count($_POST)>0 )
{
    $ORDERID = $_POST['ORDERID'];
    $MID = $_POST['MID'];
    $TXNID = $_POST['TXNID'];
    $TXNAMOUNT = $_POST['TXNAMOUNT'];
    $PAYMENTMODE = $_POST['PAYMENTMODE'];
    $CURRENCY = $_POST['CURRENCY'];
    $TXNDATE = $_POST['TXNDATE'];
    $STATUS = $_POST['STATUS'];
    $RESPCODE = $_POST['RESPCODE'];
    $RESPMSG = $_POST['RESPMSG'];
    $GATEWAYNAME = $_POST['GATEWAYNAME'];
    $BANKTXNID = $_POST['BANKTXNID'];
    $BANKNAME = $_POST['BANKNAME'];
    $CHECKSUMHASH =$_POST['CHECKSUMHASH'];

    $query = "INSERT into transaction (`ORDERID`,`MID`,`TXNID`,`TXNAMOUNT`,`PAYMENTMODE`,`CURRENCY`,`TXNDATE`,`STATUS`,`RESPCODE`,`RESPMSG`,`GATEWAYNAME`,`BANKTXNID`,`BANKNAME`,`CHECKSUMHASH`)
    VALUES ('$ORDERID','$MID','$TXNID','$TXNAMOUNT','$PAYMENTMODE','$CURRENCY','$TXNDATE','$STATUS','$RESPCODE','$RESPMSG','$GATEWAYNAME','$BANKTXNID','$BANKNAME','$CHECKSUMHASH')";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    }
</code>```

<p>}</p>

Body:
I am new in php and payment gateway integration. I have successfully integrated the payment system but the problem is that I am facing to store those information in database. Here is my response.php code.
Right now there are no errors but those information is not storing data in to my database.

<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");

// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");

$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";

$paramList = $_POST;
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] :
""; //Sent by Paytm pg

//Verify all parameters received from Paytm pg to your application. Like MID
received from paytm pg is same as your application’s MID, TXN_AMOUNT and
ORDER_ID are same as what was sent by you to Paytm PG for initiating
transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY,
$paytmChecksum); //will return TRUE or FALSE string.

if($isValidChecksum == "TRUE") {
echo "Checksum matched and following are the transaction details:" .
"
";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
    echo "Transaction status is success" . "
";
    //Process your transaction here as success transaction.

    //Verify amount & order id received from Payment gateway with your
 application's order id and amount.
 }
 else {
    echo "Transaction status is failure" . "
";
    header("Location: ../wallet.php?wallet");
 }
 if (isset($_POST) && count($_POST)>0 )
 {
 var_dump($_POST);
include("db.php");
$TRANS_DATE_TIME= date('Y-m-d H:i:s');
#$ORDERID = $_POST["ORDERID"];
#$TXNID= $_POST["TXNID"];

$GETTING_INFO="INSERT INTO `wallet_transaction`
(`ORDERID`,`TXNID`,`TRANS_DATE_TIME`) VALUES ('".$_POST['ORDERID']."',
'".$_POST['TXNID']."','$TRANS_DATE_TIME')";
$dbsuccess=$conn->query($GETTING_INFO);

if($dbsuccess){
     header("Location: ../wallet.php?wallet");
 }
}

}
else {
echo "Checksum mismatched.";
//Process transaction as suspicious.
header("Location: ../wallet.php?wallet");
}
?>

Redirect page

<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");

$checkSum = "";
$paramList = array();

$ORDER_ID = $_POST["ORDER_ID"];
$CUST_ID = $_POST["CUST_ID"];
$INDUSTRY_TYPE_ID = $_POST["INDUSTRY_TYPE_ID"];
$CHANNEL_ID = $_POST["CHANNEL_ID"];
$TXN_AMOUNT = $_POST["TXN_AMOUNT"];
$MSISDN = $_POST["MSISDN"];
$EMAIL = $_POST["EMAIL"];

// Create an array having all required parameters for creating checksum.
$paramList["MID"] = PAYTM_MERCHANT_MID;
$paramList["ORDER_ID"] = $ORDER_ID;
$paramList["CUST_ID"] = $CUST_ID;
$paramList["INDUSTRY_TYPE_ID"] = $INDUSTRY_TYPE_ID;
$paramList["CHANNEL_ID"] = $CHANNEL_ID;
$paramList["TXN_AMOUNT"] = $TXN_AMOUNT;
$paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;

$paramList["CALLBACK_URL"] =
"https://shareworld.com/PaytmKit/pgResponse.php";
$paramList["MSISDN"] = $MSISDN; //Mobile number of customer
$paramList["EMAIL"] = $EMAIL; //Email ID of customer
$paramList["VERIFIED_BY"] = "EMAIL"; //
$paramList["IS_USER_VERIFIED"] = "YES"; //

 //Here checksum string will return by getChecksumFromArray() function.
 $checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
?>

<title>Merchant Check Out Page</title>

Please do not refresh this page...

    <form method="post" action="<?php echo PAYTM_TXN_URL ?>" name="f1">

        <?php
        foreach($paramList as $name => $value) {
            echo '<input type="hidden" name="' . $name .'" value="' . $value
 . '">';
 //Database connection will be there

        }
        ?>
        <input type="hidden" name="CHECKSUMHASH" value="<?php echo $checkSum
 ?>">

</form>

Body:
if($isValidChecksum == "TRUE") {
echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
    echo "<b>Transaction status is success</b>" . "<br/>";
    //Process your transaction here as success transaction.
    //Verify amount & order id received from Payment gateway with your application's order id and amount.
}
else {
    echo "<b>Transaction status is failure</b>" . "<br/>";
}

if (isset($_POST) && count($_POST)>0 )
{
    $ORDERID = $_POST['ORDERID'];
    $MID = $_POST['MID'];
    $TXNID = $_POST['TXNID'];
    $TXNAMOUNT = $_POST['TXNAMOUNT'];
    $PAYMENTMODE = $_POST['PAYMENTMODE'];
    $CURRENCY = $_POST['CURRENCY'];
    $TXNDATE = $_POST['TXNDATE'];
    $STATUS = $_POST['STATUS'];
    $RESPCODE = $_POST['RESPCODE'];
    $RESPMSG = $_POST['RESPMSG'];
    $GATEWAYNAME = $_POST['GATEWAYNAME'];
    $BANKTXNID = $_POST['BANKTXNID'];
    $BANKNAME = $_POST['BANKNAME'];
    $CHECKSUMHASH =$_POST['CHECKSUMHASH'];

    $query = "INSERT into transaction (`ORDERID`,`MID`,`TXNID`,`TXNAMOUNT`,`PAYMENTMODE`,`CURRENCY`,`TXNDATE`,`STATUS`,`RESPCODE`,`RESPMSG`,`GATEWAYNAME`,`BANKTXNID`,`BANKNAME`,`CHECKSUMHASH`)
    VALUES ('$ORDERID','$MID','$TXNID','$TXNAMOUNT','$PAYMENTMODE','$CURRENCY','$TXNDATE','$STATUS','$RESPCODE','$RESPMSG','$GATEWAYNAME','$BANKTXNID','$BANKNAME','$CHECKSUMHASH')";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    }

}


问:
Google VR SDK stuck in portrait mode
I've built the app and compiled it with VR enabled and cardboard selected as my VR device. I can install and run it on my phone (Samsung S8) BUT the in game camera is stuck in portrait mode and the yew is inverted (turning my head left turns the camera right). I have scoured the internet but still can't find a way to fix this.

I've enabled VR in playersettings and added google cardboard as my VR.

I've also disabled portrait views under orientation.

I've set the camera as both a child and parent object.

I've built the app with both cardboard and daydream selected as the VR (and each individually) but still the same issue.

I've tried forcing different higher levels of API requirement

I have added and removed GvrEditorEmulator from the project and the GvrControllerMain and no luck.

I've even flipped the camera manually by a 180 degrees and this made the view be in landscape but in this case the pitch was inverted (when I look up the camera looks down) and I haven't found a way to resolve this.

In the editor view the screen looks fine, but every time I run it on my Android phone it force starts in portrait mode and the pitch or yew is inverted.

Is there a hidden option I need to switch, does anybody have more suggestions that I could try?

You can see what the app looks like when I hold the phone i portrait mode on the link bellow (the image breaks when I try to add it to the post for some reason).
https://imgur.com/a/o80NRe4

Its worth mentioning that I'm working with Unity version 2019 2.0b2 because any other version I tried would not detect my installed Android SDK and would not let me build the project. I've tried on multiple machines and always had that problem so I'm afraid of attempting an upgrade to a newer version would break my build ability.

答:
This seems to be a known and reported issue for Google VR SDK for unity. Its been reported on their github page.

The only possible fix is reverting back to Unity 2018.3.14f1. I did this by exporting my v2019 project, then creating a new 2018.3.14f1 version project and importing the original into it. This rebuilds the project and should avoid conflicts if you're lucky.

Title: Google VR SDK stuck in portrait mode


问:
what are the ways to create web App that will execute shell script smoothly
I am trying to build an web interface to execute the shell script on the linux environment.

I tried the same using the PHP shell_exec("test.sh") but it did not work properly. It is unable to execute few commands on the test.sh file and if i try executing the test.sh file it works properly though linux terminal.

```<code><?php
   shell_exec(command);
?>
</code>```

I just want to execute shell script through web interface , language can be any(Php, Java, nodejs..)

答: Share more information for a better answer, by the way, it's probably caused by users permissions. When you run a command with shell_exec() the user running it is www-data.

Body:
I am trying to build an web interface to execute the shell script on the linux environment.

I tried the same using the PHP shell_exec("test.sh") but it did not work properly. It is unable to execute few commands on the test.sh file and if i try executing the test.sh file it works properly though linux terminal.

<?php
   shell_exec(command);
?>

I just want to execute shell script through web interface , language can be any(Php, Java, nodejs..)


Title: array filter in python?

Body:
>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>>


问:
how to create a job task to run every 3 minutes during only at day time from 6AM to 10PM using python schedule
i want to run a task like generate IPv6 traffic every 3 minutes at all days from 6AM to 10PM (i.e. avoid traffic generation during night) using light weight python schedule. like for example the crontab equivalent:
*/3   6-22    *    *   * command_here

this above schedule should be executed during day time from 6 to 22 hours

schedule.every(3).minute.day.interval(6,22).do(genIPv6Traffic)

答:
The schedule module is very lightweight.  Looking at the source code, there is no support for conditionals or complex schedules.  You can easily write a gate job that stops calls to your task when conditions aren't met.

This simple utility prints the time when the second is between 6 and 21 (inclusive).  Obviously you'd want to change it to hours instead of seconds.

```<code>import schedule
import datetime
import time

def genIPv6TrafficGate():
    second = datetime.datetime.now().second
    if 6 <= second <= 21:
        genIPv6Traffic()

def genIPv6Traffic():
    print(datetime.datetime.now().second)

schedule.every(1).seconds.do(genIPv6TrafficGate)

while True:
    schedule.run_pending()
    time.sleep(1)
</code>```

Body:
The schedule module is very lightweight.  Looking at the source code, there is no support for conditionals or complex schedules.  You can easily write a gate job that stops calls to your task when conditions aren't met.

This simple utility prints the time when the second is between 6 and 21 (inclusive).  Obviously you'd want to change it to hours instead of seconds.

import schedule
import datetime
import time

def genIPv6TrafficGate():
    second = datetime.datetime.now().second
    if 6 <= second <= 21:
        genIPv6Traffic()

def genIPv6Traffic():
    print(datetime.datetime.now().second)

schedule.every(1).seconds.do(genIPv6TrafficGate)

while True:
    schedule.run_pending()
    time.sleep(1)


问:
How do I trigger HTML5 validation error popup when custom validation message is set manually?
I have the following code:

document.getElementById('testSubmit').addEventListener('click', (e) => {
  e.preventDefault();
  document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?');
  console.log(document.getElementById('test').validationMessage);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id = "test" type = "email" required>
<input id = "testSubmit" type = "submit"></code>```

As you can see, I can indicate that an error happens in the input field. However, I would like to display the message in my input.validationMessage which is set by setCustomValidity method in my error popup (which does not appear). How do I make the UI validation error popup to appear. For reference, the popup I'm referring to can be seen in the following code:

document.getElementById('btn-submit').addEventListener("click", function() {
  if (!document.getElementById('form').checkValidity()) {
    document.getElementById("submit-hidden").click();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" action="">

  <input type="text" required />
  <input id="submit-hidden" type="submit" style="display: none" />

</form>

<button id="btn-submit">Submit</button></code>```

Which displays the popup 'Please fill out this field' when you submit without filling the field. How do I trigger that popup, but with my custom validation message?

答:
You can do so by using the .reportValidity().
Here is an example:

document.getElementById('testSubmit').addEventListener('click', (e) => {
  e.preventDefault();
  document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?');
  document.getElementById('test').reportValidity();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id = "test" type = "email" oninput="validateInput();" required>
<input id = "testSubmit" type = "submit"></code>```

Body:
I have the following code:

document.getElementById('testSubmit').addEventListener('click', (e) => {
  e.preventDefault();
  document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?');
  console.log(document.getElementById('test').validationMessage);
});

<input id = "test" type = "email" required>
<input id = "testSubmit" type = "submit">

As you can see, I can indicate that an error happens in the input field. However, I would like to display the message in my input.validationMessage which is set by setCustomValidity method in my error popup (which does not appear). How do I make the UI validation error popup to appear. For reference, the popup I'm referring to can be seen in the following code:

document.getElementById('btn-submit').addEventListener("click", function() {
  if (!document.getElementById('form').checkValidity()) {
    document.getElementById("submit-hidden").click();
  }
});

<form id="form" action="">

  <input type="text" required />
  <input id="submit-hidden" type="submit" style="display: none" />

</form>

<button id="btn-submit">Submit</button>

Which displays the popup 'Please fill out this field' when you submit without filling the field. How do I trigger that popup, but with my custom validation message?

Body:
You can do so by using the .reportValidity().
Here is an example:

document.getElementById('testSubmit').addEventListener('click', (e) => {
  e.preventDefault();
  document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?');
  document.getElementById('test').reportValidity();
});

<input id = "test" type = "email" oninput="validateInput();" required>
<input id = "testSubmit" type = "submit">


问:
How to Set minimum and maximum date dynamically in Element-ui date picker
I am having 2 date pickers for startDate and endDate.
In startDate Picker,I want to disabled all dates before endDate and vise versa.
how to disable dates using elemnt-ui.

                  ></p>

答:
An easier solution would be limiting min/max values dynamically. I suggest this:

```<code><input type="date" class="form-control" v-model="dateFrom" :max="dateTo">
<input type="date" class="form-control" v-model="dateTo" :min="dateFrom">
</code>```

This would limit the date picker to proper date ranges.

Body:
An easier solution would be limiting min/max values dynamically. I suggest this:

<input type="date" class="form-control" v-model="dateFrom" :max="dateTo">
<input type="date" class="form-control" v-model="dateTo" :min="dateFrom">

This would limit the date picker to proper date ranges.


问:
Why LSTM Output_shape different from input_shape
I have a multi layer LSTM Model; My problem is the first layer has a different output_shape (Different number of features) from the input shape. Because of this, I cannot fit the model; an error is throwing. Can you explain why this happens and any solution will be much appreciated.</p>

```<code>trainingModel = keras.Sequential()

print('training_batch_size : ',training_batch_size, 'DataX.shape[1] : ',trainingDataX.shape[1],'DataX.shape[2] : ', trainingDataX.shape[2])

trainingModel.add(keras.layers.LSTM(numberOfNeurons
                    , batch_input_shape=(training_batch_size, trainingDataX.shape[1], trainingDataX.shape[2])
                    , return_sequences=True
                    , stateful=True
                    , dropout = keyDropOut))

for idx in range(numberOfLSTMLayers - 1):

    trainingModel.add(keras.layers.LSTM(
        numberOfNeurons
        , return_sequences= True
        , dropout = keyDropOut * (idx +1)
        ))

trainingModel.compile(optimizer='adam',loss='mean_squared_error')#,metrics=['accuracy'])

#Model Layer Shapes ========================
for layer in trainingModel.layers:

    print('Input shape', layer.input_shape)
    print('Output shape', layer.output_shape)

Output
===============
training_batch_size :  96 trainingDataX.shape[1] :  10 trainingDataX.shape[2] :  4
Model Layer Shapes
Input shape (96, 10, 4)
Output shape (96, 10, 5) *<<<THIS IS MY PROBLEM
Input shape (96, 10, 5)
Output shape (96, 10, 5)
Input shape (96, 10, 5)
Output shape (96, 10, 5)

Finally when I fit the model, it trhows error like:

ValueError: A target array with shape (2880, 10, 4) was passed for an output of shape (96, 10, 5) while using as loss `mean_squared_error`. This loss expects targets to have the same shape as the output
</code>```

答: Answering my own question as I solved it: The First Layer of LSTM should have number of neurons = number of features; i.e in first layer there should be only 4 neurons where I used 5.</p>

Body:
I have a multi layer LSTM Model; My problem is the first layer has a different output_shape (Different number of features) from the input shape. Because of this, I cannot fit the model; an error is throwing. Can you explain why this happens and any solution will be much appreciated.

trainingModel = keras.Sequential()

print('training_batch_size : ',training_batch_size, 'DataX.shape[1] : ',trainingDataX.shape[1],'DataX.shape[2] : ', trainingDataX.shape[2])

trainingModel.add(keras.layers.LSTM(numberOfNeurons
                    , batch_input_shape=(training_batch_size, trainingDataX.shape[1], trainingDataX.shape[2])
                    , return_sequences=True
                    , stateful=True
                    , dropout = keyDropOut))

for idx in range(numberOfLSTMLayers - 1):

    trainingModel.add(keras.layers.LSTM(
        numberOfNeurons
        , return_sequences= True
        , dropout = keyDropOut * (idx +1)
        ))

trainingModel.compile(optimizer='adam',loss='mean_squared_error')#,metrics=['accuracy'])

#Model Layer Shapes ========================
for layer in trainingModel.layers:

    print('Input shape', layer.input_shape)
    print('Output shape', layer.output_shape)

Output
===============
training_batch_size :  96 trainingDataX.shape[1] :  10 trainingDataX.shape[2] :  4
Model Layer Shapes
Input shape (96, 10, 4)
Output shape (96, 10, 5) *<<<THIS IS MY PROBLEM
Input shape (96, 10, 5)
Output shape (96, 10, 5)
Input shape (96, 10, 5)
Output shape (96, 10, 5)

Finally when I fit the model, it trhows error like:

ValueError: A target array with shape (2880, 10, 4) was passed for an output of shape (96, 10, 5) while using as loss `mean_squared_error`. This loss expects targets to have the same shape as the output


问:
Get autocomplete input value to a hidden input Vue.Js
I use https://santiblanko.github.io/vue-instant/ for autocompletion with Vue.

It works as I expected, except I cannot post the value inside the 'input' value to a form.

When I submit the form, the value inside the input is not posted to my backend server.

So that I have to create a hidden value when I submit so that I can read that input value.

How to do this. I just want the form and the value to be submitted as I cick magnifier icon.

https://codepen.io/snarex/pen/vwQjWR

<link rel="stylesheet" type="text/css" href="https://unpkg.com/vue-instant@0.0.10/dist/vue-instant.css">

<form action="https://www.google.com" method="GET">

    {{selectedEvent}}
    <vue-instant :suggestonallwords="true" :suggestion-attribute="suggestionAttribute" v-model="value" :disabled="false" @input="changed" @click-input="clickInput" @click-button="clickButton" @selected="selected" @enter="enter" @key-up="keyUp" @key-down="keyDown"
      @key-right="keyRight" @clear="clear" @escape="escape" :show-autocomplete="true" :autofocus="false" :suggestions="suggestions" name="customName" placeholder="custom placeholder" type="google"></vue-instant>

</form>```

答: You can add the following to the html of your form element v-on:submit.prevent="send". And then add a send function to your component's methods in which you access this.value and do whatever you need to do with it.


问:
How to change encoding bitrate dynamically while streaming in Gstreamer?
I am developing c program to perform adaptive streaming but I could't change the "bitrate" property of x264enc element with g_object_set() function.How can i change this?

Thanks.

答: Install the git version of the gstreamer ugly plugin.Then g_object_set() function works fine.


答:
You can you below code for Customize default validation message, But I have doning for required validation not for other, if you want to do for other validation as well please customize more

Form Code

```<code><form action="" method="get">
    <input type="text" name="a" id="a">
    <input type="text" name="b" id="b" required>
    <button type="submit">Submit</button>
</form>
</code>```

Js Code

```<code>document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByTagName("input");
    for (var inp of elements) {
        inp.oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Change Validation Message");
            }
        };
        inp.oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})
</code>```

Title: How do I trigger HTML5 validation error popup when custom validation message is set manually?

Body:
You can you below code for Customize default validation message, But I have doning for required validation not for other, if you want to do for other validation as well please customize more

Form Code

<form action="" method="get">
    <input type="text" name="a" id="a">
    <input type="text" name="b" id="b" required>
    <button type="submit">Submit</button>
</form>

Js Code

document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByTagName("input");
    for (var inp of elements) {
        inp.oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Change Validation Message");
            }
        };
        inp.oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})


问:
How to use sync in 3 column pivot table?
```<code>Pivot: team_member
team_id  |  member_id  |  status  |
-----------------------------------
   1     |      1      |    1     |
   1     |      2      |    1     |
   2     |      3      |    1     |
   3     |      4      |    1     |
</code>```

How to update the last record to status 0 by using sync function?

```<code>$team = Team::find(3);
$member_ids = [4];
$status = 0;

$team->members()->sync($member_ids, ['status' => 0]);
</code>```

Sync is not working if the team_id and member_id are same like exisitng one.

Team Model

```<code>   public function members() {
        return $this->belongsToMany(Member::class, 'team_member', 'team_id', 'member_id')->withPivot('status');
    }
</code>```

答:
Try to use this:

Updating A Record On A Pivot Table

If you need to update an existing row in your pivot table, you may use updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:

```<code>$team->members()->updateExistingPivot($memberId, ['status' => 0]);
</code>```

source

Regards

Body:
Pivot: team_member
team_id  |  member_id  |  status  |
-----------------------------------
   1     |      1      |    1     |
   1     |      2      |    1     |
   2     |      3      |    1     |
   3     |      4      |    1     |

How to update the last record to status 0 by using sync function?

$team = Team::find(3);
$member_ids = [4];
$status = 0;

$team->members()->sync($member_ids, ['status' => 0]);

Sync is not working if the team_id and member_id are same like exisitng one.

Team Model

   public function members() {
        return $this->belongsToMany(Member::class, 'team_member', 'team_id', 'member_id')->withPivot('status');
    }

Body:
Try to use this:

Updating A Record On A Pivot Table

If you need to update an existing row in your pivot table, you may use updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:

$team->members()->updateExistingPivot($memberId, ['status' => 0]);

source

Regards


问:
searching static list of fixed strings in a huge number of files
I have a large number of fixed strings (~5 million) that i want to search in a a lot of files.

I saw that two of the most commonly used algorithms for string searching using finite set of patterns are: Aho-Corasick and Commentz-Walter.

My goal is to find an exact match and not patterns (it means that the list of strings is not regular expressions).

After some research, I found a lot of articles that states that Commentz-Walter tends to be faster than Aho-Corasick in real world scenarios (Article1,Article2) and it is also the algorithm behind GNU-grep.

I tried to use grep -F also in the parallel way (taken from here):

```<code>free=$(awk '/^((Swap)?Cached|MemFree|Buffers):/ { sum += $2 }
          END { print sum }' /proc/meminfo)
percpu=$((free / 200 / $(parallel --number-of-cores)))k
parallel --pipepart -a regexps.txt --block $percpu --compress \
grep -F -f - -n bigfile
</code>```

and it seems that the problem is too big. I get this error:

```<code>grep: memory exhausted
</code>```

I thought about trying to split patterns list into a number of files and run grep number of times for the same file - but it seems clumsy. Is there any other solution? or I'm not running the grep in the correct way?

By running the Commentz-Walter algorithm grep should do some pre-processing work. I assume that running grep with the same pattern file on two different files will cause grep executing the same pre-processing stage twice. Is there a way to run grep on a list of files and cause it to run the patterns pre-processing only once?

Is there any good implementation of Commentz-Walter in c\c++? i only found code in python (here)?

--- Update ---

According to some comments, i tried to test the different Aho-Corasick c\c++ implementations (Komodia ,Cjgdev,chasan) non of them could have managed the 5 million pattern set example (all of them had memory issues (segmentation fault/ stack overflow)) - they do work on small sets.
The example file was generated by this code:

```<code>with open(r"C:\very_large_pattern", 'w') as out:
for _ in range(0, 5000000):
    out.write(str(uuid.uuid4()) + '\n')
</code>```

Does anybody have a suggestion to an implementation that can handle those numbers?

答:
Here is a simple solution that should be fast.

Put your fixed-length strings to search, one by line, into a file, and sort the file. Call that file S.

For each file that you want to search, do:

If the length of the strings to search is k, break the file into every possible strings of length k. Call that file B. For example, if k = 5, and the file to search is:

```<code>abcdefgh
123
123456
</code>```

The file of broken strings would be:

```<code>abcde
bcdef
cdefg
defgh
12345
23456
</code>```

Now, in order to know the position of each broken string in the oroginal file, append its line and column numbers in file B. For example,

```<code>abcde 1 1
bcdef 1 2
cdefg 1 3
defgh 1 4
12345 3 1
23456 3 2
</code>```

Sort B, and merge it with S. Call the resulting file M. For example, if S is:

```<code>23456
cdefg
</code>```

M would be:

```<code>12345 3 1
23456
23456 3 2
abcde 1 1
bcdef 1 2
cdefg
cdefg 1 3
defgh 1 4
</code>```

Retrieve from M all occurrences of the strings of S found in the file. For example:

```<code>23456
23456 3 2
cdefg
cdefg 1 3
</code>```

If a string has multiple occurrences, you can get all of them.

I do not know what OS you work with, but the above steps can most likely be performed with commands like sort, awk, grep, etc.

Body:
I have a large number of fixed strings (~5 million) that i want to search in a a lot of files.

I saw that two of the most commonly used algorithms for string searching using finite set of patterns are: Aho-Corasick and Commentz-Walter.

My goal is to find an exact match and not patterns (it means that the list of strings is not regular expressions).

After some research, I found a lot of articles that states that Commentz-Walter tends to be faster than Aho-Corasick in real world scenarios (Article1,Article2) and it is also the algorithm behind GNU-grep.

I tried to use grep -F also in the parallel way (taken from here):

free=$(awk '/^((Swap)?Cached|MemFree|Buffers):/ { sum += $2 }
          END { print sum }' /proc/meminfo)
percpu=$((free / 200 / $(parallel --number-of-cores)))k
parallel --pipepart -a regexps.txt --block $percpu --compress \
grep -F -f - -n bigfile

and it seems that the problem is too big. I get this error:

grep: memory exhausted

I thought about trying to split patterns list into a number of files and run grep number of times for the same file - but it seems clumsy. Is there any other solution? or I'm not running the grep in the correct way?

By running the Commentz-Walter algorithm grep should do some pre-processing work. I assume that running grep with the same pattern file on two different files will cause grep executing the same pre-processing stage twice. Is there a way to run grep on a list of files and cause it to run the patterns pre-processing only once?

Is there any good implementation of Commentz-Walter in c\c++? i only found code in python (here)?

--- Update ---

According to some comments, i tried to test the different Aho-Corasick c\c++ implementations (Komodia ,Cjgdev,chasan) non of them could have managed the 5 million pattern set example (all of them had memory issues (segmentation fault/ stack overflow)) - they do work on small sets.
The example file was generated by this code:

with open(r"C:\very_large_pattern", 'w') as out:
for _ in range(0, 5000000):
    out.write(str(uuid.uuid4()) + '\n')

Does anybody have a suggestion to an implementation that can handle those numbers?

Body:
Here is a simple solution that should be fast.

Put your fixed-length strings to search, one by line, into a file, and sort the file. Call that file S.

For each file that you want to search, do:

If the length of the strings to search is k, break the file into every possible strings of length k. Call that file B. For example, if k = 5, and the file to search is:

abcdefgh
123
123456

The file of broken strings would be:

abcde
bcdef
cdefg
defgh
12345
23456

Now, in order to know the position of each broken string in the oroginal file, append its line and column numbers in file B. For example,

abcde 1 1
bcdef 1 2
cdefg 1 3
defgh 1 4
12345 3 1
23456 3 2

Sort B, and merge it with S. Call the resulting file M. For example, if S is:

23456
cdefg

M would be:

12345 3 1
23456
23456 3 2
abcde 1 1
bcdef 1 2
cdefg
cdefg 1 3
defgh 1 4

Retrieve from M all occurrences of the strings of S found in the file. For example:

23456
23456 3 2
cdefg
cdefg 1 3

If a string has multiple occurrences, you can get all of them.

I do not know what OS you work with, but the above steps can most likely be performed with commands like sort, awk, grep, etc.


问:
Print largest and smallest number in python
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

I am having problem in printing the largest and smallest number. Its printing incorrect number by the approach below:

```<code>largest = None
smallest = None
list1 = []
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        val = int(num)
        if int(num):
            list1.append(num)
    except:
        print("Invalid input")
print("Maximum is " + max(list1))
print("Minimum is " + min(list1))
</code>```

I am entering numbers as 7, 2, bob, 10, and 4.

Its printing output as:
Invalid input
Maximum is 7
Minimum is 10

While the output I am looking for is:
Invalid input
Maximum is 10
Minimum is 2

答:
You must append int in your list, not str.

Change this:

```<code>if int(num):
    list1.append(num)
</code>```

to one of the following: (the if int(num) is unnecessary.)

```<code>list1.append(int(num))
</code>```

or

```<code>list1.append(val)
</code>```

You must also convert to string before concatenating in the print statement:

```<code>print("Maximum is " + str(max(list1)))
print("Minimum is " + str(min(list1)))
</code>```

With the modifications, your program should look like this:

```<code>largest = None
smallest = None
list1 = []
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        val = int(num)
        list1.append(val)
    except ValueError:         # it is always better to specify what type of error you are expecting to catch
        print("Invalid input")
print("Maximum is " + str(max(list1)))
print("Minimum is " + str(min(list1)))
</code>```

Body:
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

I am having problem in printing the largest and smallest number. Its printing incorrect number by the approach below:

largest = None
smallest = None
list1 = []
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        val = int(num)
        if int(num):
            list1.append(num)
    except:
        print("Invalid input")
print("Maximum is " + max(list1))
print("Minimum is " + min(list1))

I am entering numbers as 7, 2, bob, 10, and 4.

Its printing output as:
Invalid input
Maximum is 7
Minimum is 10

While the output I am looking for is:
Invalid input
Maximum is 10
Minimum is 2

Body:
You must append int in your list, not str.

Change this:

if int(num):
    list1.append(num)

to one of the following: (the if int(num) is unnecessary.)

list1.append(int(num))

or

list1.append(val)

You must also convert to string before concatenating in the print statement:

print("Maximum is " + str(max(list1)))
print("Minimum is " + str(min(list1)))

With the modifications, your program should look like this:

largest = None
smallest = None
list1 = []
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        val = int(num)
        list1.append(val)
    except ValueError:         # it is always better to specify what type of error you are expecting to catch
        print("Invalid input")
print("Maximum is " + str(max(list1)))
print("Minimum is " + str(min(list1)))


问:
SQLAlchemy many-to-many relationship updating association object with extra column
In my application, a 'set' can have a number of 'products' associated with it. Products listed against a set must have quantities defined. For this many-to-many relationship I have followed the SQLAlchemy documentation to use an association table with an additional column (quantity).

I am trying to create a form where the user can assign products and quantities against a given set. Both the sets and products already exist in the database. The data from the form are:

set.id

product.id

quantity

This works to create a new association (e.g. set 1 is 'linked' to product 3 with quantity=XYZ) but I get an integrity error when I try to update an existing record.

I can manually add a relationship/record (dummy data) or within the Flask view function as follows:

```<code>s = Set.query.get(2)
p = Product.query.get(3)
a = Set_Product_Association(set=s, product=p, quantity=23)
db.session.add(a)
db.session.commit()
</code>```

Updating the record (different quantity) manually as follows works:

```<code>s.products[0].quantity = 43
db.session.add(s)
db.session.commit()
</code>```

However when I use the code from the first block instead (with the aim to update the quantity field for a given, existing set and product ID), i.e.:

```<code>a = Set_Product_Association(set=s, product=p, quantity=43)
</code>```

I get an integrity error

```<code>sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: set_product_association.set_id, set_product_association.product_id [SQL: 'INSERT INTO set_product_association (set_id, product_id, quantity) VALUES (?, ?, ?)'] [parameters: (2, 3, 43)]
</code>```

I assume this is to tell me that I'm trying to append a new record rather than updating the existing one.

How should I approach this? The 'manual' method works but relies on working out the correct index in the list (i.e. for the correct product.id).

Curiously, if I use form.popluate_obj(set) in my Flask view function to process the form data as described in my question here, I can update fields but not create new 'associations'. Unfortunately, I don't know what goes on behind the scenes there....

My models are defined like so:

```<code>class Set_Product_Association(db.Model):
    __tablename__ = 'set_product_association'

    set_id = db.Column(db.Integer, db.ForeignKey('sets.id'), primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), primary_key=True)

    quantity = db.Column(db.Integer)

    product = db.relationship("Product", back_populates="sets")
    set = db.relationship("Set", back_populates="products")

class Set(db.Model):
    __tablename__ = 'sets'

    id = db.Column(db.Integer, primary_key=True)
    products = db.relationship("Set_Product_Association",
                                        back_populates="set")

class Product(db.Model):
    __tablename__= 'products'

    id = db.Column(db.Integer, primary_key=True)
    part_number = db.Column(db.String(100), unique=True, nullable=False)
    sets = db.relationship("Set_Product_Association",
                                     back_populates="product")
</code>```

Edit:
I've also tried reversing the operation as suggested here:

```<code>s = Set.query.get(2)
a = Set_Product_Association()
a.quantity = 43
a.product = Product.query.get(3)
a.set = s
db.session.commit()
</code>```

But I still get an error:

```<code>sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: set_product_association.set_id, set_product_association.product_id [SQL: 'INSERT INTO set_product_association (set_id, product_id, quantity) VALUES (?, ?, ?)'] [parameters: (2, 3, 43)]
</code>```

答:
You get an integrity error because you are trying to create a new object with the same primary keys.

This:

```<code>a = Set_Product_Association(set=s, product=p, quantity=43)
</code>```

Does not update, but create.

If you want to update the actual row in the table, you need to update the existing one:

```<code>assoc = Set_Product_Association.query.filter_by(set=s, product=p).first()
assoc.quantity = 43
db.session.commit()
</code>```

Also, from the documentation it is advised to not use a model but an actual table.

Body:
In my application, a 'set' can have a number of 'products' associated with it. Products listed against a set must have quantities defined. For this many-to-many relationship I have followed the SQLAlchemy documentation to use an association table with an additional column (quantity).

I am trying to create a form where the user can assign products and quantities against a given set. Both the sets and products already exist in the database. The data from the form are:

set.id

product.id

quantity

This works to create a new association (e.g. set 1 is 'linked' to product 3 with quantity=XYZ) but I get an integrity error when I try to update an existing record.

I can manually add a relationship/record (dummy data) or within the Flask view function as follows:

s = Set.query.get(2)
p = Product.query.get(3)
a = Set_Product_Association(set=s, product=p, quantity=23)
db.session.add(a)
db.session.commit()

Updating the record (different quantity) manually as follows works:

s.products[0].quantity = 43
db.session.add(s)
db.session.commit()

However when I use the code from the first block instead (with the aim to update the quantity field for a given, existing set and product ID), i.e.:

a = Set_Product_Association(set=s, product=p, quantity=43)

I get an integrity error

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: set_product_association.set_id, set_product_association.product_id [SQL: 'INSERT INTO set_product_association (set_id, product_id, quantity) VALUES (?, ?, ?)'] [parameters: (2, 3, 43)]

I assume this is to tell me that I'm trying to append a new record rather than updating the existing one.

How should I approach this? The 'manual' method works but relies on working out the correct index in the list (i.e. for the correct product.id).

Curiously, if I use form.popluate_obj(set) in my Flask view function to process the form data as described in my question here, I can update fields but not create new 'associations'. Unfortunately, I don't know what goes on behind the scenes there....

My models are defined like so:

class Set_Product_Association(db.Model):
    __tablename__ = 'set_product_association'

    set_id = db.Column(db.Integer, db.ForeignKey('sets.id'), primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), primary_key=True)

    quantity = db.Column(db.Integer)

    product = db.relationship("Product", back_populates="sets")
    set = db.relationship("Set", back_populates="products")

class Set(db.Model):
    __tablename__ = 'sets'

    id = db.Column(db.Integer, primary_key=True)
    products = db.relationship("Set_Product_Association",
                                        back_populates="set")

class Product(db.Model):
    __tablename__= 'products'

    id = db.Column(db.Integer, primary_key=True)
    part_number = db.Column(db.String(100), unique=True, nullable=False)
    sets = db.relationship("Set_Product_Association",
                                     back_populates="product")

Edit:
I've also tried reversing the operation as suggested here:

s = Set.query.get(2)
a = Set_Product_Association()
a.quantity = 43
a.product = Product.query.get(3)
a.set = s
db.session.commit()

But I still get an error:

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: set_product_association.set_id, set_product_association.product_id [SQL: 'INSERT INTO set_product_association (set_id, product_id, quantity) VALUES (?, ?, ?)'] [parameters: (2, 3, 43)]

Body:
You get an integrity error because you are trying to create a new object with the same primary keys.

This:

a = Set_Product_Association(set=s, product=p, quantity=43)

Does not update, but create.

If you want to update the actual row in the table, you need to update the existing one:

assoc = Set_Product_Association.query.filter_by(set=s, product=p).first()
assoc.quantity = 43
db.session.commit()

Also, from the documentation it is advised to not use a model but an actual table.


问:
A non-relational embedded database with a permissive free software license?
many thanks in advance for taking the time to look at my question.

(I am aware of this question Nonrelational Databases for C++, but my needs are a bit different and it only has one answer.)

I am developing a commercial C++ library that must, among other things, persist messages. I would like to avoid reinventing the wheel by writing my own DBMS. Unfortunately, I have the following restricting criteria:

It must be usable from C++ - I'm writing a C++ library. Bindings are potentially acceptable, if the level of effort to make them work isn't too high.

I need an embedded database. Stand-alone will not work.

I want to avoid a relational database. In addition to concerns about performance overhead, there are technical politics beyond my control as a developer that discourage a relational database.

I need a permissive free software license. It'll be hard to buy licenses, but the client doesn't want to give his source away.

I'd like a solution that's established (been around for at least a little while, beyond the experimental stage, has been used by several projects).

Sadly, the two go-to choices don't work because of the above:
-SQLite is relational
-BerkeleyDB is GPL or commercial

Again, thanks for any help.

答: Both Tokyo Cabinet and QDBM are LGPL and have C APIs.</p>


答:
You converted num to an int and stored it in val, but then you ignored that and inserted the original, num, in your list. Since it is a string, Python will take the minimum sorted alphabetically, so "10" is less than "2".

To fix it you just need to insert val in your list instead.

```<code>    val = int(num)
    if val:
        list1.append(val)
</code>```

Title: Print largest and smallest number in python

Body:
You converted num to an int and stored it in val, but then you ignored that and inserted the original, num, in your list. Since it is a string, Python will take the minimum sorted alphabetically, so "10" is less than "2".

To fix it you just need to insert val in your list instead.

    val = int(num)
    if val:
        list1.append(val)


问:
using the same Dockerfile to build images with different python version
I have a python script that I'd want to run on 2 different containers running python 2.7 and python 3.6.

I want to use the same docker file to build 2 different images, with the difference being the python version(i.e one time it's FROM python:3.6 and the other is FROM python:2.7, and do it through a makefile.

Makefile

```<code>.PHONY = all clean build run

all: build run

# DOCKER TASKS
# Build the container
build: ## Build the container for tests
        docker build -t myscript:python2.7 .
        docker build -t myscript:python3.6 .
run: ## Run container
        docker run myscript:python2.7
        docker run myscript:python3.6
</code>```

I have a Dockerfile for building the image:
Dockerfile

```<code>FROM python:3.6

WORKDIR /usr/local/bin
RUN pip install pytest
COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]
</code>```

Since it's the same Docker file it's tricky, I was thinking to create two different Dockerfiles each with a different python version (and all the rest the same), but was wondering if there's more elegant way to do it.

thanks

答:
You can use a build argument for it.

Your Dockerfile should look like this:

```<code>ARG VERSION=3.6

FROM python:3.6

WORKDIR /usr/local/bin
RUN pip install pytest
COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]
</code>```

To build for 3.6:

```<code>docker build -t python-app:3.6 .
</code>```

To build for 2.7:

```<code>docker build -t python-app:2.7 --build-arg VERSION=2.7 .
</code>```

Note that 3.6 is the default version in case you don't specify one (ARG VERSION=3.6). You can also not assign a default value in which case you have to always pass a value in the build argument (--build-arg VERSION=...)

Body:
I have a python script that I'd want to run on 2 different containers running python 2.7 and python 3.6.

I want to use the same docker file to build 2 different images, with the difference being the python version(i.e one time it's FROM python:3.6 and the other is FROM python:2.7, and do it through a makefile.

Makefile

.PHONY = all clean build run

all: build run

# DOCKER TASKS
# Build the container
build: ## Build the container for tests
        docker build -t myscript:python2.7 .
        docker build -t myscript:python3.6 .
run: ## Run container
        docker run myscript:python2.7
        docker run myscript:python3.6

I have a Dockerfile for building the image:
Dockerfile

FROM python:3.6

WORKDIR /usr/local/bin
RUN pip install pytest
COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]

Since it's the same Docker file it's tricky, I was thinking to create two different Dockerfiles each with a different python version (and all the rest the same), but was wondering if there's more elegant way to do it.

thanks

Body:
You can use a build argument for it.

Your Dockerfile should look like this:

ARG VERSION=3.6

FROM python:3.6

WORKDIR /usr/local/bin
RUN pip install pytest
COPY myscript.py test_regex_script.py ./

CMD ["pytest", "test_regex_script.py"]

To build for 3.6:

docker build -t python-app:3.6 .

To build for 2.7:

docker build -t python-app:2.7 --build-arg VERSION=2.7 .

Note that 3.6 is the default version in case you don't specify one (ARG VERSION=3.6). You can also not assign a default value in which case you have to always pass a value in the build argument (--build-arg VERSION=...)