问:
Parse JSON object in Flatlist React Native
I am new in React Native , I am developing an application like Ecommerce App, I am using Woocommerce (Wordpress) as backend and through Woocomrce Api response I am trying to implement in my React Native App, but I have one problem while parsing JSON. Basically I don't konw how to parse images array in flatlist. My code and API response are mentioned below, I remind you that item.images[0].src is not working.
Thank you in advance.

My Woocommerce  API Response

```<code>{
  "id": 794,
  "name": "Premium Quality",
  "slug": "premium-quality-19",
  "permalink": "https://example.com/product/premium-quality-19/",
  "date_created": "2017-03-23T17:01:14",
  "date_created_gmt": "2017-03-23T20:01:14",
  "date_modified": "2017-03-23T17:01:14",
  "date_modified_gmt": "2017-03-23T20:01:14",
  "type": "simple",
  "status": "publish",
  "featured": false,
  "catalog_visibility": "visible",
  "description": "<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>\n",
  "short_description": "<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>\n",
  "sku": "",
  "price": "21.99",
  "regular_price": "21.99",
  "sale_price": "",
  "date_on_sale_from": null,
  "date_on_sale_from_gmt": null,
  "date_on_sale_to": null,
  "date_on_sale_to_gmt": null,
  "price_html": "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">$</span>21.99</span>",
  "on_sale": false,
  "purchasable": true,
  "total_sales": 0,
  "virtual": false,
  "downloadable": false,
  "downloads": [],
  "download_limit": -1,
  "download_expiry": -1,
  "external_url": "",
  "button_text": "",
  "tax_status": "taxable",
  "tax_class": "",
  "manage_stock": false,
  "stock_quantity": null,
  "stock_status": "instock",
  "backorders": "no",
  "backorders_allowed": false,
  "backordered": false,
  "sold_individually": false,
  "weight": "",
  "dimensions": {
    "length": "",
    "width": "",
    "height": ""
  },
  "shipping_required": true,
  "shipping_taxable": true,
  "shipping_class": "",
  "shipping_class_id": 0,
  "reviews_allowed": true,
  "average_rating": "0.00",
  "rating_count": 0,
  "related_ids": [
    53,
    40,
    56,
    479,
    99
  ],
  "upsell_ids": [],
  "cross_sell_ids": [],
  "parent_id": 0,
  "purchase_note": "",
  "categories": [
    {
      "id": 9,
      "name": "Clothing",
      "slug": "clothing"
    },
    {
      "id": 14,
      "name": "T-shirts",
      "slug": "t-shirts"
    }
  ],
  "tags": [],
  "images": [
    {
      "id": 792,
      "date_created": "2017-03-23T14:01:13",
      "date_created_gmt": "2017-03-23T20:01:13",
      "date_modified": "2017-03-23T14:01:13",
      "date_modified_gmt": "2017-03-23T20:01:13",
      "src": "https://example.com/wp-content/uploads/2017/03/T_2_front-4.jpg",
      "name": "",
      "alt": ""
    },
    {
      "id": 793,
      "date_created": "2017-03-23T14:01:14",
      "date_created_gmt": "2017-03-23T20:01:14",
      "date_modified": "2017-03-23T14:01:14",
      "date_modified_gmt": "2017-03-23T20:01:14",
      "src": "https://example.com/wp-content/uploads/2017/03/T_2_back-2.jpg",
      "name": "",
      "alt": ""
    }
  ],
  "attributes": [],
  "default_attributes": [],
  "variations": [],
  "grouped_products": [],
  "menu_order": 0,
  "meta_data": [],
  "_links": {
    "self": [
      {
        "href": "https://example.com/wp-json/wc/v3/products/794"
      }
    ],
    "collection": [
      {
        "href": "https://example.com/wp-json/wc/v3/products"
      }
    ]
  }
}
</code>```

My APP.js Code

```<code> import React, { Component } from 'react';
    import { View, Text, Image, Dimensions, ActivityIndicator, StatusBar, FlatList } from 'react-native';
    import WooCommerceAPI from 'react-native-woocommerce-api';

var WooCommerceApp = new WooCommerceAPI({
    url: 'http://store.oruga.in/', // Your store URL
    ssl: true,
    consumerKey: 'ck_113e04d8a91ce34cbfeaf21971b6d5e18e7XXXXX', // Your consumer secret
    consumerSecret: 'cs_fd0f4b6a5573837b1f7732a98dccb355a233XXXXX', // Your consumer secret
    wpAPI: true, // Enable the WP REST API integration
    version: 'wc/v3', // WooCommerce WP REST API version
    queryStringAuth: true
});

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            responsedata: [],
            loading: true
        };
        WooCommerceApp.get('products/')
            .then(data => {
                this.setState({ responsedata: data }, () => {
                    this.setState({ loading: false });
                });
            })
            .catch(error => {
                console.log(error);
            });

    }

    render() {
        return (
            <View>
                <StatusBar hidden />
                {this.state.loading === true ? (
                    <View style={{ justifyContent: 'center', alignItems: 'center', height: Dimensions.get('window').height }}>
                        <ActivityIndicator size="large" color="#0f3443" />
                    </View>
                ) : (
                        <View>
                            <FlatList
                                data={this.state.responsedata}
                                keyExtractor={this._keyExtractor}
                                renderItem={({ item }) => (
                                    <View>
                                        <Image source={{ uri: item.images[0].src }} />
                                        <Text >{item.name}</Text>
                                    </View>

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

答:
You should pass an array as data to your FlatList, in your example you passed a JSON object to your flatlist that's why it doesn't render any thing. Also you should pass height and width to you image or it will not show.

Change your flatlist like this and it should work.

```<code><View>
  <FlatList
    data={this.state.responsedata.images}
    keyExtractor={item => `${item.id}`}
    renderItem={({ item }) => (
      <View>
        <Image style={{ height: 100, width: 100 }} source={{ uri: item.src }} />
        <Text>{item.name}</Text>
      </View>

    )}
  />
</View>
</code>```

Other thing, don't call setState in your constructor, it will show you a warning. Move the api call to componentDidMount function:

```<code>componentDidMount() {
  WooCommerceApp.get('products/')
    .then((data) => {
      this.setState({ responsedata: data }, () => {
        this.setState({ loading: false });
      });
    })
    .catch((error) => {
      console.log(error);
    });
}
</code>```

Edit:
If you need the response json then you don't need FlatList, FlatList is to show a List of items. And if you want to show only first image then change your FlatList like this

```<code><Image style={{ height: 100, width: 100 }} source={{ uri: this.state.responsedata.images[0].src }} />
</code>```

Body:
I am new in React Native , I am developing an application like Ecommerce App, I am using Woocommerce (Wordpress) as backend and through Woocomrce Api response I am trying to implement in my React Native App, but I have one problem while parsing JSON. Basically I don't konw how to parse images array in flatlist. My code and API response are mentioned below, I remind you that item.images[0].src is not working.
Thank you in advance.

My Woocommerce  API Response

{
  "id": 794,
  "name": "Premium Quality",
  "slug": "premium-quality-19",
  "permalink": "https://example.com/product/premium-quality-19/",
  "date_created": "2017-03-23T17:01:14",
  "date_created_gmt": "2017-03-23T20:01:14",
  "date_modified": "2017-03-23T17:01:14",
  "date_modified_gmt": "2017-03-23T20:01:14",
  "type": "simple",
  "status": "publish",
  "featured": false,
  "catalog_visibility": "visible",
  "description": "
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
\n",
  "short_description": "
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
\n",
  "sku": "",
  "price": "21.99",
  "regular_price": "21.99",
  "sale_price": "",
  "date_on_sale_from": null,
  "date_on_sale_from_gmt": null,
  "date_on_sale_to": null,
  "date_on_sale_to_gmt": null,
  "price_html": "$21.99",
  "on_sale": false,
  "purchasable": true,
  "total_sales": 0,
  "virtual": false,
  "downloadable": false,
  "downloads": [],
  "download_limit": -1,
  "download_expiry": -1,
  "external_url": "",
  "button_text": "",
  "tax_status": "taxable",
  "tax_class": "",
  "manage_stock": false,
  "stock_quantity": null,
  "stock_status": "instock",
  "backorders": "no",
  "backorders_allowed": false,
  "backordered": false,
  "sold_individually": false,
  "weight": "",
  "dimensions": {
    "length": "",
    "width": "",
    "height": ""
  },
  "shipping_required": true,
  "shipping_taxable": true,
  "shipping_class": "",
  "shipping_class_id": 0,
  "reviews_allowed": true,
  "average_rating": "0.00",
  "rating_count": 0,
  "related_ids": [
    53,
    40,
    56,
    479,
    99
  ],
  "upsell_ids": [],
  "cross_sell_ids": [],
  "parent_id": 0,
  "purchase_note": "",
  "categories": [
    {
      "id": 9,
      "name": "Clothing",
      "slug": "clothing"
    },
    {
      "id": 14,
      "name": "T-shirts",
      "slug": "t-shirts"
    }
  ],
  "tags": [],
  "images": [
    {
      "id": 792,
      "date_created": "2017-03-23T14:01:13",
      "date_created_gmt": "2017-03-23T20:01:13",
      "date_modified": "2017-03-23T14:01:13",
      "date_modified_gmt": "2017-03-23T20:01:13",
      "src": "https://example.com/wp-content/uploads/2017/03/T_2_front-4.jpg",
      "name": "",
      "alt": ""
    },
    {
      "id": 793,
      "date_created": "2017-03-23T14:01:14",
      "date_created_gmt": "2017-03-23T20:01:14",
      "date_modified": "2017-03-23T14:01:14",
      "date_modified_gmt": "2017-03-23T20:01:14",
      "src": "https://example.com/wp-content/uploads/2017/03/T_2_back-2.jpg",
      "name": "",
      "alt": ""
    }
  ],
  "attributes": [],
  "default_attributes": [],
  "variations": [],
  "grouped_products": [],
  "menu_order": 0,
  "meta_data": [],
  "_links": {
    "self": [
      {
        "href": "https://example.com/wp-json/wc/v3/products/794"
      }
    ],
    "collection": [
      {
        "href": "https://example.com/wp-json/wc/v3/products"
      }
    ]
  }
}

My APP.js Code

 import React, { Component } from 'react';
    import { View, Text, Image, Dimensions, ActivityIndicator, StatusBar, FlatList } from 'react-native';
    import WooCommerceAPI from 'react-native-woocommerce-api';

var WooCommerceApp = new WooCommerceAPI({
    url: 'http://store.oruga.in/', // Your store URL
    ssl: true,
    consumerKey: 'ck_113e04d8a91ce34cbfeaf21971b6d5e18e7XXXXX', // Your consumer secret
    consumerSecret: 'cs_fd0f4b6a5573837b1f7732a98dccb355a233XXXXX', // Your consumer secret
    wpAPI: true, // Enable the WP REST API integration
    version: 'wc/v3', // WooCommerce WP REST API version
    queryStringAuth: true
});

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            responsedata: [],
            loading: true
        };
        WooCommerceApp.get('products/')
            .then(data => {
                this.setState({ responsedata: data }, () => {
                    this.setState({ loading: false });
                });
            })
            .catch(error => {
                console.log(error);
            });

    }

    render() {
        return (
            <View>
                <StatusBar hidden />
                {this.state.loading === true ? (
                    <View style={{ justifyContent: 'center', alignItems: 'center', height: Dimensions.get('window').height }}>
                        <ActivityIndicator size="large" color="#0f3443" />
                    </View>
                ) : (
                        <View>
                            <FlatList
                                data={this.state.responsedata}
                                keyExtractor={this._keyExtractor}
                                renderItem={({ item }) => (
                                    <View>
                                        <Image source={{ uri: item.images[0].src }} />
                                        <Text >{item.name}</Text>
                                    </View>

                                )} />
                        </View>)
                }
            </View>
        );
    }
}

Body:
You should pass an array as data to your FlatList, in your example you passed a JSON object to your flatlist that's why it doesn't render any thing. Also you should pass height and width to you image or it will not show.

Change your flatlist like this and it should work.

<View>
  <FlatList
    data={this.state.responsedata.images}
    keyExtractor={item => `${item.id}`}
    renderItem={({ item }) => (
      <View>
        <Image style={{ height: 100, width: 100 }} source={{ uri: item.src }} />
        <Text>{item.name}</Text>
      </View>

    )}
  />
</View>

Other thing, don't call setState in your constructor, it will show you a warning. Move the api call to componentDidMount function:

componentDidMount() {
  WooCommerceApp.get('products/')
    .then((data) => {
      this.setState({ responsedata: data }, () => {
        this.setState({ loading: false });
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

Edit:
If you need the response json then you don't need FlatList, FlatList is to show a List of items. And if you want to show only first image then change your FlatList like this

<Image style={{ height: 100, width: 100 }} source={{ uri: this.state.responsedata.images[0].src }} />


来源: stackexchange

问:
Wrapping elements with Vue
Sorry for the long post.
In my vue code, I fetch cities from an API.

```<code>new Vue({
  data: {
    cities: []
  },
  el: '#app',
  methods: {
    fetchCities() {
      fetch('https://fakeapi.app/cities/')
        .then(response => response.json())
        .then(result => {
          this.cities = result
          console.log(result)

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

... Using this HTML code:

```<code><div id="app">
      <dl>
        <dt>
          <li v-for="city in cities">{{ city.name }}</li>
        </dt>
        <dd>
          <li v-for="city in cities">{{ city.population }}</li>
        </dd>
    </dl>
      <input @click="fetchCities" type="button" value="Get cities">
    </div>
</code>```

Which produces:

```<code>Stockholm
Göteborg
Malmö
Uppsala
Västerås
Örebro
Linköping
Helsingborg
Jönköping
Norrköping
   • 1372565
   • 549839
   • 280415
   • 140454
   • 110877
   • 107038
   • 104232
   • 97122
   • 89396
   • 87247
</code>```

To be overly-specific: The first row are the cities, and the row under are their respective population.

I want to make so each city name name is in it's own dt-element, and the population is also in it's on dd-element. I also want to use the v-for in combination with atemplete-element so that a dt and a dd-element is created for each city, as the dt-and the dd elements are direct children of the dl-element in the HTML-structure.

I want the outcome to look something like this:

```<code>Stockholm
• 1372565
Göteborg
• 549839
Malmö
• 280415
Uppsala
• 140454
Västerås
• 110877
Örebro
• 107038
Linköping
• 104232
Helsingborg
• 97122
Jönköping
• 89396
Norrköping
• 87247
</code>```

答:
No need to use
, that's only for
 and

Iterate using a <template> to get through the cities.

```<code><div id="app">
  <dl>
    <template v-for="city in cities">
      <dt :key="city.name">{{ city.name }}</dt>
      <dd :key="`${city.name}-pop`">{{ city.population}}</dd>
    </template>
  </dl>
  <input @click="fetchCities" type="button" value="Get cities">
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Wrapping elements with Vue

Body:
Sorry for the long post.
In my vue code, I fetch cities from an API.

new Vue({
  data: {
    cities: []
  },
  el: '#app',
  methods: {
    fetchCities() {
      fetch('https://fakeapi.app/cities/')
        .then(response => response.json())
        .then(result => {
          this.cities = result
          console.log(result)

        })
    }
  }
})

... Using this HTML code:

{{ city.name }}

{{ city.population }}

      <input @click="fetchCities" type="button" value="Get cities">

Which produces:

Stockholm
Göteborg
Malmö
Uppsala
Västerås
Örebro
Linköping
Helsingborg
Jönköping
Norrköping
   • 1372565
   • 549839
   • 280415
   • 140454
   • 110877
   • 107038
   • 104232
   • 97122
   • 89396
   • 87247

To be overly-specific: The first row are the cities, and the row under are their respective population.

I want to make so each city name name is in it's own dt-element, and the population is also in it's on dd-element. I also want to use the v-for in combination with atemplete-element so that a dt and a dd-element is created for each city, as the dt-and the dd elements are direct children of the dl-element in the HTML-structure.

I want the outcome to look something like this:

Stockholm
• 1372565
Göteborg
• 549839
Malmö
• 280415
Uppsala
• 140454
Västerås
• 110877
Örebro
• 107038
Linköping
• 104232
Helsingborg
• 97122
Jönköping
• 89396
Norrköping
• 87247

Body:
No need to use <li>, that's only for <ol> and <ul>

Iterate using a <template> to get through the cities.

<div id="app">
  <dl>
    <template v-for="city in cities">
      <dt :key="city.name">{{ city.name }}</dt>
      <dd :key="`${city.name}-pop`">{{ city.population}}</dd>
    </template>
  </dl>
  <input @click="fetchCities" type="button" value="Get cities">
</div>


问:
How to search string with strstr but with a key word that was not assigned by the user
This is the code

```<code>int main()
{
    FILE* fptr;
    char c_id[50];
    char str[BUFFER_SIZE];
    int choices;
    char* pos;
    int customer_id;
    printf("Enter customer ID: ");
    scanf("%d", &customer_id);
    sprintf(c_id, "%d", customer_id);
    fptr = fopen("servicestest.txt", "r");
    printf("\n1. Check for unpaid\n2. Check for paid\n");
    scanf("%d", &choices);
    switch (choices)
    {
    case 1:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");

            if (pos == 1)
            {
                printf("%s\n", str);
            }
        }
        break;
    case 2:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");
            if (pos =! 1)
            {
                printf("%s\n", str);
            }
        }
  }
}
</code>```

Was planning to check a line with not and print them how to do that? Why is it not printing anything when I inputted "1" as choices

I wanted to assign

```<code>char ch[50];
ch[1] = "Not";
</code>```

but when i tried the strstr (str, ch[1]) it caused an error

Any idea how to do it?

答:
"Why is it not printing anything when I inputted 1 as choices

char ch[1] = "Not"; is problematic, and invokes undefined behavior (UB)

The string literal "Not" has 4 characters:  |N|o|t|\0|

The statement char ch[1]; creates space for only one character, accessible in the zeroth element: ch[0].

This causes the statement strstr (str, ch[1]) to also invoke UB, since ch[1] does not exist, only 1 element exists - ch[0].

The fix for this is to always provide enough space for the content needed.  These are valid way to create ch with enough space:

```<code>char ch[50] = "Not";//char array of 50 initialized to "Not"
char ch[4] = "Not";//char array of 4 initialized to "Not"
char ch[] = "Not";//char array of 4 initialized to "Not" (implicitly sized)
char *ch = "Not";//char * initialized to same string literal but not editable.
</code>```

Using any of these will work with as shown in your code segment:

```<code>pos = strstr(str, "Not");
</code>```

But usage of the result pos is to evaluate its contents as a pointer, not as an integer:

```<code>pos = strstr(str, "Not");
//if (pos =! 1)//wrong - pos is a pointer
// if (pos =! NULL)//ok - test for non-NULL
if (pos)//ok - implicit test for non-NULL
{
    printf("%s\n", str);
}
</code>```

Body:
This is the code

int main()
{
    FILE* fptr;
    char c_id[50];
    char str[BUFFER_SIZE];
    int choices;
    char* pos;
    int customer_id;
    printf("Enter customer ID: ");
    scanf("%d", &customer_id);
    sprintf(c_id, "%d", customer_id);
    fptr = fopen("servicestest.txt", "r");
    printf("\n1. Check for unpaid\n2. Check for paid\n");
    scanf("%d", &choices);
    switch (choices)
    {
    case 1:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");

            if (pos == 1)
            {
                printf("%s\n", str);
            }
        }
        break;
    case 2:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");
            if (pos =! 1)
            {
                printf("%s\n", str);
            }
        }
  }
}

Was planning to check a line with not and print them how to do that? Why is it not printing anything when I inputted "1" as choices

I wanted to assign

char ch[50];
ch[1] = "Not";

but when i tried the strstr (str, ch[1]) it caused an error

Any idea how to do it?

Body:
"Why is it not printing anything when I inputted 1 as choices

char ch[1] = "Not"; is problematic, and invokes undefined behavior (UB)

The string literal "Not" has 4 characters:  |N|o|t|\0|

The statement char ch[1]; creates space for only one character, accessible in the zeroth element: ch[0].

This causes the statement strstr (str, ch[1]) to also invoke UB, since ch[1] does not exist, only 1 element exists - ch[0].

The fix for this is to always provide enough space for the content needed.  These are valid way to create ch with enough space:

char ch[50] = "Not";//char array of 50 initialized to "Not"
char ch[4] = "Not";//char array of 4 initialized to "Not"
char ch[] = "Not";//char array of 4 initialized to "Not" (implicitly sized)
char *ch = "Not";//char * initialized to same string literal but not editable.

Using any of these will work with as shown in your code segment:

pos = strstr(str, "Not");

But usage of the result pos is to evaluate its contents as a pointer, not as an integer:

pos = strstr(str, "Not");
//if (pos =! 1)//wrong - pos is a pointer
// if (pos =! NULL)//ok - test for non-NULL
if (pos)//ok - implicit test for non-NULL
{
    printf("%s\n", str);
}


问:
Autosize textview is not working
Hi I am using autosize textview in my android application. My app minSdkVersion is 19 so I am using support library.

https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.app.android.registration.RegistrationActivity"
    tools:ignore="missingPrefix">

    <include
        android:id="@+id/toolbar_registration_layout"
        layout="@layout/toolbar" />

    <TextView
        android:id="@+id/textview_registration_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lato_medium"
        android:padding="8dp"
        android:text="@string/registration_title"
        app:autoSizeTextType="uniform"
        app:layout_constraintTop_toBottomOf="@id/toolbar" />

</android.support.constraint.ConstraintLayout>
</code>```

Does anyone know why it is not resizing as there is lot of space available on right side of it.

答: In my case using only fixed dimension or match_parent didn't work. I had to add "maxLines=1" and "lines=1". Don't know why is this not made obvious in the documentation.</p>

ContentLicense: CC BY-SA 3.0

Title: Autosize textview is not working

Body:
Hi I am using autosize textview in my android application. My app minSdkVersion is 19 so I am using support library.

https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.app.android.registration.RegistrationActivity"
    tools:ignore="missingPrefix">

    <include
        android:id="@+id/toolbar_registration_layout"
        layout="@layout/toolbar" />

    <TextView
        android:id="@+id/textview_registration_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lato_medium"
        android:padding="8dp"
        android:text="@string/registration_title"
        app:autoSizeTextType="uniform"
        app:layout_constraintTop_toBottomOf="@id/toolbar" />

</android.support.constraint.ConstraintLayout>

Does anyone know why it is not resizing as there is lot of space available on right side of it.


问:
how to change the bounding box color in the video output in yolov3 darknet
I have trained YOLOv3 darknet model on my custom dataset. First I have cloned the https://github.com/kriyeng/darknet/ repository in google colab and then run the whole code in google colab. But I want to change the color of the bounding boxes in the output video. Please suggest how to do it. Thanks in advance.

答:
Here is a solution in C++ but you can apply it to python as well. Just change the values in Scalar. In the example below it is set to the color red. </p>

```<code>//Draw a rectangle displaying the bounding box
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255));

</code>```

Body:
Here is a solution in C++ but you can apply it to python as well. Just change the values in Scalar. In the example below it is set to the color red.

//Draw a rectangle displaying the bounding box
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255));


问:
Flyway integration with Git and connecting to Snowflake
We have an existing database with several tables and every time we make any changes to the schema of some table we had to run some manual scripts to avoid any data loss.
we are looking for software that can integrate with our Git repo and generate the updated DDL's for the database.

I came across Flyway database migration tool and going through the documentation had this question about integration with code repo where changes to database schema are pushed.

Also Does FLyway work with Snowflake. if yes, where can i add the required jdbc drivers to connect to the database and what would be the .conf file for Snowflake connection.

答:
I use flyway 6.4.2 and is working with this configuration in pom file:</p>

```<code><execution>
    <id>my_sf_migration</id>
    <phase>compile</phase>
    <goals>
        <goal>migrate</goal>
    </goals>
    <configuration>
        <!--This is where I got the driver wrong, that is why it was not working -->
        <driver>net.snowflake.client.jdbc.SnowflakeDriver</driver>
        <configFiles>
            <configFile>./conf/flyway_sf.conf</configFile>
        </configFiles>
    </configuration>
</execution>
</code>```

Body:
I use flyway 6.4.2 and is working with this configuration in pom file:

<execution>
    <id>my_sf_migration</id>
    <phase>compile</phase>
    <goals>
        <goal>migrate</goal>
    </goals>
    <configuration>
        <!--This is where I got the driver wrong, that is why it was not working -->
        <driver>net.snowflake.client.jdbc.SnowflakeDriver</driver>
        <configFiles>
            <configFile>./conf/flyway_sf.conf</configFile>
        </configFiles>
    </configuration>
</execution>


问:
CUDA syntax error '<'
in my test.cu file (cu file item type is CUDA C/C++)

```<code>__global__ void foo()
{
}

void CudaMain()
{

  foo<<<1,1>>>();
}
</code>```

and in my test.cpp file

```<code>#include "mycuda.cu"

int main()
{

CudaMain();
return 0;

}
</code>```

and compilator send me error "error c2059 syntax error ' <' " in test.cu file

答:
Based on the thread here: https://forums.developer.nvidia.com/t/cuda-build-error/52615/4

Your test file extension should be .cu as well, but if you're using MSCV rename does not enough you should create a new CUDA C/C++ source module in your VS project.

Also you should put spaces between the <> operators like.

```<code>foo< < <1,1> > >();
</code>```

Because C++ cannot parse the <<<>>>.

Title: CUDA syntax error '<'

Body:
in my test.cu file (cu file item type is CUDA C/C++)

__global__ void foo()
{
}

void CudaMain()
{

  foo<<<1,1>>>();
}

and in my test.cpp file

#include "mycuda.cu"

int main()
{

CudaMain();
return 0;

}

and compilator send me error "error c2059 syntax error ' <' " in test.cu file

Body:
Based on the thread here: https://forums.developer.nvidia.com/t/cuda-build-error/52615/4

Your test file extension should be .cu as well, but if you're using MSCV rename does not enough you should create a new CUDA C/C++ source module in your VS project.

Also you should put spaces between the <> operators like.

foo< < <1,1> > >();

Because C++ cannot parse the <<<>>>.


问:
Django - validating and saving ModelForm with editable=false fields
I do apologise for all the questions I'm posting today, but I'm at my wits end on this one.

I'm trying to make a Q&A thing for a video site, and I'm trying to get the question to submit via AJAX.

Question model:

```<code>class Question(models.Model):
    user = models.ForeignKey(User, editable=False)
    video = models.ForeignKey(Video, editable=False)
    section = models.ForeignKey(Section, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
</code>```

ModelForm:

```<code>class QuestionForm(ModelForm):
    def __init__(self, video, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['section'].queryset = Section.objects.filter(video=video)

    class Meta:
        model = Question
</code>```

POST parameters sent by jQuery's AJAX request (the video parameter is added by the Javascript code):

```<code>section=6&title=test&description=test&video=1
</code>```

And finally, here's the view I'm working on to handle the submit:

```<code>def question_submit(request):
    u = request.user
    if u.is_authenticated():
        q=QuestionForm(request.POST)

        if q.is_valid():
            logger.debug("YES!")
        else:
            logger.debug("NO!")

        f=q.save(commit=False)
        f.user=u
        f.video_id=int(request.POST['video'])

        f.save()
        return HttpResponse("OK")
    else:
        return JsonResponse({'failed': 'You are not logged in. Try logging in in a new tab, then re-submit your question.'})
</code>```

As suggested by the docs, I'm saving with commit=false so that I can modify the object.

I have two problems:

When it reaches q.is_valid(), it throws the error "'QuestionForm' object has no attribute 'cleaned_data'".

If I take out the q.is_valid() bit, f.save() succeeds, but it inserts a blank row into the database.

To anyone who can help, I owe you my sanity.

答:
You aren't passing in video in the view:

forms.py

```<code>def __init__(self, video, *args, **kwargs):
</code>```

views.py

```<code>q=QuestionForm(request.POST)
</code>```

as video is a positional argument, I'd imagine it is interpreting request.POST as the video?

You could change video to a keyword argument:

```<code>def __init__(self, video=None, *args, **kwargs):
    if video:
         ...
</code>```

as mordi metions, you should check if a) it's a valid POST, and b) it's an ajax request

```<code>def question_submit(request):
    if request.method == "POST" and request.is_ajax():
        ...
</code>```

Body:
I do apologise for all the questions I'm posting today, but I'm at my wits end on this one.

I'm trying to make a Q&A thing for a video site, and I'm trying to get the question to submit via AJAX.

Question model:

class Question(models.Model):
    user = models.ForeignKey(User, editable=False)
    video = models.ForeignKey(Video, editable=False)
    section = models.ForeignKey(Section, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)

ModelForm:

class QuestionForm(ModelForm):
    def __init__(self, video, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['section'].queryset = Section.objects.filter(video=video)

    class Meta:
        model = Question

POST parameters sent by jQuery's AJAX request (the video parameter is added by the Javascript code):

section=6&title=test&description=test&video=1

And finally, here's the view I'm working on to handle the submit:

def question_submit(request):
    u = request.user
    if u.is_authenticated():
        q=QuestionForm(request.POST)

        if q.is_valid():
            logger.debug("YES!")
        else:
            logger.debug("NO!")

        f=q.save(commit=False)
        f.user=u
        f.video_id=int(request.POST['video'])

        f.save()
        return HttpResponse("OK")
    else:
        return JsonResponse({'failed': 'You are not logged in. Try logging in in a new tab, then re-submit your question.'})

As suggested by the docs, I'm saving with commit=false so that I can modify the object.

I have two problems:

When it reaches q.is_valid(), it throws the error "'QuestionForm' object has no attribute 'cleaned_data'".

If I take out the q.is_valid() bit, f.save() succeeds, but it inserts a blank row into the database.

To anyone who can help, I owe you my sanity.

Body:
You aren't passing in video in the view:

forms.py

def __init__(self, video, *args, **kwargs):

views.py

q=QuestionForm(request.POST)

as video is a positional argument, I'd imagine it is interpreting request.POST as the video?

You could change video to a keyword argument:

def __init__(self, video=None, *args, **kwargs):
    if video:
         ...

as mordi metions, you should check if a) it's a valid POST, and b) it's an ajax request

def question_submit(request):
    if request.method == "POST" and request.is_ajax():
        ...


问:
Building Doxygen on MSYS2
Currently I'm facing a problem, compiling Doxygen on MSYS2 using either MinGW32 or Mingw-w64 on Windows 10.

I did:

git clone https://github.com/doxygen/doxygen.git

cd doxygen && mkdir build && cd build

cmake -G "Unix Makefiles" ..

make

When using MinGW32 I get the following errors:

```<code>In file included from C:/msys64/home/dglaser/GIT/doxygen/src/layout.cpp:36:0:
C:/msys64/home/dglaser/GIT/doxygen/build/generated_src/layout_default.xml.h:1:1: warning: missing terminating " character
  \n"doxygenlayout version=\"1.0\">
  ^
[...]
</code>```

When using Mingw-w64 (after deleting build and do above steps again), everything compiles fine and I get errors during linkage:

```<code>C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36dd6): undefined reference to `QFileInfo::absFilePath() const'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36e84): undefined reference to `QFileInfo::isFile() const'
[...]
</code>```

How can one of those be solved?

答:
When using MSYS2 you should use:

```<code>cmake.exe -G"MSYS Makefiles"
</code>```

When I build from the latest source tarball http://doxygen.nl/files/doxygen-1.8.18.src.tar.gz it works after I removed the line containing /bigobj from CMakeLists.txt.

Title: Building Doxygen on MSYS2

Body:
Currently I'm facing a problem, compiling Doxygen on MSYS2 using either MinGW32 or Mingw-w64 on Windows 10.

I did:

git clone https://github.com/doxygen/doxygen.git

cd doxygen && mkdir build && cd build

cmake -G "Unix Makefiles" ..

make

When using MinGW32 I get the following errors:

In file included from C:/msys64/home/dglaser/GIT/doxygen/src/layout.cpp:36:0:
C:/msys64/home/dglaser/GIT/doxygen/build/generated_src/layout_default.xml.h:1:1: warning: missing terminating " character
  \n"doxygenlayout version=\"1.0\">
  ^
[...]

When using Mingw-w64 (after deleting build and do above steps again), everything compiles fine and I get errors during linkage:

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36dd6): undefined reference to `QFileInfo::absFilePath() const'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36e84): undefined reference to `QFileInfo::isFile() const'
[...]

How can one of those be solved?

Body:
When using MSYS2 you should use:

cmake.exe -G"MSYS Makefiles"

When I build from the latest source tarball http://doxygen.nl/files/doxygen-1.8.18.src.tar.gz it works after I removed the line containing /bigobj from CMakeLists.txt.


问:
What is the right way to destroy a form in Delphi?
I only kept main form in auto-create forms and removed the rest. Basically I call those forms with

```<code>TMyForm.Create(Self).Show;
</code>```

But when my works are done with this form, how can I release the resources this form used with best way? I looked up Free, Action.CaFree, Destroy, FreeAndNil functions but I can't get it all.

I'm looking for best practices.

Thanks.

答:
if you are creating a form and you want it to free itself up after closing then in the ONCLOSE event write
action := cafree;

this way you won't have to use TRY ... Finally block to free it up.

Body:
I only kept main form in auto-create forms and removed the rest. Basically I call those forms with

TMyForm.Create(Self).Show;

But when my works are done with this form, how can I release the resources this form used with best way? I looked up Free, Action.CaFree, Destroy, FreeAndNil functions but I can't get it all.

I'm looking for best practices.

Thanks.


问:
creating new pages in ruby on rails 6
I have created a rails 6 app with scaffold that has two fields, name_of_the_user and user_country, now there are only three  possible countries "USA", "AUSTRALIA" & "JAPAN" I want to move users from each country to a new page. As a result my index.html.haml should have three new links for "USA", "AUSTRALIA" & "JAPAN" which redirect me to users of japan page, users of Australia page and users of USA page. I am new to ruby and not able to find any solution for this.</p>

```<code>%h1 USER
= link_to 'New User', new_user_path
%table
 %thead
  %tr
  %th Name
  %th Country

%tbody
- @users.each do |user|
  %tr
    %td= link_to user.name,user
    %td= user.country
</code>```

答:
You could just add some links to the same index page but with query parameters  to your view:

```<code>= link_to 'All Users', users_path
= link_to 'USA', users_path(country: 'USA')
= link_to 'Australia', users_path(country: 'AUSTRALIA')
= link_to 'Japan', users_path(country: 'JAPAN')
</code>```

And when use add an additional database where conditions to your index method in the controller:

```<code>def index
  @users = User.all
  @users = @users.where(country: params[:country]) if params[:country].present?
end
</code>```

This will only work when the country in your database is actually stored only in uppercase characters like you wrote in your question. When it is stored downcase or titleized then you would need to change the format of the query string or sanitize the input in your controller.

Title: creating new pages in ruby on rails 6

Body:
I have created a rails 6 app with scaffold that has two fields, name_of_the_user and user_country, now there are only three  possible countries "USA", "AUSTRALIA" & "JAPAN" I want to move users from each country to a new page. As a result my index.html.haml should have three new links for "USA", "AUSTRALIA" & "JAPAN" which redirect me to users of japan page, users of Australia page and users of USA page. I am new to ruby and not able to find any solution for this.

%h1 USER
= link_to 'New User', new_user_path
%table
 %thead
  %tr
  %th Name
  %th Country

%tbody
- @users.each do |user|
  %tr
    %td= link_to user.name,user
    %td= user.country

Body:
You could just add some links to the same index page but with query parameters  to your view:

= link_to 'All Users', users_path
= link_to 'USA', users_path(country: 'USA')
= link_to 'Australia', users_path(country: 'AUSTRALIA')
= link_to 'Japan', users_path(country: 'JAPAN')

And when use add an additional database where conditions to your index method in the controller:

def index
  @users = User.all
  @users = @users.where(country: params[:country]) if params[:country].present?
end

This will only work when the country in your database is actually stored only in uppercase characters like you wrote in your question. When it is stored downcase or titleized then you would need to change the format of the query string or sanitize the input in your controller.


问:
Modal Popup Extender animation in ASP.net
I am currently developing an ASP.net c# application. I have a grid view which has bound link buttons inside. When the link button is pressed I want to display the modal popup using a fade in animation and a fade out animation when a button inside the modal popup is clicked.

I have added the animation extender into the code and set the TargetControlID to the ID of the link button, however, when I try to run the website it displays the error System.InvalidOperationException  the TargetControID of ModalPopupExtender is not valid. A control with ID 'sofLink' could not be found. sofLink is the ID of the LinkButton.

Below is the code for the grid view

```<code><asp:GridView ID="tblSoftware" runat="server" Width="100%"
                        EnableModelValidation="True" AutoGenerateColumns="False"
                        onselectedindexchanged="tblSoftware_SelectedIndexChanged"
                        CellPadding="2">
                        <Columns>
                            <asp:TemplateField HeaderText="Software Name">
                                <ItemTemplate>
                                <asp:LinkButton ID="sofLink" Text='<%# Bind("sof_softwareName") %>'
                                 CommandName="sofID" OnCommand="GetSoftwareModal" CommandArgument='<%# Eval("sof_id") %>' runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="sof_platform" HeaderText="Platform" ReadOnly="True" SortExpression="sof_platform" />
                        </Columns>
                        <HeaderStyle CssClass="gridHeader" />
                        <PagerSettings Position="Bottom" />
                        <PagerStyle HorizontalAlign="Right" VerticalAlign="Middle" CssClass="gridPage" />
                        <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
                    </asp:GridView>
</code>```

And below is the code for the ModalPopupExtender

```<code><ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="sofLink"
                    PopupControlID="ModalPanel" DropShadow="true" Drag="true" OkControlID="OKButton" />

               <asp:Panel ID="ModalPanel"  runat="server" Width="500px" style="width: auto; height: auto;" CssClass="modalPopup">
                    <asp:Label ID="softwareTitle" Font-Bold="true" Font-Size="Medium" runat="server" Width="100%" style="text-align: center;" /><br /><br />
                    <asp:Literal ID="litSoftware" runat="server"></asp:Literal>
                    <asp:Button id="OKButton" runat="server" Text="Close" style="position: relative; right: 0px; width: 100px;" />
               </asp:Panel>

               <asp:ScriptManager ID="asm" runat="server" />
</code>```

And below is the code for the animation

```<code>       <ajaxToolkit:AnimationExtender ID="popupAnimation" runat="server"
            TargetControlID="sofLink">

            <Animations>
                <OnClick>
                    <Parallel AnimationTarget="ModalPanel"
                    Duration="0.3" Fps="25">
                    <FadeIn />
                    </Parallel>
                </OnClick>
            </Animations>
       </ajaxToolkit:AnimationExtender>
</code>```

Thanks for any help you can provide.

答:
The TargetControlID (as far as I am aware) should be a control in the popup panel itself, not in the grid control. When I use the ModalPopupExtender I usually use  an asp:Button with 'display:none' as the TargetControlID. Eg,

```<code><ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="btnPopup"
                PopupControlID="ModalPanel" DropShadow="true" Drag="true" OkControlID="OKButton" />
<asp:Panel ID="ModalPanel"  runat="server" Width="500px" style="width: auto; height: auto;" CssClass="modalPopup">
<asp:Button id="btnPopup" runat="server" style="display:none" />
</code>```

In the code-behind you have to control the showing and hiding of the control base on an event, eg, GetSoftwareModal. You will also also to bind what you need if applicable.

Hope that helps.

Body:
I am currently developing an ASP.net c# application. I have a grid view which has bound link buttons inside. When the link button is pressed I want to display the modal popup using a fade in animation and a fade out animation when a button inside the modal popup is clicked.

I have added the animation extender into the code and set the TargetControlID to the ID of the link button, however, when I try to run the website it displays the error System.InvalidOperationException  the TargetControID of ModalPopupExtender is not valid. A control with ID 'sofLink' could not be found. sofLink is the ID of the LinkButton.

Below is the code for the grid view

<asp:GridView ID="tblSoftware" runat="server" Width="100%"
                        EnableModelValidation="True" AutoGenerateColumns="False"
                        onselectedindexchanged="tblSoftware_SelectedIndexChanged"
                        CellPadding="2">
                        <Columns>
                            <asp:TemplateField HeaderText="Software Name">
                                <ItemTemplate>
                                <asp:LinkButton ID="sofLink" Text='<%# Bind("sof_softwareName") %>'
                                 CommandName="sofID" OnCommand="GetSoftwareModal" CommandArgument='<%# Eval("sof_id") %>' runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="sof_platform" HeaderText="Platform" ReadOnly="True" SortExpression="sof_platform" />
                        </Columns>
                        <HeaderStyle CssClass="gridHeader" />
                        <PagerSettings Position="Bottom" />
                        <PagerStyle HorizontalAlign="Right" VerticalAlign="Middle" CssClass="gridPage" />
                        <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
                    </asp:GridView>

And below is the code for the ModalPopupExtender

<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="sofLink"
                    PopupControlID="ModalPanel" DropShadow="true" Drag="true" OkControlID="OKButton" />

               <asp:Panel ID="ModalPanel"  runat="server" Width="500px" style="width: auto; height: auto;" CssClass="modalPopup">
                    <asp:Label ID="softwareTitle" Font-Bold="true" Font-Size="Medium" runat="server" Width="100%" style="text-align: center;" />

                    <asp:Literal ID="litSoftware" runat="server"></asp:Literal>
                    <asp:Button id="OKButton" runat="server" Text="Close" style="position: relative; right: 0px; width: 100px;" />
               </asp:Panel>

               <asp:ScriptManager ID="asm" runat="server" />

And below is the code for the animation

       <ajaxToolkit:AnimationExtender ID="popupAnimation" runat="server"
            TargetControlID="sofLink">

            <Animations>
                <OnClick>
                    <Parallel AnimationTarget="ModalPanel"
                    Duration="0.3" Fps="25">
                    <FadeIn />
                    </Parallel>
                </OnClick>
            </Animations>
       </ajaxToolkit:AnimationExtender>

Thanks for any help you can provide.

Body:
The TargetControlID (as far as I am aware) should be a control in the popup panel itself, not in the grid control. When I use the ModalPopupExtender I usually use  an asp:Button with 'display:none' as the TargetControlID. Eg,

<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="btnPopup"
                PopupControlID="ModalPanel" DropShadow="true" Drag="true" OkControlID="OKButton" />
<asp:Panel ID="ModalPanel"  runat="server" Width="500px" style="width: auto; height: auto;" CssClass="modalPopup">
<asp:Button id="btnPopup" runat="server" style="display:none" />

In the code-behind you have to control the showing and hiding of the control base on an event, eg, GetSoftwareModal. You will also also to bind what you need if applicable.

Hope that helps.


问:
What does 'No renderer supporting SKP version 68 found. Rotation disabled.' mean and how do I resolve it?
I've upgraded to Android Studio 4.0 and am attempting to use the new 3D view of the Layout Inspector, but am unable to 'rotate it'. At the top of the tool window, there's a message reading "No renderer supporting SKP version 68 found. Rotation disabled.", which is apparently the reason. What does this message mean and how to I resolve it? I do have Enable Live Layout Inspector checked in File > Settings > Experimental and Enable Live Layout Inspector checked in the layout Inspector window.

Update: Part of the issue might have been that I was targeting SDK 28 and this is an API-29+ feature. When I changed the target SDK to 29, the "Skia Parser Server" component was automatically installed. But now the Live Updates checkbox is sometimes grayed-out and the message "Unable to detect a live inspection service, restart the device." is displayed if I hover on it. Restarting the device (Pixel 3 running API 29) has no effect. Other times, the checkbox is enabled (and checked) but nothing displays in the window.

答: Maybe we need newer emulator image so we can run this. I guess soon there will be new release for API29.</p>


问:
Is there a way to increase the stack size in Twincat 3
I am getting stack overflow problems and I can clearly see that it happens with the introductions of some new arrays. I cannot find the option to increase the stack size on the soft PLC (Twincat) running on my machine.

Any help is appreciated

答:
regedit:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Beckhoff\TwinCAT3\System
add a costum DWORD
with the key: DefaultStackSize
value: Hex(80) or Decimal(128)

Regedit DWORD

this will set your stacksize to 128 instead of 64 :)
change it to whatever you want,  not sure what happens when it's too high.
but this works,  we use it on all our PLC's as we always have issues with the amount of strings parsed with Json converters etc.

this works with 4022.xx versions of twincat. trailed and tested for a couple of years already.


问:
Print optimal solution for coin change algorithm
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, what is the optimal way to make change for N cents.

Example:

```<code>S = {2, 5, 10}
N = 6, then optimal solution is : 2, 2, 2
</code>```

I have below working code:

```<code>public static void main(String argv[]) {
        long n = 10L;
        int[] combo = new int[100];
        int[] amounts = { 2, 5, 10 };
        ways(n, amounts, combo, 0, 0, 0);
    }

    public static void ways(long n, int[] amounts, int[] combo, int startIndex, int sum, int index) {
        if (sum == n) {
            printArray(combo, index);
        }

        if (sum > n) {
            return;
        }

        for (int i = 0; i < amounts.length; i++) {
            sum = sum + amounts[i];
            combo[index] = amounts[i];
            ways(n, amounts, combo, startIndex, sum, index + 1);
            sum = sum - amounts[i];
        }
    }

    public static void printArray(int[] combo, int index) {
        for (int i = 0; i < index; i++) {
            System.out.print(combo[i] + " ");
        }
        System.out.println();
    }
</code>```

Output:

```<code>2 2 2 2 2
5 5
10
</code>```

Here I just need to optimal combination with less number of coins so only 10 in this example code.

But this code uses recursive approach, my value for N is Long type so as the value of N increases I am getting stackoverflow error.

The recursive approach I am following here is not correct, What is the correct way to solve this problem?

Update:

Based on MBo answer I tried below program, but I am not able to get the correct results:

```<code>static void testcase() {
        // make int array A of size N+1
        int N = 6;
        int[] A = new int[N + 1];
        // make int array P of size N+1
        int[] P = new int[N + 1];
        // fill A[] with large value (len(S) + 1)
        int[] S = { 2, 5, 10 };
        int lengthOfS = S.length;
        for (int i = 0; i < A.length; i++) {
            A[i] = lengthOfS + 1;
        }

        A[0] = 0;

        for (int s : S) {// coin value
            for (int i = s; i <= N; i++) {
                if (A[i - s] < A[i] + 1) { // using this coin we can get better
                                            // result for sum i
                    A[i] = A[i - s] + 1;
                    P[i] = s; // write down coin for this sum
                }
            }
        }
        System.out.println(Arrays.toString(P)); // [0, 0, 2, 2, 2, 5, 2]
        System.out.println(A[N]);// 3
        int idx = N;
        for (int i = 0; i < A[N]; i++) {
            int result = idx - P[idx];
            System.out.println(result); // 4 2 0
            idx = result;
        }
    }
</code>```

This code prints:

```<code>[0, 0, 2, 2, 2, 5, 2]
3

4
2
0
</code>```

How to fix this code?

答:
As the number of coins is small, and since the amount can be large, it is likely that backtracking can provide a good solution

Here is an implementation in C++

(Note: this code was already posted, but I can't find the post. Question deleted ?)

The coins are first sorted if descending order, to fasten the search.

In order to minimize the number of coins, we first try solutions with maximum possible number of coins of largest value.

In a given search, if the current number of coins is larger than the current minimum number of coins, we stopped the search ("premature abandon").

In the code, "UP" means that we will consider adding coins with a lower value

"DOWN" means that we will try to decrease the number of coins of higher value.

At a given step, we maintain an array corresponding to the number of coins for each coin value

```<code>#include    <iostream>
#include    <vector>
#include    <algorithm>
#include    <numeric>

//  The order of array coins is modified

std::vector<int> get_change(std::vector<int>& coins, int amount) {
    std::vector<int> n_coins(coins.size(), 0);
    std::vector<int> n_coins_opt(coins.size(), 0);
    int n = coins.size();

    std::sort(coins.begin(), coins.end(), std::greater<int>());

    int sum = 0;    // current sum
    int i = 0;      // index of the coin being examined
    int n_min_coins = amount / coins[n - 1] + 1;
    int n_total_coins = 0;
    bool up_down = true;

    while (true) {          // UP
        if (up_down) {
            n_coins[i] = (amount - sum) / coins[i];     // max possible number of coins[i]
            sum += n_coins[i] * coins[i];
            n_total_coins += n_coins[i];
            if (sum == amount) {
                if (n_total_coins < n_min_coins) {
                    n_min_coins = n_total_coins;
                    n_coins_opt = n_coins;
                }
                up_down = false;
                sum -= n_coins[i] * coins[i];
                n_total_coins -= n_coins[i];
                n_coins[i] = 0;
                i--;
            }
            else {
                if (i == (n - 1) || (n_total_coins >= n_min_coins)) {   // premature abandon
                    sum -= n_coins[i] * coins[i];
                    n_total_coins -= n_coins[i];
                    n_coins[i] = 0;
                    up_down = false;
                    i--;
                }
                else {
                    i++;
                }
            }

        }
        else {            // DOWN
            if (i < 0) break;
            if (n_coins[i] == 0) {
                if (i == 0) break;
                i--;
            }
            else {
                sum -= coins[i];
                n_coins[i] --;
                n_total_coins--;
                i++;
                up_down = true;
            }
        }
    }

    return n_coins_opt;
}

int main() {
    std::vector<int> coins = {2, 5, 10};
    int amount = 1731;
    auto n_coins = get_change(coins, amount);

    int sum = std::accumulate (n_coins.begin(), n_coins.end(), 0);
    if (sum == 0) {
        std::cout << "no solution\n";
    } else {
        std::cout << amount << " = ";
        for (int i = 0; i < n_coins.size(); i++) {
                std::cout << n_coins[i] << "*" << coins[i] << " ";
        }
        std::cout << "\n";
    }
    return 1;
}
</code>```

Body:
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, what is the optimal way to make change for N cents.

Example:

S = {2, 5, 10}
N = 6, then optimal solution is : 2, 2, 2

I have below working code:

public static void main(String argv[]) {
        long n = 10L;
        int[] combo = new int[100];
        int[] amounts = { 2, 5, 10 };
        ways(n, amounts, combo, 0, 0, 0);
    }

    public static void ways(long n, int[] amounts, int[] combo, int startIndex, int sum, int index) {
        if (sum == n) {
            printArray(combo, index);
        }

        if (sum > n) {
            return;
        }

        for (int i = 0; i < amounts.length; i++) {
            sum = sum + amounts[i];
            combo[index] = amounts[i];
            ways(n, amounts, combo, startIndex, sum, index + 1);
            sum = sum - amounts[i];
        }
    }

    public static void printArray(int[] combo, int index) {
        for (int i = 0; i < index; i++) {
            System.out.print(combo[i] + " ");
        }
        System.out.println();
    }

Output:

2 2 2 2 2
5 5
10

Here I just need to optimal combination with less number of coins so only 10 in this example code.

But this code uses recursive approach, my value for N is Long type so as the value of N increases I am getting stackoverflow error.

The recursive approach I am following here is not correct, What is the correct way to solve this problem?

Update:

Based on MBo answer I tried below program, but I am not able to get the correct results:

static void testcase() {
        // make int array A of size N+1
        int N = 6;
        int[] A = new int[N + 1];
        // make int array P of size N+1
        int[] P = new int[N + 1];
        // fill A[] with large value (len(S) + 1)
        int[] S = { 2, 5, 10 };
        int lengthOfS = S.length;
        for (int i = 0; i < A.length; i++) {
            A[i] = lengthOfS + 1;
        }

        A[0] = 0;

        for (int s : S) {// coin value
            for (int i = s; i <= N; i++) {
                if (A[i - s] < A[i] + 1) { // using this coin we can get better
                                            // result for sum i
                    A[i] = A[i - s] + 1;
                    P[i] = s; // write down coin for this sum
                }
            }
        }
        System.out.println(Arrays.toString(P)); // [0, 0, 2, 2, 2, 5, 2]
        System.out.println(A[N]);// 3
        int idx = N;
        for (int i = 0; i < A[N]; i++) {
            int result = idx - P[idx];
            System.out.println(result); // 4 2 0
            idx = result;
        }
    }

This code prints:

[0, 0, 2, 2, 2, 5, 2]
3

4
2
0

How to fix this code?

Body:
As the number of coins is small, and since the amount can be large, it is likely that backtracking can provide a good solution

Here is an implementation in C++

(Note: this code was already posted, but I can't find the post. Question deleted ?)

The coins are first sorted if descending order, to fasten the search.

In order to minimize the number of coins, we first try solutions with maximum possible number of coins of largest value.

In a given search, if the current number of coins is larger than the current minimum number of coins, we stopped the search ("premature abandon").

In the code, "UP" means that we will consider adding coins with a lower value

"DOWN" means that we will try to decrease the number of coins of higher value.

At a given step, we maintain an array corresponding to the number of coins for each coin value

#include    <iostream>
#include    <vector>
#include    <algorithm>
#include    <numeric>

//  The order of array coins is modified

std::vector<int> get_change(std::vector<int>& coins, int amount) {
    std::vector<int> n_coins(coins.size(), 0);
    std::vector<int> n_coins_opt(coins.size(), 0);
    int n = coins.size();

    std::sort(coins.begin(), coins.end(), std::greater<int>());

    int sum = 0;    // current sum
    int i = 0;      // index of the coin being examined
    int n_min_coins = amount / coins[n - 1] + 1;
    int n_total_coins = 0;
    bool up_down = true;

    while (true) {          // UP
        if (up_down) {
            n_coins[i] = (amount - sum) / coins[i];     // max possible number of coins[i]
            sum += n_coins[i] * coins[i];
            n_total_coins += n_coins[i];
            if (sum == amount) {
                if (n_total_coins < n_min_coins) {
                    n_min_coins = n_total_coins;
                    n_coins_opt = n_coins;
                }
                up_down = false;
                sum -= n_coins[i] * coins[i];
                n_total_coins -= n_coins[i];
                n_coins[i] = 0;
                i--;
            }
            else {
                if (i == (n - 1) || (n_total_coins >= n_min_coins)) {   // premature abandon
                    sum -= n_coins[i] * coins[i];
                    n_total_coins -= n_coins[i];
                    n_coins[i] = 0;
                    up_down = false;
                    i--;
                }
                else {
                    i++;
                }
            }

        }
        else {            // DOWN
            if (i < 0) break;
            if (n_coins[i] == 0) {
                if (i == 0) break;
                i--;
            }
            else {
                sum -= coins[i];
                n_coins[i] --;
                n_total_coins--;
                i++;
                up_down = true;
            }
        }
    }

    return n_coins_opt;
}

int main() {
    std::vector<int> coins = {2, 5, 10};
    int amount = 1731;
    auto n_coins = get_change(coins, amount);

    int sum = std::accumulate (n_coins.begin(), n_coins.end(), 0);
    if (sum == 0) {
        std::cout << "no solution\n";
    } else {
        std::cout << amount << " = ";
        for (int i = 0; i < n_coins.size(); i++) {
                std::cout << n_coins[i] << "*" << coins[i] << " ";
        }
        std::cout << "\n";
    }
    return 1;
}


问:
what is the function of the method times in kotlin?
I am new to the world of programming and I am working on operator overload, I would like you to explain to me what function the times method fulfills in this exercise.    </p>

```<code>class Vector {
    val arreglo = IntArray(5)

    fun cargar() {
        for (i in arreglo.indices)
            arreglo[i] = (Math.random() * 11 + 1).toInt()
    }

    fun imprimir() {
        for (elemento in arreglo)
            print("$elemento ")
        println()
    }

    operator fun times(valor: Int): Vector {
        var suma = Vector()
        for (i in arreglo.indices)
            suma.arreglo[i] = arreglo[i] * valor
        return suma
    }
}

fun main(args: Array<String>) {
    val vec1 = Vector()
    vec1.cargar()
    vec1.imprimir()
    println("El producto de un vector con el número 10 es")
    val vecProductoEnt = vec1 * 10
    vecProductoEnt.imprimir()
}
</code>```

答:
```<code>operator fun times(valor: Int): Vector
</code>```

this is the function invoked at this line val vecProductoEnt = vec1 * 10.

you can read more about it here

Body:
I am new to the world of programming and I am working on operator overload, I would like you to explain to me what function the times method fulfills in this exercise.

class Vector {
    val arreglo = IntArray(5)

    fun cargar() {
        for (i in arreglo.indices)
            arreglo[i] = (Math.random() * 11 + 1).toInt()
    }

    fun imprimir() {
        for (elemento in arreglo)
            print("$elemento ")
        println()
    }

    operator fun times(valor: Int): Vector {
        var suma = Vector()
        for (i in arreglo.indices)
            suma.arreglo[i] = arreglo[i] * valor
        return suma
    }
}

fun main(args: Array<String>) {
    val vec1 = Vector()
    vec1.cargar()
    vec1.imprimir()
    println("El producto de un vector con el número 10 es")
    val vecProductoEnt = vec1 * 10
    vecProductoEnt.imprimir()
}

Body:
operator fun times(valor: Int): Vector

this is the function invoked at this line val vecProductoEnt = vec1 * 10.

you can read more about it here


问:
Filter multiple CSV for text and create new files
I have about 2500 CSV files each around 20MB in terms of file size. I am trying to filter out certain rows from each file and save that to a new file.

So, if i have :

```<code>File 1 :
    Row1
    Row2
    Row3
File 2 :
    Row2
    Row3
and so on..
</code>```

If i filter for all files and select "Row2" as filter text the new folder should have all the files with only rows that match the filter text.

Looking through some forums, I came up with the following that might help me filter the rows, but Im not sure how I can do it recursively, plus I also don't know if this is a fast enough method. Any help is appreciated.

```<code>Get-Content "C:\Path to file" | Where{$_ -match "Rowfiltertext*"} | Out-File "Path to Out file"
</code>```

I'm using windows so I guess Powershell type of solution would be the best here.

The text to be filtered will always be in the first column.

Thanks
Siddhant

答:
Re. "fast enough method":

Get-Content is extremely slow.
You could use "System.IO.StreamReader" instead, i.e. read the complete file content into a string, then split this string into rows and so on, e.g.:

```<code>[System.IO.FileStream]$objFileStream = New-Object System.IO.FileStream($Csv.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
[System.IO.StreamReader]$objStreamReader = New-Object System.IO.StreamReader($objFileStream, [System.Text.Encoding]::UTF8)
$strFileContent = ($objStreamReader.ReadToEnd())
$objStreamReader.Close()
$objStreamReader.Dispose()
$objFileStream.Close()
$objFileStream.Dispose()

[string[]]$arrFileContent = $strFileContent -split("`r`n")
</code>```

Body:
I have about 2500 CSV files each around 20MB in terms of file size. I am trying to filter out certain rows from each file and save that to a new file.

So, if i have :

File 1 :
    Row1
    Row2
    Row3
File 2 :
    Row2
    Row3
and so on..

If i filter for all files and select "Row2" as filter text the new folder should have all the files with only rows that match the filter text.

Looking through some forums, I came up with the following that might help me filter the rows, but Im not sure how I can do it recursively, plus I also don't know if this is a fast enough method. Any help is appreciated.

Get-Content "C:\Path to file" | Where{$_ -match "Rowfiltertext*"} | Out-File "Path to Out file"

I'm using windows so I guess Powershell type of solution would be the best here.

The text to be filtered will always be in the first column.

Thanks
Siddhant

Body:
Re. "fast enough method":

Get-Content is extremely slow.
You could use "System.IO.StreamReader" instead, i.e. read the complete file content into a string, then split this string into rows and so on, e.g.:

[System.IO.FileStream]$objFileStream = New-Object System.IO.FileStream($Csv.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
[System.IO.StreamReader]$objStreamReader = New-Object System.IO.StreamReader($objFileStream, [System.Text.Encoding]::UTF8)
$strFileContent = ($objStreamReader.ReadToEnd())
$objStreamReader.Close()
$objStreamReader.Dispose()
$objFileStream.Close()
$objFileStream.Dispose()

[string[]]$arrFileContent = $strFileContent -split("`r`n")


问:
image on option value on one fiddle works but my new copy doesn't
This will be the dumbest question I've asked, but I found this fiddle which I edited some to make it as minimal as possible:http://jsfiddle.net/5pzcoy7k/

And since It didn't work on my own site I tried to make a new fiddle with the same resouces: https://jsfiddle.net/rqLu72o1/

Why is the result different, what am I missing?

The log I get is that $("select").msDropDown(); is not defined, but why is it defined on the other one?:/

答: One fiddle-URL is HTTPS, one is only HTTP. The one with SSL does not work since the linked resources are not behind SSL and you get an CORS-Issue.</p>


问:
Comparing date part only without comparing time in JavaScript
What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn't find my exact problem.

BTW, when I display the two dates in an alert, they show as exactly the same.

My code:

```<code>window.addEvent('domready', function() {
    var now = new Date();
    var input = $('datum').getValue();
    var dateArray = input.split('/');
    var userMonth = parseInt(dateArray[1])-1;
    var userDate = new Date();
    userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());

    if (userDate > now)
    {
        alert(now + '\n' + userDate);
    }
});
</code>```

Is there a simpler way to compare dates and not including the time?

答:
This might be a little cleaner version, also note that you should always use a radix when using parseInt.

```<code>window.addEvent('domready', function() {
    // Create a Date object set to midnight on today's date
    var today = new Date((new Date()).setHours(0, 0, 0, 0)),
    input = $('datum').getValue(),
    dateArray = input.split('/'),
    // Always specify a radix with parseInt(), setting the radix to 10 ensures that
    // the number is interpreted as a decimal.  It is particularly important with
    // dates, if the user had entered '09' for the month and you don't use a
    // radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
    userMonth = parseInt(dateArray[1], 10) - 1,
    // Create a Date object set to midnight on the day the user specified
    userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);

    // Convert date objects to milliseconds and compare
    if(userDate.getTime() > today.getTime())
    {
            alert(today+'\n'+userDate);
    }
});
</code>```

Checkout the MDC parseInt page for more information about the radix.

JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors.  It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.

Body:
What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn't find my exact problem.

BTW, when I display the two dates in an alert, they show as exactly the same.

My code:

window.addEvent('domready', function() {
    var now = new Date();
    var input = $('datum').getValue();
    var dateArray = input.split('/');
    var userMonth = parseInt(dateArray[1])-1;
    var userDate = new Date();
    userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());

    if (userDate > now)
    {
        alert(now + '\n' + userDate);
    }
});

Is there a simpler way to compare dates and not including the time?

Body:
This might be a little cleaner version, also note that you should always use a radix when using parseInt.

window.addEvent('domready', function() {
    // Create a Date object set to midnight on today's date
    var today = new Date((new Date()).setHours(0, 0, 0, 0)),
    input = $('datum').getValue(),
    dateArray = input.split('/'),
    // Always specify a radix with parseInt(), setting the radix to 10 ensures that
    // the number is interpreted as a decimal.  It is particularly important with
    // dates, if the user had entered '09' for the month and you don't use a
    // radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
    userMonth = parseInt(dateArray[1], 10) - 1,
    // Create a Date object set to midnight on the day the user specified
    userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);

    // Convert date objects to milliseconds and compare
    if(userDate.getTime() > today.getTime())
    {
            alert(today+'\n'+userDate);
    }
});

Checkout the MDC parseInt page for more information about the radix.

JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors.  It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.


问:
how to get the uri of a cropped image selected from gallery using sound cloud in android studio
```<code>if(requestCode == GET_FROM_GALLERY && resultCode == RESULT_OK) {
    try {
        Uri source_uri = imageUri;
        Uri dest_uri = Uri.fromFile(new File(getCacheDir(), "cropped"));
        // need to crop it to square image as CNN's always required square input
        Crop.of(source_uri, dest_uri).asSquare().start(MainActivity.this);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

// if cropping acitivty is finished,
// get the resulting cropped image uri and send it
// to 'Classify' activity

else if(requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK) {
    imageUri = Crop.getOutput(data);
    Intent i = new Intent(MainActivity.this, Classify.class);
    // put image data in extras to send
    i.putExtra("resID_uri", imageUri);
    // put filename in extras
    i.putExtra("chosen", chosen);
    // put model type in extras
    i.putExtra("quant", quant);
    // send other required data
    startActivity(i);
}
</code>```

This code is meant to select an image from gallery crop it and then send the cropped image output to the image classifier activity.

答:
I had to set the button that picks the image as shown in the code with the model initialized as model= "model.tflite"

```<code> pick_image = findViewById(R.id.pick_picture);
        pick_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // filename in assets
                model = "model.tflite";
                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery, GET_FROM_GALLERY);
            }
        });
</code>```

then the onActivity has to look like the one below

```<code>if(requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {
            try {
                Uri source_uri = imageUri;
                Uri dest_uri = Uri.fromFile(new File(getCacheDir(), "cropped"));
                // need to crop it to square image as CNN's always required square input
                Crop.of(source_uri, dest_uri).asSquare().start(MainActivity.this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // if cropping acitivty is finished, get the resulting cropped image uri and send it to 'Classify' activity
        else if(requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK){
            imageUri = Crop.getOutput(data);

            Intent i = new Intent(MainActivity.this, Classify.class);
            // put image data in extras to send
            i.putExtra("resID_uri", imageUri);
            // put filename in extras
            i.putExtra("chosen", chosen);

            // send other required data
            startActivity(i);

        }

        if (requestCode == GET_FROM_GALLERY && resultCode == RESULT_OK){
//            beginCrop(data.getData());
            try{
            Uri source =data.getData();
            Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
            Crop.of(source, destination).asSquare().start(this);
            }catch (Exception e){
                e.printStackTrace();
            }

        }else if (requestCode == Crop.REQUEST_CROP && resultCode ==RESULT_OK){
//            handleCrop(resultCode, data);
            Uri gon = Crop.getOutput(data);
            Intent i = new Intent(MainActivity.this, Classify.class);
            // put image data in extras to send
            i.putExtra("resID_uri", gon);
            // put filename in extras
            i.putExtra("chosen", chosen);

            // send other required data
            startActivity(i);
        }
</code>```

Body:
if(requestCode == GET_FROM_GALLERY && resultCode == RESULT_OK) {
    try {
        Uri source_uri = imageUri;
        Uri dest_uri = Uri.fromFile(new File(getCacheDir(), "cropped"));
        // need to crop it to square image as CNN's always required square input
        Crop.of(source_uri, dest_uri).asSquare().start(MainActivity.this);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

// if cropping acitivty is finished,
// get the resulting cropped image uri and send it
// to 'Classify' activity

else if(requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK) {
    imageUri = Crop.getOutput(data);
    Intent i = new Intent(MainActivity.this, Classify.class);
    // put image data in extras to send
    i.putExtra("resID_uri", imageUri);
    // put filename in extras
    i.putExtra("chosen", chosen);
    // put model type in extras
    i.putExtra("quant", quant);
    // send other required data
    startActivity(i);
}

This code is meant to select an image from gallery crop it and then send the cropped image output to the image classifier activity.

Body:
I had to set the button that picks the image as shown in the code with the model initialized as model= "model.tflite"

 pick_image = findViewById(R.id.pick_picture);
        pick_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // filename in assets
                model = "model.tflite";
                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery, GET_FROM_GALLERY);
            }
        });

then the onActivity has to look like the one below

if(requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {
            try {
                Uri source_uri = imageUri;
                Uri dest_uri = Uri.fromFile(new File(getCacheDir(), "cropped"));
                // need to crop it to square image as CNN's always required square input
                Crop.of(source_uri, dest_uri).asSquare().start(MainActivity.this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // if cropping acitivty is finished, get the resulting cropped image uri and send it to 'Classify' activity
        else if(requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK){
            imageUri = Crop.getOutput(data);

            Intent i = new Intent(MainActivity.this, Classify.class);
            // put image data in extras to send
            i.putExtra("resID_uri", imageUri);
            // put filename in extras
            i.putExtra("chosen", chosen);

            // send other required data
            startActivity(i);

        }

        if (requestCode == GET_FROM_GALLERY && resultCode == RESULT_OK){
//            beginCrop(data.getData());
            try{
            Uri source =data.getData();
            Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
            Crop.of(source, destination).asSquare().start(this);
            }catch (Exception e){
                e.printStackTrace();
            }

        }else if (requestCode == Crop.REQUEST_CROP && resultCode ==RESULT_OK){
//            handleCrop(resultCode, data);
            Uri gon = Crop.getOutput(data);
            Intent i = new Intent(MainActivity.this, Classify.class);
            // put image data in extras to send
            i.putExtra("resID_uri", gon);
            // put filename in extras
            i.putExtra("chosen", chosen);

            // send other required data
            startActivity(i);
        }


问:
How tune LFR_benchmark_graph method in networkx for generating large graph
I want to generate random community in below way:

```<code>from random import randint
import networkx
from networkx.algorithms.community import LFR_benchmark_graph

n = [250, 500, 600, 700, 800, 900, 1000, 1200, 1500, 1600, 1900, 2000, 2500, 2800, 3000, 3500, 4000, 4600, 5000]
index = randint(0, len(n) - 1)
tau1 = 3
tau2 = 1.5
mu = 0.1
mm = randint(0, len(n) - 1)
G = LFR_benchmark_graph(n[index], tau1, tau2, mu, average_degree=5,
                        min_community=20, seed=10)
</code>```

but rise mentioned error:

```<code>networkx.exception.ExceededMaxIterations: Could not assign communities; try increasing min_community
</code>```

when I use size 250 I have any error, but when I want to use other sizes to generate a network with the random size, I get that error. How can I fix it?

答:
This is mentioned in the documentation page:

Though the authors describe the algorithm as quite robust, testing
  during development indicates that a somewhat narrower parameter set is
  likely to successfully produce a graph. Some suggestions have been
  provided in the event of exceptions.

Here are some configurations that worked for me:

```<code>def genrate_lfr_graph(size=250):
    params = {"n":size, "tau1":2, "tau2":1.1, "mu":0.1, "min_degree":20, "max_degree":50}

    G = LFR_benchmark_graph(params["n"], params["tau1"], params["tau2"], params["mu"],
                        min_degree=params["min_degree"],
                        max_degree=params["max_degree"],
                        max_iters=5000, seed = 10,
                        )
    print("Generation Completed")
    return G

sizes = [250, 500, 600, 700, 800, 900, 1000, 1200, 2000, 2500, 2800, 3000]
for n in sizes:
    G = genrate_lfr_graph(size=n)
</code>```

Body:
I want to generate random community in below way:

from random import randint
import networkx
from networkx.algorithms.community import LFR_benchmark_graph

n = [250, 500, 600, 700, 800, 900, 1000, 1200, 1500, 1600, 1900, 2000, 2500, 2800, 3000, 3500, 4000, 4600, 5000]
index = randint(0, len(n) - 1)
tau1 = 3
tau2 = 1.5
mu = 0.1
mm = randint(0, len(n) - 1)
G = LFR_benchmark_graph(n[index], tau1, tau2, mu, average_degree=5,
                        min_community=20, seed=10)

but rise mentioned error:

networkx.exception.ExceededMaxIterations: Could not assign communities; try increasing min_community

when I use size 250 I have any error, but when I want to use other sizes to generate a network with the random size, I get that error. How can I fix it?

Body:
This is mentioned in the documentation page:

Though the authors describe the algorithm as quite robust, testing
  during development indicates that a somewhat narrower parameter set is
  likely to successfully produce a graph. Some suggestions have been
  provided in the event of exceptions.

Here are some configurations that worked for me:

def genrate_lfr_graph(size=250):
    params = {"n":size, "tau1":2, "tau2":1.1, "mu":0.1, "min_degree":20, "max_degree":50}

    G = LFR_benchmark_graph(params["n"], params["tau1"], params["tau2"], params["mu"],
                        min_degree=params["min_degree"],
                        max_degree=params["max_degree"],
                        max_iters=5000, seed = 10,
                        )
    print("Generation Completed")
    return G

sizes = [250, 500, 600, 700, 800, 900, 1000, 1200, 2000, 2500, 2800, 3000]
for n in sizes:
    G = genrate_lfr_graph(size=n)


问:
Insert React component into a String variable with html content
I need to insert a React component into a String variable that contains html content.
This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

```<code>const ShareThis = ({ text }) => {
  return (
    <div class="one-line">{text}</div>
)}

export default ShareThis
</code>```

var content (string variable with html content)

```<code><p>Text 1</p>
!#ShareButton
<p>Text 2</p>
</code>```

Page:

```<code>const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (
  <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />
)
</code>```

Result:

```<code>Text 1
[object Object]
Text 2
</code>```

Do you know how to insert a React component into a String variable with html content?

答:
You can't render React component as innerHTML because its an object, don't confuse between JSX and HTML.

To solve it your need content to be a valid HTML.

Can be done by making ShareThis a function returning a valid HTML as a string:

```<code>const ShareThis = ({ text }) => {
  return `<div class="one-line">${text}</div>`;
};

const content = `
<p>Text 1</p>
!#ShareButton
<p>Text 2</p>
`;

const htmlcontent = content.replace(
  /!#ShareButton/g,
  ShareThis({ text: "Hello" })
);

const App = () => {
  return <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />;
};
</code>```

Note that you have a typo in regex expression: /!#ShareButton/

Body:
I need to insert a React component into a String variable that contains html content.
This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

const ShareThis = ({ text }) => {
  return (

{text}

)}

export default ShareThis

var content (string variable with html content)

Text 1

!#ShareButton

Text 2

Page:

const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (

)

Result:

Text 1
[object Object]
Text 2

Do you know how to insert a React component into a String variable with html content?

Body:
You can't render React component as innerHTML because its an object, don't confuse between JSX and HTML.

To solve it your need content to be a valid HTML.

Can be done by making ShareThis a function returning a valid HTML as a string:

const ShareThis = ({ text }) => {
  return `<div class="one-line">${text}</div>`;
};

const content = `
<p>Text 1</p>
!#ShareButton
<p>Text 2</p>
`;

const htmlcontent = content.replace(
  /!#ShareButton/g,
  ShareThis({ text: "Hello" })
);

const App = () => {
  return <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />;
};

Note that you have a typo in regex expression: /!#ShareButton/


问:
centos not update, centos 7.8 (2003)
```<code> dnf -y upgrade http://mirror.bytemark.co.uk/centos/8/BaseOS/x86_64/os/Packages/centos-release-8.1-1.1911.0.8.el8.x86_64.rpm
Last metadata expiration check: 0:35:45 ago on Tue May 12 20:59:10 2020.
centos-release-8.1-1.1911.0.8.el8.x86_64.rpm     55 kB/s |  21 kB     00:00
Dependencies resolved.

 Problem: cannot install the best update candidate for package centos-release-7-8.2003.0.el7.centos.x86_64
  - nothing provides centos-gpg-keys = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
  - nothing provides centos-repos = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
================================================================================
 Package            Arch       Version                   Repository        Size
================================================================================
Skipping packages with broken dependencies:
 centos-release     x86_64     8.1-1.1911.0.8.el8        @commandline      21 k

Transaction Summary
================================================================================
Skip  1 Package

Nothing to do.
Complete!
</code>```

I want to update centos 7.8, I can’t get help.
first there was version 7.2, I upgraded to 7.8

答:
yes the gpg need also submitted to the download.

Try this:

dnf install http://mirror.centos.org/centos/8/BaseOS/x86_64/os/Packages/{centos-release-8.1-1.1911.0.9.el8.x86_64.rpm,centos-gpg-keys-8.1-1.1911.0.9.el8.noarch.rpm,centos-repos-8.1-1.1911.0.9.el8.x86_64.rpm} (should be the newest release)

Title: centos not update, centos 7.8 (2003)

Body:
 dnf -y upgrade http://mirror.bytemark.co.uk/centos/8/BaseOS/x86_64/os/Packages/centos-release-8.1-1.1911.0.8.el8.x86_64.rpm
Last metadata expiration check: 0:35:45 ago on Tue May 12 20:59:10 2020.
centos-release-8.1-1.1911.0.8.el8.x86_64.rpm     55 kB/s |  21 kB     00:00
Dependencies resolved.

 Problem: cannot install the best update candidate for package centos-release-7-8.2003.0.el7.centos.x86_64
  - nothing provides centos-gpg-keys = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
  - nothing provides centos-repos = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
================================================================================
 Package            Arch       Version                   Repository        Size
================================================================================
Skipping packages with broken dependencies:
 centos-release     x86_64     8.1-1.1911.0.8.el8        @commandline      21 k

Transaction Summary
================================================================================
Skip  1 Package

Nothing to do.
Complete!

I want to update centos 7.8, I can’t get help.
first there was version 7.2, I upgraded to 7.8