问:
ReactJS - Fade between 2 different components
I am trying to figure out how to fade between 2 different components with a nice easy 1 second transition.  I have played around with SwitchTransition and CSSTransition and TransitionGroup and nothing seems to work quite right for me.  It looks like SwitchTransition is what I am looking for but the only examples I can find they are just swapping out text and not whole components.

So here is the code for my two components which are shown conditionally based on state variables.  Each component has a button that will swap the state variable values so it will currently swap between the two, but it doesn't look real pretty.

```<code><div className="login col-md-6 mt-5 mx-auto">
  {showLogin && (
    <LoginForm
      onLoginSubmit={onLoginSubmit}
      email={email}
      setEmail={setEmail}
      password={password}
      setPassword={setPassword}
      showPasswordReset={showPasswordReset}
    />
  )}
  {showForgotPassword && (
    <ForgotPasswordForm
      onPasswordResetSubmit={onPasswordResetSubmit}
      setShowForgotPassword={setShowForgotPassword}
    />
  )}
</div>
</code>```

答:
You can use react-spring to animate your components, first

```<code>import { animated, useTransition } from "react-spring";
</code>```

then inside your component

```<code>const [showLogin, set] = useState(false);

const toggle = () => {
    set(!showLogin);
};

const transitions = useTransition(showLogin, null, {
        from: { position: "absolute", opacity: 0 },
        enter: { opacity: 1 },
        leave: { opacity: 0 }
      });
</code>```

and then you will render your components, make sure to replace div with animated.div

```<code><div className="login col-md-6 mt-5 mx-auto">
    {transitions.map(({ item, key, props }) =>
        item ? (
            <LoginForm //animated.div
                onLoginSubmit={onLoginSubmit}
                email={email}
                setEmail={setEmail}
                password={password}
                setPassword={setPassword}
                showPasswordReset={showPasswordReset}
            />
        ) : (
            <ForgotPasswordForm //animated.div
                onPasswordResetSubmit={onPasswordResetSubmit}
                setShowForgotPassword={toggle}
            />
        )
    )}
</div>
</code>```

I made a simple example, you can check it out here

Body:
I am trying to figure out how to fade between 2 different components with a nice easy 1 second transition.  I have played around with SwitchTransition and CSSTransition and TransitionGroup and nothing seems to work quite right for me.  It looks like SwitchTransition is what I am looking for but the only examples I can find they are just swapping out text and not whole components.

So here is the code for my two components which are shown conditionally based on state variables.  Each component has a button that will swap the state variable values so it will currently swap between the two, but it doesn't look real pretty.

  {showLogin && (
    <LoginForm
      onLoginSubmit={onLoginSubmit}
      email={email}
      setEmail={setEmail}
      password={password}
      setPassword={setPassword}
      showPasswordReset={showPasswordReset}
    />
  )}
  {showForgotPassword && (
    <ForgotPasswordForm
      onPasswordResetSubmit={onPasswordResetSubmit}
      setShowForgotPassword={setShowForgotPassword}
    />
  )}

Body:
You can use react-spring to animate your components, first

import { animated, useTransition } from "react-spring";

then inside your component

const [showLogin, set] = useState(false);

const toggle = () => {
    set(!showLogin);
};

const transitions = useTransition(showLogin, null, {
        from: { position: "absolute", opacity: 0 },
        enter: { opacity: 1 },
        leave: { opacity: 0 }
      });

and then you will render your components, make sure to replace div with animated.div

<div className="login col-md-6 mt-5 mx-auto">
    {transitions.map(({ item, key, props }) =>
        item ? (
            <LoginForm //animated.div
                onLoginSubmit={onLoginSubmit}
                email={email}
                setEmail={setEmail}
                password={password}
                setPassword={setPassword}
                showPasswordReset={showPasswordReset}
            />
        ) : (
            <ForgotPasswordForm //animated.div
                onPasswordResetSubmit={onPasswordResetSubmit}
                setShowForgotPassword={toggle}
            />
        )
    )}
</div>

I made a simple example, you can check it out here


来源: stackexchange

问:
number of php query results does not match terminal results from Oracle's Toad
I got the fix but I need the explanation why and leaving this as a references for other people:

The Problem is we got this view, say A, that is built upon another view B. If you do a select * from view A, you get say 37 records. Great, now if you run this via PHP adobdb, it gives you 525 records!

The reason why this happened as it turns out, thanks to my coworkers, is because view B have this funky line that PHP ignores but TOAD doesn't:

```<code>          AND p.created_on > TO_DATE ('23-SEP-10')
</code>```

The fix was:

```<code>          AND p.created_on > TO_DATE ('2010/09/23', 'YYYY/MM/DD')
</code>```

Summary:
If your php query results does not match your terminal results then try this solution.

答:
The bug was this line:

```<code>      AND p.created_on > TO_DATE ('23-SEP-10')
</code>```

The fix is:

```<code>      AND p.created_on > TO_DATE ('2010/09/23', 'YYYY/MM/DD')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got the fix but I need the explanation why and leaving this as a references for other people:

The Problem is we got this view, say A, that is built upon another view B. If you do a select * from view A, you get say 37 records. Great, now if you run this via PHP adobdb, it gives you 525 records!

The reason why this happened as it turns out, thanks to my coworkers, is because view B have this funky line that PHP ignores but TOAD doesn't:

          AND p.created_on > TO_DATE ('23-SEP-10')

The fix was:

          AND p.created_on > TO_DATE ('2010/09/23', 'YYYY/MM/DD')

Summary:
If your php query results does not match your terminal results then try this solution.

Body:
The bug was this line:

      AND p.created_on > TO_DATE ('23-SEP-10')

The fix is:

      AND p.created_on > TO_DATE ('2010/09/23', 'YYYY/MM/DD')


问:
2D array to populate combobox
I am trying to populate a combobox from 2D array. I want it the first dimension to be assigned as DisplayMember values, and the second as ValueMemeber. Have been looking online, but I could not find a solution that would work for me. Below is the code that I am trying to use. This does not work.

```<code>string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };

cboOption.DataSource = Options;
</code>```

I have tried using a for loop and it does not work either and I get this error message: "Items collection cannot be modified when the DataSource property is set." Example below:

```<code>string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };

cboOption.DisplayMember = "Text";
cboOption.ValueMember = "Key";

for (int i = 0; i < Options.GetLength(0); i++)
{
    cboOption.Items.Add(new { Text = Options[i, 0], Key=Convert.ToInt16(Options[i, 1]) });
}
</code>```

Can I do that? If I can could you give me an example.

Thank you

答:
Thanks to @gmiley for the advise. After trying all the different options came up with a solution.

So I created a class Options instead of the array

```<code>    public class Options
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }
</code>```

Then I used the code below to populate combobox

```<code>        var items = new List<Options>
        {
            new Options() { Name="Invoice", Value=3},
            new Options() { Name="Group Invoice", Value=4},
            new Options() { Name="Group Invoice BUCKS", Value=5},
        };

        cboOption.DataSource = items;
        cboOption.DisplayMember = "Name";
        cboOption.ValueMember = "Value";
</code>```

ContentLicense: CC BY-SA 4.0

Title: 2D array to populate combobox

Body:
I am trying to populate a combobox from 2D array. I want it the first dimension to be assigned as DisplayMember values, and the second as ValueMemeber. Have been looking online, but I could not find a solution that would work for me. Below is the code that I am trying to use. This does not work.

string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };

cboOption.DataSource = Options;

I have tried using a for loop and it does not work either and I get this error message: "Items collection cannot be modified when the DataSource property is set." Example below:

string[,] Options = new string[3, 2]{
        {"Invoice", "3"},
        {"Group Invoice", "4"},
        {"Group Invoice BUCKS", "5"} };

cboOption.DisplayMember = "Text";
cboOption.ValueMember = "Key";

for (int i = 0; i < Options.GetLength(0); i++)
{
    cboOption.Items.Add(new { Text = Options[i, 0], Key=Convert.ToInt16(Options[i, 1]) });
}

Can I do that? If I can could you give me an example.

Thank you

Body:
Thanks to @gmiley for the advise. After trying all the different options came up with a solution.

So I created a class Options instead of the array

    public class Options
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }

Then I used the code below to populate combobox

        var items = new List<Options>
        {
            new Options() { Name="Invoice", Value=3},
            new Options() { Name="Group Invoice", Value=4},
            new Options() { Name="Group Invoice BUCKS", Value=5},
        };

        cboOption.DataSource = items;
        cboOption.DisplayMember = "Name";
        cboOption.ValueMember = "Value";


问:
In operation for StringExpression
I am working on SpringBoot with JPA repository. I am using querydsl for dynamic search criteria.

I am able to implement equals, not equals, like commands.The only issue is with "IN " expression.

Like

```<code>public BooleanExpression like(String str)
</code>```

Which is working fine. Can anyone suggest to me what I have to use for "IN"

Thanks,
Sri.

答:
BooleanExpression is a SimpleExpression which has a method public BooleanExpression in(T... right) that takes a set of values and public BooleanExpression in(Expression<? extends T>... right) that takes a set of expressions.

You can wrap any Expression in a SimpleExpression using its constructor: new SimpleExpression<>(expression).

Title: In operation for StringExpression

Body:
I am working on SpringBoot with JPA repository. I am using querydsl for dynamic search criteria.

I am able to implement equals, not equals, like commands.The only issue is with "IN " expression.

Like

public BooleanExpression like(String str)

Which is working fine. Can anyone suggest to me what I have to use for "IN"

Thanks,
Sri.


问:
Spring JPA CriteriaQuery child entity columns
I am trying to make some dynamic mechanism to fetch data from db using criteria query based on given class, specification, select columns, aggregated columns and group by columns.

Here's the code which is working fine:

```<code>    public <T> List<T> findDataByConfiguration(Specification<T> specification,
        Class clazz, List<String> selectColumns,
        List<String> aggregationColumns, List<String> groupByColumns) {
        CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
        Root<T> root = query.from(clazz);

        List<Selection<?>> multiSelectColumns = new ArrayList<>();
        for (String s : selectColumns) {
            multiSelectColumns.add(root.get(s).alias(s));
        }

        for (String s : aggregationColumns) {
            multiSelectColumns.add(criteriaBuilder.sum(root.get(s)).alias(s));
        }

        List<Expression<?>> groupByColumnsList = new ArrayList<>();
        for (String s : groupByColumns) {
            groupByColumnsList.add(root.get(s));
        }

        query.groupBy(groupByColumnsList);
        query.multiselect(multiSelectColumns);
        query.where(specification.toPredicate(root, query, criteriaBuilder));

        List<Tuple> resultList = this.entityManager.createQuery(query).getResultList();

        // resultList processing
    }
</code>```

This code is working fine when when I want to fetch data of flat entity class.
But when I am trying to add child entiti'es field in select/aggregate/group by then it's throwing an error:

java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [child.id] on this ManagedType [com.sup.as.data.entity.co.Annual]

```<code>// annotations
public class Annual {
    private Long id;
    private String fp;
    private ID iDetails;
    // getter-setter
}

public class ID {
    private Long id;
    private BigDecimal amount;
    // getter-setter

    public String giveMeData() {
        if(id != null && amount != null) {
            return "FILED";
        } else {
            return "NOT FILED";
        }
    }
}
</code>```

now suppose I want field Annual.id, Annual.fp, SUM(Annual.iDetails.amount), Annual.iDetails.giveMeData

So is it possible to add child entities columns in select/aggregate/group by ?
If anyone have done this type of solution then please help me to resolve this.

答:
If some of column names are dot-separated (for instance, child.id) you have to use root.get("child").get("id") instead of root.get("child.id")

You need method like this

```<code>private Path<Object> getPath(Root<?> root, String columnPath) {

    if(!columnPath.contains(".")) {
       return root.get(columnPath);
    }

    String[] levels = columnPath.split(".");
    Path<T> path = root;
    for(String level : levels) {
        path = path.get(level);
    }

    return path;
}
</code>```

Then use it for selectColumns, aggregationColumns and groupByColumns this way

```<code>for (String s : selectColumns) {
   multiSelectColumns.add(getPath(root, s).alias(s));
}
</code>```

Body:
I am trying to make some dynamic mechanism to fetch data from db using criteria query based on given class, specification, select columns, aggregated columns and group by columns.

Here's the code which is working fine:

    public <T> List<T> findDataByConfiguration(Specification<T> specification,
        Class clazz, List<String> selectColumns,
        List<String> aggregationColumns, List<String> groupByColumns) {
        CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
        Root<T> root = query.from(clazz);

        List<Selection<?>> multiSelectColumns = new ArrayList<>();
        for (String s : selectColumns) {
            multiSelectColumns.add(root.get(s).alias(s));
        }

        for (String s : aggregationColumns) {
            multiSelectColumns.add(criteriaBuilder.sum(root.get(s)).alias(s));
        }

        List<Expression<?>> groupByColumnsList = new ArrayList<>();
        for (String s : groupByColumns) {
            groupByColumnsList.add(root.get(s));
        }

        query.groupBy(groupByColumnsList);
        query.multiselect(multiSelectColumns);
        query.where(specification.toPredicate(root, query, criteriaBuilder));

        List<Tuple> resultList = this.entityManager.createQuery(query).getResultList();

        // resultList processing
    }

This code is working fine when when I want to fetch data of flat entity class.
But when I am trying to add child entiti'es field in select/aggregate/group by then it's throwing an error:

java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [child.id] on this ManagedType [com.sup.as.data.entity.co.Annual]

// annotations
public class Annual {
    private Long id;
    private String fp;
    private ID iDetails;
    // getter-setter
}

public class ID {
    private Long id;
    private BigDecimal amount;
    // getter-setter

    public String giveMeData() {
        if(id != null && amount != null) {
            return "FILED";
        } else {
            return "NOT FILED";
        }
    }
}

now suppose I want field Annual.id, Annual.fp, SUM(Annual.iDetails.amount), Annual.iDetails.giveMeData

So is it possible to add child entities columns in select/aggregate/group by ?
If anyone have done this type of solution then please help me to resolve this.

Body:
If some of column names are dot-separated (for instance, child.id) you have to use root.get("child").get("id") instead of root.get("child.id")

You need method like this

private Path<Object> getPath(Root<?> root, String columnPath) {

    if(!columnPath.contains(".")) {
       return root.get(columnPath);
    }

    String[] levels = columnPath.split(".");
    Path<T> path = root;
    for(String level : levels) {
        path = path.get(level);
    }

    return path;
}

Then use it for selectColumns, aggregationColumns and groupByColumns this way

for (String s : selectColumns) {
   multiSelectColumns.add(getPath(root, s).alias(s));
}


问:
Backgound service or webservers of Ansible?
is there any background service or webservers that are used by ansible? like chef we have background services like nginx, solar, rabbit. is ansible use any webservers or background services?</p>

答:
No, there are no services required other then ssh on the target server. Some modules might require specific librarys installed (most often encountered with community supported modules)

https://docs.ansible.com/ansible/latest/dev_guide/overview_architecture.html#ansible-architecture

It uses no agents and no additional custom security infrastructure, so it’s easy to deploy


问:
PHP automatic binding of $this, is it a copy or an extend?
When using an anonymous PHP function that is defined inside a class context, the docs say "the current class is automatically bound to it, making $this available inside of the function's scope".

But I'm a little confused what that means, does it mean the anonymous function has a copy of the class or is it now part of the class? So if I use the anonymous function to make changes to the class, they will stay in the original class where the anonymous function was defined?

答:
$this variable inside anonymous function in PHP is not a copy, is a binding, so if you alter the content of $this inside the anonymous function, the parent class would be affected.

You can check it running this snippet:

```<code>class Foo
{
    private $test = 1;

    function __construct()
    {
        $func = function() {
            $this->test = 2;
        };
        $func();
        var_dump($this);
    }
};

new Foo();
</code>```

Body:
$this variable inside anonymous function in PHP is not a copy, is a binding, so if you alter the content of $this inside the anonymous function, the parent class would be affected.

You can check it running this snippet:

class Foo
{
    private $test = 1;

    function __construct()
    {
        $func = function() {
            $this->test = 2;
        };
        $func();
        var_dump($this);
    }
};

new Foo();


问:
React exporting context returns Parsing error: Export 'SearchContextConsumer' is not defined
I am trying to create a context in order to pass data to another component without using props drilling, but when I export my consumer I get that Parsing error: Export 'SearchContextConsumer' is not defined
What seems to be the problem and how can I export it successfully?

Here is my code:

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

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    SearchContext = React.createContext('context');
    SearchContextConsumer = SearchContext.Consumer;
    data = { searchResults: this.state.searchResults }

    Search = ({ children }) => (
        <SearchContext.Provider value={searchResults}>{children}</SearchContext.Provider>
    )

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <div>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </div>
        );
    }
}

export { SearchContextConsumer }
export default Search;

</code>```

答:
This looks uneccessary complicated to me. Why don't you straight up export the created context and wrap the children
in the Provider directly:

```<code>import React, { Component } from "react";
import axios from "axios";
</code>```

export const SearchContext = React.createContext();

```<code>class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    data = { searchResults: this.state.searchResults }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <SearchContext.Provider value={searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>
        );
    }
}

export default Search;
</code>```

Components which want to use the context will have to be wrapped inside the Consumer:

```<code>import {SearchContext} from "Search"

<SearchContext.Consumer>
  {value => /* render something based on the context value */}
</SearchContext.Consumer>
</code>```

Body:
I am trying to create a context in order to pass data to another component without using props drilling, but when I export my consumer I get that Parsing error: Export 'SearchContextConsumer' is not defined
What seems to be the problem and how can I export it successfully?

Here is my code:

import React, { Component } from "react";
import axios from "axios";

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    SearchContext = React.createContext('context');
    SearchContextConsumer = SearchContext.Consumer;
    data = { searchResults: this.state.searchResults }

    Search = ({ children }) => (
        <SearchContext.Provider value={searchResults}>{children}</SearchContext.Provider>
    )

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (

                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />

        );
    }
}

export { SearchContextConsumer }
export default Search;

Body:
This looks uneccessary complicated to me. Why don't you straight up export the created context and wrap the children
in the Provider directly:

import React, { Component } from "react";
import axios from "axios";

export const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    data = { searchResults: this.state.searchResults }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        return (
            <SearchContext.Provider value={searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>
        );
    }
}

export default Search;

Components which want to use the context will have to be wrapped inside the Consumer:

import {SearchContext} from "Search"

<SearchContext.Consumer>
  {value => /* render something based on the context value */}
</SearchContext.Consumer>


问:
Converting separate month, day and year values into a timestamp
I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.

How can I give this to strtotime() in a way it can convert it to a timestamp?

答:
You can provide it to function strtotime() in many ways, as mentioned in documentation. Some examples include:

```<code>$your_time = strtotime('12/31/2011 9:59');
$your_time = strtotime('2011-12-31 9:59');
$your_time = strtotime('December 31, 2011 9:59');
</code>```

etc. It really is very flexible.

You can find the list of valid formats in the documentation, and that is (from the "Compound Formats" list in the mentioned documentation) for example:

10/Oct/2000:13:55:36 -0700,

2008:08:07 18:11:31,

2008-08-07 18:11:31,

2008-07-01T22:35:17.02,

2008-07-01T22:35:17.03+08:00,

20080701T22:38:07,

20080701T9:38:07,

20080701t223807,

20080701T093807,

2008-7-1T9:3:37,

(this is really copy of the documentation)

Body:
You can provide it to function strtotime() in many ways, as mentioned in documentation. Some examples include:

$your_time = strtotime('12/31/2011 9:59');
$your_time = strtotime('2011-12-31 9:59');
$your_time = strtotime('December 31, 2011 9:59');

etc. It really is very flexible.

You can find the list of valid formats in the documentation, and that is (from the "Compound Formats" list in the mentioned documentation) for example:

10/Oct/2000:13:55:36 -0700,

2008:08:07 18:11:31,

2008-08-07 18:11:31,

2008-07-01T22:35:17.02,

2008-07-01T22:35:17.03+08:00,

20080701T22:38:07,

20080701T9:38:07,

20080701t223807,

20080701T093807,

2008-7-1T9:3:37,

(this is really copy of the documentation)


问:
Compare Nested Objects and save difference in new object using Javascript
I have two Javascript objects

```<code>var order1 = {
    sandwich: 'tuna',
    chips: true,
    drink: 'soda',
    order: 1,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 20, PreferredFlag: false, SupportedFlag: true}],
    details: {
        name: 'Chris',
        phone: '555-555-5555',
        email: 'no@thankyou.com'
    },
    otherVal1: '1'
};

var order2 = {
    sandwich: 'turkey',
    chips: true,
    drink: 'soda',
    order: 2,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: false}, {VendorNumber: 20, PreferredFlag: true, SupportedFlag: true}],
    details: {
        name: 'Jon',
        phone: '(555) 555-5555',
        email: 'yes@please.com'
    },
    otherVal1: '2'
};
</code>```

What I need is to compare these two objects (order1 is existing and order2 is the edited data) and store the difference in a new variable named var order3. However if there is an array inside an object like the toppings array to be copied as whole with the changes.

In short the result should be

```<code>{
  details: {
    email: "yes@please.com",
    name: "Jon",
    phone: "(555) 555-5555"
  },
  order: 2,
  otherVal1: "2",
  sandwich: "turkey",
  toppings: [{
  PreferredFlag: false,
  SupportedFlag: true,
  VendorNumber: 18
}, {
  PreferredFlag: false,
  SupportedFlag: false,
  VendorNumber: 19
}, {
  PreferredFlag: true,
  SupportedFlag: true,
  VendorNumber: 20
}]
}
</code>```

How can i achieve this ?

答:
This gives you exactly what you wanted:</p>

```<code>function diff(tgt, src) {

    if (Array.isArray(tgt)) { // if you got array
        return tgt; // just copy it
    }

    // if you got object
    var rst = {};
    for (var k in tgt) { // visit all fields
        if (typeof src[k] === "object") { // if field contains object (or array because arrays are objects too)
            rst[k] = diff(tgt[k], src[k]); // diff the contents
        } else if (src[k] !== tgt[k]) { // if field is not an object and has changed
            rst[k] = tgt[k]; // use new value
        }
        // otherwise just skip it
    }
    return rst;
}
console.log(diff(order2, order1));
</code>```

Body:
I have two Javascript objects

var order1 = {
    sandwich: 'tuna',
    chips: true,
    drink: 'soda',
    order: 1,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 20, PreferredFlag: false, SupportedFlag: true}],
    details: {
        name: 'Chris',
        phone: '555-555-5555',
        email: 'no@thankyou.com'
    },
    otherVal1: '1'
};

var order2 = {
    sandwich: 'turkey',
    chips: true,
    drink: 'soda',
    order: 2,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: false}, {VendorNumber: 20, PreferredFlag: true, SupportedFlag: true}],
    details: {
        name: 'Jon',
        phone: '(555) 555-5555',
        email: 'yes@please.com'
    },
    otherVal1: '2'
};

What I need is to compare these two objects (order1 is existing and order2 is the edited data) and store the difference in a new variable named var order3. However if there is an array inside an object like the toppings array to be copied as whole with the changes.

In short the result should be

{
  details: {
    email: "yes@please.com",
    name: "Jon",
    phone: "(555) 555-5555"
  },
  order: 2,
  otherVal1: "2",
  sandwich: "turkey",
  toppings: [{
  PreferredFlag: false,
  SupportedFlag: true,
  VendorNumber: 18
}, {
  PreferredFlag: false,
  SupportedFlag: false,
  VendorNumber: 19
}, {
  PreferredFlag: true,
  SupportedFlag: true,
  VendorNumber: 20
}]
}

How can i achieve this ?

Body:
This gives you exactly what you wanted:

function diff(tgt, src) {

    if (Array.isArray(tgt)) { // if you got array
        return tgt; // just copy it
    }

    // if you got object
    var rst = {};
    for (var k in tgt) { // visit all fields
        if (typeof src[k] === "object") { // if field contains object (or array because arrays are objects too)
            rst[k] = diff(tgt[k], src[k]); // diff the contents
        } else if (src[k] !== tgt[k]) { // if field is not an object and has changed
            rst[k] = tgt[k]; // use new value
        }
        // otherwise just skip it
    }
    return rst;
}
console.log(diff(order2, order1));


问:
regex check if text between two strings contains a certain word
I have the following text:

Best Content Marketing Tips to Make Your Website Standout from the Rest

I need to find out with regex if text between the words "Best" and "Rest" contains word "marketing":

My formula is as follows: (?<=Best|)(marketing?)(?=Rest).

This formula works only if I want to find a word exactly before the "Rest", which in this case is "the ".

How do I make it to search if any word between two specified strings matches my Keyword?

答:
Maybe something like:

```<code>\b[Bb]est\b.*\b[Mm]arketing\b.*\b[Rr]est\b
</code>```

or instead of character classes set case insensitive flag first:

```<code>(?i)\bbest\b.*\bmarketing\b.*\brest\b
</code>```

I've used word boundaries just to prevent Best and Rest or Marketing from being substrings.

Body:
Maybe something like:

\b[Bb]est\b.*\b[Mm]arketing\b.*\b[Rr]est\b

or instead of character classes set case insensitive flag first:

(?i)\bbest\b.*\bmarketing\b.*\brest\b

I've used word boundaries just to prevent Best and Rest or Marketing from being substrings.


问:
Questions about using @eq and @paginate in same query for data search
Here is my DB tables:

Here is my query :

```<code>products(
        product_id: String! @eq
        orderBy: _ @orderBy(columns: ["created_at", "product_id"])
    ): [Product!]! @paginate(defaultCount: 10)
</code>```

First question is  :

I need to pass it like this

```<code>products( product_id: "" or null )
</code>```

And it will return nothings from db. But i want to return all data when "product_id" get empty string or null.

Is there any ways to ignore "product_id" when the "product_id" get empty string or null?

Second question is :

As you see the DB tables
If i want to do a query to search "products" table with "product name" which is in "product_langs" table.
@eq seems not support in this case. Is there any suggestion for this case?

Or i need to create a query with custom search and paginate? If yes, how can i do it? Is there any example about how to create custom paginate and search?

Thanks and regards!

答:
I can't try it out at the moment so it's untested.
Please note that I'm a newbie and only providing suggestions as this has been unanswered for a little while.

Regarding your first question, try removing ! and see what happens. That should be worth a try.

```<code>
product_id: String! @eq
product_id: String @eq

</code>```

You could also try this
https://lighthouse-php.com/master/eloquent/complex-where-conditions.html

For your second questions I believe this is what you are looking for.

https://lighthouse-php.com/master/eloquent/complex-where-conditions.html#wherehasconditions

Say you are defining a relationship productLang on your Product model in eloquent.

```<code>
products(
        hasProductLang: _ @whereHasConditions(columns: ["product_name"])
        orderBy: _ @orderBy(columns: ["created_at", "product_id"])
    ): [Product!]! @paginate(defaultCount: 10)

</code>```

```<code>
products(hasProductLang: { column: PRODUCT_NAME, operator: EQ, value: $searchString })

</code>```

Body:
Here is my DB tables:

Here is my query :

products(
        product_id: String! @eq
        orderBy: _ @orderBy(columns: ["created_at", "product_id"])
    ): [Product!]! @paginate(defaultCount: 10)

First question is  :

I need to pass it like this

products( product_id: "" or null )

And it will return nothings from db. But i want to return all data when "product_id" get empty string or null.

Is there any ways to ignore "product_id" when the "product_id" get empty string or null?

Second question is :

As you see the DB tables
If i want to do a query to search "products" table with "product name" which is in "product_langs" table.
@eq seems not support in this case. Is there any suggestion for this case?

Or i need to create a query with custom search and paginate? If yes, how can i do it? Is there any example about how to create custom paginate and search?

Thanks and regards!

Body:
I can't try it out at the moment so it's untested.
Please note that I'm a newbie and only providing suggestions as this has been unanswered for a little while.

Regarding your first question, try removing ! and see what happens. That should be worth a try.

product_id: String! @eq
product_id: String @eq

You could also try this
https://lighthouse-php.com/master/eloquent/complex-where-conditions.html

For your second questions I believe this is what you are looking for.

https://lighthouse-php.com/master/eloquent/complex-where-conditions.html#wherehasconditions

Say you are defining a relationship productLang on your Product model in eloquent.

products(
        hasProductLang: _ @whereHasConditions(columns: ["product_name"])
        orderBy: _ @orderBy(columns: ["created_at", "product_id"])
    ): [Product!]! @paginate(defaultCount: 10)

products(hasProductLang: { column: PRODUCT_NAME, operator: EQ, value: $searchString })


问:
How can I subscribe a dynamic topic in graphql?
I have a graphql subscription in nodejs as below:

```<code>const resolvers = {
    Query: () => { ... },
    Mutation: () => { ... },
    Subscription: {
        commentAdded: {
          subscribe: withFilter(
            () => pubsub.asyncIterator('COMMENT_ADDED'),
            (payload, variables) => {
             return payload.commentAdded.repository_name === variables.repoFullName;
            },
          ),
        }
    },
};
</code>```

You can see the topic this subscription uses is COMMENT_ADDED which is a hard coded string. I am wondering whether I can create a dynamic topic name based on user request.

Something like below code. It subscribes the topic with payload.id as its suffix. How can I do this in apollo server?

```<code>subscribe: withFilter(
            (payload) => pubsub.asyncIterator('COMMENT_ADDED:'+payload.id),
            (payload, variables) => {
             return payload.commentAdded.repository_name === variables.repoFullName;
            },
          ),
</code>```

答: The first function passed to withFilter is the subscribe function, which is what determines the value of the payload. So it cannot be passed the payload as a parameter. The function is passed four parameters, the same as any root resolver -- the root value, the field's arguments, the context and a GraphQLResolveInfo object.

Body:
I have a graphql subscription in nodejs as below:

const resolvers = {
    Query: () => { ... },
    Mutation: () => { ... },
    Subscription: {
        commentAdded: {
          subscribe: withFilter(
            () => pubsub.asyncIterator('COMMENT_ADDED'),
            (payload, variables) => {
             return payload.commentAdded.repository_name === variables.repoFullName;
            },
          ),
        }
    },
};

You can see the topic this subscription uses is COMMENT_ADDED which is a hard coded string. I am wondering whether I can create a dynamic topic name based on user request.

Something like below code. It subscribes the topic with payload.id as its suffix. How can I do this in apollo server?

subscribe: withFilter(
            (payload) => pubsub.asyncIterator('COMMENT_ADDED:'+payload.id),
            (payload, variables) => {
             return payload.commentAdded.repository_name === variables.repoFullName;
            },
          ),


问:
Call sql script using bat file
It is necessary to use the bat file to call the sql script and pass two variables into it, but sql complains about them. Asks to declare scalars.

Here is the bat file itself.

```<code>@ECHO OFF
echo SET @arg1 := %2, @arg2 := %3; > commands
copy /b commands + %1 + %2 > nul
"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\sqlcmd.exe" -S DESKTOP-OQ8JGR5 -U SA -P 123 -i %1
</code>```

And sql script.

```<code>USE MVA
SELECT sum(number*price2 - number*price1) AS pribil FROM sale,goods
WHERE id=goods AND datepart(month, date)=@arg1 AND shop=@ar2
</code>```

答:
you can create a stored procedure and call that via sqlcmd from the bat file. for example:

```<code>create procedure [SP_count_up]
(
@input int
)
as
begin
    select @input + 1
end
go
</code>```

and call it in you bat file via

```<code>sqlcmd -Q "exec dbo.SP_count_up @input=3" -S <server> -d <database>
</code>```

Title: Call sql script using bat file

Body:
It is necessary to use the bat file to call the sql script and pass two variables into it, but sql complains about them. Asks to declare scalars.

Here is the bat file itself.

@ECHO OFF
echo SET @arg1 := %2, @arg2 := %3; > commands
copy /b commands + %1 + %2 > nul
"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\sqlcmd.exe" -S DESKTOP-OQ8JGR5 -U SA -P 123 -i %1

And sql script.

USE MVA
SELECT sum(number*price2 - number*price1) AS pribil FROM sale,goods
WHERE id=goods AND datepart(month, date)=@arg1 AND shop=@ar2

Body:
you can create a stored procedure and call that via sqlcmd from the bat file. for example:

create procedure [SP_count_up]
(
@input int
)
as
begin
    select @input + 1
end
go

and call it in you bat file via

sqlcmd -Q "exec dbo.SP_count_up @input=3" -S <server> -d <database>


问:
What is the proper way to retrieve all class definitions that contain a specific mixin?
I'm working on a django application, and I want to create a mixin that will always be applied to model definitions. The functionality added by the mixin isn't important for the question.

However, I need to be able to retrieve a list of all the class definitions that inherit from this mixin. These classes can be in different apps within the django project.

Possible answers I've found so far are:

How to find all the subclasses of a class given its name?

How to auto register a class when it's defined

I'm mostly wondering what the best method would be to accomplish this goal.

答:
Typically the way you would get a list of all the classes that inherit a particular class would be by registering the classes with a meta-class (as is explained in one of the questions you have linked). Django models however use their own meta class to achieve a lot of what they do automatically. I wouldn't recommend adding another meta-class into the mix - things could go wrong here!!

Fortunately however, django has something called the content-types framework  which is essentially a registry of all of your models in a particular project.

To get a list of all of your models you can do this:

```<code>from django.contrib.contenttypes.models import ContentType

content_types = ContentType.objects.all()
</code>```

This won't get the actual models, but rather a queryset of ContentType instances. To then get the model classes from this you can do

```<code>models = [x.model_class() for x in content_types]
</code>```

So we now have a list of models. Then we can just filter the list down to those models which inherit your mixin:

```<code>models_with_mixin = [x for x in models if issubclass(x, MyMixin)]
</code>```

We can simplify all of the above into the following:

```<code>from django.contrib.contenttypes.models import ContentType

models_with_mixin = [
    x.model_class()
    for x in ContentType.objects.all()
    if issubclass(x.model_class(), MyMixin)
]
</code>```

Body:
Typically the way you would get a list of all the classes that inherit a particular class would be by registering the classes with a meta-class (as is explained in one of the questions you have linked). Django models however use their own meta class to achieve a lot of what they do automatically. I wouldn't recommend adding another meta-class into the mix - things could go wrong here!!

Fortunately however, django has something called the content-types framework  which is essentially a registry of all of your models in a particular project.

To get a list of all of your models you can do this:

from django.contrib.contenttypes.models import ContentType

content_types = ContentType.objects.all()

This won't get the actual models, but rather a queryset of ContentType instances. To then get the model classes from this you can do

models = [x.model_class() for x in content_types]

So we now have a list of models. Then we can just filter the list down to those models which inherit your mixin:

models_with_mixin = [x for x in models if issubclass(x, MyMixin)]

We can simplify all of the above into the following:

from django.contrib.contenttypes.models import ContentType

models_with_mixin = [
    x.model_class()
    for x in ContentType.objects.all()
    if issubclass(x.model_class(), MyMixin)
]


问:
How to debug or print in Flutter web?
I'm using Flutter 1.10.15 and Android Studio 3.5.1 for  Flutter Web development and my big! problem is I can't debug and even I can't print something in console because only a white page is displayed in chrome when I press "run" or "debug" button in toolbar.

The only way I can run project is in web-server mode with following command and showing variable values and exceptions in AlertDialog popup!:

```<code>flutter run -d web-server --web-hostname=192.168.50.147 --web-port=5624 --local-engine=host_debug_unopt --profile -v lib\pages\splash.dart
</code>```

Can anyone tell me a solution?

答:
```<code>Flutter Channel beta, 1.18.0-11.1.pre
</code>```

You can print in the console and also debug in Android Studio and Chrome at the same time.

In order to do so, you need to select Chrome (web) from the dropdown. Web Server (web) doesn't work for me.

Hit the Debug button and wait the for the new window to be opened.

Put the breakpoint in AS, not in Chrome.

Open Chrome's Developer tools.

Hit the plus button or whatever to hit your breatpoint.

Inspect the Dart code in Chrome.

And btw, print prints in both Chrome's and AS's consoles.

Title: How to debug or print in Flutter web?

Body:
I'm using Flutter 1.10.15 and Android Studio 3.5.1 for  Flutter Web development and my big! problem is I can't debug and even I can't print something in console because only a white page is displayed in chrome when I press "run" or "debug" button in toolbar.

The only way I can run project is in web-server mode with following command and showing variable values and exceptions in AlertDialog popup!:

flutter run -d web-server --web-hostname=192.168.50.147 --web-port=5624 --local-engine=host_debug_unopt --profile -v lib\pages\splash.dart

Can anyone tell me a solution?

Body:
Flutter Channel beta, 1.18.0-11.1.pre

You can print in the console and also debug in Android Studio and Chrome at the same time.

In order to do so, you need to select Chrome (web) from the dropdown. Web Server (web) doesn't work for me.

Hit the Debug button and wait the for the new window to be opened.

Put the breakpoint in AS, not in Chrome.

Open Chrome's Developer tools.

Hit the plus button or whatever to hit your breatpoint.

Inspect the Dart code in Chrome.

And btw, print prints in both Chrome's and AS's consoles.


问:
ESP8266: Mismatch between generated example binaries using gen_appbin.py utility
I use the official ESP8266 SDK v3.0.0: https://github.com/espressif/ESP8266_NONOS_SDK/releases/tag/v3.0.3 and, seems I found some inconsistency in a RAW content of generated binaries.

As I understand the SDK generates the ready FW .bin file from the *.elf file using the 'gen_appbin.py'  script (delivered with SDK): https://github.com/espressif/ESP8266_NONOS_SDK/blob/release/v3.0.0/tools/gen_appbin.py#L224

This script contains the following code:

```<code>if boot_mode == '2':
    // write irom bin head
    data_bin = struct.pack('<BBBBI',BIN_MAGIC_IROM,4,0,app,long(entry_addr,16))
    sum_size = len(data_bin)
    write_file(flash_bin_name,data_bin) // <<< **HERE IN FIRST TIME**

    //irom0.text.bin
    combine_bin(irom0text_bin_name,flash_bin_name,0x0,0)
if boot_mode == '1':
     data_bin = struct.pack('<BBBBI',BIN_MAGIC_FLASH,3,0,app,long(entry_addr,16))
else:
     data_bin = struct.pack('<BBBBI',BIN_MAGIC_FLASH,3,byte2,byte3,long(entry_addr,16))
sum_size = len(data_bin)
write_file(flash_bin_name,data_bin) // <<< **HERE IN SECOND TIME**
</code>```

As you can see, this code writes the 'data_bin' pattern (aka "EA 04 00 01 ...") to the resulting FW binary twice.

So, when I compile any example (e.g. AT example), then I see in a generated FW two this patterns.

BUT, a problem is that the provided AT example binaries (in SDK): https://github.com/espressif/ESP8266_NONOS_SDK/tree/release/v3.0.0/bin/at/1024%2B1024

contains only one this "EA 04 00 01 ..." patern.

So, my question is: What happens? Is the 'gen_appbin.py' utility has a bugs?

PS: I have creates an issue here: https://github.com/espressif/ESP8266_NONOS_SDK/issues/313

答: Sorry, my fault. All there are fine. Just somehow my output binary had duplicates of own content.</p>

Body:
I use the official ESP8266 SDK v3.0.0: https://github.com/espressif/ESP8266_NONOS_SDK/releases/tag/v3.0.3 and, seems I found some inconsistency in a RAW content of generated binaries.

As I understand the SDK generates the ready FW .bin file from the *.elf file using the 'gen_appbin.py'  script (delivered with SDK): https://github.com/espressif/ESP8266_NONOS_SDK/blob/release/v3.0.0/tools/gen_appbin.py#L224

This script contains the following code:

if boot_mode == '2':
    // write irom bin head
    data_bin = struct.pack('<BBBBI',BIN_MAGIC_IROM,4,0,app,long(entry_addr,16))
    sum_size = len(data_bin)
    write_file(flash_bin_name,data_bin) // <<< **HERE IN FIRST TIME**

    //irom0.text.bin
    combine_bin(irom0text_bin_name,flash_bin_name,0x0,0)
if boot_mode == '1':
     data_bin = struct.pack('<BBBBI',BIN_MAGIC_FLASH,3,0,app,long(entry_addr,16))
else:
     data_bin = struct.pack('<BBBBI',BIN_MAGIC_FLASH,3,byte2,byte3,long(entry_addr,16))
sum_size = len(data_bin)
write_file(flash_bin_name,data_bin) // <<< **HERE IN SECOND TIME**

As you can see, this code writes the 'data_bin' pattern (aka "EA 04 00 01 ...") to the resulting FW binary twice.

So, when I compile any example (e.g. AT example), then I see in a generated FW two this patterns.

BUT, a problem is that the provided AT example binaries (in SDK): https://github.com/espressif/ESP8266_NONOS_SDK/tree/release/v3.0.0/bin/at/1024%2B1024

contains only one this "EA 04 00 01 ..." patern.

So, my question is: What happens? Is the 'gen_appbin.py' utility has a bugs?

PS: I have creates an issue here: https://github.com/espressif/ESP8266_NONOS_SDK/issues/313


问:
can't able to mock a variable while testing
I am trying testing on node js I want to mock a variable outside of a function that is going to be unit tested.
for example

```<code>const sample = [];
function uploadDoc {
sample.push('fileLocation')
}
function toSave(){
for (i=0;i<sample.length;i++)
**some process read and access doc
}
</code>```

I am facing issue while unit testing the second function
I have tried rewire npm that is also not working

答:
Programming likes this will work,You should call uploadDoc firstly.</p>

```<code>const sample = [];
    function uploadDoc {
    sample.push('fileLocation')
}
function toSave(){
    uploadDoc();
    for (var i=0;i<sample.length;i++)
    **some process read and access doc
}
</code>```

Body:
I am trying testing on node js I want to mock a variable outside of a function that is going to be unit tested.
for example

const sample = [];
function uploadDoc {
sample.push('fileLocation')
}
function toSave(){
for (i=0;i<sample.length;i++)
**some process read and access doc
}

I am facing issue while unit testing the second function
I have tried rewire npm that is also not working

Body:
Programming likes this will work,You should call uploadDoc firstly.

const sample = [];
    function uploadDoc {
    sample.push('fileLocation')
}
function toSave(){
    uploadDoc();
    for (var i=0;i<sample.length;i++)
    **some process read and access doc
}


问:
What's the procedure to re-download locally deleted files using SFTP Inbound
As per this doc couldn't find the right process to re-downloading a locally removed file from remote SFTP.

The requirement is, to delete local file which already been fetched from remote SFTP and use sftp-inbound-adapter (DSL configuration) to re-fetch that same file when required. In this implementation, MetadataStore haven't been persisted into any external system like PropertiesPersistingMetadataStore or Redis Metadata Store. So as per doc, MetadataStore stored in In-Memory.

Couldn't find any way to remove meta data of that remote file from MetadataStore to re-fetch the locally deleted file using file_name. And don't have any clue, how should this removeRemoteFileMetadata() callback needs to be implemented (according to this doc).

Configuration class contain followings:

```<code>    @Bean
    public IntegrationFlow fileFlow() {
        SftpInboundChannelAdapterSpec spec = Sftp.inboundAdapter(sftpConfig.getSftpSessionFactory())
                .preserveTimestamp(true)
                .patternFilter(Constants.FILE_NAME_CONVENTION)
                .remoteDirectory(sftpConfig.getSourceLocation())
                .autoCreateLocalDirectory(true)
                .deleteRemoteFiles(false)
                .localDirectory(new File(sftpConfig.getDestinationLocation()));

        return IntegrationFlows
                .from(spec, e -> e.id("sftpInboundAdapter").autoStartup(false)
                        .poller(Pollers.fixedDelay(5000).get()))
                .channel(MessageChannels.direct().get())
                .handle(message -> {
                    log.info("Fetching File : " + message.getHeaders().get("file_name").toString());
                })
                .get();
    }
</code>```

答:
I tried to solve this and I used Tanvir Hossain's reference code. I coded like this.

```<code>@Bean
public IntegrationFlow fileFlow() {
    SftpInboundChannelAdapterSpec spec = Sftp
            .inboundAdapter(sftpConfig.getSftpSessionFactory())
            .preserveTimestamp(true)
            .filter(sftpFileListFilter())
            .localFilter(systemFileListFilter())
            .remoteDirectory(sftpConfig.getSourceLocation())
            .autoCreateLocalDirectory(true)
            .deleteRemoteFiles(false)
            .localDirectory(new File(sftpConfig.getDestinationLocation()));

    return IntegrationFlows
            .from(spec, e -> e.id("sftpInboundAdapter").autoStartup(false)
                    .poller(Pollers.fixedDelay(5000).get()))
            .channel(MessageChannels.direct().get())
            .handle(message -> {
                log.info("Fetching File : "
                        + message.getHeaders().get("file_name").toString());
            })
            .get();
}

private FileSystemPersistentAcceptOnceFileListFilter systemFileListFilter() {

    return new FileSystemPersistentAcceptOnceFileListFilter(store(), prefix);
}

private ChainFileListFilter<ChannelSftp.LsEntry> sftpFileListFilter() {

    ChainFileListFilter<ChannelSftp.LsEntry> chainFileListFilter =
                                                new ChainFileListFilter<>();
    chainFileListFilter.addFilters(
            new SftpPersistentAcceptOnceFileListFilter(store(), prefix),
            new SftpSimplePatternFileListFilter(sftpConfig.getFileFilterValue())
    );
    return chainFileListFilter;
}

@Bean
public SimpleMetadataStore store() {
    return new SimpleMetadataStore();
}
</code>```

and my Controller for removing metadata is like below :

```<code>public class Controller {

    private final SimpleMetadataStore simpleMetadataStore;

    public Controller(SimpleMetadataStore simpleMetadataStore) {

           this.simpleMetadataStore = simpleMetadataStore;

    }

    @GetMapping("/test/remove-metadata/{type}/{fileName}")
    @ResponseBody
    public String removeFileMetadata(
             @PathVariable("fileName") String fileName,
             @PathVariable("type") String type
    ) {
        String prefix = definedPrefix;
        String filePath = "";
        if(type.equals("local")){
            filePath = "/local/storage/path/" + fileName;
        }else if(type.equals("remote")){
            filePath = fileName
        }
        String key = prefix + filePath;

        simpleMetadataStore.remove(key);
        return key;
    }

}
</code>```

I am getting my desired file. It is re-fetching file for me.

Body:
As per this doc couldn't find the right process to re-downloading a locally removed file from remote SFTP.

The requirement is, to delete local file which already been fetched from remote SFTP and use sftp-inbound-adapter (DSL configuration) to re-fetch that same file when required. In this implementation, MetadataStore haven't been persisted into any external system like PropertiesPersistingMetadataStore or Redis Metadata Store. So as per doc, MetadataStore stored in In-Memory.

Couldn't find any way to remove meta data of that remote file from MetadataStore to re-fetch the locally deleted file using file_name. And don't have any clue, how should this removeRemoteFileMetadata() callback needs to be implemented (according to this doc).

Configuration class contain followings:

    @Bean
    public IntegrationFlow fileFlow() {
        SftpInboundChannelAdapterSpec spec = Sftp.inboundAdapter(sftpConfig.getSftpSessionFactory())
                .preserveTimestamp(true)
                .patternFilter(Constants.FILE_NAME_CONVENTION)
                .remoteDirectory(sftpConfig.getSourceLocation())
                .autoCreateLocalDirectory(true)
                .deleteRemoteFiles(false)
                .localDirectory(new File(sftpConfig.getDestinationLocation()));

        return IntegrationFlows
                .from(spec, e -> e.id("sftpInboundAdapter").autoStartup(false)
                        .poller(Pollers.fixedDelay(5000).get()))
                .channel(MessageChannels.direct().get())
                .handle(message -> {
                    log.info("Fetching File : " + message.getHeaders().get("file_name").toString());
                })
                .get();
    }

Body:
I tried to solve this and I used Tanvir Hossain's reference code. I coded like this.

@Bean
public IntegrationFlow fileFlow() {
    SftpInboundChannelAdapterSpec spec = Sftp
            .inboundAdapter(sftpConfig.getSftpSessionFactory())
            .preserveTimestamp(true)
            .filter(sftpFileListFilter())
            .localFilter(systemFileListFilter())
            .remoteDirectory(sftpConfig.getSourceLocation())
            .autoCreateLocalDirectory(true)
            .deleteRemoteFiles(false)
            .localDirectory(new File(sftpConfig.getDestinationLocation()));

    return IntegrationFlows
            .from(spec, e -> e.id("sftpInboundAdapter").autoStartup(false)
                    .poller(Pollers.fixedDelay(5000).get()))
            .channel(MessageChannels.direct().get())
            .handle(message -> {
                log.info("Fetching File : "
                        + message.getHeaders().get("file_name").toString());
            })
            .get();
}

private FileSystemPersistentAcceptOnceFileListFilter systemFileListFilter() {

    return new FileSystemPersistentAcceptOnceFileListFilter(store(), prefix);
}

private ChainFileListFilter<ChannelSftp.LsEntry> sftpFileListFilter() {

    ChainFileListFilter<ChannelSftp.LsEntry> chainFileListFilter =
                                                new ChainFileListFilter<>();
    chainFileListFilter.addFilters(
            new SftpPersistentAcceptOnceFileListFilter(store(), prefix),
            new SftpSimplePatternFileListFilter(sftpConfig.getFileFilterValue())
    );
    return chainFileListFilter;
}

@Bean
public SimpleMetadataStore store() {
    return new SimpleMetadataStore();
}

and my Controller for removing metadata is like below :

public class Controller {

    private final SimpleMetadataStore simpleMetadataStore;

    public Controller(SimpleMetadataStore simpleMetadataStore) {

           this.simpleMetadataStore = simpleMetadataStore;

    }

    @GetMapping("/test/remove-metadata/{type}/{fileName}")
    @ResponseBody
    public String removeFileMetadata(
             @PathVariable("fileName") String fileName,
             @PathVariable("type") String type
    ) {
        String prefix = definedPrefix;
        String filePath = "";
        if(type.equals("local")){
            filePath = "/local/storage/path/" + fileName;
        }else if(type.equals("remote")){
            filePath = fileName
        }
        String key = prefix + filePath;

        simpleMetadataStore.remove(key);
        return key;
    }

}

I am getting my desired file. It is re-fetching file for me.


问:
How to add navigation menu for interactive report?
I have created an interactive report without choosing a new navigation menu option. Now I want to add a new navigation menu on the left side for my interactive report which I have created. How can I achieve it?

Thanks

答: The navigation menu is just a list. You can go to "Shared Components" > "Lists", and open it there. Alternatively, it will be visible from the page builder. In the page builder for that page, in the left pane, the far right tab says "Page Shared Components". The navigation is under "Lists" > "Page Navigation". That will open the list region for that page. Click the ">" icon next to "Source" to edit the list.</p>


问:
F# broken in VS build tools 2019 16.6.0
After installing this version, nothing that touches F# will build, everything throws the same exception:

```<code>error FS0193: Could not load file or assembly System.Buffers, Version=4.0.3.0, blablabla..
</code>```

Apparently it's nothing to do with what I'm building. Even trying to execute let x = 3 in fsi.exe has the same problem.

Anyone else had this problem?

答:
Yes, this is a known problem, see https://github.com/dotnet/fsharp/issues/9295.

While the next fix isn't out yet, you can resolve it by manually copying the missing assemblies. The exact list of missing assemblies is mentioned in this comment. The cause was explained by Kevin Ransom to be that the Setup for MSBuild didn't get the new dependencies for fsc.exe.

Note that FSI from within Visual Studio shouldn't have this issue, nor should building from within Visual Studio 2019. The way I understand it, only the MSBuild Tools are affected.

For posterity, in case the links go dead, the workaround in the Github issue is to just copy the dlls over:

```<code>copy "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\PublicAssemblies\*.dll" "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp"
</code>```

Edit: the source path given above may not always be correct, depending on what versions of VS you've installed. Alternatively, try:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\PublicAssemblies

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\PublicAssemblies

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\PublicAssemblies

If you only want to copy the minimal set that's needed, just copy only these files, that's the diff set:

```<code>System.Buffers.dll
System.Memory.dll
System.Numerics.Vectors.dll
System.Reflection.Metadata.dll
System.Resources.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.Threading.Tasks.Dataflow.dll
</code>```

Title: F# broken in VS build tools 2019 16.6.0

Body:
After installing this version, nothing that touches F# will build, everything throws the same exception:

error FS0193: Could not load file or assembly System.Buffers, Version=4.0.3.0, blablabla..

Apparently it's nothing to do with what I'm building. Even trying to execute let x = 3 in fsi.exe has the same problem.

Anyone else had this problem?

Body:
Yes, this is a known problem, see https://github.com/dotnet/fsharp/issues/9295.

While the next fix isn't out yet, you can resolve it by manually copying the missing assemblies. The exact list of missing assemblies is mentioned in this comment. The cause was explained by Kevin Ransom to be that the Setup for MSBuild didn't get the new dependencies for fsc.exe.

Note that FSI from within Visual Studio shouldn't have this issue, nor should building from within Visual Studio 2019. The way I understand it, only the MSBuild Tools are affected.

For posterity, in case the links go dead, the workaround in the Github issue is to just copy the dlls over:

copy "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\PublicAssemblies\*.dll" "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp"

Edit: the source path given above may not always be correct, depending on what versions of VS you've installed. Alternatively, try:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\PublicAssemblies

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\PublicAssemblies

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\PublicAssemblies

If you only want to copy the minimal set that's needed, just copy only these files, that's the diff set:

System.Buffers.dll
System.Memory.dll
System.Numerics.Vectors.dll
System.Reflection.Metadata.dll
System.Resources.Extensions.dll
System.Runtime.CompilerServices.Unsafe.dll
System.Threading.Tasks.Dataflow.dll


问:
TelecomManager.ACTION_CHANGE_DEFAULT_DIALER returns RESULT_CANCELED on huawei P8 Lite
I want to change Android default dialer and want to make my own customized dialer. For this purpose I have choose this  GIthub repo as start up project. This works well on all other phone and stops working on huawei p8 lite. The default pop up message does not shows up for setting the app as default.
Here is code block

private fun checkDefaultDialer() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return

    val telecomManager = getSystemService(TELECOM_SERVICE) as TelecomManager
    val isAlreadyDefaultDialer = packageName == telecomManager.defaultDialerPackage
    if (isAlreadyDefaultDialer) return

    val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName)
    startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}

private fun checkSetDefaultDialerResult(resultCode: Int) {
    val message = when (resultCode) {
        RESULT_OK -> "User accepted request to become default dialer"
        RESULT_CANCELED -> "User declined request to become default dialer"
        else -> "Unexpected result code $resultCode"
    }
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
```
<p><code>StertActivityforResult</code> returns with <code>RESULT_CANCELED</code> and message</p>
```User declined request to become default dialer
```

Can't find any solution for this. Any help will be greatly appreciated.

答: You'll also get a RESULT_CANCELED when targeting Android Q or higher, as the PermissionPolicyService removes the Action. You should use RoleManager.createRequestRoleIntent() instead.</p>

Body:
I want to change Android default dialer and want to make my own customized dialer. For this purpose I have choose this  GIthub repo as start up project. This works well on all other phone and stops working on huawei p8 lite. The default pop up message does not shows up for setting the app as default.
Here is code block

private fun checkDefaultDialer() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return

    val telecomManager = getSystemService(TELECOM_SERVICE) as TelecomManager
    val isAlreadyDefaultDialer = packageName == telecomManager.defaultDialerPackage
    if (isAlreadyDefaultDialer) return

    val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName)
    startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}

private fun checkSetDefaultDialerResult(resultCode: Int) {
    val message = when (resultCode) {
        RESULT_OK -> "User accepted request to become default dialer"
        RESULT_CANCELED -> "User declined request to become default dialer"
        else -> "Unexpected result code $resultCode"
    }
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

StertActivityforResult returns with RESULT_CANCELED and message

User declined request to become default dialer

Can't find any solution for this. Any help will be greatly appreciated.


问:
Unstacking a column into several columns with differing number of rows
I have a data frame with two columns:

```<code>dat_test <- data.frame(code     = c("A", "A", "A", "A", "B", "B", "B", "C", "C"),
                       response = c("A", "AA", "AB", "ABC", "BC", "AB", "B", "CDE", "BC"),
                       stringsAsFactors = FALSE)

dat_test

  code response  n
1    A        A 69
2    A       AA 85
3    A       AB 10
4    A      ABC 87
5    B       BC  3
6    B       AB 79
7    B        B 50
8    C      CDE 81
9    C       BC 32
</code>```

I now want to unstack/pivot_wider this data in a way (ideally in the tidyverse), where the code column is reshaped into three columns and rows would just be values from the response column. There is no logical link between the three codes, i.e. there is no identifier that would tell me which response of code "A" would belong to the same row for code "B" and "C", respectively.

So basically I just want three columns that lists all the responses as rows with everything else filled as NAs.

I tried tidyr's pivot_wider, but failed. I saw that there are some parameters in the pivot_wider function, likes values_fill and values_fn, but I don#t know if I could use these to get the desired behaviour.

Expected outcome would be:

```<code># A tibble: 4 x 3
  A     B     C
  <chr> <chr> <chr>
1 A     BC    CDE
2 AA    AB    BC
3 AB    B     NA
4 ABC   NA    NA
</code>```

Any ideas?

I guess I could first create an additional id column that goes from 1:4 for code "A", 1:3 for code "B" and 1:2 for code "C", but not sure how I could do this dynamically for any other data set (i.e. with a different number of codes and responses per code). But once I have such an id column, the pivoting should work.

答:
Oh my, nevermind (can be closed).

Creating the id was simple enough. This code works like a charme:

```<code>dat_test %>%
  group_by(code) %>%
  mutate(id = 1:n()) %>%
  ungroup() %>%
  pivot_wider(names_from = "code", values_from = "response")
</code>```

and gives:

```<code># A tibble: 4 x 4
     id A     B     C
  <int> <chr> <chr> <chr>
1     1 A     BC    CDE
2     2 AA    AB    BC
3     3 AB    B     NA
4     4 ABC   NA    NA
</code>```

Body:
I have a data frame with two columns:

dat_test <- data.frame(code     = c("A", "A", "A", "A", "B", "B", "B", "C", "C"),
                       response = c("A", "AA", "AB", "ABC", "BC", "AB", "B", "CDE", "BC"),
                       stringsAsFactors = FALSE)

dat_test

  code response  n
1    A        A 69
2    A       AA 85
3    A       AB 10
4    A      ABC 87
5    B       BC  3
6    B       AB 79
7    B        B 50
8    C      CDE 81
9    C       BC 32

I now want to unstack/pivot_wider this data in a way (ideally in the tidyverse), where the code column is reshaped into three columns and rows would just be values from the response column. There is no logical link between the three codes, i.e. there is no identifier that would tell me which response of code "A" would belong to the same row for code "B" and "C", respectively.

So basically I just want three columns that lists all the responses as rows with everything else filled as NAs.

I tried tidyr's pivot_wider, but failed. I saw that there are some parameters in the pivot_wider function, likes values_fill and values_fn, but I don#t know if I could use these to get the desired behaviour.

Expected outcome would be:

# A tibble: 4 x 3
  A     B     C
  <chr> <chr> <chr>
1 A     BC    CDE
2 AA    AB    BC
3 AB    B     NA
4 ABC   NA    NA

Any ideas?

I guess I could first create an additional id column that goes from 1:4 for code "A", 1:3 for code "B" and 1:2 for code "C", but not sure how I could do this dynamically for any other data set (i.e. with a different number of codes and responses per code). But once I have such an id column, the pivoting should work.

Body:
Oh my, nevermind (can be closed).

Creating the id was simple enough. This code works like a charme:

dat_test %>%
  group_by(code) %>%
  mutate(id = 1:n()) %>%
  ungroup() %>%
  pivot_wider(names_from = "code", values_from = "response")

and gives:

# A tibble: 4 x 4
     id A     B     C
  <int> <chr> <chr> <chr>
1     1 A     BC    CDE
2     2 AA    AB    BC
3     3 AB    B     NA
4     4 ABC   NA    NA


问:
To move Folder from one location to another in WSO2 EI 6.1.1
I have developed API which is used to download images to local path with Specific Folder name which works fine. My requirement here is to move folder with Files(Images) to SFTP Location. Nothing happened, File resides in the same Input path. Can anyone please help me?

Download Folder Name: Stock001 which has image File(.jpg )

Proxy Code:

VFS:

```<code><?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="SFTP_Proxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log level="custom">
            <property name="STATUS:" value="---------SFTP Proxy Invoked-------------------"/>
         </log>
      </inSequence>
      <outSequence/>
      <faultSequence/>
   </target>
   <parameter name="transport.PollInterval">15</parameter>
   <parameter name="transport.vfs.FileURI">file:///D:/Test/CarSalesStockImages/Input/</parameter>
   <parameter name="transport.vfs.ContentType">text/plain</parameter>
   <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
   <parameter name="transport.vfs.MoveAfterFailure">file:///D:/Test/CarSalesStockImages/Failed/</parameter>
   <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
   <parameter name="transport.vfs.FileNamePattern">.*.*</parameter>
   <parameter name="transport.vfs.MoveAfterProcess">vfs:sftp://test-dev:U46A0hTf2vhjytqq@3.109.0.212/wso2/QRSagProcess/VB/CarSalesStockImages</parameter>
   <description/>
</proxy>
</code>```

FileConnetor:

```<code><?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="SFTP_Proxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log level="custom">
            <property name="STATUS:" value="---------SFTP Proxy Invoked-------------------"/>
         </log>
         <fileconnector.copy>
            <source>file:///D:/Test/CarSalesStockImages/Input/</source>
            <destination>sftp://test-dev:pwd@ipaddress/wso2/QRSagProcess/VB/CarSalesStockImages/</destination>
         </fileconnector.copy>
         <log level="custom">
            <property name="STATUS:" value="---------File Copied-------------------"/>
         </log>
         <fileconnector.delete>
            <source>file:///D:/Test/CarSalesStockImages/Input/</source>
            <setUserDirIsRoot>true</setUserDirIsRoot>
         </fileconnector.delete>
         <log level="custom">
            <property name="STATUS:"
                      value="---------File Deleted from Source-------------------"/>
         </log>
         <fileconnector.create>
            <source>file:///D:/Test/CarSalesStockImages/Input/</source>
         </fileconnector.create>
      </inSequence>
      <outSequence/>
      <faultSequence>
         <log level="custom">
            <property name="STATUS:"
                      value="------------faultSequence Invoked----------------"/>
         </log>
         <log level="full"/>
      </faultSequence>
   </target>
   <description/>
</proxy>
</code>```

Error:

```<code>[2020-05-29 10:59:23,145] [] ERROR - VFSTransportListener Error resolving directory to move after processing : sftp://qrs-dev":***@"3.109.0.212/wso2/QRSagProcess/VB/CarSalesStockI
ages/
org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://test-dev:***@3.109.0.212/".
        at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:108)
        at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.getFileSystem(AbstractOriginatingFileProvider.java:155)
        at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:119)
        at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:88)
        at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:747)
        at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:626)
        at org.apache.synapse.transport.vfs.VFSTransportListener.moveOrDeleteAfterProcessing(VFSTransportListener.java:662)
        at org.apache.synapse.transport.vfs.VFSTransportListener.scanFileOrDirectory(VFSTransportListener.java:499)
        at org.apache.synapse.transport.vfs.VFSTransportListener.poll(VFSTransportListener.java:188)
        at org.apache.synapse.transport.vfs.VFSTransportListener.poll(VFSTransportListener.java:134)
        at org.apache.axis2.transport.base.AbstractPollingTransportListener$1$1.run(AbstractPollingTransportListener.java:67)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "3.105.0.247".
        at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:268)
        at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:97)
        ... 14 more
Caused by: com.jcraft.jsch.JSchException: Auth fail
        at com.jcraft.jsch.Session.connect(Session.java:512)
        at com.jcraft.jsch.Session.connect(Session.java:183)
        at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:264)
        ... 15 more
[2020-05-29 10:59:23,150] [] ERROR - VFSTransportListener File object 'file:///D:/Test/CarSalesStockImages/Input/Test.txt'cloud not be moved, will remain in "locked" state
</code>```

答:
Would you be able to verify the syntax of the destination? A sample I came across this: http://mrmalakasilva.blogspot.com/2016/07/automating-file-processing-with-wso2.html
Thanks,</p>

Body:
I have developed API which is used to download images to local path with Specific Folder name which works fine. My requirement here is to move folder with Files(Images) to SFTP Location. Nothing happened, File resides in the same Input path. Can anyone please help me?

Download Folder Name: Stock001 which has image File(.jpg )

Proxy Code:

VFS:

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="SFTP_Proxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log level="custom">
            <property name="STATUS:" value="---------SFTP Proxy Invoked-------------------"/>
         </log>
      </inSequence>
      <outSequence/>
      <faultSequence/>
   </target>
   <parameter name="transport.PollInterval">15</parameter>
   <parameter name="transport.vfs.FileURI">file:///D:/Test/CarSalesStockImages/Input/</parameter>
   <parameter name="transport.vfs.ContentType">text/plain</parameter>
   <parameter name="transport.vfs.ActionAfterProcess">MOVE</parameter>
   <parameter name="transport.vfs.MoveAfterFailure">file:///D:/Test/CarSalesStockImages/Failed/</parameter>
   <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
   <parameter name="transport.vfs.FileNamePattern">.*.*</parameter>
   <parameter name="transport.vfs.MoveAfterProcess">vfs:sftp://test-dev:U46A0hTf2vhjytqq@3.109.0.212/wso2/QRSagProcess/VB/CarSalesStockImages</parameter>
   <description/>
</proxy>

FileConnetor:

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="SFTP_Proxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log level="custom">
            <property name="STATUS:" value="---------SFTP Proxy Invoked-------------------"/>
         </log>
         <fileconnector.copy>
            <source>file:///D:/Test/CarSalesStockImages/Input/</source>
            <destination>sftp://test-dev:pwd@ipaddress/wso2/QRSagProcess/VB/CarSalesStockImages/</destination>
         </fileconnector.copy>
         <log level="custom">
            <property name="STATUS:" value="---------File Copied-------------------"/>
         </log>
         <fileconnector.delete>
            <source>file:///D:/Test/CarSalesStockImages/Input/</source>
            <setUserDirIsRoot>true</setUserDirIsRoot>
         </fileconnector.delete>
         <log level="custom">
            <property name="STATUS:"
                      value="---------File Deleted from Source-------------------"/>
         </log>
         <fileconnector.create>
            <source>file:///D:/Test/CarSalesStockImages/Input/</source>
         </fileconnector.create>
      </inSequence>
      <outSequence/>
      <faultSequence>
         <log level="custom">
            <property name="STATUS:"
                      value="------------faultSequence Invoked----------------"/>
         </log>
         <log level="full"/>
      </faultSequence>
   </target>
   <description/>
</proxy>

Error:

[2020-05-29 10:59:23,145] [] ERROR - VFSTransportListener Error resolving directory to move after processing : sftp://qrs-dev":***@"3.109.0.212/wso2/QRSagProcess/VB/CarSalesStockI
ages/
org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://test-dev:***@3.109.0.212/".
        at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:108)
        at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.getFileSystem(AbstractOriginatingFileProvider.java:155)
        at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:119)
        at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:88)
        at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:747)
        at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:626)
        at org.apache.synapse.transport.vfs.VFSTransportListener.moveOrDeleteAfterProcessing(VFSTransportListener.java:662)
        at org.apache.synapse.transport.vfs.VFSTransportListener.scanFileOrDirectory(VFSTransportListener.java:499)
        at org.apache.synapse.transport.vfs.VFSTransportListener.poll(VFSTransportListener.java:188)
        at org.apache.synapse.transport.vfs.VFSTransportListener.poll(VFSTransportListener.java:134)
        at org.apache.axis2.transport.base.AbstractPollingTransportListener$1$1.run(AbstractPollingTransportListener.java:67)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "3.105.0.247".
        at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:268)
        at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:97)
        ... 14 more
Caused by: com.jcraft.jsch.JSchException: Auth fail
        at com.jcraft.jsch.Session.connect(Session.java:512)
        at com.jcraft.jsch.Session.connect(Session.java:183)
        at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:264)
        ... 15 more
[2020-05-29 10:59:23,150] [] ERROR - VFSTransportListener File object 'file:///D:/Test/CarSalesStockImages/Input/Test.txt'cloud not be moved, will remain in "locked" state


问:
Issue with a loop which checks members in a Discord server
I'm pretty new to Python so this is very confusing to me. I'm trying to check all members in a list, where for every member it checks whether it is person A/person B or neither, and then does a certain thing based on whether it is that person or not. For some reason, when the first person checked is the same as the person it checks for, it says that all the following people are that person too.
The code is used to get rid of all members in a discord server except a few (for resetting after a minigame).

```<code>async def serverreset(ctx):
for member in ctx.message.guild.members:
    print(member)
    if member == "person1#1234" or "person2#2345":
        print(f"Unable to ban {member.display_name}")
    else:
        await member.ban(reason="Reset", delete_message_days=7)
        print(f"Banned {member.display_name}")
</code>```

Result of running the program:

```<code>person1#1234
Unable to ban person1
person2#2345
Unable to ban person2
accountthatshouldbebanned#5678
Unable to ban accountthatshouldbebanned
</code>```

答:
The expression member == "person1#1234" or "person2#2345"
is actually resolved as ( member == "person1#1234") or ("person2#2345) which will always evaluate to True.

You need to use
member == "person1#1234" or member == "person2#2345".

You can also use
member in ("person1#1234", "person2#2345")

Body:
I'm pretty new to Python so this is very confusing to me. I'm trying to check all members in a list, where for every member it checks whether it is person A/person B or neither, and then does a certain thing based on whether it is that person or not. For some reason, when the first person checked is the same as the person it checks for, it says that all the following people are that person too.
The code is used to get rid of all members in a discord server except a few (for resetting after a minigame).

async def serverreset(ctx):
for member in ctx.message.guild.members:
    print(member)
    if member == "person1#1234" or "person2#2345":
        print(f"Unable to ban {member.display_name}")
    else:
        await member.ban(reason="Reset", delete_message_days=7)
        print(f"Banned {member.display_name}")

Result of running the program:

person1#1234
Unable to ban person1
person2#2345
Unable to ban person2
accountthatshouldbebanned#5678
Unable to ban accountthatshouldbebanned


问:
how to connect expo app on my own phone to firebase?Is it possible?
I'm new to React native. Today I wanted to create a login and sign up page linked to firebase. I followed this tutorial  -https://www.youtube.com/watch?v=TkuQAjnaSbM&t=110s - word for word and found it very successful.

I installed the expo application on my ios phone and I get the builds from there. The only difference between us and the tutorial in the video is that it uses an android emulator and I get build on the expo application on my real phone. But the problem is that I cannot add new users to the firebase via the script. I also share the code. I would appreciate if you help.

```<code>handleSignUp=() => {
    firebase
    .auth()
    .createUserWithEmailAndPassword(this.state.email, this.state.password)
    .then(userCredentinals => {
            return userCredentinals.user.updateProfile({
                displayName: this.state.name
            });
    })
    .catch(error => this.setState({ errorMessage: error.messsage}));
};
</code>```

somehow I can't connect with firebase. but I'm sure I put the config code block in the right place. Maybe I am not authorized to write my own phone to the database I use as an emulator?

```<code><TouchableOpacity style={styles.button}>
                        <Text style={{color:"#FFF", fontWeight: "500"}}
                        onPress={this.handleSignUp}
                        onPress={() => this.props.navigation.navigate("Home")}
                        >Kayıt Ol</Text>
                    </TouchableOpacity>
</code>```

答:
Please update your function like this.

```<code>const handleSignUp = () => {
    console.log('Function is called');

    firebase
    .auth()
    .createUserWithEmailAndPassword(this.state.email, this.state.password)
    .then(userCredentinals => {
            console.log('Success');
            return userCredentinals.user.updateProfile({
                displayName: this.state.name
            });
    })
    .catch(error => {
       console.log(error);
       this.setState({ errorMessage: error.messsage});
    });
};
</code>```

Then please update your question with what you get displayed in the console. Then I will be able to help you to solve this problem.

Body:
I'm new to React native. Today I wanted to create a login and sign up page linked to firebase. I followed this tutorial  -https://www.youtube.com/watch?v=TkuQAjnaSbM&t=110s - word for word and found it very successful.

I installed the expo application on my ios phone and I get the builds from there. The only difference between us and the tutorial in the video is that it uses an android emulator and I get build on the expo application on my real phone. But the problem is that I cannot add new users to the firebase via the script. I also share the code. I would appreciate if you help.

handleSignUp=() => {
    firebase
    .auth()
    .createUserWithEmailAndPassword(this.state.email, this.state.password)
    .then(userCredentinals => {
            return userCredentinals.user.updateProfile({
                displayName: this.state.name
            });
    })
    .catch(error => this.setState({ errorMessage: error.messsage}));
};

somehow I can't connect with firebase. but I'm sure I put the config code block in the right place. Maybe I am not authorized to write my own phone to the database I use as an emulator?

<TouchableOpacity style={styles.button}>
                        <Text style={{color:"#FFF", fontWeight: "500"}}
                        onPress={this.handleSignUp}
                        onPress={() => this.props.navigation.navigate("Home")}
                        >Kayıt Ol</Text>
                    </TouchableOpacity>

Body:
Please update your function like this.

const handleSignUp = () => {
    console.log('Function is called');

    firebase
    .auth()
    .createUserWithEmailAndPassword(this.state.email, this.state.password)
    .then(userCredentinals => {
            console.log('Success');
            return userCredentinals.user.updateProfile({
                displayName: this.state.name
            });
    })
    .catch(error => {
       console.log(error);
       this.setState({ errorMessage: error.messsage});
    });
};

Then please update your question with what you get displayed in the console. Then I will be able to help you to solve this problem.


问:
Bullet points in jspdf
I'm trying to build a pdf page using jspdf, manually not from the html, I'm not able to get bullet points in the pdf page, I need the bullet before the text rendered like this doc.text('/bulletpoint/'+data,60,60); I've tried "u2022" for the bullet it doesn't work.

答:
Try this:</p>

```<code>doc.text('\u2022 ' + your text here);
</code>```

Title: Bullet points in jspdf

Body:
Try this:

doc.text('\u2022 ' + your text here);


问:
Python: joining 2 lists of the same size
Let's say I have 2 following lists:

list1 = [1,1,1,1]
list2 = [3,3,3,3]

I want the result of join to be:

list3 [4,4,4,4]

What's would be the best way to do it?

答:
```<code>list3 = [x + y for (x, y) in itertools.izip(list1, list2)]
</code>```

or

```<code>list3 = map(operator.add, list1, list2)
</code>```

Body:
list3 = [x + y for (x, y) in itertools.izip(list1, list2)]

or

list3 = map(operator.add, list1, list2)


问:
Prevent overlapping between 2 Experiments in Google Optimize?
Could you please help me with a rule that can exclude users that have already been exposed to one of other experiments in Google Optimize?

What is the best approach?

I am thinking about using 1st party cookie variable or some other custom variable that would mark the user as "exposed" so that another experiment will not affect him.

In addition I can use "run custom "JavaScript" in Optimize's visual editor that will create such a cookie. Will that solve the problem?

Also I can't understand how to prevent 2 experiments from running simultaneously. So that user who sees experiment A will not see experiment B or C (free version is limited to 3 experiments). Is there any rules or configuration that can help with that?

答:
When we create any experiment, google creates an experiment id which we can find in the details section. Also when an experiment is triggered for a user, it sets a _gaexp cookie which contains that experiment id (apart from other identifiers).

So, if you want to run two mutually exclusive experiments, all you need to do is exclude a user from the experiment if _gaexp contains the id of other. Here are the steps:

In audience targeting, add a rule and choose First-party cookie

Create a variable and set it's value to _gaexp

Choose the does not contain option and add other experiment's id in value

Save

Repeat the same steps for the other experiment


问:
How do you assign a value to different values in an array?
In this program I am putting values in an array those and the assign to those values a float number.
It should work like this:
Ex.

```<code>Formula name: Addition
how many unknown values?: 3
unknown value:x
unknown value:y
unknown value:z
enter the value of x: 2
enter the value of y: 3
enter the value of z:
</code>```

(instead of writing enter the value of y, in the second-last line, it writes enter the value of x again)
how can I fix it?
This is the code:

```<code>import math
name = input('Formula name: ')
unknown_values = int(input('how may unknown values?: '))
unknown_array = []
for i in range(unknown_values):
    unknown_name = input('unknown value:')
    unknown_array += [unknown_name]

values = []
x = -1
for i in range(len(unknown_array)):
    values[i] += [input('enter the value of ' + str(unknown_array[x+1] + ': '))]

print(values)
</code>```

答:
You aren't incrementing your x value inside of the second for loop, so it will always refer to the same element in unknown_array. In other words, in each iteration of the loop it will refer to unknown_array[0], or the first unknown you input, which in your example is x. You should add a line to increment this value in the loop.

A couple of other things:

values[i] += ... will produce an IndexError as these elements have not been initialized yet, I think you meant to write values += ... instead (or you can use .append rather than +=):

Doing str(unknown_array... is unnecessary because unknown_array already stores strs, due to the return type of input

```<code>x = -1
for i in range(len(unknown_array)):
    values += [input('enter the value of ' + unknown_array[x+1] + ': ')]
    x += 1
</code>```

Better yet, since x + 1 is the same value as i, you should just use the i iterator instead of x + 1:

```<code>for i in range(len(unknown_array)):
    values += [input('enter the value of ' + unknown_array[i] + ': ')]
</code>```

Body:
In this program I am putting values in an array those and the assign to those values a float number.
It should work like this:
Ex.

Formula name: Addition
how many unknown values?: 3
unknown value:x
unknown value:y
unknown value:z
enter the value of x: 2
enter the value of y: 3
enter the value of z:

(instead of writing enter the value of y, in the second-last line, it writes enter the value of x again)
how can I fix it?
This is the code:

import math
name = input('Formula name: ')
unknown_values = int(input('how may unknown values?: '))
unknown_array = []
for i in range(unknown_values):
    unknown_name = input('unknown value:')
    unknown_array += [unknown_name]

values = []
x = -1
for i in range(len(unknown_array)):
    values[i] += [input('enter the value of ' + str(unknown_array[x+1] + ': '))]

print(values)

Body:
You aren't incrementing your x value inside of the second for loop, so it will always refer to the same element in unknown_array. In other words, in each iteration of the loop it will refer to unknown_array[0], or the first unknown you input, which in your example is x. You should add a line to increment this value in the loop.

A couple of other things:

values[i] += ... will produce an IndexError as these elements have not been initialized yet, I think you meant to write values += ... instead (or you can use .append rather than +=):

Doing str(unknown_array... is unnecessary because unknown_array already stores strs, due to the return type of input

x = -1
for i in range(len(unknown_array)):
    values += [input('enter the value of ' + unknown_array[x+1] + ': ')]
    x += 1

Better yet, since x + 1 is the same value as i, you should just use the i iterator instead of x + 1:

for i in range(len(unknown_array)):
    values += [input('enter the value of ' + unknown_array[i] + ': ')]