问:
Filter gender in an ecommerce site with ReactJs
Im totally new to programming, i'am making an ecommerce site and i have to filter the gender of clothes by Male or Female if it is possible to do.
I am using react and redux!

++++++++++++

```<code> class ProductList extends Component {
    state = {
        slug: 'Products'
    }
    render() {
        return (
            <div className='itemlist'>
                {
                    this.props.theItems.items.map(item => <Product item={item}/>)
                }
            </div>
        )
    }
}
const mapStateToProps = state => {
    return{
         theItems: state.items
    }

}
export default connect(mapStateToProps)(ProductList)
</code>```

```<code>

const Product = ({ item, addToCart }) => {

    return (
        <div className='itemcard'>
            <Card style={{ width: '18rem' }}>
                <Card.Img variant="top" src={item.img} />
                <Card.Body>
                    <Card.Title className='card-title'>{item.title}</Card.Title>
                    <Card.Text className='card-text'>
                        {item.description}
                        {item.price}$
                     </Card.Text>
                    <Button variant="light" onClick={() => { addToCart(item.id) }} >Add to cart</Button>
                </Card.Body>
            </Card>

        </div>
    )
}

export default connect(null, {addToCart})(Product)

</code>```

This is my Data file in the reducer, i have to add the gender attribute here?
Thank you for your answer

```<code>
    items: [
            {
                id: uuid(),
                img: 'https://images.thejacketmaker.com/Men%27s+Noah+Black+Leather+Biker+Jacket1-4-1557058576770',
                title: 'Noah Black Leather Biker Jacket',
                description: '',
                price: '230'
            },
            {
                id: uuid(),
                img: 'https://images.thejacketmaker.com/Men%27s+Lavendard+Brown+Leather+Biker+Jacket7846-4-1577528725717.jpg',
                title: 'Lavendard Brown Leather Biker Jacket',
                description: '',
                price: '230'
            },
            {
                id: uuid(),
                img: 'https://images.thejacketmaker.com/Men%27s+Bomia+Ma-1+Brown+Leather+Bomber+Jacket7819-4-1579778569432.jpg',
                title: 'Bomia Ma-1 Brown Leather Bomber Jacket',
                description: '',
                price: '265'
            }

</code>```

答:
Your question lacks of information, but assuming that items are products with a gender attribute that can be either Male or Female, you could do something like that:

```<code> class ProductList extends Component {
    state = {
        slug: 'Products'
    }
    render() {
        return (
            <div className='itemlist'>
                {
                    this.props.theItems.items
                         .filter(item => item.gender === 'Male')
                         .map(item => <Product item={item}/>)
                }
            </div>
        )
    }
}
const mapStateToProps = state => {
    return{
         theItems: state.items
    }

}
export default connect(mapStateToProps)(ProductList)
</code>```

To understand how it works, check the docs about filter method.

Body:
Im totally new to programming, i'am making an ecommerce site and i have to filter the gender of clothes by Male or Female if it is possible to do.
I am using react and redux!

++++++++++++

 class ProductList extends Component {
    state = {
        slug: 'Products'
    }
    render() {
        return (

                {
                    this.props.theItems.items.map(item => <Product item={item}/>)
                }

        )
    }
}
const mapStateToProps = state => {
    return{
         theItems: state.items
    }

}
export default connect(mapStateToProps)(ProductList)

const Product = ({ item, addToCart }) => {

    return (

            <Card style={{ width: '18rem' }}>
                <Card.Img variant="top" src={item.img} />
                <Card.Body>
                    <Card.Title className='card-title'>{item.title}</Card.Title>
                    <Card.Text className='card-text'>
                        {item.description}
                        {item.price}$
                     </Card.Text>
                    <Button variant="light" onClick={() => { addToCart(item.id) }} >Add to cart</Button>
                </Card.Body>
            </Card>

    )
}

export default connect(null, {addToCart})(Product)

This is my Data file in the reducer, i have to add the gender attribute here?
Thank you for your answer

    items: [
            {
                id: uuid(),
                img: 'https://images.thejacketmaker.com/Men%27s+Noah+Black+Leather+Biker+Jacket1-4-1557058576770',
                title: 'Noah Black Leather Biker Jacket',
                description: '',
                price: '230'
            },
            {
                id: uuid(),
                img: 'https://images.thejacketmaker.com/Men%27s+Lavendard+Brown+Leather+Biker+Jacket7846-4-1577528725717.jpg',
                title: 'Lavendard Brown Leather Biker Jacket',
                description: '',
                price: '230'
            },
            {
                id: uuid(),
                img: 'https://images.thejacketmaker.com/Men%27s+Bomia+Ma-1+Brown+Leather+Bomber+Jacket7819-4-1579778569432.jpg',
                title: 'Bomia Ma-1 Brown Leather Bomber Jacket',
                description: '',
                price: '265'
            }

Body:
Your question lacks of information, but assuming that items are products with a gender attribute that can be either Male or Female, you could do something like that:

 class ProductList extends Component {
    state = {
        slug: 'Products'
    }
    render() {
        return (
            <div className='itemlist'>
                {
                    this.props.theItems.items
                         .filter(item => item.gender === 'Male')
                         .map(item => <Product item={item}/>)
                }
            </div>
        )
    }
}
const mapStateToProps = state => {
    return{
         theItems: state.items
    }

}
export default connect(mapStateToProps)(ProductList)

To understand how it works, check the docs about filter method.


来源: stackexchange

问:
Extracting parameters from astropy.modeling Gaussian2D
I have managed to use astropy.modeling to model a 2D Gaussian over my image and the parameters it has produced to fit the image seem reasonable. However, I need to run the 2D Gaussian over thousands of images because we are interested in examining the mean x and y of the model and also the x and y standard deviations over our images. The model output looks like this:

```<code>m2
<Gaussian2D(amplitude=0.0009846091239480168, x_mean=30.826676737477573, y_mean=31.004045976953222, x_stddev=2.5046722491074536, y_stddev=3.163048479350727, theta=-0.0070295894129793896)>
</code>```

I can also tell you this:

```<code>type(m2)
<class 'astropy.modeling.functional_models.Gaussian2D'>
Name: Gaussian2D
Inputs: (u'x', u'y')
Outputs: (u'z',)
Fittable parameters: ('amplitude', 'x_mean', 'y_mean', 'x_stddev', 'y_stddev', 'theta')
</code>```

What I need is a method to extract the parameters of the model, namely:

```<code>x_mean
y_mean
x_stddev
y_stddev
</code>```

I am not familiar with this form output so I am really stuck on how to extract the parameters.

答:
An alternative approach is to use estimate_line_parameters. The docs for it aren't very clear in this area (or so I think). If the problem is getting starting parameters for the Gaussians for the lines, it is a good place to start.

To approach it this way:

```<code>from specutils.spectra import Spectrum2D
from specutils.fitting import estimate_line_parameters
</code>```

...

```<code>e1 = estimate_line_parameters(spectrum, models.Gaussian2D())
a = e1.amplitude.value
b = e1.x_mean.value
c = e1.y_mean.value
d = x_stddev.value
e = y_stddev.value
</code>```

estimate_line_parameters gives the results loads of decimal places, so if you are trying to estimate starting values you would probably want to use round(value_name, n) where n is the number of dec places that you feel are appropriate.

NOTE that a,b,c etc are returned as values and don't preserve units. so you will also need:

```<code>from astropy import units as u
</code>```

and then (e.g.) a = e1.amplitude.value*u.(flux_units) where flux_units is Jy or something similar and/or scaled versions thereof.

Of course all this assumes that you have got your background sufficiently well subtracted...

ContentLicense: CC BY-SA 3.0

Body:
I have managed to use astropy.modeling to model a 2D Gaussian over my image and the parameters it has produced to fit the image seem reasonable. However, I need to run the 2D Gaussian over thousands of images because we are interested in examining the mean x and y of the model and also the x and y standard deviations over our images. The model output looks like this:

m2
<Gaussian2D(amplitude=0.0009846091239480168, x_mean=30.826676737477573, y_mean=31.004045976953222, x_stddev=2.5046722491074536, y_stddev=3.163048479350727, theta=-0.0070295894129793896)>

I can also tell you this:

type(m2)
<class 'astropy.modeling.functional_models.Gaussian2D'>
Name: Gaussian2D
Inputs: (u'x', u'y')
Outputs: (u'z',)
Fittable parameters: ('amplitude', 'x_mean', 'y_mean', 'x_stddev', 'y_stddev', 'theta')

What I need is a method to extract the parameters of the model, namely:

x_mean
y_mean
x_stddev
y_stddev

I am not familiar with this form output so I am really stuck on how to extract the parameters.

Body:
An alternative approach is to use estimate_line_parameters. The docs for it aren't very clear in this area (or so I think). If the problem is getting starting parameters for the Gaussians for the lines, it is a good place to start.

To approach it this way:

from specutils.spectra import Spectrum2D
from specutils.fitting import estimate_line_parameters

...

e1 = estimate_line_parameters(spectrum, models.Gaussian2D())
a = e1.amplitude.value
b = e1.x_mean.value
c = e1.y_mean.value
d = x_stddev.value
e = y_stddev.value

estimate_line_parameters gives the results loads of decimal places, so if you are trying to estimate starting values you would probably want to use round(value_name, n) where n is the number of dec places that you feel are appropriate.

NOTE that a,b,c etc are returned as values and don't preserve units. so you will also need:

from astropy import units as u

and then (e.g.) a = e1.amplitude.value*u.(flux_units) where flux_units is Jy or something similar and/or scaled versions thereof.

Of course all this assumes that you have got your background sufficiently well subtracted...

ContentLicense: CC BY-SA 4.0


问:
How to add column with specific condition for oracle DB
How do add a field – DOC with Date type to the Registration table.
Also DOC (Date of Completion) should be greater than DOJ (Date of joining).

I wrote this query but it is showing error : Column check constraint cannot reference other column

```<code>ALTER TABLE Registration add DOC date CHECK(DOC > DOJ);
</code>```

答:
You need to create the constraint at table level instead of column level.

For example:

```<code>SQL> create table t(x number, doj date);

Table created.

SQL> alter table t add doc date;

Table altered.

SQL> alter table t add constraint check_doc check (doc > doj);

Table altered.

SQL>
</code>```

Body:
How do add a field – DOC with Date type to the Registration table.
Also DOC (Date of Completion) should be greater than DOJ (Date of joining).

I wrote this query but it is showing error : Column check constraint cannot reference other column

ALTER TABLE Registration add DOC date CHECK(DOC > DOJ);

Body:
You need to create the constraint at table level instead of column level.

For example:

SQL> create table t(x number, doj date);

Table created.

SQL> alter table t add doc date;

Table altered.

SQL> alter table t add constraint check_doc check (doc > doj);

Table altered.

SQL>


问:
sorting input numbers in ascending order in python
```<code>name = int(input('>>>'))
ascending_order = name.split(', ')
ascending_order.sort()
print(ascending_order)
</code>```

I am having error in line 1: int(input(">>>")

name = int(input('>>>'))
ValueError: invalid literal for int()

答:
with string conversion into integer:

```<code>name = input('>>>')
ascending_order = name.split(',')
for i in range(len(ascending_order)):
     ascending_order[i] = int(ascending_order[i])
ascending_order = sorted(ascending_order, reverse=True)
print(ascending_order)
</code>```

without string conversion into integer:

```<code>name = input('>>>')
ascending_order = name.split(',')
ascending_order = sorted(ascending_order, reverse=True)
print(ascending_order)
</code>```

Body:
name = int(input('>>>'))
ascending_order = name.split(', ')
ascending_order.sort()
print(ascending_order)

I am having error in line 1: int(input(">>>")

name = int(input('>>>'))
ValueError: invalid literal for int()

Body:
with string conversion into integer:

name = input('>>>')
ascending_order = name.split(',')
for i in range(len(ascending_order)):
     ascending_order[i] = int(ascending_order[i])
ascending_order = sorted(ascending_order, reverse=True)
print(ascending_order)

without string conversion into integer:

name = input('>>>')
ascending_order = name.split(',')
ascending_order = sorted(ascending_order, reverse=True)
print(ascending_order)


问:
How to retry fetching after refresh token using redux-observable?
I'm new in RxJS and I faced with need to retry fetching items to api if it responded with unauthorized error. I need to call refresh token endpoint and then retry fetching. How can I do it using epics from redux-observable? I guess it should looks like this code, but I'm not sure what to do in catchError block.</p>

```<code>export const getItemsEpic = (action$) =>
action$.pipe(
    ofType('FETCH_ITEMS'),
    switchMap(() => getItemsRequest()),
    map((response) => addItemsAction(response.data)),
    catchError(err => {
        ???
    }),
);
</code>```

答:
You can try to add a pipe like that

export const getItemsEpic = (action$) =>
action$.pipe(
  ofType('FETCH_ITEMS'),
  switchMap(() => getItemsRequest()),
  map((response) => addItemsAction(response.data)),
  catchError(error => {
    // some logic how to refresh to token.
    return ajax('refreshtoken').pipe(switchMapTo(throwError(error)));
  ),
  retry(1), // allows only 1 failure.
);
```

Body:
I'm new in RxJS and I faced with need to retry fetching items to api if it responded with unauthorized error. I need to call refresh token endpoint and then retry fetching. How can I do it using epics from redux-observable? I guess it should looks like this code, but I'm not sure what to do in catchError block.

export const getItemsEpic = (action$) =>
action$.pipe(
    ofType('FETCH_ITEMS'),
    switchMap(() => getItemsRequest()),
    map((response) => addItemsAction(response.data)),
    catchError(err => {
        ???
    }),
);


问:
nls troubles: Missing value or an infinity produced when evaluating the model
I am an R newbie trying to fit plant photosynthetic light response curves (saturating, curvilinear) to a particular model accepted by experts. The goal is to get estimated coefficient values for Am, Rd, and LCP. Here is the error I keep getting:

Error in numericDeriv(form[[3L]], names(ind), env) :
Missing value or an infinity produced when evaluating the model

I have switched around the starting values a number of times, but still no luck. Help? Thanks you in advance. Example dataset below.

```<code>photolrc= c(3.089753, 6.336478, 7.737142, 8.004812, 8.031599)
PARlrc= c(48.69624, 200.08539, 499.29840, 749.59222, 1250.09363)
curvelrc<-data.frame(PARlrc,photolrc)
curve.nlslrc = nls(photolrc ~ Am*(1-((1-(Rd/Am))^(1-(PARlrc/LCP)))),start=list(Am=(max(photolrc)-min(photolrc)),Rd=-min(photolrc),LCP= (max(photolrc)-1)))
coef(curve.nlslrc)
</code>```

答: Try removing any row observations with zero, especially in the predictor variables and try the nls function. It worked for me.</p>

Body:
I am an R newbie trying to fit plant photosynthetic light response curves (saturating, curvilinear) to a particular model accepted by experts. The goal is to get estimated coefficient values for Am, Rd, and LCP. Here is the error I keep getting:

Error in numericDeriv(form[[3L]], names(ind), env) :
Missing value or an infinity produced when evaluating the model

I have switched around the starting values a number of times, but still no luck. Help? Thanks you in advance. Example dataset below.

photolrc= c(3.089753, 6.336478, 7.737142, 8.004812, 8.031599)
PARlrc= c(48.69624, 200.08539, 499.29840, 749.59222, 1250.09363)
curvelrc<-data.frame(PARlrc,photolrc)
curve.nlslrc = nls(photolrc ~ Am*(1-((1-(Rd/Am))^(1-(PARlrc/LCP)))),start=list(Am=(max(photolrc)-min(photolrc)),Rd=-min(photolrc),LCP= (max(photolrc)-1)))
coef(curve.nlslrc)


问:
Displaying Google Map page via jQuery AJAX
Here's what I am trying to do.

I am using a jQuery tooltip plug-in called jTip (http://www.codylindley.com/blogstuff/js/jtip/).

This plugin effectively loads another page into the tooltip it is displaying.

So I have created another page, which has a small google map in it. The page is nothing special, it just displays a google map with a single marker.

The link to the google map page is written as below.

```<code><a  href="my_ajax_page.php?width=375" class="jTip" id="one" name="This is a tooltip header">Click here!</a>
</code>```

If I go to this page directly, then the page displays fine. However, via the tooltip plugin, map doesn't show anymore. The map page is as follow.

```<code><!DOCTYPE html>
<html>
  <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">
    function initialize()
    {
        var latlng = new google.maps.LatLng(35, 101);
        var myOptions = { zoom: 15, center: latlng,
                          mapTypeId: google.maps.MapTypeId.ROADMAP };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var marker = new google.maps.Marker( { position:latlng,
                                               map: map,
                                               animation: google.maps.Animation.DROP });

    }
  </script>
</head>
<body>
  <div id="map_canvas" style="width:300px;height:300px"></div>
</body>
</html>
</code>```

Any suggestions on how this could be done?

答:
Make jTip open the new page in an iframe, or make another page which consists of an iframe of the page with the map, and load that page into jTip.

If you don't want to use iframes, then look into Google Maps Asynchronously Loading the Javascript API.

Body:
Here's what I am trying to do.

I am using a jQuery tooltip plug-in called jTip (http://www.codylindley.com/blogstuff/js/jtip/).

This plugin effectively loads another page into the tooltip it is displaying.

So I have created another page, which has a small google map in it. The page is nothing special, it just displays a google map with a single marker.

The link to the google map page is written as below.

Click here!

If I go to this page directly, then the page displays fine. However, via the tooltip plugin, map doesn't show anymore. The map page is as follow.

<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

Any suggestions on how this could be done?


问:
Save EA diagram with transparent background
How do we specify the background color (or transparency) for exported images?

We are trying to export a diagram from EA 14 to PowerPoint and when we do it is always a large white box. We'd like the background to be transparent so we can place it on a rectangle filled with one of the theme colors. It would even be acceptable to use the current gradient fill in a frame, but it always exports a frame filled with white.

答:
There is a workaround.

Go into Swimlanes.

Add a single vertical swimlane, name is arbitrary.

Set its Back Color as desired.

Set the Line Color in Details to the same color.

In Details, check Hide Names.

After exiting Swimlanes, resize the single swimlane so it acts as the background.

When the diagram is saved or copied, it takes the background with it. A little downside: You will have to resize the swimlane if the width of the active area of the diagram changes.


问:
How to get the desired character by split or substring method in stringArray JS?
There is an array and there are strings that are different from each other but contain operations.All of the strings have a large operator and a small operator.I want to separate the characters from the operator and later.

My example Array;

```<code>[definitions1<=3123,definitions31241>=32414,definitions123213123>=12]
</code>```

The result I want;

```<code>[<=3123,>=32414,>=12]
</code>```

When i try with split method like this,

(split(<).pop()) or (split(>).pop())

Result = [=3123,=32414,=12]  i could not get (<,>) operator.

When i tried with subStr, I cannot give standard start and finish parameters because strings are different lengths.

I would be glad if someone shows regular expression method or a simpler way.

答:
you can split it with a RegExp with capture group

const strs = ["definitions1<=3123","definitions31241>=32414","definitions123213123>=12"];

const result = strs
  // matches multiple occurrences of "<", "=" and ">"
  // like "<", "<=", "===", ">=", but also "<<=====>>", ">><<"
  .map((x) => x.split(/([<=>]+)/))
  .map(([definition, operator, value]) => [operator, value].join(""));

document.write(JSON.stringify(result, null, 2));```

Body:
There is an array and there are strings that are different from each other but contain operations.All of the strings have a large operator and a small operator.I want to separate the characters from the operator and later.

My example Array;

[definitions1<=3123,definitions31241>=32414,definitions123213123>=12]

The result I want;

[<=3123,>=32414,>=12]

When i try with split method like this,

(split(<).pop()) or (split(>).pop())

Result = [=3123,=32414,=12]  i could not get (<,>) operator.

When i tried with subStr, I cannot give standard start and finish parameters because strings are different lengths.

I would be glad if someone shows regular expression method or a simpler way.


问:
How to send Local notifications when app is closed (swift)?
I have a database where products with expiration dates are stored. When the expiry date expires, the user should receive a notification about this. But these notifications should also come if the user turned off their application (kill app). Question: how to do this? Show me the code, please.
My code is (AppDelegate):

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in }

    return true
}
</code>```

and (ViewController):

```<code>    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "title"
    content.body = "\(overdueProductsStringArray)"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "t", content: content, trigger: trigger)

    center.add(request, withCompletionHandler: nil)
</code>```

答:
didFinishWithLaunchOptions

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

     if let launchOptions = launchOptions,
            let userInfo =  launchOptions[.remoteNotification] as? [AnyHashable: Any] {
            //some code here and post when needed like below
            NotificationCenter.default.post(name: NSNotification.Name("your notification name"),  object: nil)
        }
}
</code>```

Body:
I have a database where products with expiration dates are stored. When the expiry date expires, the user should receive a notification about this. But these notifications should also come if the user turned off their application (kill app). Question: how to do this? Show me the code, please.
My code is (AppDelegate):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in }

    return true
}

and (ViewController):

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "title"
    content.body = "\(overdueProductsStringArray)"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "t", content: content, trigger: trigger)

    center.add(request, withCompletionHandler: nil)

Body:
didFinishWithLaunchOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

     if let launchOptions = launchOptions,
            let userInfo =  launchOptions[.remoteNotification] as? [AnyHashable: Any] {
            //some code here and post when needed like below
            NotificationCenter.default.post(name: NSNotification.Name("your notification name"),  object: nil)
        }
}


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答:
The easiest and quickest way I can think of would be to use sp_help

sp_help 'TableName'

Title: T-SQL query to show table definition?


问:
How to print the results of this code using recursion?
Here is source code of the C Program to Find the Sum of Series 1^2 + 2^2 + …. + n^2.

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

int main()
{
    int number, i;
    int sum = 0;

    printf("Enter maximum values of series number: ");
    scanf("%d", &number);
    sum = (number * (number + 1) * (2 * number + 1 )) / 6;
    printf("Sum of the above given series : ");
    for (i = 1; i <= number; i++)
    {
        if (i != number)
            printf("%d^2 + ", i);
        else
            printf("%d^2 = %d ", i, sum);
    }
    return 0;
</code>```

}

can someone please tell me how to get the same results of this code, but by using recursion

答:
What you need is to introduce a new function:</p>

```<code>#include <stdio.h>
void printNumber(int, int, int);

int main()
{
    int number, i = 1;
    int sum = 0;

    printf("Enter maximum values of series number: ");
    scanf("%d", &number);
    sum = (number * (number + 1) * (2 * number + 1 )) / 6;
    printf("Sum of the above given series : ");

    printNumber(i, number, sum);
    return 0;
}

void printNumber(int i, int number, int sum){
    //if (i >= number) return;
    //safe to remove above as i == number won't call the function again
    if (i != number){
        printf("%d^2 + ", i);
        printNumber(i + 1, number, sum);
    }
    else{
        printf("%d^2 = %d ", i, sum);
    }
}
</code>```

Body:
Here is source code of the C Program to Find the Sum of Series 1^2 + 2^2 + …. + n^2.

#include <stdio.h>

int main()
{
    int number, i;
    int sum = 0;

    printf("Enter maximum values of series number: ");
    scanf("%d", &number);
    sum = (number * (number + 1) * (2 * number + 1 )) / 6;
    printf("Sum of the above given series : ");
    for (i = 1; i <= number; i++)
    {
        if (i != number)
            printf("%d^2 + ", i);
        else
            printf("%d^2 = %d ", i, sum);
    }
    return 0;

}

can someone please tell me how to get the same results of this code, but by using recursion

Body:
What you need is to introduce a new function:

#include <stdio.h>
void printNumber(int, int, int);

int main()
{
    int number, i = 1;
    int sum = 0;

    printf("Enter maximum values of series number: ");
    scanf("%d", &number);
    sum = (number * (number + 1) * (2 * number + 1 )) / 6;
    printf("Sum of the above given series : ");

    printNumber(i, number, sum);
    return 0;
}

void printNumber(int i, int number, int sum){
    //if (i >= number) return;
    //safe to remove above as i == number won't call the function again
    if (i != number){
        printf("%d^2 + ", i);
        printNumber(i + 1, number, sum);
    }
    else{
        printf("%d^2 = %d ", i, sum);
    }
}


问:
new PR includes changes from older PR in Github
I have created 2 PR's to a repo; I was making changes to the new PR and did a

```<code>git pull upstream/master
</code>```

and then create a new branch with git checkout -b <new-Pr>
and modified a file and did git add . and then git commit and git push origin <new-Pr> by doing this my files which I modified from older PR(which was not needed) also appeared in the new PR. How can I rectify the same?

答:
So, after much headaches I found this as a solution

```<code>git reflog
</code>```

which shows my commits and rebased logs

then i choose to go back to the state by the help of comments and

```<code>git reset --hard HEAD@{80}
</code>```

Then i finally do

```<code>git push --force
</code>```

Body:
I have created 2 PR's to a repo; I was making changes to the new PR and did a

git pull upstream/master

and then create a new branch with git checkout -b <new-Pr>
and modified a file and did git add . and then git commit and git push origin <new-Pr> by doing this my files which I modified from older PR(which was not needed) also appeared in the new PR. How can I rectify the same?

Body:
So, after much headaches I found this as a solution

git reflog

which shows my commits and rebased logs

then i choose to go back to the state by the help of comments and

git reset --hard HEAD@{80}

Then i finally do

git push --force


问:
How to break a dynamic(changing) string into two different parts?
I had a field from the API response which gives me data like "Welcome Name" or it can be "Welcome back Name". Name can be any combination of firstName middleName lastName. I want to break it into two parts,

1 - "Welcome" or "Welcome back" (as per the response from API)

2 - "Name"

```<code>for example :

if data is "Welcome Aman Pratap Singh" break into 1-"Welcome" 2-"Aman Pratap Singh"

if data is "Welcome back ABCDE PQR XYZ" break into 1-"Welcome back" 2-"ABCDE PQR XYZ"

if data is "Welcome ABC XYZ" break into 1-"Welcome" 2-"ABC XYZ"

if data is "Welcome back ABC XYZ" break into 1-"Welcome back" 2-"ABC XYZ"

if data is  "Welcome ABCDE" break into 1-"Welcome" 2-"ABCDE"

if data is  "Welcome back ABCDE" break into 1-"Welcome back" 2-"ABCDE"
</code>```

答:
you may use the the split() method in javascript to 'split' your string into an array of strings.

example:

```<code>var str = "hello sir";
var arrayOfStrings = str.split(" ");
</code>```

so now arrayOfStrings[0] contains "hello" in it,
and arrayOfStrings[1] contains "sir" in it

Body:
I had a field from the API response which gives me data like "Welcome Name" or it can be "Welcome back Name". Name can be any combination of firstName middleName lastName. I want to break it into two parts,

1 - "Welcome" or "Welcome back" (as per the response from API)

2 - "Name"

for example :

if data is "Welcome Aman Pratap Singh" break into 1-"Welcome" 2-"Aman Pratap Singh"

if data is "Welcome back ABCDE PQR XYZ" break into 1-"Welcome back" 2-"ABCDE PQR XYZ"

if data is "Welcome ABC XYZ" break into 1-"Welcome" 2-"ABC XYZ"

if data is "Welcome back ABC XYZ" break into 1-"Welcome back" 2-"ABC XYZ"

if data is  "Welcome ABCDE" break into 1-"Welcome" 2-"ABCDE"

if data is  "Welcome back ABCDE" break into 1-"Welcome back" 2-"ABCDE"

Body:
you may use the the split() method in javascript to 'split' your string into an array of strings.

example:

var str = "hello sir";
var arrayOfStrings = str.split(" ");

so now arrayOfStrings[0] contains "hello" in it,
and arrayOfStrings[1] contains "sir" in it


问:
How can I convert a list to string
```<code>data class Movie(
    @SerializedName("movie_name")
    val movieName : String
    @SerializedName("genres")
    val movieGenre : List<String>){}
</code>```

How can I convert a list to string created every object in this data class

答:
That's achievable in Kotlin via joinToString(separator: String), like this:

```<code>data class Movie(
    @SerializedName("movie_name")
    val movieName : String,
    @SerializedName("genres")
    val movieGenre : List<String>
) {
    val genre: String
        // concatenate the items using the separator provided
        get() = movieGenre.joinToString(" ")
}
</code>```

You would use it in a main as follows

```<code>fun main() {
    val genreList: List<String> = listOf(
        "Horror", "Splatter", "Romance", "Comedy", "Mystery", "Adult"
    )
    val movieName = "A.R. Bitrary"

    val movie = Movie(movieName, genreList)

    println(movie.genre)
}
</code>```

which then outputs

Horror Splatter Romance Comedy Mystery Adult
```

Title: How can I convert a list to string

Body:
data class Movie(
    @SerializedName("movie_name")
    val movieName : String
    @SerializedName("genres")
    val movieGenre : List<String>){}

How can I convert a list to string created every object in this data class

Body:
That's achievable in Kotlin via joinToString(separator: String), like this:

data class Movie(
    @SerializedName("movie_name")
    val movieName : String,
    @SerializedName("genres")
    val movieGenre : List<String>
) {
    val genre: String
        // concatenate the items using the separator provided
        get() = movieGenre.joinToString(" ")
}

You would use it in a main as follows

fun main() {
    val genreList: List<String> = listOf(
        "Horror", "Splatter", "Romance", "Comedy", "Mystery", "Adult"
    )
    val movieName = "A.R. Bitrary"

    val movie = Movie(movieName, genreList)

    println(movie.genre)
}

which then outputs

Horror Splatter Romance Comedy Mystery Adult


问:
Calling the variable property directly vs getter/setters - OOP Design
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

```<code>class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();
</code>```

Suggested Optimization:

```<code>$rover = new dog();
$rover->name = 'rover';
echo $rover->name;
</code>```

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

答:
I would say this is really a matter of personal preference. If performance is truly that important, then I think you answered your own question.

However, in your first example, you can still access dog::name without the getter/setter just like you do in your second example: $rover->name = 'rover'; because $name is public.

If you specifically want to hide a class member, you would need to declare the variable private or protected and then a getter/setter would be necessary.

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?


问:
How to test whether an optional module is present at runtime
The Java Platform Module System (JPMS) allows a module to declare an optional dependency using requires static in the module-info.java file:

```<code>module my.module {
    requires static some.optional.module;
}
</code>```

However, how should you check in your code whether the module is present at runtime?

The Project Jigsaw: Optional Modules page proposed:

```<code>public boolean isModulePresent(String mn);
</code>```

But, it appears that was dropped because there is no such method in the latest Java releases. Neither am I able to find the @RequireOptionalModule annotation mentioned there in the current Java version.

This example on blog@CodeFX suggests a quite verbose method chain on StackWalker (which is explained here).

Edit: That example tries to find out if a module is available to the caller class, which is not necessary in my case.

Is there an easier way to perform this check, or can a simple Class.forName check suffice if the presence of a certain class indicates that a module is present?

答:
To find out if some module is available at runtime, you can simply call ModuleLayer.findModule():

```<code>Optional<Module> module = ModuleLayer.boot().findModule("java.desktop");
System.out.println(module.isPresent());
</code>```

Class.forName() should work too if you know the name of some specific class from the module. However, forName() throws ClassNotFoundException if a class is not found. This means you will have to surround it with try-catch to make it work. This is not very convenient.

Body:
The Java Platform Module System (JPMS) allows a module to declare an optional dependency using requires static in the module-info.java file:

module my.module {
    requires static some.optional.module;
}

However, how should you check in your code whether the module is present at runtime?

The Project Jigsaw: Optional Modules page proposed:

public boolean isModulePresent(String mn);

But, it appears that was dropped because there is no such method in the latest Java releases. Neither am I able to find the @RequireOptionalModule annotation mentioned there in the current Java version.

This example on blog@CodeFX suggests a quite verbose method chain on StackWalker (which is explained here).

Edit: That example tries to find out if a module is available to the caller class, which is not necessary in my case.

Is there an easier way to perform this check, or can a simple Class.forName check suffice if the presence of a certain class indicates that a module is present?

Body:
To find out if some module is available at runtime, you can simply call ModuleLayer.findModule():

Optional<Module> module = ModuleLayer.boot().findModule("java.desktop");
System.out.println(module.isPresent());

Class.forName() should work too if you know the name of some specific class from the module. However, forName() throws ClassNotFoundException if a class is not found. This means you will have to surround it with try-catch to make it work. This is not very convenient.


问:
convert a irregular time series of a data table with factors into a regular time series in R
I am trying to convert a irregular time series of a data table into a regular time series. My data looks like this

```<code>library(data.table)
dtRes <- data.table(time  = c(0.1, 0.8, 1, 2.3, 2.4, 4.8, 4.9),
                    abst  = c(1, 1, 1, 0, 0, 3, 3),
                    farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                    gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                    goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                    huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                    mode  = c(4, 4, 4, 2.5, NA, 3, 3))
</code>```

How is it possible to aggregate the observations in chunks by taking a chunk size of like 1 second? (with a variable number of rows - even 0 if there are no rows within a 1 second period) The result should be the mean for the numeric columns (NAs omitted) and for the factors a whole duplicated row if there is more than 1 unique value. If this is not possible for factors or doesn't make sense to you, it is also fine to just take the first value of the specific second in the factor column. This way it would be real regular time series without any duplicated times. If there is no value for an interval (like in the example for the 2nd second), the result is NA.

In the end the result can look like this (depends on duplicated rows or not):

with duplicates:

```<code>wiDups <- data.table(time  = c(1, 1, 2, 3, 4, 5, 5),
                     abst  = c(1, 1, NA, 1, NA, 5, 5),
                     farbe = as.factor(c("keine", "keine", NA, "keine", NA, "rot", "blau")),
                     gier  = c(2.5, 2.5, NA, 0, NA, 4.5, 4.5),
                     goff  = as.factor(c("haus", "maus", NA, "maus", NA, "maus", "maus")),
                     huft  = as.factor(c(NA, NA, NA, "wolle", NA, "holz", "holz")),
                     mode  = c(5, 5, NA, 2.5, NA, 4, 4))
</code>```

and without duplicates:

```<code>noDups <- data.table(time  = c(1, 2, 3, 4, 5),
                     abst  = c(1, NA, 1, NA, 5),
                     farbe = as.factor(c("keine", NA, "keine", NA, "rot")),
                     gier  = c(2.5, NA, 0, NA, 4.5),
                     goff  = as.factor(c("haus", NA, "maus", NA, "maus")),
                     huft  = as.factor(c(NA, NA, "wolle", NA, "holz")),
                     mode  = c(5, NA, 2.5, NA, 4))
</code>```

Is it better to convert it into a time series object?

答:
Not entirely sure what you want to do, but if I understood correctly something like this:

```<code>dtRes %>%
  group_by(second = ceiling(time)) %>%
  summarise(abst = mean(abst),
            farbe = farbe[1],
            gier = mean(gier),
            goff = goff[1],
            huft = huft[1],
            mode = mean(mode)) %>%
  add_row(second = c(1:10)[!(c(1:10) %in% .$second)]) %>% #change 10 to however many seconds you will have
  arrange(second)

# A tibble: 10 x 7
   second  abst farbe  gier goff  huft   mode
    <dbl> <dbl> <fct> <dbl> <fct> <fct> <dbl>
 1      1     1 keine   2.5 haus  NA        4
 2      2    NA NA     NA   NA    NA       NA
 3      3     0 keine   0   maus  wolle    NA
 4      4    NA NA     NA   NA    NA       NA
 5      5     3 rot     3   maus  holz      3
 6      6    NA NA     NA   NA    NA       NA
 7      7    NA NA     NA   NA    NA       NA
 8      8    NA NA     NA   NA    NA       NA
 9      9    NA NA     NA   NA    NA       NA
10     10    NA NA     NA   NA    NA       NA
</code>```

Note that from your example it is not clear how you round the time to seconds, but I think you always want to round up?

Body:
I am trying to convert a irregular time series of a data table into a regular time series. My data looks like this

library(data.table)
dtRes <- data.table(time  = c(0.1, 0.8, 1, 2.3, 2.4, 4.8, 4.9),
                    abst  = c(1, 1, 1, 0, 0, 3, 3),
                    farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                    gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                    goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                    huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                    mode  = c(4, 4, 4, 2.5, NA, 3, 3))

How is it possible to aggregate the observations in chunks by taking a chunk size of like 1 second? (with a variable number of rows - even 0 if there are no rows within a 1 second period) The result should be the mean for the numeric columns (NAs omitted) and for the factors a whole duplicated row if there is more than 1 unique value. If this is not possible for factors or doesn't make sense to you, it is also fine to just take the first value of the specific second in the factor column. This way it would be real regular time series without any duplicated times. If there is no value for an interval (like in the example for the 2nd second), the result is NA.

In the end the result can look like this (depends on duplicated rows or not):

with duplicates:

wiDups <- data.table(time  = c(1, 1, 2, 3, 4, 5, 5),
                     abst  = c(1, 1, NA, 1, NA, 5, 5),
                     farbe = as.factor(c("keine", "keine", NA, "keine", NA, "rot", "blau")),
                     gier  = c(2.5, 2.5, NA, 0, NA, 4.5, 4.5),
                     goff  = as.factor(c("haus", "maus", NA, "maus", NA, "maus", "maus")),
                     huft  = as.factor(c(NA, NA, NA, "wolle", NA, "holz", "holz")),
                     mode  = c(5, 5, NA, 2.5, NA, 4, 4))

and without duplicates:

noDups <- data.table(time  = c(1, 2, 3, 4, 5),
                     abst  = c(1, NA, 1, NA, 5),
                     farbe = as.factor(c("keine", NA, "keine", NA, "rot")),
                     gier  = c(2.5, NA, 0, NA, 4.5),
                     goff  = as.factor(c("haus", NA, "maus", NA, "maus")),
                     huft  = as.factor(c(NA, NA, "wolle", NA, "holz")),
                     mode  = c(5, NA, 2.5, NA, 4))

Is it better to convert it into a time series object?

Body:
Not entirely sure what you want to do, but if I understood correctly something like this:

dtRes %>%
  group_by(second = ceiling(time)) %>%
  summarise(abst = mean(abst),
            farbe = farbe[1],
            gier = mean(gier),
            goff = goff[1],
            huft = huft[1],
            mode = mean(mode)) %>%
  add_row(second = c(1:10)[!(c(1:10) %in% .$second)]) %>% #change 10 to however many seconds you will have
  arrange(second)

# A tibble: 10 x 7
   second  abst farbe  gier goff  huft   mode
    <dbl> <dbl> <fct> <dbl> <fct> <fct> <dbl>
 1      1     1 keine   2.5 haus  NA        4
 2      2    NA NA     NA   NA    NA       NA
 3      3     0 keine   0   maus  wolle    NA
 4      4    NA NA     NA   NA    NA       NA
 5      5     3 rot     3   maus  holz      3
 6      6    NA NA     NA   NA    NA       NA
 7      7    NA NA     NA   NA    NA       NA
 8      8    NA NA     NA   NA    NA       NA
 9      9    NA NA     NA   NA    NA       NA
10     10    NA NA     NA   NA    NA       NA

Note that from your example it is not clear how you round the time to seconds, but I think you always want to round up?


问:
Session guard doesn't found
I use laravel and I use mltiple auth for the connection.
My code in authentification

```<code>if (Auth::guard('patient')->attempt(['email' => $email, 'password' => $password])) {
            //if(Auth::attempt($request->only($field, 'password'))){
                //put session
                Session::put('key', $user->id);
                //change le status en ligne
                Patient::WHERE('id', Auth::patient()->id)->UPDATE(['status' => 1]);
                //redirect url
                return redirect('/users/profile')->with('success', 'Bienvenue '.$user->firstname.', vous êtes bien connecté');
            }else{
                return redirect('/users/login')->with('error', 'Email or username incorrect!');
            }
</code>```

In auth.php, I have

```<code>'guards' => [
    'user' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'patient' => [
        'driver' => 'session',
        'provider' => 'patients',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
   ],
],
</code>```

After execute, I found this error

BadMethodCallException
Method Illuminate\Auth\SessionGuard::patient does not exist.

What is the wrong in my code?

答:
if define your own login or signup and you got this kind of error
BadMethodCallException
Method Illuminate\Auth\SessionGuard:: guard does not exist.
Then you should  import or use then session class  as define below
use Illuminate\Support\Facades\Session;
And your function should be defined as</p>

```<code>public function postSingIn(Request $request)
{
   if(Auth::attempt(['email'=>$request['email'],['password'=>$request['password']]]))
   {

      return redirect()->action('BackendController@deshboard');
   }
   return redirect()->back();
}
</code>```

Title: Session guard doesn't found

Body:
I use laravel and I use mltiple auth for the connection.
My code in authentification

if (Auth::guard('patient')->attempt(['email' => $email, 'password' => $password])) {
            //if(Auth::attempt($request->only($field, 'password'))){
                //put session
                Session::put('key', $user->id);
                //change le status en ligne
                Patient::WHERE('id', Auth::patient()->id)->UPDATE(['status' => 1]);
                //redirect url
                return redirect('/users/profile')->with('success', 'Bienvenue '.$user->firstname.', vous êtes bien connecté');
            }else{
                return redirect('/users/login')->with('error', 'Email or username incorrect!');
            }

In auth.php, I have

'guards' => [
    'user' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'patient' => [
        'driver' => 'session',
        'provider' => 'patients',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
   ],
],

After execute, I found this error

BadMethodCallException
Method Illuminate\Auth\SessionGuard::patient does not exist.

What is the wrong in my code?

Body:
if define your own login or signup and you got this kind of error
BadMethodCallException
Method Illuminate\Auth\SessionGuard:: guard does not exist.
Then you should  import or use then session class  as define below
use Illuminate\Support\Facades\Session;
And your function should be defined as

public function postSingIn(Request $request)
{
   if(Auth::attempt(['email'=>$request['email'],['password'=>$request['password']]]))
   {

      return redirect()->action('BackendController@deshboard');
   }
   return redirect()->back();
}


问:
TypeError: props.routes.map is not a function
I'm new to react-redux. I am trying to pull data from Asp.Net Core Web Api to my react project.

I get an error when mapping the data I receive with redux in react.

I see the data coming in redux DevTools. State is filling up.

```<code>import React, { useEffect } from "react";
import * as actions from "../redux/actions/routeActions";
import { connect } from "react-redux";
import PropTypes from 'prop-types'

function Data({ ...props }) {
  useEffect(() => {
    props.fetchRoutes();
  });

    function renderData() {
        return props.routes.map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (
                <tr key={id}>
                    <td>{id}</td>
                    <td>{departureLocation}</td>
                    <td>{arrivalLocation}</td>
                    <td>{distance}</td>
                </tr>
            )
        })
    }
    return(
        < div >
            <table className="table">
                <thead>
                    <tr>
                        <th />
                        <th>departureLocation</th>
                        <th>arrivalLocation</th>
                        <th>Distance</th>
                    </tr>
                </thead>
                <tbody>
                    {renderData()}
                </tbody>
            </table>
        </div >
    );
}

Data.propTypes = {
    routes: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  routes: state.routes,
});

const mapDispatchToProps = {
  fetchRoutes: actions.fetchAll,
};

export default connect(mapStateToProps, mapActionToProps)(Data);
</code>```

And i get this error.

```<code>TypeError: props.routes.map is not a function.
</code>```

I couldn't find where I made a mistake.

答:
It because routes are not ready on first render.

Rendering with condition will ensure that you dont map into routes that does not exist.

  {props.routes && props.renderData()}

```

Better solution would be setting your routes initial value in reducer of redux as an empty array.

Body:
I'm new to react-redux. I am trying to pull data from Asp.Net Core Web Api to my react project.

I get an error when mapping the data I receive with redux in react.

I see the data coming in redux DevTools. State is filling up.

import React, { useEffect } from "react";
import * as actions from "../redux/actions/routeActions";
import { connect } from "react-redux";
import PropTypes from 'prop-types'

function Data({ ...props }) {
  useEffect(() => {
    props.fetchRoutes();
  });

    function renderData() {
        return props.routes.map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (

                    {id}
                    {departureLocation}
                    {arrivalLocation}
                    {distance}

            )
        })
    }
    return(

                        departureLocation
                        arrivalLocation
                        Distance

                    {renderData()}

    );
}

Data.propTypes = {
    routes: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  routes: state.routes,
});

const mapDispatchToProps = {
  fetchRoutes: actions.fetchAll,
};

export default connect(mapStateToProps, mapActionToProps)(Data);

And i get this error.

TypeError: props.routes.map is not a function.

I couldn't find where I made a mistake.

Body:
It because routes are not ready on first render.

Rendering with condition will ensure that you dont map into routes that does not exist.

<tbody>
  {props.routes && props.renderData()}
</tbody>

Better solution would be setting your routes initial value in reducer of redux as an empty array.


问:
Merging multiple txt files into csv with python
*very new to Python
I need to merge a large number of txt files from a single directory into one csv file. The text from the files needs to be converted into separate rows and columns (five columns in each file, N number of rows).
I used the code from this question:

```<code>import os
import csv

dirpath = 'path_of_directory'
output = 'output_file.csv'
with open(output, 'w') as outfile:
    csvout = csv.writer(outfile)
    csvout.writerow(['FileName', 'Content'])

    files = os.listdir(dirpath)

    for filename in files:
        with open(dirpath + '/' + filename) as afile:
            csvout.writerow([filename, afile.read()])
            afile.close()

    outfile.close()
</code>```

It works for me but it puts all the content from the file into one table cell. I read through a lot of Q&As and couldn't figure out how to modify the code in order to separate the content into different columns and rows.

答:
You have to read the five words in a line with loop for all the lines. Next, write the five words along the filename as shown below. Hope that helps. I have added pseudo code for the concept. Hope that helps!!!

```<code>files = os.listdir(dirpath)

for filename in files:
    with open(dirpath + '/' + filename) as afile:
        #for line in afile.read()
        #     words_in_a_line = split_line_to_get_words(line)
        #     csvout.writerow([filename, words_in_a_file])

        csvout.writerow([filename, afile.read()]) # delete this line
        afile.close()

outfile.close()
</code>```

Here the function split_line_to_get_words will return a list of five words from the line. If the lines are separated according to space or comma, use them to get five words from a line.

Body:
*very new to Python
I need to merge a large number of txt files from a single directory into one csv file. The text from the files needs to be converted into separate rows and columns (five columns in each file, N number of rows).
I used the code from this question:

import os
import csv

dirpath = 'path_of_directory'
output = 'output_file.csv'
with open(output, 'w') as outfile:
    csvout = csv.writer(outfile)
    csvout.writerow(['FileName', 'Content'])

    files = os.listdir(dirpath)

    for filename in files:
        with open(dirpath + '/' + filename) as afile:
            csvout.writerow([filename, afile.read()])
            afile.close()

    outfile.close()

It works for me but it puts all the content from the file into one table cell. I read through a lot of Q&As and couldn't figure out how to modify the code in order to separate the content into different columns and rows.

Body:
You have to read the five words in a line with loop for all the lines. Next, write the five words along the filename as shown below. Hope that helps. I have added pseudo code for the concept. Hope that helps!!!

files = os.listdir(dirpath)

for filename in files:
    with open(dirpath + '/' + filename) as afile:
        #for line in afile.read()
        #     words_in_a_line = split_line_to_get_words(line)
        #     csvout.writerow([filename, words_in_a_file])

        csvout.writerow([filename, afile.read()]) # delete this line
        afile.close()

outfile.close()

Here the function split_line_to_get_words will return a list of five words from the line. If the lines are separated according to space or comma, use them to get five words from a line.


问:
converting json Array into Json object and adding more items to it on MySQL
In a MySQL table how do i convert the values of a column which currently holds JSON array values to an array of JSON objects using the previous values ?

current column( contains only IDs):

```<code>items
-------

[1,2,3]
[2,3]
...

</code>```

required format:

```<code>
items
-------

[ { id:1, lastUpdatedBy:"", timeStamp:"--" },{ id:2, lastUpdatedBy:"", timeStamp:"--" },{ id:3, lastUpdatedBy:"", timeStamp:"--" }]
[  { id:2, lastUpdatedBy:"", timeStamp:"--" },{ id:3, lastUpdatedBy:"", timeStamp:"--" }]
...

</code>```

答:
If you are running MySQL 8.0, you can unnest the array with json_table(), and then build json objects and aggregate with json_arrayagg().

For this to work, you need a primary key - I assumed pk:

```<code>select json_arrayagg(json_object(
    'id', i.id,
    'lastUpdatedBy', 12,
    'timestamp', '--'
)) items
from mytable t
cross join json_table(t.items, '$[*]' columns (id int path '$')) i
group by t.pk
</code>```

If you want an update query:

```<code>update mytable t
inner join (
    select json_arrayagg(json_object(
        'id', i.id,
        'lastUpdatedBy', 12,
        'timestamp', '--'
    )) items
    from mytable t
    cross join json_table(t.items, '$[*]' columns (id int path '$')) i
    group by t.pk
) x on x.pk = t.pk
set x.items = t.items
</code>```

Body:
In a MySQL table how do i convert the values of a column which currently holds JSON array values to an array of JSON objects using the previous values ?

current column( contains only IDs):

items
-------

[1,2,3]
[2,3]
...

required format:

items
-------

[ { id:1, lastUpdatedBy:"", timeStamp:"--" },{ id:2, lastUpdatedBy:"", timeStamp:"--" },{ id:3, lastUpdatedBy:"", timeStamp:"--" }]
[  { id:2, lastUpdatedBy:"", timeStamp:"--" },{ id:3, lastUpdatedBy:"", timeStamp:"--" }]
...

Body:
If you are running MySQL 8.0, you can unnest the array with json_table(), and then build json objects and aggregate with json_arrayagg().

For this to work, you need a primary key - I assumed pk:

select json_arrayagg(json_object(
    'id', i.id,
    'lastUpdatedBy', 12,
    'timestamp', '--'
)) items
from mytable t
cross join json_table(t.items, '$[*]' columns (id int path '$')) i
group by t.pk

If you want an update query:

update mytable t
inner join (
    select json_arrayagg(json_object(
        'id', i.id,
        'lastUpdatedBy', 12,
        'timestamp', '--'
    )) items
    from mytable t
    cross join json_table(t.items, '$[*]' columns (id int path '$')) i
    group by t.pk
) x on x.pk = t.pk
set x.items = t.items


问:
Android:Java, Alert on same Page
Hi Guys
How could I do this Alert on the same Page without "reloading" this page? This one here "reload" the page and that do not show so fine. </p>

```<code>    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Bündel extras erstellen, mit den Werten von "putExtras" (aus FormularActivity)
    final Bundle extras = getIntent().getExtras();

    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
    alertbox.setMessage("Nettobetrag: " + "\t\t" + strNetto + "\n" + "Umsatzsteuer: " + "\t\t" + strUmsatz + "\n" + "Nettobetrag: " + "\t\t" + strBrutto);
    alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {

            startActivity(new Intent("com.mseiz.ustcalc.splashscreen.FormularActivity"));
        }
    });
    alertbox.show();
</code>```

答:
In general, it's best to do the following for any type of dialog. Use a showDialog(int) command to show the dialog, where int is any unique number. You can have as many dialogs as you wish, they just all need to have their own number. The second step is to add a function called onCreateDialog() to your activity, which contains the instructions to build the dialog. The SDK has some good examples of how you should go about doing this.</p>

```<code>public Dialog onCreateDialog(int dialog_num)
</code>```

Title: Android:Java, Alert on same Page

Body:
Hi Guys
How could I do this Alert on the same Page without "reloading" this page? This one here "reload" the page and that do not show so fine.

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Bündel extras erstellen, mit den Werten von "putExtras" (aus FormularActivity)
    final Bundle extras = getIntent().getExtras();

    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
    alertbox.setMessage("Nettobetrag: " + "\t\t" + strNetto + "\n" + "Umsatzsteuer: " + "\t\t" + strUmsatz + "\n" + "Nettobetrag: " + "\t\t" + strBrutto);
    alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {

            startActivity(new Intent("com.mseiz.ustcalc.splashscreen.FormularActivity"));
        }
    });
    alertbox.show();

Body:
In general, it's best to do the following for any type of dialog. Use a showDialog(int) command to show the dialog, where int is any unique number. You can have as many dialogs as you wish, they just all need to have their own number. The second step is to add a function called onCreateDialog() to your activity, which contains the instructions to build the dialog. The SDK has some good examples of how you should go about doing this.

public Dialog onCreateDialog(int dialog_num)


问:
Corda with token and accounts
We are working with token and accounts at Corda with Kotlin. I will detail the scenario to clarify.
We have a node1 and a node2.
We created a "OurTokenType" that extends from TokenType.
We created two accounts (seller and buyer) on node1 and shared them with node2.
By the business rule of the application, node2 is the one who issues the tokens (FungibleToken), and the issue worked correctly. In the end, node1 and node2 have access to the FungibleStates for the issue transaction.
Our problem is in the transfer of these tokens. When we try to transfer the tokens from the account seller to the buyer.
In our scenario, the transfer of tokens can happen on node1 or node2.
When we transfer through node1, which is the host of the accounts, we can use the MoveFungibleTokensFlow class that works and the FungibleStates on node1 are updated to the correct value. However, when we added node2 as an observer in the observerSessions parameter, the FungibleStates on node2 were not updated correctly.
And when we do the transfer by node2, which is NOT the host of the accounts, using the MoveFungibleTokensFlow class, it doesn't work, it generates an exception of com.r3.corda.lib.tokens.selection.InsufficientBalanceException: Insufficient spendable states identified, even with balance .

My question is, can I use the MoveFungibleTokensFlow class to transfer between accounts even if they are on another host?
And when we run on the node that hosts the accounts, what is the problem to update the FungibleStates when using observerSessions?
Or if I must follow the example of the link https://github.com/corda/samples-kotlin/tree/master/Accounts/worldcupticketbooking?

答:
Let me break down your question into two parts:

Observer session doesn't update automatically:
Here is an example of how we would trigger the update on the observer session: https://github.com/corda/samples-kotlin/blob/master/Tokens/stockpaydividend/workflows/src/main/kotlin/net/corda/samples/stockpaydividend/flows/AnnounceDividend.kt#L37
This will ensure the observer's token state is updated whenever the maintainer makes an update. (Note: only the maintainer should make the update, not the owner)

Fungible token transfer between two parties: Yes. it is doable. This line of code is the beginning of FungibleToken transfer in the worldcupticketbooking sample: https://github.com/corda/samples-kotlin/blob/master/Accounts/worldcupticketbooking/workflows/src/main/kotlin/com/t20worldcup/flows/DVPAccountsHostedOnDifferentNodes.kt#L102 It definitely works.

I see you mentioned that you had an error message on InsufficientBalanceException, if I were you, I would start digging in from there, and see which token is being queried exactly.

Title: Corda with token and accounts


问:
How to make visible circle around button on focus only using Qt StyleSheet
Given the stylesheet for a button:

```<code>top: 960px;
left: 944px;
width: 40px;
height: 40px;
background: transparent url('img/play_circle_filled-24px-2.png') 0% 0% no-repeat;
padding-box; opacity: 1;
</code>```

and the stylesheet for a circle around it:

```<code>top: 944px;
left: 928px;
width: 72px;
height: 72px;
background: #EEEEEE 0% 0% no-repeat padding-box;
opacity: 0.2;
</code>```

how to make the circle visible on focus only? Is it possible inside one stylesheet (QAbstractButton{) or it'll need to use some QLabel additionally for this task?
I'm totally incompetent in css, so I'm here to ask you.

P.S
The following stylesheet makes almost what I want except it doesn't draw circle but square.

```<code>"QAbstractButton {"
"top: 960px;"
"left: 944px;"
"width: 40px;"
"height: 40px;"
"border-image: url('img/play_circle_filled-24px-2.png') 0% 0% no-repeat padding-box;"
"opacity: 1;"
"}"

"QAbstractButton:focus {"
"border-radius: 72px;"
"background-color: blue ;"
"opacity: 0.2;"
"}"
</code>```

答:
You can use outline property in css.

HTML:

```<code><div class="img_outline">
    <button class="outline-button">Button</button>
</div>
</code>```

CSS:

```<code> .outline-button:focus{
           border:none;
           outline: 3px solid #4CAF50;
     }
</code>```

You can also add "outline-offset:20px" in ".outline__photo" class, if you want a space between the border and image.
It worked for me.

Body:
Given the stylesheet for a button:

top: 960px;
left: 944px;
width: 40px;
height: 40px;
background: transparent url('img/play_circle_filled-24px-2.png') 0% 0% no-repeat;
padding-box; opacity: 1;

and the stylesheet for a circle around it:

top: 944px;
left: 928px;
width: 72px;
height: 72px;
background: #EEEEEE 0% 0% no-repeat padding-box;
opacity: 0.2;

how to make the circle visible on focus only? Is it possible inside one stylesheet (QAbstractButton{) or it'll need to use some QLabel additionally for this task?
I'm totally incompetent in css, so I'm here to ask you.

P.S
The following stylesheet makes almost what I want except it doesn't draw circle but square.

"QAbstractButton {"
"top: 960px;"
"left: 944px;"
"width: 40px;"
"height: 40px;"
"border-image: url('img/play_circle_filled-24px-2.png') 0% 0% no-repeat padding-box;"
"opacity: 1;"
"}"

"QAbstractButton:focus {"
"border-radius: 72px;"
"background-color: blue ;"
"opacity: 0.2;"
"}"

Body:
You can use outline property in css.

HTML:

<div class="img_outline">
    <button class="outline-button">Button</button>
</div>

CSS:

 .outline-button:focus{
           border:none;
           outline: 3px solid #4CAF50;
     }

You can also add "outline-offset:20px" in ".outline__photo" class, if you want a space between the border and image.
It worked for me.


问:
delete without a head pointer
Question:
You are given a certain node somewhere in the middle of the linked list and you need to delete that node.
You are not given the head node to the linked list.
Condition: the given node has atleast one node next to it.

The structure of the node:

```<code>struct Node {
  int data;
  struct Node *next;
  Node(int x) {
    data = x;
    next = NULL;
  }
}*head;
</code>```

My solution:

```<code>Node* temp=node->next;
node->data=node->next->data;
node->next=node->next->next;
delete temp;
</code>```

Another solution(that i didn't understand):

```<code>Node *temp = node->next;
*node = *(node->next);
delete temp;
</code>```

Both give correct results but i did not understand the 2nd line of the latter solution.

答:
The second solution is the same as the first, except it uses the assignment operator of the class instead of assigning the members separately.

so you mean in the 2nd solution too the data member gets copied(like in the 1st one)?

Yes, that is what the copy assignment operator of the class does.

see don't understand this line.. *node = *(node->next); so can you elaborate/explain this line.

*node indirects through the pointer node which points to an object of type Node. The result is an lvalue to Node.

*(node->next) first indirects through the pointer node to access its member next which is pointer to another object of type Node. This other pointer is also indirected through, which results in lvalue to another Node.

Finally, the assignment operator assigns the first Node to the other Node. The copy assignment operator of the class copies each member from the right hand operand to the corresponding member of the left hand operand.

Title: delete without a head pointer

Body:
Question:
You are given a certain node somewhere in the middle of the linked list and you need to delete that node.
You are not given the head node to the linked list.
Condition: the given node has atleast one node next to it.

The structure of the node:

struct Node {
  int data;
  struct Node *next;
  Node(int x) {
    data = x;
    next = NULL;
  }
}*head;

My solution:

Node* temp=node->next;
node->data=node->next->data;
node->next=node->next->next;
delete temp;

Another solution(that i didn't understand):

Node *temp = node->next;
*node = *(node->next);
delete temp;

Both give correct results but i did not understand the 2nd line of the latter solution.


问:
Unable to start ignite client in spring
I have a Spring cloud project which uses cache mechanism. We are using ignite cache in application by adding the dependency in pom.xml

```<code>    <dependency>
        <groupId>org.apache.ignite</groupId>
        <artifactId>ignite-core</artifactId>
        <version>${ignite.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.ignite</groupId>
        <artifactId>ignite-spring</artifactId>
        <version>${ignite.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.ignite</groupId>
      <artifactId>ignite-rest-http</artifactId>
      <version>${ignite.version}</version>
    </dependency>
</code>```

In properties tag we mentioned the ignite version as 2.7.0(Client). The ignite standalone server also having the same version which is running in the same machine.I am getting the below given error while trying to start the application.

```<code>    [19:45:37,471][SEVERE][restartedMain][IgniteKernal] Failed to start manager: GridManagerAdapter [enabled=true, name=o.a.i.i.managers.discovery.GridDiscoveryManager]
    class org.apache.ignite.IgniteCheckedException: Failed to start SPI: TcpDiscoverySpi [addrRslvr=null, sockTimeout=5000, ackTimeout=5000, marsh=JdkMarshaller [clsFilter=org.apache.ignite.marshaller.MarshallerUtils$1@334f6d54], reconCnt=10, reconDelay=2000, maxAckTimeout=600000, forceSrvMode=false, clientReconnectDisabled=false, internalLsnr=null]
        at org.apache.ignite.internal.managers.GridManagerAdapter.startSpi(GridManagerAdapter.java:300)
        at org.apache.ignite.internal.managers.discovery.GridDiscoveryManager.start(GridDiscoveryManager.java:939)
        at org.apache.ignite.internal.IgniteKernal.startManager(IgniteKernal.java:1682)
        at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:1066)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:2038)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1730)
        at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1158)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:656)
        at org.apache.ignite.IgniteSpring.start(IgniteSpring.java:66)
        at org.apache.ignite.cache.spring.SpringCacheManager.onApplicationEvent(SpringCacheManager.java:332)
        at org.apache.ignite.cache.spring.SpringCacheManager.onApplicationEvent(SpringCacheManager.java:146)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
        at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403)
        at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360)
        at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
        at com.ibs.ps.PsAuthServiceApplication.main(PsAuthServiceApplication.java:21)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
    Caused by: class org.apache.ignite.spi.IgniteSpiException: Local node and remote node have different version numbers (node will not join, Ignite does not support rolling updates, so versions must be exactly the same) [locBuildVer=2.8.0, rmtBuildVer=2.7.0, locNodeAddrs=[test.test.com/0:0:0:0:0:0:0:1, /127.0.0.1, /192.168.00.00], rmtNodeAddrs=[127.0.0.1], locNodeId=9aa05a68-b0f4-4fa9-b288-cc7c32caf691, rmtNodeId=14ea4223-b6e7-4084-b5a8-89481d99de53]
        at org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi.checkFailedError(TcpDiscoverySpi.java:1946)
        at org.apache.ignite.spi.discovery.tcp.ClientImpl$MessageWorker.body(ClientImpl.java:1888)
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
        at org.apache.ignite.spi.discovery.tcp.ClientImpl$1.body(ClientImpl.java:304)
        at org.apache.ignite.spi.IgniteSpiThread.run(IgniteSpiThread.java:62)
</code>```

Can anyone help me to resolve the issue. Thanks in advance.

答:
According to the exception:

Caused by: class org.apache.ignite.spi.IgniteSpiException: Local node and remote node have different version numbers (node will not join, Ignite does not support rolling updates, so versions must be exactly the same) [locBuildVer=2.8.0, rmtBuildVer=2.7.0, locNodeAddrs=[test.test.com/0:0:0:0:0:0:0:1, /127.0.0.1, /192.168.00.00], rmtNodeAddrs=[127.0.0.1], locNodeId=9aa05a68-b0f4-4fa9-b288-cc7c32caf691, rmtNodeId=14ea4223-b6e7-4084-b5a8-89481d99de53]

It's not possible to have a mixed cluster in Apache Ignite.
You should choose either 2.8.0 or 2.7.0.

The GridGain edition does allow you to have a cluster with a multiple versions though.

Title: Unable to start ignite client in spring

Body:
I have a Spring cloud project which uses cache mechanism. We are using ignite cache in application by adding the dependency in pom.xml

    <dependency>
        <groupId>org.apache.ignite</groupId>
        <artifactId>ignite-core</artifactId>
        <version>${ignite.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.ignite</groupId>
        <artifactId>ignite-spring</artifactId>
        <version>${ignite.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.ignite</groupId>
      <artifactId>ignite-rest-http</artifactId>
      <version>${ignite.version}</version>
    </dependency>

In properties tag we mentioned the ignite version as 2.7.0(Client). The ignite standalone server also having the same version which is running in the same machine.I am getting the below given error while trying to start the application.

    [19:45:37,471][SEVERE][restartedMain][IgniteKernal] Failed to start manager: GridManagerAdapter [enabled=true, name=o.a.i.i.managers.discovery.GridDiscoveryManager]
    class org.apache.ignite.IgniteCheckedException: Failed to start SPI: TcpDiscoverySpi [addrRslvr=null, sockTimeout=5000, ackTimeout=5000, marsh=JdkMarshaller [clsFilter=org.apache.ignite.marshaller.MarshallerUtils$1@334f6d54], reconCnt=10, reconDelay=2000, maxAckTimeout=600000, forceSrvMode=false, clientReconnectDisabled=false, internalLsnr=null]
        at org.apache.ignite.internal.managers.GridManagerAdapter.startSpi(GridManagerAdapter.java:300)
        at org.apache.ignite.internal.managers.discovery.GridDiscoveryManager.start(GridDiscoveryManager.java:939)
        at org.apache.ignite.internal.IgniteKernal.startManager(IgniteKernal.java:1682)
        at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:1066)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:2038)
        at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1730)
        at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1158)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:656)
        at org.apache.ignite.IgniteSpring.start(IgniteSpring.java:66)
        at org.apache.ignite.cache.spring.SpringCacheManager.onApplicationEvent(SpringCacheManager.java:332)
        at org.apache.ignite.cache.spring.SpringCacheManager.onApplicationEvent(SpringCacheManager.java:146)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
        at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403)
        at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360)
        at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
        at com.ibs.ps.PsAuthServiceApplication.main(PsAuthServiceApplication.java:21)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
    Caused by: class org.apache.ignite.spi.IgniteSpiException: Local node and remote node have different version numbers (node will not join, Ignite does not support rolling updates, so versions must be exactly the same) [locBuildVer=2.8.0, rmtBuildVer=2.7.0, locNodeAddrs=[test.test.com/0:0:0:0:0:0:0:1, /127.0.0.1, /192.168.00.00], rmtNodeAddrs=[127.0.0.1], locNodeId=9aa05a68-b0f4-4fa9-b288-cc7c32caf691, rmtNodeId=14ea4223-b6e7-4084-b5a8-89481d99de53]
        at org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi.checkFailedError(TcpDiscoverySpi.java:1946)
        at org.apache.ignite.spi.discovery.tcp.ClientImpl$MessageWorker.body(ClientImpl.java:1888)
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
        at org.apache.ignite.spi.discovery.tcp.ClientImpl$1.body(ClientImpl.java:304)
        at org.apache.ignite.spi.IgniteSpiThread.run(IgniteSpiThread.java:62)

Can anyone help me to resolve the issue. Thanks in advance.


问:
How do I prevent the creation of a new property in a Luabind class?
I'm using Luabind to bind C++ classes to Lua. From the Lua script, I can add arbitrary properties (key/value pairs) to the tables that represent my classes, even if I never told Luabind these properties exist:

cheese = Cheese()
cheese.type = "gouda"
cheese.age = 2
cheese.hippopotamus = "monkey" -- Oops! This member was not defined!
```

The hippopotamus line, though nonsensical, will execute without causing a Lua error.

How do I prevent these new properties? I know that when using just the Lua C API this can be accomplished using the __newindex metamethod, but is there a way to do this with Luabind?

答: I don't speak from experience, but here are some email threads from the luabind-user mailing list: first, a monologue by a guy trying to do exactly what you want. Second, somewhat old (Nov 2009) email from the luabind maintainer, stating that providing custom __newindex metamethod is not currently possible, but planned for 1.0 (current version is 0.9.something).</p>

Body:
I'm using Luabind to bind C++ classes to Lua. From the Lua script, I can add arbitrary properties (key/value pairs) to the tables that represent my classes, even if I never told Luabind these properties exist:

cheese = Cheese()
cheese.type = "gouda"
cheese.age = 2
cheese.hippopotamus = "monkey" -- Oops! This member was not defined!

The hippopotamus line, though nonsensical, will execute without causing a Lua error.

How do I prevent these new properties? I know that when using just the Lua C API this can be accomplished using the __newindex metamethod, but is there a way to do this with Luabind?


问:
Remove all text after 3 word - Excel
I have a large CSV file, where one field contains a huge list of words in the following format

word 1, word 2, word 3, word 4, word 5, word 6  and so

What formula could I use to keep the first 3 words and delete everything after that?

答:
Several options; one is SUBSTITUTE to change the 3rd comma to some other character, and then LEFT and FIND to retain only everything beforehand:

```<code>=LEFT(A1,FIND("~",SUBSTITUTE(A1,",","~",3))-1)
</code>```

Title: Remove all text after 3 word - Excel

Body:
Several options; one is SUBSTITUTE to change the 3rd comma to some other character, and then LEFT and FIND to retain only everything beforehand:

=LEFT(A1,FIND("~",SUBSTITUTE(A1,",","~",3))-1)


问:
The application failed to start (exited with code 1) in R Shiny
I am getting the error " The application failed to start (exited with code 1)" while deploying shiny app.

The error message is attached.In console I get the following message after deploying:

```<code>Preparing to deploy application...DONE
Uploading bundle for application: 365672...DONE
Deploying bundle: 1444503 for application: 365672 ...
Waiting for task: 533366947
building: Parsing manifest
building: Building image: 1457861
building: Fetching packages
building: Installing packages
building: Installing files
building: Pushing image: 1457861
deploying: Starting instances
rollforward: Activating new instances
success: Stopping old instances
Application successfully deployed to
https://programmingrpython.shinyapps.io/shinyapp/
</code>```

The application runs locally. However I get these  messages in the console when I run the app:

```<code>The following object is masked from ‘package:ggplot2’:

last_plot

The following object is masked from ‘package:stats’:

filter

The following object is masked from ‘package:graphics’:

layout

Warning in origRenderFunc() :
Ignoring explicitly provided widget ID "52982fb160e2"; Shiny doesn't use them
Warning in origRenderFunc() :
Ignoring explicitly provided widget ID "5298324e516f"; Shiny doesn't use them
</code>```

Packages I am using are :

```<code>library(shiny)
library(plotly)
library(data.table)
</code>```

Is it because of the warning messages ?
I have followed https://github.com/ropensci/plotly/issues/985 but still I am getting this warning.

Can any please suggest why the error message is shown after deployment?

答: I had the same issue. I commented the library(Shiny) line that I had on while creating the app and it deployed successfully.

Body:
I am getting the error " The application failed to start (exited with code 1)" while deploying shiny app.

The error message is attached.In console I get the following message after deploying:

Preparing to deploy application...DONE
Uploading bundle for application: 365672...DONE
Deploying bundle: 1444503 for application: 365672 ...
Waiting for task: 533366947
building: Parsing manifest
building: Building image: 1457861
building: Fetching packages
building: Installing packages
building: Installing files
building: Pushing image: 1457861
deploying: Starting instances
rollforward: Activating new instances
success: Stopping old instances
Application successfully deployed to
https://programmingrpython.shinyapps.io/shinyapp/

The application runs locally. However I get these  messages in the console when I run the app:

The following object is masked from ‘package:ggplot2’:

last_plot

The following object is masked from ‘package:stats’:

filter

The following object is masked from ‘package:graphics’:

layout

Warning in origRenderFunc() :
Ignoring explicitly provided widget ID "52982fb160e2"; Shiny doesn't use them
Warning in origRenderFunc() :
Ignoring explicitly provided widget ID "5298324e516f"; Shiny doesn't use them

Packages I am using are :

library(shiny)
library(plotly)
library(data.table)

Is it because of the warning messages ?
I have followed https://github.com/ropensci/plotly/issues/985 but still I am getting this warning.

Can any please suggest why the error message is shown after deployment?


问:
dyld: Library not loaded: /usr/local/opt/unixodbc/lib/libodbc.2.dylib
I am facing the following issue on Mac when I run rake ts:index for Thinking Sphinx indexing:

dyld: Library not loaded: /usr/local/opt/unixodbc/lib/libodbc.2.dylib

I am using mysql version 8.0.13 for osx10.13 on x86_64.
How can I resolve this issue?

答:
In addition to

```<code>brew install unixodbc
</code>```

you can also install the mssql drivers after this with the following brew instructions:

```<code>brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql mssql-tools
</code>```

After this I was able to use "ODBC Driver 17 for SQL Server" in python.

Body:
In addition to

brew install unixodbc

you can also install the mssql drivers after this with the following brew instructions:

brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql mssql-tools

After this I was able to use "ODBC Driver 17 for SQL Server" in python.


问:
dplyr - how to select columns of certain type
Is there a concise way to select columns of certain type in dplyr? For example, how to select all character columns within a dplyr chain?

答:
As of dplyr 1.0.0 *_if functions and friends have been superseded. Using the  selection helper where from tidyselect is now recommended.

https://dplyr.tidyverse.org/reference/select.html

https://tidyselect.r-lib.org/reference/where.html

library(dplyr)

starwars %>%
    select(where(is.character))
#> # A tibble: 87 x 8
#>    name        hair_color   skin_color eye_color sex   gender  homeworld species
#>    <chr>       <chr>        <chr>      <chr>     <chr> <chr>   <chr>     <chr>
#>  1 Luke Skywa~ blond        fair       blue      male  mascul~ Tatooine  Human
#>  2 C-3PO       <NA>         gold       yellow    none  mascul~ Tatooine  Droid
#>  3 R2-D2       <NA>         white, bl~ red       none  mascul~ Naboo     Droid
#>  4 Darth Vader none         white      yellow    male  mascul~ Tatooine  Human
#>  5 Leia Organa brown        light      brown     fema~ femini~ Alderaan  Human
#>  6 Owen Lars   brown, grey  light      blue      male  mascul~ Tatooine  Human
#>  7 Beru White~ brown        light      blue      fema~ femini~ Tatooine  Human
#>  8 R5-D4       <NA>         white, red red       none  mascul~ Tatooine  Droid
#>  9 Biggs Dark~ black        light      brown     male  mascul~ Tatooine  Human
#> 10 Obi-Wan Ke~ auburn, whi~ fair       blue-gray male  mascul~ Stewjon   Human
#> # ... with 77 more rows
```

Created on 2020-06-02 by the reprex package (v0.3.0)

Body:
As of dplyr 1.0.0 *_if functions and friends have been superseded. Using the  selection helper where from tidyselect is now recommended.

https://dplyr.tidyverse.org/reference/select.html

https://tidyselect.r-lib.org/reference/where.html

library(dplyr)

starwars %>%
    select(where(is.character))
#> # A tibble: 87 x 8
#>    name        hair_color   skin_color eye_color sex   gender  homeworld species
#>    <chr>       <chr>        <chr>      <chr>     <chr> <chr>   <chr>     <chr>
#>  1 Luke Skywa~ blond        fair       blue      male  mascul~ Tatooine  Human
#>  2 C-3PO       <NA>         gold       yellow    none  mascul~ Tatooine  Droid
#>  3 R2-D2       <NA>         white, bl~ red       none  mascul~ Naboo     Droid
#>  4 Darth Vader none         white      yellow    male  mascul~ Tatooine  Human
#>  5 Leia Organa brown        light      brown     fema~ femini~ Alderaan  Human
#>  6 Owen Lars   brown, grey  light      blue      male  mascul~ Tatooine  Human
#>  7 Beru White~ brown        light      blue      fema~ femini~ Tatooine  Human
#>  8 R5-D4       <NA>         white, red red       none  mascul~ Tatooine  Droid
#>  9 Biggs Dark~ black        light      brown     male  mascul~ Tatooine  Human
#> 10 Obi-Wan Ke~ auburn, whi~ fair       blue-gray male  mascul~ Stewjon   Human
#> # ... with 77 more rows

Created on 2020-06-02 by the reprex package (v0.3.0)


问:
Is there a way to compare every array value with eachother effectively?
So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.</p>

```<code>public static double FindSmallestNum(double[] arr)
    {
            double max = 0;
      for (int x=0;x<arr.Length-1;x++){
                if ( arr[x]>= arr[x+1]){
                    if (max >= arr[x+1]){
                       max = arr[x+1];
                    }
                }
                else if (max >=arr[x]){
                        max = arr[x];
                }
                else {
                            max = arr[x];
                }
            }
            return max;
        }
</code>```

答:
Your code can further be optimized. you can see the below logic. Complexity of this code is O(N)

```<code>static void GetSmallest(int[] arr)
{
    int first, arr_size = arr.Length;

    first = int.MaxValue;

    for (int i = 0; i < arr_size; i++)
    {
        if (arr[i] < first)
        {
            first = arr[i];
        }
    }
}
</code>```

You can use the below code also.

```<code>int[] arr = new int[5] { 1, 2, 3, 4, 5 };
int min = arr.Min();
</code>```

Body:
So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.

public static double FindSmallestNum(double[] arr)
    {
            double max = 0;
      for (int x=0;x<arr.Length-1;x++){
                if ( arr[x]>= arr[x+1]){
                    if (max >= arr[x+1]){
                       max = arr[x+1];
                    }
                }
                else if (max >=arr[x]){
                        max = arr[x];
                }
                else {
                            max = arr[x];
                }
            }
            return max;
        }

Body:
Your code can further be optimized. you can see the below logic. Complexity of this code is O(N)

static void GetSmallest(int[] arr)
{
    int first, arr_size = arr.Length;

    first = int.MaxValue;

    for (int i = 0; i < arr_size; i++)
    {
        if (arr[i] < first)
        {
            first = arr[i];
        }
    }
}

You can use the below code also.

int[] arr = new int[5] { 1, 2, 3, 4, 5 };
int min = arr.Min();


问:
Cross Origin Resource Sharing error while making put request in nodejs
I got this error while making put request.

Access to XMLHttpRequest at
  'http://localhost:5000/api/products/undefined' from origin
  'http://localhost:3000' has been blocked by CORS policy: Method PUT is
  not allowed by Access-Control-Allow-Methods in preflight response.

I have even included CORS policy in main server file

```<code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization",
    "Access-Control-Allow-Methods","GET, PUT, POST, OPTIONS"
  );
  next();
});
</code>```

答:
Did you notice that the parameter you send request to is "undefined" ?
("'http://localhost:5000/api/products/undefined'")

If the problem is caused by cors error, you can try this:
install cors package to your nodejs server

```<code>npm install cors
</code>```

then put this line to your server file:

```<code>....
var cors = require('cors')
app.use(cors())
....
</code>```

Body:
I got this error while making put request.

Access to XMLHttpRequest at
  'http://localhost:5000/api/products/undefined' from origin
  'http://localhost:3000' has been blocked by CORS policy: Method PUT is
  not allowed by Access-Control-Allow-Methods in preflight response.

I have even included CORS policy in main server file

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization",
    "Access-Control-Allow-Methods","GET, PUT, POST, OPTIONS"
  );
  next();
});

Body:
Did you notice that the parameter you send request to is "undefined" ?
("'http://localhost:5000/api/products/undefined'")

If the problem is caused by cors error, you can try this:
install cors package to your nodejs server

npm install cors

then put this line to your server file:

....
var cors = require('cors')
app.use(cors())
....


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答:
 </p>

```<code>sp_help 'YourTableName'
</code>```

Title: T-SQL query to show table definition?

Body: sp_help 'YourTableName'