问:
How to have some pages without bottom navigation?
I want to have bottom navigation in my app as described on this page but I also have a login page which should not have the bottom navigation tabs. So as the user enters the app, he's shown the login page and after login he should get to the first tab of the bottom navigation. The docs do not mention how this would be achieved. How can this be done?

Attempt 1:

app.js

```<code>let startPage = 'login/login-page';
if(settings.hasKey('token')){
    startPage = 'app-root';
}
application.run({ moduleName: startPage });
</code>```

This does take me to the login page but then nothing works to get me to app-root or another similar page that could house a BottomNavigation

Attempt 2:

On login page, nothing happens.

app.js

```<code>application.run({ moduleName: 'app-root' });
</code>```

app-root.xml

```<code><Frame defaultPage="login/login-page"></Frame>
</code>```

login/login-page.js

```<code>//send email and password. check if its correct. send user forward on authentication
page.frame.navigate({
    moduleName: 'router/router-page',
    clearHistory: true
});
</code>```

router/router-page.xml

```<code><BottomNavigation id="bottomNav" automationText="tabNavigation" selectedIndex="0">
    <TabStrip>
        <TabStripItem>
            <Image src="font://" class="mdi"></Image>
            <Label text="Products"></Label>
        </TabStripItem>
        <TabStripItem>
            <Image src="font://" class="mdi"></Image>
            <Label text="Gallery"></Label>
        </TabStripItem>
    </TabStrip>
    <TabContentItem>
        <Frame id="main" defaultPage="categories/categories-page"></Frame>
    </TabContentItem>
    <TabContentItem>
        <Frame id="gallery" defaultPage="gallery/gallery-page"></Frame>
    </TabContentItem>
</BottomNavigation>
//note there's no router-page.js
//is it necessary?
</code>```

答:
Here's how I finally did it

app.js

```<code>application.run({ moduleName: 'app-root' });
</code>```

app-root.xml

```<code><Page actionBarHidden="true" loaded="onLoaded" xmlns="http://schemas.nativescript.org/tns.xsd">
    <Frame id="rootframe" defaultPage="{{ defaultPage }}"></Frame>
</Page>
</code>```

app-root.js

```<code>const Observable = require("@nativescript/core/data/observable").fromObject;
const settings = require("@nativescript/core/application-settings");

exports.onLoaded = function(args){
    const page = args.object;

    page.bindingContext = Observable({
        defaultPage: (settings.hasKey('token')) ? 'router/router-page' : 'login/login-page'
    })
}
</code>```

router/router-page.xml

```<code><Page actionBarHidden="true" loaded="onLoaded" class="page" xmlns="http://schemas.nativescript.org/tns.xsd">
    <BottomNavigation id="bottomNav" automationText="tabNavigation" selectedIndex="0" selectedIndexChanged="onSelectedIndexChanged">
        <TabStrip>
            <TabStripItem>
                <Image src="font://" class="mdi"></Image>
                <Label text="Products"></Label>
            </TabStripItem>
            <TabStripItem>
                <Image src="font://" class="mdi"></Image>
                <Label text="Gallery"></Label>
            </TabStripItem>
        </TabStrip>
        <TabContentItem>
            <Frame id="main" defaultPage="categories/categories-page"></Frame>
        </TabContentItem>
        <TabContentItem>
            <Frame id="gallery" defaultPage="gallery/gallery-page"></Frame>
        </TabContentItem>
    </BottomNavigation>
</Page>
</code>```

Body:
I want to have bottom navigation in my app as described on this page but I also have a login page which should not have the bottom navigation tabs. So as the user enters the app, he's shown the login page and after login he should get to the first tab of the bottom navigation. The docs do not mention how this would be achieved. How can this be done?

Attempt 1:

app.js

let startPage = 'login/login-page';
if(settings.hasKey('token')){
    startPage = 'app-root';
}
application.run({ moduleName: startPage });

This does take me to the login page but then nothing works to get me to app-root or another similar page that could house a BottomNavigation

Attempt 2:

On login page, nothing happens.

app.js

application.run({ moduleName: 'app-root' });

app-root.xml

<Frame defaultPage="login/login-page"></Frame>

login/login-page.js

//send email and password. check if its correct. send user forward on authentication
page.frame.navigate({
    moduleName: 'router/router-page',
    clearHistory: true
});

router/router-page.xml

<BottomNavigation id="bottomNav" automationText="tabNavigation" selectedIndex="0">
    <TabStrip>
        <TabStripItem>
            <Image src="font://" class="mdi"></Image>

        </TabStripItem>
        <TabStripItem>
            <Image src="font://" class="mdi"></Image>

        </TabStripItem>
    </TabStrip>
    <TabContentItem>
        <Frame id="main" defaultPage="categories/categories-page"></Frame>
    </TabContentItem>
    <TabContentItem>
        <Frame id="gallery" defaultPage="gallery/gallery-page"></Frame>
    </TabContentItem>
</BottomNavigation>
//note there's no router-page.js
//is it necessary?

Body:
Here's how I finally did it

app.js

application.run({ moduleName: 'app-root' });

app-root.xml

<Page actionBarHidden="true" loaded="onLoaded" xmlns="http://schemas.nativescript.org/tns.xsd">
    <Frame id="rootframe" defaultPage="{{ defaultPage }}"></Frame>
</Page>

app-root.js

const Observable = require("@nativescript/core/data/observable").fromObject;
const settings = require("@nativescript/core/application-settings");

exports.onLoaded = function(args){
    const page = args.object;

    page.bindingContext = Observable({
        defaultPage: (settings.hasKey('token')) ? 'router/router-page' : 'login/login-page'
    })
}

router/router-page.xml

<Page actionBarHidden="true" loaded="onLoaded" class="page" xmlns="http://schemas.nativescript.org/tns.xsd">
    <BottomNavigation id="bottomNav" automationText="tabNavigation" selectedIndex="0" selectedIndexChanged="onSelectedIndexChanged">
        <TabStrip>
            <TabStripItem>
                <Image src="font://&#xe41d;" class="mdi"></Image>
                <Label text="Products"></Label>
            </TabStripItem>
            <TabStripItem>
                <Image src="font://&#xe413;" class="mdi"></Image>
                <Label text="Gallery"></Label>
            </TabStripItem>
        </TabStrip>
        <TabContentItem>
            <Frame id="main" defaultPage="categories/categories-page"></Frame>
        </TabContentItem>
        <TabContentItem>
            <Frame id="gallery" defaultPage="gallery/gallery-page"></Frame>
        </TabContentItem>
    </BottomNavigation>
</Page>


来源: stackexchange

问:
Sort array by value and alphabet React Native
I get an array from firebase, it is now sorted alphabetically. If an object contains 'routes' then it will get the text 'Bekijk' button otherwise the text 'coming soon' button, what I would like is that the objects with the name 'Bekijk' are displayed first and then the other objects alphabetically order, does anyone know if that is possible?

This is my code:

```<code>import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, ImageBackground, StatusBar, ScrollView, Dimensions, TouchableOpacity} from 'react-native';
import { Header, Icon,Button,Rating, AirbnbRating  } from 'react-native-elements';
import firebase from 'react-native-firebase';

class routeScreen extends Component {

  constructor(props){
    super(props);
    this.state = {
      goverments: [],
    }
}

  getGovermentData = () => {
    let ref = firebase.database().ref('Goverments');
    ref.on('value' , snapshot =>{
        var state = snapshot.val();
        this.setState({
          goverments: state,
        })
        console.log(state);
      })

  }

    componentWillMount(){
      this.getGovermentData();
    }

    render() {
      const width = {
       width: (Dimensions.get('window').width / 2),
      };
      return (
        <ScrollView>

          {
            this.state.goverments.sort(function(a, b) {
              if(a.name.toLowerCase() < b.name.toLowerCase()) return -1;
              if(a.name.toLowerCase() > b.name.toLowerCase()) return 1;
              return 0;
             }).map((item, i) => (
              <View style={[styles.cards, { backgroundColor: (i % 2  == 0) ? '#D1A96E' : '#A58657'  }]}>
              <View style={styles.leftcolum}>
            <Text style={styles.title}>{item.name}</Text>
                <Text style={styles.undertitle}>4km - 5km - 7km</Text>
                <Image source={require('./assets/images/stars.png')} style={styles.stars}/>

                <Button buttonStyle={{
                          backgroundColor: item.routes ? "#3F494B" : "#018786",
                          marginTop: 40,
                          borderRadius: 50,
                      }} title={item.routes ? "Bekijk" : "Coming soon"}
                      onPress={() => item.routes ? this.props.navigation.navigate('Location', {govermentData: item}) : '#'}
                      />

              </View>
              <View style={styles.rightcolum}>
                <Image source={{uri: item.logoUrl}} style={{width: 150, height: 68}}/>
              </View>

            </View>
          ))
        }
    </ScrollView>

      );
    }
  }

  const styles = StyleSheet.create({
    cards:{
      backgroundColor: '#D1A96E',
      borderRadius: 10,
      marginTop: 20,
      marginRight: 10,
      marginLeft: 10,
      paddingLeft: 20,
      paddingRight: 20,
      paddingTop: 20,
      paddingBottom: 20,
      flex: 1,
      flexDirection: 'row',
      flexWrap: 'wrap',
      alignItems: 'flex-start'
    },
    stars:{
      marginTop: 10,
    },
    leftcolum:{
      width: '50%',
    },
    rightcolum:{
      width: '50%',
      paddingTop:30,
      paddingLeft:10,
    },
    title:{
      fontSize: 17,
      color: '#fff',
      marginTop: 5,
      fontWeight: '800',
    },
    undertitle:{
      fontSize: 12,
      color: '#fff',
      fontWeight: '200',
    },
    button:{
      backgroundColor: '#3F494B',
      borderRadius: 22,
      marginTop: 20,
    },
    valkenburg:{
      backgroundColor: '#A58657',
    },
    gulpen:{
      backgroundColor: '#EBC285',
    },
    logoValkenburg:{
      width: '50%',
      paddingTop:10,
      paddingLeft:10,
    },
    logoGulpen:{
      width: '50%',
      paddingTop:30,
      paddingLeft:10,
    }

  });

  export default routeScreen;
</code>```

Structure of array:

what I would like:
now the array is shown in alphabetical order, that is good, I would only like to show object 1 of Goverments at the top because it contains the value routes, with the others the value routes being empty. so if it is filled, it must show it at the top

答:
const Goverments = [
  {
    name: 'Valkenburg',
  },
  {
    name: 'Eijsden-Margeaten',
  },
  {
    name: 'Gulpen',
    routes: [],
  },
];
const SortedGoverments = Goverments.sort(function(a, b) {
  if(a.routes) return -1; // new check
  if(b.routes) return 1; // new check
  if(a.name.toLowerCase()  b.name.toLowerCase()) return 1;
  return 0;
});

console.log("Goverments : ", Goverments);
console.log("SortedGoverments : ", SortedGoverments);```

ContentLicense: CC BY-SA 4.0

Body:
I get an array from firebase, it is now sorted alphabetically. If an object contains 'routes' then it will get the text 'Bekijk' button otherwise the text 'coming soon' button, what I would like is that the objects with the name 'Bekijk' are displayed first and then the other objects alphabetically order, does anyone know if that is possible?

This is my code:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, ImageBackground, StatusBar, ScrollView, Dimensions, TouchableOpacity} from 'react-native';
import { Header, Icon,Button,Rating, AirbnbRating  } from 'react-native-elements';
import firebase from 'react-native-firebase';

class routeScreen extends Component {

  constructor(props){
    super(props);
    this.state = {
      goverments: [],
    }
}

  getGovermentData = () => {
    let ref = firebase.database().ref('Goverments');
    ref.on('value' , snapshot =>{
        var state = snapshot.val();
        this.setState({
          goverments: state,
        })
        console.log(state);
      })

  }

    componentWillMount(){
      this.getGovermentData();
    }

    render() {
      const width = {
       width: (Dimensions.get('window').width / 2),
      };
      return (
        <ScrollView>

          {
            this.state.goverments.sort(function(a, b) {
              if(a.name.toLowerCase()  b.name.toLowerCase()) return 1;
              return 0;
             }).map((item, i) => (
              <View style={[styles.cards, { backgroundColor: (i % 2  == 0) ? '#D1A96E' : '#A58657'  }]}>
              <View style={styles.leftcolum}>
            <Text style={styles.title}>{item.name}</Text>
                <Text style={styles.undertitle}>4km - 5km - 7km</Text>
                <Image source={require('./assets/images/stars.png')} style={styles.stars}/>

                <Button buttonStyle={{
                          backgroundColor: item.routes ? "#3F494B" : "#018786",
                          marginTop: 40,
                          borderRadius: 50,
                      }} title={item.routes ? "Bekijk" : "Coming soon"}
                      onPress={() => item.routes ? this.props.navigation.navigate('Location', {govermentData: item}) : '#'}
                      />

              </View>
              <View style={styles.rightcolum}>
                <Image source={{uri: item.logoUrl}} style={{width: 150, height: 68}}/>
              </View>

            </View>
          ))
        }
    </ScrollView>

      );
    }
  }

  const styles = StyleSheet.create({
    cards:{
      backgroundColor: '#D1A96E',
      borderRadius: 10,
      marginTop: 20,
      marginRight: 10,
      marginLeft: 10,
      paddingLeft: 20,
      paddingRight: 20,
      paddingTop: 20,
      paddingBottom: 20,
      flex: 1,
      flexDirection: 'row',
      flexWrap: 'wrap',
      alignItems: 'flex-start'
    },
    stars:{
      marginTop: 10,
    },
    leftcolum:{
      width: '50%',
    },
    rightcolum:{
      width: '50%',
      paddingTop:30,
      paddingLeft:10,
    },
    title:{
      fontSize: 17,
      color: '#fff',
      marginTop: 5,
      fontWeight: '800',
    },
    undertitle:{
      fontSize: 12,
      color: '#fff',
      fontWeight: '200',
    },
    button:{
      backgroundColor: '#3F494B',
      borderRadius: 22,
      marginTop: 20,
    },
    valkenburg:{
      backgroundColor: '#A58657',
    },
    gulpen:{
      backgroundColor: '#EBC285',
    },
    logoValkenburg:{
      width: '50%',
      paddingTop:10,
      paddingLeft:10,
    },
    logoGulpen:{
      width: '50%',
      paddingTop:30,
      paddingLeft:10,
    }

  });

  export default routeScreen;

Structure of array:

what I would like:
now the array is shown in alphabetical order, that is good, I would only like to show object 1 of Goverments at the top because it contains the value routes, with the others the value routes being empty. so if it is filled, it must show it at the top

Body:
const Goverments = [
  {
    name: 'Valkenburg',
  },
  {
    name: 'Eijsden-Margeaten',
  },
  {
    name: 'Gulpen',
    routes: [],
  },
];
const SortedGoverments = Goverments.sort(function(a, b) {
  if(a.routes) return -1; // new check
  if(b.routes) return 1; // new check
  if(a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  if(a.name.toLowerCase() > b.name.toLowerCase()) return 1;
  return 0;
});

console.log("Goverments : ", Goverments);
console.log("SortedGoverments : ", SortedGoverments);


问:
C# Testing - compare list of custom type
I'm trying to write test checking if JSON converter corectly deserialize input to my custom list

```<code>    [TestMethod]
    public void JSONInput_Changed()
    {
        List<PointOnChart> _expectedPointsOnChart;
        _expectedPointsOnChart = new List<PointOnChart>();
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:00:00.000Z", Value1 = 10, Value2 = 20, Value3 = 30 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:01:00.000Z", Value1 = 11, Value2 = 21, Value3 = 31 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:02:00.000Z", Value1 = 12, Value2 = 22, Value3 = 32 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:03:00.000Z", Value1 = 13, Value2 = 23, Value3 = 33 });

        MultipleBarChart multipleBarChartTest = new MultipleBarChart();
        multipleBarChartTest.MeInitialize(DateTimeIntervalType.Minutes);
        string JSONstring = System.IO.File.ReadAllText(@"C:\Users\slawomirk\source\repos\VIXCharts\iFixMultipleBarChartTests\TestJson.txt");
        multipleBarChartTest.JSONInput = JSONstring;
        List<PointOnChart> resultPointsOnChart = multipleBarChartTest.PointsOnChart;

        //bool areEqual = _expectedPointsOnChart.SequenceEqual(resultPointsOnChart);
        IEnumerable<PointOnChart> resultList;
        resultList = _expectedPointsOnChart.Except(resultPointsOnChart);
        if (resultList.Any())
        {
            Assert.Fail();
        }
    }
</code>```

List contains object of this class

```<code>public class PointOnChart
{
    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }
}
</code>```

And this is file I'm reading to deserialize:

[{"Timestamp":"2020-02-14T09:00:00.000Z","Value1":10,"Value2":20,"Value3":30},
  {"Timestamp":"2020-02-14T09:01:00.000Z","Value1":11,"Value2":21,"Value3":31},
  {"Timestamp":"2020-02-14T09:02:00.000Z","Value1":12,"Value2":22,"Value3":32},
  {"Timestamp":"2020-02-14T09:03:00.000Z","Value1":13,"Value2":23,"Value3":33}]

I tried numerous ways to compare two Lists but all of them fails eg.:
 - Fluent Assertion
 - CollectionAssert

When I inspect both List in debug they are identical.
I know it's probably trivial but I could find any solution online, thanks in advance.

答:
In addition to the other answers, i suggest implementing IEquatable<T> as well as overriding GetHashCode() and Equals(Object) like this.

public class PointOnChart : IEquatable<PointOnChart> {

    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }

    public override Int32 GetHashCode() => Timestamp.GetHashCode() ^ Value1.GetHashCode() ^ Value2.GetHashCode() ^ Value3.GetHashCode();

    public override Boolean Equals(Object obj) => Equals(obj as PointOnChart);

    public Boolean Equals(PointOnChart other) => other != null && other.Timestamp == Timestamp && other.Value1.Equals(Value1) && other.Value2.Equals(Value2) && other.Value3.Equals(Value3);

}
```

That'll give you all the comparing you'll need.
Will also make it easier to implement an IEqualityComparer or IEqualityComparer<T> if you need it later on.

Body:
I'm trying to write test checking if JSON converter corectly deserialize input to my custom list

    [TestMethod]
    public void JSONInput_Changed()
    {
        List<PointOnChart> _expectedPointsOnChart;
        _expectedPointsOnChart = new List<PointOnChart>();
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:00:00.000Z", Value1 = 10, Value2 = 20, Value3 = 30 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:01:00.000Z", Value1 = 11, Value2 = 21, Value3 = 31 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:02:00.000Z", Value1 = 12, Value2 = 22, Value3 = 32 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:03:00.000Z", Value1 = 13, Value2 = 23, Value3 = 33 });

        MultipleBarChart multipleBarChartTest = new MultipleBarChart();
        multipleBarChartTest.MeInitialize(DateTimeIntervalType.Minutes);
        string JSONstring = System.IO.File.ReadAllText(@"C:\Users\slawomirk\source\repos\VIXCharts\iFixMultipleBarChartTests\TestJson.txt");
        multipleBarChartTest.JSONInput = JSONstring;
        List<PointOnChart> resultPointsOnChart = multipleBarChartTest.PointsOnChart;

        //bool areEqual = _expectedPointsOnChart.SequenceEqual(resultPointsOnChart);
        IEnumerable<PointOnChart> resultList;
        resultList = _expectedPointsOnChart.Except(resultPointsOnChart);
        if (resultList.Any())
        {
            Assert.Fail();
        }
    }

List contains object of this class

public class PointOnChart
{
    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }
}

And this is file I'm reading to deserialize:

[{"Timestamp":"2020-02-14T09:00:00.000Z","Value1":10,"Value2":20,"Value3":30},
  {"Timestamp":"2020-02-14T09:01:00.000Z","Value1":11,"Value2":21,"Value3":31},
  {"Timestamp":"2020-02-14T09:02:00.000Z","Value1":12,"Value2":22,"Value3":32},
  {"Timestamp":"2020-02-14T09:03:00.000Z","Value1":13,"Value2":23,"Value3":33}]

I tried numerous ways to compare two Lists but all of them fails eg.:
 - Fluent Assertion
 - CollectionAssert

When I inspect both List in debug they are identical.
I know it's probably trivial but I could find any solution online, thanks in advance.

Body:
In addition to the other answers, i suggest implementing IEquatable<T> as well as overriding GetHashCode() and Equals(Object) like this.

public class PointOnChart : IEquatable<PointOnChart> {

    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }

    public override Int32 GetHashCode() => Timestamp.GetHashCode() ^ Value1.GetHashCode() ^ Value2.GetHashCode() ^ Value3.GetHashCode();

    public override Boolean Equals(Object obj) => Equals(obj as PointOnChart);

    public Boolean Equals(PointOnChart other) => other != null && other.Timestamp == Timestamp && other.Value1.Equals(Value1) && other.Value2.Equals(Value2) && other.Value3.Equals(Value3);

}

That'll give you all the comparing you'll need.
Will also make it easier to implement an IEqualityComparer or IEqualityComparer<T> if you need it later on.


问:
Using the gem globalize, how to switch locales for input only and not the whole page?
Context: For a Ruby on Rails app for bike rentals, I am using the gem globalize to deal with input :description in different languages.

Curent state: The globalize implementation worked, depending on my locale I am able to store description in a specific language. The input for :description is dealt with on the basis of the locale of an entire webpage.

This means that everything on this page has to change in language in order to store :description in the correct language.

Alternatively, I am also able to show all available locales and show description for each of them. (See also the commented out code below).

Question: I'm searching for a way to let the user select a language for :description only and then save :description in the correct language without changing the language of the entire webpage.

Code

form

```<code><div class="row">
        <%# I18n.available_locales.each do |locale| %>
          <!-- <h1><%#= locale %></h1> -->
          <%= f.globalize_fields_for locale do |ff| %>
          <div class="col-10">
            <div class="form-group">
              <label class="form-control-label text required" for="accommodation_category_description">Description</label>
              <div><%= ff.text_area :description, :rows =>"5", :cols =>"30",  class:"form-control is-valid text required" %></div>
              </div>
            </div>
          <% end %>
        <%# end %>
        </div>
      </div>
</code>```

initializers/globalization.rb

```<code>module ActionView
  module Helpers
    class FormBuilder
      #
      # Helper that renders translations fields
      # on a per-locale basis, so you can use them separately
      # in the same form and still saving them all at once
      # in the same request.

      def globalize_fields_for(locale, *args, &proc)
        raise ArgumentError, "Missing block" unless block_given?
        @index = @index ? @index + 1 : 1
        object_name = "#{@object_name}[translations_attributes][#{@index}]"
        object = @object.translations.find_by_locale locale.to_s
        @template.concat @template.hidden_field_tag("#{object_name}[id]", object ? object.id : "")
        @template.concat @template.hidden_field_tag("#{object_name}[locale]", locale)
        @template.fields_for(object_name, object, *args, &proc)
      end
    end
  end
end

</code>```

答:
You can use Globalize.with_locale to temporarily set locale, this works for views too:

```<code><% Globalize.with_locale(some_other_locale) do %>
  in this part of the page locale will be <%= locale.inspect %>
<% end %>
</code>```

But for your case more user-friendly way would be to make the form dynamic, so that user can add translation for several languages of their liking.

Globalize translations are just an additional table/model YourModel::Translation with fields for locale and translated fields, so you can work directly with these as with any other nested forms.

Add gem cocoon to your project, that will handle dynamic forms (if you're using webpacker instead of asset pipeline - that may require additional steps, to add global jquery and require js from gem using erb interpolation, see more here).

In your model:

translates :description #, ...
accepts_nested_attributes_for :translations, allow_destroy: true
```

<p>in controller:</p>

<pre class="lang-rb prettyprint-override"><code>def your_some_params
  params.require(:your_model_name).permit(
        ...
        translations_attributes: [
          :id, :_destroy,
          :locale,
          :description,
        ]
      )
end
</code>```

in form:

```<code>  <div id='translations'>
    <%= form.fields_for :translations do |t| %>
      <%= render 'translation_fields', f: t %>
    <% end %>

    <div class='links'>
      <%= link_to_add_association 'add translation', form, :translations  %>
    </div>
  </div>
</code>```

partial for translations like:

```<code><div class='nested-fields'>
  <%= f.hidden_field  :id %>
  <%= f.select :locale, I18n.available_locales %>
  <%= f.text_area :description %>

  <%= link_to_remove_association "remove this translation", f %>
</div>
</code>```

Body:
Context: For a Ruby on Rails app for bike rentals, I am using the gem globalize to deal with input :description in different languages.

Curent state: The globalize implementation worked, depending on my locale I am able to store description in a specific language. The input for :description is dealt with on the basis of the locale of an entire webpage.

This means that everything on this page has to change in language in order to store :description in the correct language.

Alternatively, I am also able to show all available locales and show description for each of them. (See also the commented out code below).

Question: I'm searching for a way to let the user select a language for :description only and then save :description in the correct language without changing the language of the entire webpage.

Code

form

        <%# I18n.available_locales.each do |locale| %>

          <%= f.globalize_fields_for locale do |ff| %>

              Description

<%= ff.text_area :description, :rows =>"5", :cols =>"30",  class:"form-control is-valid text required" %>

          <% end %>
        <%# end %>

initializers/globalization.rb

module ActionView
  module Helpers
    class FormBuilder
      #
      # Helper that renders translations fields
      # on a per-locale basis, so you can use them separately
      # in the same form and still saving them all at once
      # in the same request.

      def globalize_fields_for(locale, *args, &proc)
        raise ArgumentError, "Missing block" unless block_given?
        @index = @index ? @index + 1 : 1
        object_name = "#{@object_name}[translations_attributes][#{@index}]"
        object = @object.translations.find_by_locale locale.to_s
        @template.concat @template.hidden_field_tag("#{object_name}[id]", object ? object.id : "")
        @template.concat @template.hidden_field_tag("#{object_name}[locale]", locale)
        @template.fields_for(object_name, object, *args, &proc)
      end
    end
  end
end

Body:
You can use Globalize.with_locale to temporarily set locale, this works for views too:

<% Globalize.with_locale(some_other_locale) do %>
  in this part of the page locale will be <%= locale.inspect %>
<% end %>

But for your case more user-friendly way would be to make the form dynamic, so that user can add translation for several languages of their liking.

Globalize translations are just an additional table/model YourModel::Translation with fields for locale and translated fields, so you can work directly with these as with any other nested forms.

Add gem cocoon to your project, that will handle dynamic forms (if you're using webpacker instead of asset pipeline - that may require additional steps, to add global jquery and require js from gem using erb interpolation, see more here).

In your model:

translates :description #, ...
accepts_nested_attributes_for :translations, allow_destroy: true

in controller:

def your_some_params
  params.require(:your_model_name).permit(
        ...
        translations_attributes: [
          :id, :_destroy,
          :locale,
          :description,
        ]
      )
end

in form:

  <div id='translations'>
    <%= form.fields_for :translations do |t| %>
      <%= render 'translation_fields', f: t %>
    <% end %>

    <div class='links'>
      <%= link_to_add_association 'add translation', form, :translations  %>
    </div>
  </div>

partial for translations like:

<div class='nested-fields'>
  <%= f.hidden_field  :id %>
  <%= f.select :locale, I18n.available_locales %>
  <%= f.text_area :description %>

  <%= link_to_remove_association "remove this translation", f %>
</div>


问:
React Native version mismatch
Getting the following message when I init a new project and then launch the Xcode emulator:

React-Native Version Mismatch

Javascript Version 0.50.1
  Native version: 0.50.0

Make sure you have rebuilt the native code. ...

Does anyone know what is going on here and can help me?

答:
This is working for me :</p>

```<code>react-native start --reset-cache
</code>```

Title: React Native version mismatch

Body:
This is working for me :

react-native start --reset-cache


问:
VBA type mismatch at rows.cut
I'm having problem with cutting multiple worksheets and putting it into one. I'm getting "Type mismatch" error. Can you look at my code?</p>

```<code>Public Sub Conc()
Dim ws  As Worksheet
Dim LR1 As Integer
Dim LR2 As Integer
Dim LR3 As Integer
Dim first As Integer
LR1 = 0
LR2 = 0
LR3 = 0
first = 1
With ThisWorkbook
    .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Conc"
End With

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "Conc" Then
        LR1 = Sheets("Conc").Cells(Rows.Count, 2).End(xlUp).Row + 1
        LR2 = ws.Cells(Rows.Count, 2).End(xlUp).Row
        LR3 = LR1 + LR2
        Worksheets(ws).Rows(first & ":" & LR2).Cut
        Worksheets("Conc").Rows(LR1 & ":" & LR3).Insert
    End If
Next ws
End Sub
</code>```

答:
Try:</p>

```<code>Public Sub Conc()

    Dim ws  As Worksheet
    Dim LR1 As Long, LR2 As Log, LR3 As Long
    Dim first As Integer

    LR1 = 0
    LR2 = 0
    LR3 = 0
    first = 1

    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Conc"
    End With

    With ThisWorkbook.Worksheets("Conc")
        LR1 = .Cells(.Rows.Count, 2).End(xlUp).Row + 1
    End With

    For Each ws In ActiveWorkbook.Worksheets

        If ws.Name <> "Conc" Then

            With ws

                LR2 = .Cells(.Rows.Count, 2).End(xlUp).Row
                LR3 = LR1 + LR2
                .Rows(first & ":" & LR2).Cut
            End With

            ThisWorkbook.Worksheets("Conc").Rows(LR1 & ":" & LR3).Insert

        End If

    Next ws

End Sub
</code>```

Title: VBA type mismatch at rows.cut

Body:
I'm having problem with cutting multiple worksheets and putting it into one. I'm getting "Type mismatch" error. Can you look at my code?

Public Sub Conc()
Dim ws  As Worksheet
Dim LR1 As Integer
Dim LR2 As Integer
Dim LR3 As Integer
Dim first As Integer
LR1 = 0
LR2 = 0
LR3 = 0
first = 1
With ThisWorkbook
    .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Conc"
End With

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "Conc" Then
        LR1 = Sheets("Conc").Cells(Rows.Count, 2).End(xlUp).Row + 1
        LR2 = ws.Cells(Rows.Count, 2).End(xlUp).Row
        LR3 = LR1 + LR2
        Worksheets(ws).Rows(first & ":" & LR2).Cut
        Worksheets("Conc").Rows(LR1 & ":" & LR3).Insert
    End If
Next ws
End Sub

Body:
Try:

Public Sub Conc()

    Dim ws  As Worksheet
    Dim LR1 As Long, LR2 As Log, LR3 As Long
    Dim first As Integer

    LR1 = 0
    LR2 = 0
    LR3 = 0
    first = 1

    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Conc"
    End With

    With ThisWorkbook.Worksheets("Conc")
        LR1 = .Cells(.Rows.Count, 2).End(xlUp).Row + 1
    End With

    For Each ws In ActiveWorkbook.Worksheets

        If ws.Name <> "Conc" Then

            With ws

                LR2 = .Cells(.Rows.Count, 2).End(xlUp).Row
                LR3 = LR1 + LR2
                .Rows(first & ":" & LR2).Cut
            End With

            ThisWorkbook.Worksheets("Conc").Rows(LR1 & ":" & LR3).Insert

        End If

    Next ws

End Sub


问:
Using models clean method for fields validation
I need to check the model field for a list of available items before I save them to the database.

models.py

```<code>class Vendors(models.Model):
    COUNTRY_CHOICES = tuple(countries)
    ...
    country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
    ...
</code>```

class for saving models

```<code>class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        for key, vendor in data.items():
            Vendors(
                ...,
                country=vendor['Country'],
                ...,

            ).save()

        return Response({'received data': request.data,
                         'message': 'Vendors from vendors_list were successfully added to the database'})
</code>```

For validation Im added clean method to models

```<code>def clean(self):
    if self.country not in [x[1] for x in countries]:
        raise ValidationError(detail="Country name does not match to the country list ")
</code>```

But it doesnt work

Next step I added the same code to method save

```<code>def save(self):
    if self.country not in [x[1] for x in countries]:
        raise ValidationError(detail="Country name does not match to the country list ")
</code>```

And it works, but  I read that using validation in the save method is not correct. And the correct method for use - clean, why in my case it does not work?

答:
See model validation for a full explanation of how validating models works.

In short: To validate an object, you need to call full_clean() on the object. This does not happen automatically! It happens when:

You use a ModelForm and call is_valid() on the form

You use a ModelSerializer in DRF and call is_valid() on the serializer

You call full_clean() explicitly

In your case, just create the object, call full_clean() and then save(). Note you don't even have to add your own check (clean() method) because the check for valid choices is automatically performed by Django during clean_fields() when choices is set on a field:

```<code>v = Vendors(country=vendor['country'], ...)
try:
    v.full_clean()
except ValidationError as e:
    # do something e.g. return error response
v.save()
return Response(...)
</code>```

Body:
I need to check the model field for a list of available items before I save them to the database.

models.py

class Vendors(models.Model):
    COUNTRY_CHOICES = tuple(countries)
    ...
    country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
    ...

class for saving models

class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        for key, vendor in data.items():
            Vendors(
                ...,
                country=vendor['Country'],
                ...,

            ).save()

        return Response({'received data': request.data,
                         'message': 'Vendors from vendors_list were successfully added to the database'})

For validation Im added clean method to models

def clean(self):
    if self.country not in [x[1] for x in countries]:
        raise ValidationError(detail="Country name does not match to the country list ")

But it doesnt work

Next step I added the same code to method save

def save(self):
    if self.country not in [x[1] for x in countries]:
        raise ValidationError(detail="Country name does not match to the country list ")

And it works, but  I read that using validation in the save method is not correct. And the correct method for use - clean, why in my case it does not work?

Body:
See model validation for a full explanation of how validating models works.

In short: To validate an object, you need to call full_clean() on the object. This does not happen automatically! It happens when:

You use a ModelForm and call is_valid() on the form

You use a ModelSerializer in DRF and call is_valid() on the serializer

You call full_clean() explicitly

In your case, just create the object, call full_clean() and then save(). Note you don't even have to add your own check (clean() method) because the check for valid choices is automatically performed by Django during clean_fields() when choices is set on a field:

v = Vendors(country=vendor['country'], ...)
try:
    v.full_clean()
except ValidationError as e:
    # do something e.g. return error response
v.save()
return Response(...)


答:
I suspect you just need to set your delimiter. Your default will probably be a comma or a semicolon - I think it may depend on location settings.

When you create the reader, set:

```<code>reader = csv.reader(f, delimiter="\t")
</code>```

(At least, if the seperator is tabs, which I think it is, looking at your data).

at the moment, the data contains no seperator (i.e. no ","), so it just reads a string, leaving you with one val instead of 3.

Title: Calculating Distance From Coordinates

Body:
I want to calculate the distance from a file I have containing cartesian coordinates. I thought the best way to do this would be to read in the data using csv and try to right a look which can calculate the distance between points.

Sample of coordinate file: (x y z)

0.0     0.0     1.2
0.0     0.0     2.4
0.0     0.0     3.6
0.0     0.0     4.8
0.0     0.0     6.0
0.0     0.0     7.2
0.0     0.0     8.4
0.0     0.0     9.6
0.0     0.0     10.8
0.0     0.0     12.0
0.0     0.0     13.2
0.0     0.0     14.4
0.0     0.0     15.6
0.0     0.0     16.8
0.0     0.0     18.0
0.0     0.0     19.2
0.0     0.0     20.4
0.0     0.0     21.6
0.0     0.0     22.8
0.0     0.0     24.0
2.10602 4.30161 15.4191
1.63363 3.84311 14.6922
1.0001799999999998      3.49724 14.0046
1.4663  2.88937 13.3751
0.9758450000000001      2.6336  12.8105
0.65735 1.4835200000000002      12.7484
0.46493 0.5138590000000001      12.9022
0.08873760000000001     -0.398863       12.5105
0.201499        -1.09372        11.6219
0.7903600000000001      -1.72045        11.0056
0.241616        -2.2128900000000002     11.9763
-0.20944000000000002    -2.29307        11.1821
-0.89938        -1.56606        11.1211
-1.41711        -2.4558 11.2009
-1.8840700000000001     -2.52969        12.2187
-1.81385        -1.49946        11.8263
-0.789176       -1.79308        12.1988
-1.17975        -1.1326 12.8
-1.0421200000000002     -0.111174       12.8198
-0.39158699999999996    -0.355446       13.5661
-0.453186       -0.8214870000000001     19.3475
-0.701328       -1.75309        19.3045
0.259701        -1.77368        18.8392
0.15001099999999998     -0.755324       18.3631
0.564654        -0.5530970000000001     17.6175
1.14706 -0.608927       16.8936
0.984617        -0.22286999999999998    15.9514
0.800405        -0.139544       14.949000000000002
0.823068        0.11181500000000001     13.8241
0.553984        -0.08825939999999999    12.8295
-0.23958600000000002    0.412857        12.4171
0.34061199999999997     0.7038409999999999      11.6287

I cannot get the data to be read in properly and i'm not sure if i'm going about this in the best way. Can anyone help me?

Python code:

import numpy as np

from math import sqrt

def length(frame):
    N=frame.shape[0]
    for i in range(N):
        for j in range(i+1,N):
            l = sqrt(np.linalg.norm(frame[j]-frame[i]))

len = list()
frame = list()
f = open('cartesian.csv') #
for line in f:
    frame=np.array(frame)
    len.append(length(frame))
    frame=list()

with open('output.txt', 'a') as g:
    for item in len:
        g.write("%s\n" % item)
g.close()

However, in my output file all I get is a list of 'none'. I am not sure if I am even approaching this the right way.

The equation I want to compute is distance = sqrt((x2-x1)+(y2-y1)+(z2-z1)). Any help?

Body:
I suspect you just need to set your delimiter. Your default will probably be a comma or a semicolon - I think it may depend on location settings.

When you create the reader, set:

reader = csv.reader(f, delimiter="\t")

(At least, if the seperator is tabs, which I think it is, looking at your data).

at the moment, the data contains no seperator (i.e. no ","), so it just reads a string, leaving you with one val instead of 3.


问:
Passing a variable into a class to determine which method to use
im not sure what im missing but it says that my class variable (var1) is not defined

```<code>Class Example(var1):
   if var1 ==1:
      def func1(var2)
         x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
         Return x
   else pass:

Example(1).func1("example")
</code>```

could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you

答: The syntax Class Example(var1): means that you are creating a class, wich inherits from var1. If you want to define a function, use def Example(var1):

Body:
im not sure what im missing but it says that my class variable (var1) is not defined

Class Example(var1):
   if var1 ==1:
      def func1(var2)
         x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
         Return x
   else pass:

Example(1).func1("example")

could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you


问:
Android: Internal test app not showing up, but account is showing that its eligble
I uploaded an app to internal testing track to the dev console and added a user.
When I go to the app page through the link, it shows (Internal Beta). But the app version I added isn't there. Even though I got a notification that it had been processed and should be live.

So the test user is succesful, and the app was added. But even though it says I am a beta user it doesn't show any app?

答: Right so I followed the test link to store, but it turns out you can't do that on your phone as it will just get you to the store app which only shows the live version. You need to follow the link on a desktop and send it to your phone from there...</p>


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
You can iterate over your array and add a parameter to your SQL for each.  This gets you around SQL injection, but make sure you use a StringBuilder rather than strign concatenation as you build up your SQL statement.

e.g.

```<code>StringBuilder sql = new StrignBuilder("select * from Table where ");
for  (int i = 0; i < RecordIDLis.Length; i++)
{
    if (i > 0) sql.Append (" OR ");
    sql.Append(" RecordID = @param" + i.ToString() + " ");
    IDbDataParameter param = new Param();
    param.value etc.
}
</code>```

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

Body:
You can iterate over your array and add a parameter to your SQL for each.  This gets you around SQL injection, but make sure you use a StringBuilder rather than strign concatenation as you build up your SQL statement.

e.g.

StringBuilder sql = new StrignBuilder("select * from Table where ");
for  (int i = 0; i < RecordIDLis.Length; i++)
{
    if (i > 0) sql.Append (" OR ");
    sql.Append(" RecordID = @param" + i.ToString() + " ");
    IDbDataParameter param = new Param();
    param.value etc.
}

OwnerDisplayName: ck


问:
JSTL foreach var sending to jsp/servlet
I want to know a method how can I send 1 specified item for JSTL's foreach to other JSP or servlet, to print detailed info about that item.

Giving followin code:

```<code>    <c:forEach var="note" items="${notes}">
        <tr>
            <td>${note.getTitle()}</td>
            <td>${note.getRealDate()}</td>
            <td>${note.getUserDate()}</td>
            <td>
                <form action="showdetails.jsp">
                    <input type="submit" value="show details" name="details" />
                </form>
            </td>
        </tr>
    </c:forEach>
</code>```

I need to replace my form, or remake it, to get something that does the job, and I'm out of ideas...

ah, btw. Note has method shown above + showDetails() with String return. And I want to display them all, or just do String all = note.toString(); in jsp/servlet

答:
You don't need a <form>. Just add a link, using a field that uniquely identifies the item:

```<code><a href="showdetails.jsp?noteId=${note.id}">show details</a>
</code>```

ContentLicense: CC BY-SA 3.0

Title: JSTL foreach var sending to jsp/servlet

Body:
I want to know a method how can I send 1 specified item for JSTL's foreach to other JSP or servlet, to print detailed info about that item.

Giving followin code:

    <c:forEach var="note" items="${notes}">

            ${note.getTitle()}
            ${note.getRealDate()}
            ${note.getUserDate()}

                <form action="showdetails.jsp">
                    <input type="submit" value="show details" name="details" />
                </form>

    </c:forEach>

I need to replace my form, or remake it, to get something that does the job, and I'm out of ideas...

ah, btw. Note has method shown above + showDetails() with String return. And I want to display them all, or just do String all = note.toString(); in jsp/servlet

Body:
You don't need a <form>. Just add a link, using a field that uniquely identifies the item:

<a href="showdetails.jsp?noteId=${note.id}">show details</a>


问:
can't show image in my gridView by adding glide
I am trying to create a gridview with some cardview containing imageview, and I am setting the default image in the adapter getView method but it is not working.

This is my gridView Adapter:

```<code>class ImageAdapter constructor(private val mContext: Context, private val images: Array<Int>) :  BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(R.layout.card_view, null)
        }
        val image = convertView!!.findViewById<ImageView>(R.id.added_picture)

        Glide.with(mContext).load(images[position]).into(image)

        return convertView
    }

    override fun getItem(position: Int): Any? {
        return images[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return images.size
    }

}
</code>```

The layout I'm adding in the adapter :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="110dp"
  android:layout_height="110dp"
  android:layout_margin="3dp"
  app:layout_columnSpan="1"
  app:cardCornerRadius="8dp"
  app:layout_rowSpan="1"
  app:layout_column="2"
  app:layout_row="0" >
  <ImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/added_picture"
    />
</androidx.cardview.widget.CardView>
</code>```

The
MainActivity.kt onCreate method:

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gridView.adapter = ImageAdapter(this, arrayOf(R.drawable.filled_rectangle, R.drawable.filled_rectangle))
}
</code>```

My gridView is showing only empty space, if I do not use

答:
```<code>Glide.with(this).load(getImage(my_drawable_image_name)).into(myImageView);

public int getImage(String imageName) {

int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());

return drawableResourceId;
}
</code>```

or You can use  imageview.setImageResource(images[postion])

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<androidx.cardview.widget.CardView
    android:layout_width="110dp"
    android:layout_height="110dp"
    app:cardCornerRadius="8dp"
    android:layout_marginTop="10dp"
    app:layout_column="2"
    app:layout_columnSpan="1"
    app:layout_row="0"
    app:layout_rowSpan="1">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp_20" />

</androidx.cardview.widget.CardView>
</code>```

Body:
I am trying to create a gridview with some cardview containing imageview, and I am setting the default image in the adapter getView method but it is not working.

This is my gridView Adapter:

class ImageAdapter constructor(private val mContext: Context, private val images: Array<Int>) :  BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(R.layout.card_view, null)
        }
        val image = convertView!!.findViewById<ImageView>(R.id.added_picture)

        Glide.with(mContext).load(images[position]).into(image)

        return convertView
    }

    override fun getItem(position: Int): Any? {
        return images[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return images.size
    }

}

The layout I'm adding in the adapter :

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="110dp"
  android:layout_height="110dp"
  android:layout_margin="3dp"
  app:layout_columnSpan="1"
  app:cardCornerRadius="8dp"
  app:layout_rowSpan="1"
  app:layout_column="2"
  app:layout_row="0" >
  <ImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/added_picture"
    />
</androidx.cardview.widget.CardView>

The
MainActivity.kt onCreate method:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gridView.adapter = ImageAdapter(this, arrayOf(R.drawable.filled_rectangle, R.drawable.filled_rectangle))
}

My gridView is showing only empty space, if I do not use

Body:
Glide.with(this).load(getImage(my_drawable_image_name)).into(myImageView);

public int getImage(String imageName) {

int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());

return drawableResourceId;
}

or You can use  imageview.setImageResource(images[postion])

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<androidx.cardview.widget.CardView
    android:layout_width="110dp"
    android:layout_height="110dp"
    app:cardCornerRadius="8dp"
    android:layout_marginTop="10dp"
    app:layout_column="2"
    app:layout_columnSpan="1"
    app:layout_row="0"
    app:layout_rowSpan="1">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp_20" />

</androidx.cardview.widget.CardView>


问:
Your startup project doesn't reference Microsoft.EntityFrameworkCore.Design
I have 2 projects in my solution, I have a project with Entity Framework Core installed:

And in the other ASP.NET Web API project I have these packages:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.0" targetFramework="net461" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net461" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net461" />
  <package id="WebGrease" version="1.6.0" targetFramework="net461" />
</packages>
</code>```

When I run Add-Migration in PMC:

Your startup project 'API' doesn't reference
  Microsoft.EntityFrameworkCore.Design. This package is required for the
  Entity Framework Core Tools to work. Ensure your startup project is
  correct, install the package, and try again.

I installed Microsoft.EntityFrameworkCore.Design in the startup project instead of the data project that will contain all the entities and now it works, is this how the project should be setup?

答:
If you want to do migrations without adding EF references in your services, your library with data access needs a way to construct an instance of your DbContext. You can do this by implementing IDesignTimeDbContextFactory, example:</p>

```<code>public class MyContextFactory : IDesignTimeDbContextFactory<MyContext>
{
    public MyContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
        optionsBuilder.UseSqlServer("Data Source=MyDatabase");

        return new MyContext(optionsBuilder.Options);
    }
}
</code>```

Body:
I have 2 projects in my solution, I have a project with Entity Framework Core installed:

And in the other ASP.NET Web API project I have these packages:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.0" targetFramework="net461" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net461" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net461" />
  <package id="WebGrease" version="1.6.0" targetFramework="net461" />
</packages>

When I run Add-Migration in PMC:

Your startup project 'API' doesn't reference
  Microsoft.EntityFrameworkCore.Design. This package is required for the
  Entity Framework Core Tools to work. Ensure your startup project is
  correct, install the package, and try again.

I installed Microsoft.EntityFrameworkCore.Design in the startup project instead of the data project that will contain all the entities and now it works, is this how the project should be setup?

Body:
If you want to do migrations without adding EF references in your services, your library with data access needs a way to construct an instance of your DbContext. You can do this by implementing IDesignTimeDbContextFactory, example:

public class MyContextFactory : IDesignTimeDbContextFactory<MyContext>
{
    public MyContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
        optionsBuilder.UseSqlServer("Data Source=MyDatabase");

        return new MyContext(optionsBuilder.Options);
    }
}


问:
Cannot find DbContext class using dotnet ef migrations add Initial -s <project> -c <full class name from referenced project> -o <output dir>
I am trying to learn how to generate migrations using dotnet core Entity Framework.

I have an ASP.NET Core Web API project that references two projects, each containing a DBContext.

I have successfully managed to generate the migrations for one dbcontext using:

```<code>dotnet ef migrations add Initial -s <startup_project> -c <fully qualified class name from referenced project> -o <output dir>
</code>```

However, for the second DbContext it fails to find the DbContext with the message:
No DbContext named 'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext' was found.

The project file for the referenced project has the path correctly referenced with contents:

<Project Sdk="Microsoft.NET.Sdk">

  <ItemGroup>
    <ProjectReference Include="..\EventBus\EventBus.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

</Project>
```

<p>The project file for the ASP.NET Core Web API startup project is:</p>

<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk.Web">

  <ItemGroup>
    <ProjectReference Include="..\Courses.Domain\Courses.Domain.csproj" />
    <ProjectReference Include="..\Courses.Infrastructure\Courses.Infrastructure.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\WebHost.Customization\WebHost.Customization.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.AzureServiceBus" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Npgsql" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="3.0.5" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="3.0.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="MediatR" Version="8.0.0" />
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql" Version="4.1.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
    <PackageReference Include="Polly" Version="7.2.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.Http" Version="5.2.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
    <PackageReference Include="System.Reflection" Version="4.3.0" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

The source code for the context class that cannot be found is:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF
{
    public class IntegrationEventLogContext : DbContext
    {
        public IntegrationEventLogContext(DbContextOptions<IntegrationEventLogContext> options) : base(options)
        {
        }

        public DbSet<IntegrationEventLogEntry> IntegrationEventLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<IntegrationEventLogEntry>(ConfigureIntegrationEventLogEntry);
        }

        void ConfigureIntegrationEventLogEntry(EntityTypeBuilder<IntegrationEventLogEntry> builder)
        {
            builder.ToTable("IntegrationEventLog");

            builder.HasKey(e => e.EventId);

            builder.Property(e => e.EventId)
                .IsRequired();

            builder.Property(e => e.Content)
                .IsRequired();

            builder.Property(e => e.CreationTime)
                .IsRequired();

            builder.Property(e => e.State)
                .IsRequired();

            builder.Property(e => e.TimesSent)
                .IsRequired();

            builder.Property(e => e.EventTypeName)
                .IsRequired();
        }
    }
}
```

<p>The Startup.cs of the ASP.NET Core Web API project adds the DB Contexts is as follows: </p>

<pre class="lang-cs prettyprint-override"><code>services.AddEntityFrameworkNpgsql()
                   .AddDbContext<CourseContext>(options =>
                   {
                       options.UseNpgsql(configuration["ConnectionString"],
                           npgsqlOptionsAction: sqlOptions =>
                           {
                               sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                               sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                           });
                   },
                       ServiceLifetime.Scoped  //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   );

            services.AddDbContext<IntegrationEventLogContext>(options =>
            {
                options.UseNpgsql(configuration["ConnectionString"],
                                     npgsqlOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                         //Configuring Connection Resiliency: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                                         sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                                     });
            });
</code>```

Is it possible to generate migrations for many DbContext subclasses from within a startup project?

If so, what are the potential causes of not been able to find a DBContext class?

答:
The problem is that you are trying to create a code-first database from two different DbContext which are pointed to one database - only a single context can do that.

I would suggest you make a one common DbContext which is only responsible for creating the database. Then you can create your real application contexts that contain subsets from the big one.

Is it possible to generate migrations for many DbContext subclasses from within a startup project?

It is possible to generate migrations for many DbContext subclasses in case they are pointed to different databases.

What are the potential causes of not been able to find a DBContext class?

From the error that you have showed I see that you are looking for the namespace, not for the current DbContext class.

'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF' should be 'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext'

Body:
I am trying to learn how to generate migrations using dotnet core Entity Framework.

I have an ASP.NET Core Web API project that references two projects, each containing a DBContext.

I have successfully managed to generate the migrations for one dbcontext using:

dotnet ef migrations add Initial -s <startup_project> -c <fully qualified class name from referenced project> -o <output dir>

However, for the second DbContext it fails to find the DbContext with the message:
No DbContext named 'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext' was found.

The project file for the referenced project has the path correctly referenced with contents:

<Project Sdk="Microsoft.NET.Sdk">

  <ItemGroup>
    <ProjectReference Include="..\EventBus\EventBus.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

</Project>

The project file for the ASP.NET Core Web API startup project is:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <ItemGroup>
    <ProjectReference Include="..\Courses.Domain\Courses.Domain.csproj" />
    <ProjectReference Include="..\Courses.Infrastructure\Courses.Infrastructure.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\WebHost.Customization\WebHost.Customization.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.AzureServiceBus" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Npgsql" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="3.0.5" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="3.0.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="MediatR" Version="8.0.0" />
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql" Version="4.1.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
    <PackageReference Include="Polly" Version="7.2.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.Http" Version="5.2.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
    <PackageReference Include="System.Reflection" Version="4.3.0" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>

The source code for the context class that cannot be found is:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF
{
    public class IntegrationEventLogContext : DbContext
    {
        public IntegrationEventLogContext(DbContextOptions<IntegrationEventLogContext> options) : base(options)
        {
        }

        public DbSet<IntegrationEventLogEntry> IntegrationEventLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<IntegrationEventLogEntry>(ConfigureIntegrationEventLogEntry);
        }

        void ConfigureIntegrationEventLogEntry(EntityTypeBuilder<IntegrationEventLogEntry> builder)
        {
            builder.ToTable("IntegrationEventLog");

            builder.HasKey(e => e.EventId);

            builder.Property(e => e.EventId)
                .IsRequired();

            builder.Property(e => e.Content)
                .IsRequired();

            builder.Property(e => e.CreationTime)
                .IsRequired();

            builder.Property(e => e.State)
                .IsRequired();

            builder.Property(e => e.TimesSent)
                .IsRequired();

            builder.Property(e => e.EventTypeName)
                .IsRequired();
        }
    }
}

The Startup.cs of the ASP.NET Core Web API project adds the DB Contexts is as follows:

services.AddEntityFrameworkNpgsql()
                   .AddDbContext<CourseContext>(options =>
                   {
                       options.UseNpgsql(configuration["ConnectionString"],
                           npgsqlOptionsAction: sqlOptions =>
                           {
                               sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                               sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                           });
                   },
                       ServiceLifetime.Scoped  //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   );

            services.AddDbContext<IntegrationEventLogContext>(options =>
            {
                options.UseNpgsql(configuration["ConnectionString"],
                                     npgsqlOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                         //Configuring Connection Resiliency: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                                         sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                                     });
            });

Is it possible to generate migrations for many DbContext subclasses from within a startup project?

If so, what are the potential causes of not been able to find a DBContext class?


问:
PubSub returns 503 - Service Unavailable all the time
I created a small program in Python for reading messages from a Pub/Sub subscription. I am using Python 3.7 and google-cloud-pubsub 1.1.0.

My code is very simple:

```<code>from google.cloud import pubsub_v1
from google.auth import jwt
import json

service_account_info = json.load(open("service-account-info.json"))
audience_sub = "https://pubsub.googleapis.com/google.pubsub.v1.Subscriber"

credentials_sub = jwt.Credentials.from_service_account_info(
    service_account_info, audience=audience_sub
)

subscriber_ring = pubsub_v1.SubscriberClient(credentials=credentials_sub)

def callback1(message):
    print("In callback!!")
    print(message.data)
    message.ack()

sub_path = "projects/my-project/subscriptions/my-sub"
future = subscriber_ring.subscribe(sub_path, callback=callback1)
future.result()
</code>```

When the code reaches "future.result()", it hangs there forever and times out 10 minutes later with the error

pubsub 503 failed to connect to all addresses

I already verified that:

Pub/Sub is up and running

My service account has all the needed permissions. I even tried with my personal Google Cloud account (I am the project owner) with the same results.

There are unacked messages in the Topic

My network connection is OK

but I cannot make it work. Any ideas?

EDIT: I got some more info from the exception:

```<code>om_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/cloud/pubsub_v1/publisher/_batch/thread.py", line 219, in _commit
    response = self._client.api.publish(self._topic, self._messages)
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/cloud/pubsub_v1/gapic/publisher_client.py", line 498, in publish
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
    on_error=on_error,
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/api_core/retry.py", line 206, in retry_target
    last_exc,
  File "<string>", line 3, in raise_from
google.api_core.exceptions.RetryError: Deadline of 60.0s exceeded while calling functools.partial(<function _wrap_unary_errors.<locals>.error_remapped_callable at 0x7fa030891a70>,

, metadata=[('x-goog-request-params', 'topic=projects/my-project/subscriptions/my-sub'), ('x-goog-api-client', 'gl-python/3.7.6 grpc/1.26.0 gax/1.16.0 gapic/1.2.0')]), last exception: 503 failed to connect to all addresses
</code>```

答: It is likely that there is a firewall rule in place or some network configuration that is disallowing/dropping connections to *.googleapis.com (or specifically pubsub.googleapis.com). You can see an example of this with another Google product.</p>

Body:
I created a small program in Python for reading messages from a Pub/Sub subscription. I am using Python 3.7 and google-cloud-pubsub 1.1.0.

My code is very simple:

from google.cloud import pubsub_v1
from google.auth import jwt
import json

service_account_info = json.load(open("service-account-info.json"))
audience_sub = "https://pubsub.googleapis.com/google.pubsub.v1.Subscriber"

credentials_sub = jwt.Credentials.from_service_account_info(
    service_account_info, audience=audience_sub
)

subscriber_ring = pubsub_v1.SubscriberClient(credentials=credentials_sub)

def callback1(message):
    print("In callback!!")
    print(message.data)
    message.ack()

sub_path = "projects/my-project/subscriptions/my-sub"
future = subscriber_ring.subscribe(sub_path, callback=callback1)
future.result()

When the code reaches "future.result()", it hangs there forever and times out 10 minutes later with the error

pubsub 503 failed to connect to all addresses

I already verified that:

Pub/Sub is up and running

My service account has all the needed permissions. I even tried with my personal Google Cloud account (I am the project owner) with the same results.

There are unacked messages in the Topic

My network connection is OK

but I cannot make it work. Any ideas?

EDIT: I got some more info from the exception:

om_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/cloud/pubsub_v1/publisher/_batch/thread.py", line 219, in _commit
    response = self._client.api.publish(self._topic, self._messages)
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/cloud/pubsub_v1/gapic/publisher_client.py", line 498, in publish
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
    on_error=on_error,
  File "/usr/local/anaconda3/envs/loadtest/lib/python3.7/site-packages/google/api_core/retry.py", line 206, in retry_target
    last_exc,
  File "<string>", line 3, in raise_from
google.api_core.exceptions.RetryError: Deadline of 60.0s exceeded while calling functools.partial(<function _wrap_unary_errors.<locals>.error_remapped_callable at 0x7fa030891a70>,

, metadata=[('x-goog-request-params', 'topic=projects/my-project/subscriptions/my-sub'), ('x-goog-api-client', 'gl-python/3.7.6 grpc/1.26.0 gax/1.16.0 gapic/1.2.0')]), last exception: 503 failed to connect to all addresses


问:
error TS2339 when trying to add child FormGroup in Angular
I'm using Angular8 and trying to add a child FormGroup to a form using addControl:

```<code>    this.testForm = new FormGroup({
        id: new FormControl(0),
        people: new FormGroup({
        }),
    });
    this.testForm.controls['people'].addControl('numbers', new FormGroup({
        number: new FormControl('1234')
    }));
</code>```

This gives me compiler error:
error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.

Really stuck with this, so all help much appreaciated!

答:
FormGroup extended class from AbstractControl has addControl and this method is not part of parent class AbstractControl. So when you use the method get, the returned element is an AbstractControl, not FormGroup, so you should ensure the returned element is a FormGroup and cast it properly to use addControl method.

With this in mind, you can use addControl, adding in your code something like this:

```<code>abstractControl : AbstractControl = this.formGroup.get(tab.id);
if(abstractControl instanceof FormGroup){
    (<FormGroup>abstractControl).addControl(segment.id, this.formBuilder.group({}));
}
</code>```

Body:
I'm using Angular8 and trying to add a child FormGroup to a form using addControl:

    this.testForm = new FormGroup({
        id: new FormControl(0),
        people: new FormGroup({
        }),
    });
    this.testForm.controls['people'].addControl('numbers', new FormGroup({
        number: new FormControl('1234')
    }));

This gives me compiler error:
error TS2339: Property 'addControl' does not exist on type 'AbstractControl'.

Really stuck with this, so all help much appreaciated!

Body:
FormGroup extended class from AbstractControl has addControl and this method is not part of parent class AbstractControl. So when you use the method get, the returned element is an AbstractControl, not FormGroup, so you should ensure the returned element is a FormGroup and cast it properly to use addControl method.

With this in mind, you can use addControl, adding in your code something like this:

abstractControl : AbstractControl = this.formGroup.get(tab.id);
if(abstractControl instanceof FormGroup){
    (<FormGroup>abstractControl).addControl(segment.id, this.formBuilder.group({}));
}


问:
mysql get last message in conversation
I'm currently creating an inbox of private messages and want to show the last message that was either sent or received between each unique user. I currently have this

```<code>SELECT
 Message.id, Message.from, Message.body, Message.isread, Message.timestamp,
 User.id, User.username,
FROM messages as Message
 LEFT JOIN users as User ON (Message.from = User.id)
    WHERE Message.id IN
     (SELECT MAX(`id`) FROM `messages`
        WHERE `to` = '.$this->currentUser["id"].'
         OR `from` = '.$this->currentUser["id"].'
    GROUP BY `from`,`to`)
 ORDER BY Message.id DESC;
</code>```

But it gets both the last sent AND received message, I just want the last message that was sent between the current user and any other one and the user that the conversation is with.

```<code> `Message`.`id` is auto incremented, indvidual message id.
 `Message`.`from` is the ID of the user the message is from.
 `Message`.`to` is the ID of the user the message us to.
</code>```

Thanks

答:
Try this

SELECT m1.* FROM messages
m1 LEFT JOIN messages m2 ON (m1.from = m2.from AND m1.id < m2.id)
WHERE m2.id IS NULL;

Title: mysql get last message in conversation

Body:
I'm currently creating an inbox of private messages and want to show the last message that was either sent or received between each unique user. I currently have this

SELECT
 Message.id, Message.from, Message.body, Message.isread, Message.timestamp,
 User.id, User.username,
FROM messages as Message
 LEFT JOIN users as User ON (Message.from = User.id)
    WHERE Message.id IN
     (SELECT MAX(`id`) FROM `messages`
        WHERE `to` = '.$this->currentUser["id"].'
         OR `from` = '.$this->currentUser["id"].'
    GROUP BY `from`,`to`)
 ORDER BY Message.id DESC;

But it gets both the last sent AND received message, I just want the last message that was sent between the current user and any other one and the user that the conversation is with.

 `Message`.`id` is auto incremented, indvidual message id.
 `Message`.`from` is the ID of the user the message is from.
 `Message`.`to` is the ID of the user the message us to.

Thanks


问:
How to set imagesMaxWidth when html string already has a width
I am using react-native-render-html to transfer a string into html elements while developing React Native Apps. I received the string by RESTful APIs from backend, and there has already had width and height set in  tag:

```
<p>But I want the image to be resized to the largest width of the window, so I use :</p>
```imagesMaxWidth={Dimensions.get('window').width}
```
<p>The whole segment is below:</p>
```  <ScrollView style={styles.content}>
    <Text style={styles.title}>{this.props.title}</Text>
    <Text>{this.props.date}</Text>

  </ScrollView>
```

But the image could not be resized to the max width of the window.

So how could I set this?

Thank you

答: Use ignoredStyles prop to ignore width and height of the original pictures. Use ignoredStyles={['height', 'width']} to fix the issue.

Body:
I am using react-native-render-html to transfer a string into html elements while developing React Native Apps. I received the string by RESTful APIs from backend, and there has already had width and height set in  tag:

But I want the image to be resized to the largest width of the window, so I use :

imagesMaxWidth={Dimensions.get('window').width}

The whole segment is below:

  <ScrollView style={styles.content}>
    <Text style={styles.title}>{this.props.title}</Text>
    <Text>{this.props.date}</Text>

  </ScrollView>

But the image could not be resized to the max width of the window.

So how could I set this?

Thank you