问:
React Navigation 5 header overlap
I am creating an application in React Native, I am using React Navigation 5.x and I have replaced the default header with one created by me, this is part of code:

App.js

```<code>    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home" drawerContent={SideMenu} drawerStyle={{
    backgroundColor: '#fff',
    width: Dimensions.get('window').width - 120,
  }}>
        <Drawer.Screen name="Home" component={StackNav} />
      </Drawer.Navigator>
    </NavigationContainer>
</code>```

StackNav.js

```<code>    <Stack.Navigator   headerMode="float" screenOptions={{
      cardShadowEnabled: false,
      cardOverlayEnabled:false,
      headerTransparent: true,
      headerBackTitleVisible: false,
      gestureEnabled: true,
      headerTintColor: currentTheme.colors.primary,
      headerTitleStyle: styles.headerTitle,
      gestureDirection:"horizontal",
      headerStyleInterpolator: HeaderStyleInterpolators.forStatic,
      cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: ({ scene, previous, navigation }) => {
        const { options } = scene.descriptor;
        const title =
          options.headerTitle !== undefined
            ? options.headerTitle
            : options.title !== undefined
            ? options.title
            : scene.route.name;

        return (
            <MyHeader click={() => addCart()} ref={myRef} scene={scene} onPress={navigation.goBack} navigation={navigation}/>
        );
      }
      }}>
        <Stack.Screen name="Home" component={Home} options={{title: 'Home'}}/>
        <Stack.Screen name="Menu" component={RestaurantMenu} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Piatti" component={MenuItems} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Carrello" component={Cart} options={({ route }) => ({ title: route.params.name })}/>
      </Stack.Navigator>
</code>```

MyHeader.js

```<code>import * as React from 'react';
import { StyleSheet, Button, SafeAreaView, TouchableOpacity, Image,View, Text } from 'react-native';

const styles = StyleSheet.create({
    containerSafe: {
        flex: 1,
        flexDirection:"row",
        justifyContent: "space-between"
      },
      containerLeft: {
        zIndex: 1,
        alignSelf: 'flex-start',
        left: 0,
        marginTop:25,
        marginLeft:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      },
      containerCenter: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      containerRight: {
        zIndex: 1,
        alignSelf: 'flex-end',
        right: 0,
        marginTop:25,
        marginRight:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      }
  });

class CartButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()}  style={styles.containerRight}>
            <Image style={{width:"100%", height:"100%"}}
                source={require('../assets/cart.png')}
            />
            <Text>{this.props.nCart}</Text>
        </TouchableOpacity>
        )
    }
}

class HomeButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/menu.png')}
                />
            </TouchableOpacity>
        )
    }
}

class BackButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/leftArrow.png')}
                />
            </TouchableOpacity>
        )
    }
}

  class MyHeader extends React.Component {
    constructor(props) {
        super(props);
        this.state= {
            nCart: 0
        }
        this.addCart = this.addCart.bind(this);
    }

    addCart(){
        var current = this.state.nCart;
        this.setState({
            nCart: current +1
        })
    }

    render(){
        return(
            <SafeAreaView style={styles.containerSafe}>
                {(this.props.scene.route.name === "Home")? <HomeButton onPress={() =>this.props.navigation.openDrawer()} /> : <BackButton onPress={() => this.props.navigation.goBack()} />}
                <Button title="click" onPress={(() => this.props.click())} />
                <CartButton nCart={this.state.nCart} onPress={() => this.props.navigation.navigate('Carrello', {name: 'Carrello'})} />
            </SafeAreaView>
        )
    }
}

export default MyHeader;
</code>```

but it gives me this problem

The Back button and the Cart button overlap when I change the screen, but the burger menu should disappear and become the arrow of the back button while the cart should simply update in the counter as it does in the home.

答:
I solved it by adding this piece of code</p>

```<code>const progress = Animated.add(scene.progress.current, scene.progress.next || 0);

const opacity = progress.interpolate({
                  inputRange: [0, 1, 2],
                  outputRange: [0, 1, 0],
                });

return (
   <Animated.View style={{ opacity }}><MyHeader click={() => addCart()} ref={myRef} scene={scene} onPress={navigation.goBack} cartElement={cart} navigation={navigation}/></Animated.View>
);
</code>```

Title: React Navigation 5 header overlap

Body:
I am creating an application in React Native, I am using React Navigation 5.x and I have replaced the default header with one created by me, this is part of code:

App.js

    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home" drawerContent={SideMenu} drawerStyle={{
    backgroundColor: '#fff',
    width: Dimensions.get('window').width - 120,
  }}>
        <Drawer.Screen name="Home" component={StackNav} />
      </Drawer.Navigator>
    </NavigationContainer>

StackNav.js

    <Stack.Navigator   headerMode="float" screenOptions={{
      cardShadowEnabled: false,
      cardOverlayEnabled:false,
      headerTransparent: true,
      headerBackTitleVisible: false,
      gestureEnabled: true,
      headerTintColor: currentTheme.colors.primary,
      headerTitleStyle: styles.headerTitle,
      gestureDirection:"horizontal",
      headerStyleInterpolator: HeaderStyleInterpolators.forStatic,
      cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: ({ scene, previous, navigation }) => {
        const { options } = scene.descriptor;
        const title =
          options.headerTitle !== undefined
            ? options.headerTitle
            : options.title !== undefined
            ? options.title
            : scene.route.name;

        return (
            <MyHeader click={() => addCart()} ref={myRef} scene={scene} onPress={navigation.goBack} navigation={navigation}/>
        );
      }
      }}>
        <Stack.Screen name="Home" component={Home} options={{title: 'Home'}}/>
        <Stack.Screen name="Menu" component={RestaurantMenu} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Piatti" component={MenuItems} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Carrello" component={Cart} options={({ route }) => ({ title: route.params.name })}/>
      </Stack.Navigator>

MyHeader.js

import * as React from 'react';
import { StyleSheet, Button, SafeAreaView, TouchableOpacity, Image,View, Text } from 'react-native';

const styles = StyleSheet.create({
    containerSafe: {
        flex: 1,
        flexDirection:"row",
        justifyContent: "space-between"
      },
      containerLeft: {
        zIndex: 1,
        alignSelf: 'flex-start',
        left: 0,
        marginTop:25,
        marginLeft:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      },
      containerCenter: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      containerRight: {
        zIndex: 1,
        alignSelf: 'flex-end',
        right: 0,
        marginTop:25,
        marginRight:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      }
  });

class CartButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()}  style={styles.containerRight}>
            <Image style={{width:"100%", height:"100%"}}
                source={require('../assets/cart.png')}
            />
            <Text>{this.props.nCart}</Text>
        </TouchableOpacity>
        )
    }
}

class HomeButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/menu.png')}
                />
            </TouchableOpacity>
        )
    }
}

class BackButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/leftArrow.png')}
                />
            </TouchableOpacity>
        )
    }
}

  class MyHeader extends React.Component {
    constructor(props) {
        super(props);
        this.state= {
            nCart: 0
        }
        this.addCart = this.addCart.bind(this);
    }

    addCart(){
        var current = this.state.nCart;
        this.setState({
            nCart: current +1
        })
    }

    render(){
        return(
            <SafeAreaView style={styles.containerSafe}>
                {(this.props.scene.route.name === "Home")? <HomeButton onPress={() =>this.props.navigation.openDrawer()} /> : <BackButton onPress={() => this.props.navigation.goBack()} />}
                <Button title="click" onPress={(() => this.props.click())} />
                <CartButton nCart={this.state.nCart} onPress={() => this.props.navigation.navigate('Carrello', {name: 'Carrello'})} />
            </SafeAreaView>
        )
    }
}

export default MyHeader;

but it gives me this problem

The Back button and the Cart button overlap when I change the screen, but the burger menu should disappear and become the arrow of the back button while the cart should simply update in the counter as it does in the home.

Body:
I solved it by adding this piece of code

const progress = Animated.add(scene.progress.current, scene.progress.next || 0);

const opacity = progress.interpolate({
                  inputRange: [0, 1, 2],
                  outputRange: [0, 1, 0],
                });

return (
   <Animated.View style={{ opacity }}><MyHeader click={() => addCart()} ref={myRef} scene={scene} onPress={navigation.goBack} cartElement={cart} navigation={navigation}/></Animated.View>
);


来源: stackexchange

问:
What is the correct way to access the K8S dashboard?

Question

It is not clear how to access the dashboard with HTTPS and cannot find a clear documentation (it just tells to use kubectl proxy). So what is the way to access the dashboard with HTTPS?

Kubernetes Dashboard GitHub tells:

The shortcut http://localhost:8001/ui is deprecated. Use the full proxy URL shown above.

K8S Dashboard Recommended Setup or
K8S Dashboard FAQ do not tell how to access the dashboard without proxy.

I'm accessing Dashboard over HTTPS

  The reason why /ui redirect does not work for HTTPS is that it hasn't yet been updated in the core repository. You can track https://github.com/kubernetes/kubernetes/pull/53046#discussion_r145338754 to find out when it will be merged. Probably it won't be available until K8S 1.8.3+.

  Correct links that can be used to access Dashboard are in our documentation. Check Accessing Dashboard to find out more.

However, the kubernetes-dashboard.yaml manifest defines the service endpoint to the dashboard as below:

```<code>kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system
spec:
  ports:
    - port: 443
      targetPort: 8443
  selector:
    k8s-app: kubernetes-dashboard
</code>```

And the cluster IP (in my environment) assigned is below.

```<code># kubectl get svc -n kube-system
NAME                   TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)         AGE
kubernetes-dashboard   ClusterIP   10.101.199.14   <none>        443/TCP         4h
</code>```

Simply create a SSH tunnel to the 10.101.199.14:443 and access to it (https://localhost:8001) shows the dashboard.

So, basically, there is no need to use kubectl proxy and directly access the clusterIP:443 is the way to access the dashboard with HTTPS?

Kindly suggest where is the up-to-date and accurate documentation on how to use the K8S dashboard.

Environment

```<code># kubectl version
Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.0", GitCommit:"925c127ec6b946659ad0fd596fa959be43f0cc05", GitTreeState:"clean", BuildDate:"2017-12-15T21:07:38Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.0", GitCommit:"925c127ec6b946659ad0fd596fa959be43f0cc05", GitTreeState:"clean", BuildDate:"2017-12-15T20:55:30Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
</code>```

答:
For those stuck with a status-code 403 and coredns- containers stuck during creation, try installing a pod network add-on for your cluster:

Calico for example:

kubectl apply -f https://docs.projectcalico.org/v3.8/manifests/calico.yaml

source: https://kubernetes.io/fr/docs/setup/independent/create-cluster-kubeadm/

ContentLicense: CC BY-SA 3.0

Body:
Question

It is not clear how to access the dashboard with HTTPS and cannot find a clear documentation (it just tells to use kubectl proxy). So what is the way to access the dashboard with HTTPS?

Kubernetes Dashboard GitHub tells:

The shortcut http://localhost:8001/ui is deprecated. Use the full proxy URL shown above.

K8S Dashboard Recommended Setup or
K8S Dashboard FAQ do not tell how to access the dashboard without proxy.

I'm accessing Dashboard over HTTPS

  The reason why /ui redirect does not work for HTTPS is that it hasn't yet been updated in the core repository. You can track https://github.com/kubernetes/kubernetes/pull/53046#discussion_r145338754 to find out when it will be merged. Probably it won't be available until K8S 1.8.3+.

  Correct links that can be used to access Dashboard are in our documentation. Check Accessing Dashboard to find out more.

However, the kubernetes-dashboard.yaml manifest defines the service endpoint to the dashboard as below:

kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system
spec:
  ports:
    - port: 443
      targetPort: 8443
  selector:
    k8s-app: kubernetes-dashboard

And the cluster IP (in my environment) assigned is below.

# kubectl get svc -n kube-system
NAME                   TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)         AGE
kubernetes-dashboard   ClusterIP   10.101.199.14   <none>        443/TCP         4h

Simply create a SSH tunnel to the 10.101.199.14:443 and access to it (https://localhost:8001) shows the dashboard.

So, basically, there is no need to use kubectl proxy and directly access the clusterIP:443 is the way to access the dashboard with HTTPS?

Kindly suggest where is the up-to-date and accurate documentation on how to use the K8S dashboard.

Environment

# kubectl version
Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.0", GitCommit:"925c127ec6b946659ad0fd596fa959be43f0cc05", GitTreeState:"clean", BuildDate:"2017-12-15T21:07:38Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.0", GitCommit:"925c127ec6b946659ad0fd596fa959be43f0cc05", GitTreeState:"clean", BuildDate:"2017-12-15T20:55:30Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}

ContentLicense: CC BY-SA 4.0


问:
How to deal with a text[] array field type in Npgsql?
I have a Postgres 12 database with a single table:

```<code>CREATE TABLE public.messages
(
    sender text COLLATE pg_catalog."default",
    "timestamp" timestamp with time zone,
    message_id bigint,
    text text COLLATE pg_catalog."default",
    priority bigint,
    parameters text[] COLLATE pg_catalog."default"
)
</code>```

Now, when I want to use this table in met .NET Winforms (not .NET Core) application by right-clicking the project, add new item, ADO.NET Entitity Data Model, EF Code First from Database, configuring my connection (successful connection test), choosing my table, I get this error:

Severity  Code    Description Project File    Line    Suppression State
  Warning       Error 6005: The data type '_text' is currently not supported
  for the target Entity Framework version; the column 'parameters' in
  the table 'test.public.messages' was
  excluded. LogTest D:\Projekte\LogTest\Model1.cs   1

The parameters field did not make it into the messages class:

```<code>[Table("public.messages")]
public partial class message
{
    public long id { get; set; }
    public string sender { get; set; }
    public DateTimeOffset? timestamp { get; set; }
    public long? base_message_id { get; set; }
    public string text { get; set; }
    public long? priority { get; set; }
}
</code>```

Apart from parameters, the model works and I can get data from the DB. When I try to add the property manually, it still runs, but parameters is always null:

```<code>    public string[] parameters { get; set; } // also tried List<string>
</code>```

How can I make it work? From what I understand when reading the docs, I think it should be possible?

My application is targetting .NET Framework 4.6, I'm using EntityFramework6.Npgsql version 6.4.1.0 with Npgsql version 4.0.10.0.

答:
Mapping arrays is not supporting in EF6, and will probably never be - EF6's type model is very closed/restricted, and doesn't allow for exposing database-specific types (and especially not complicated cases like arrays).

The EF Core provider does have pretty good support for PostgreSQL arrays, if they're central to what you're doing I'd suggest considering Core instead.

Body:
I have a Postgres 12 database with a single table:

CREATE TABLE public.messages
(
    sender text COLLATE pg_catalog."default",
    "timestamp" timestamp with time zone,
    message_id bigint,
    text text COLLATE pg_catalog."default",
    priority bigint,
    parameters text[] COLLATE pg_catalog."default"
)

Now, when I want to use this table in met .NET Winforms (not .NET Core) application by right-clicking the project, add new item, ADO.NET Entitity Data Model, EF Code First from Database, configuring my connection (successful connection test), choosing my table, I get this error:

Severity  Code    Description Project File    Line    Suppression State
  Warning       Error 6005: The data type '_text' is currently not supported
  for the target Entity Framework version; the column 'parameters' in
  the table 'test.public.messages' was
  excluded. LogTest D:\Projekte\LogTest\Model1.cs   1

The parameters field did not make it into the messages class:

[Table("public.messages")]
public partial class message
{
    public long id { get; set; }
    public string sender { get; set; }
    public DateTimeOffset? timestamp { get; set; }
    public long? base_message_id { get; set; }
    public string text { get; set; }
    public long? priority { get; set; }
}

Apart from parameters, the model works and I can get data from the DB. When I try to add the property manually, it still runs, but parameters is always null:

    public string[] parameters { get; set; } // also tried List<string>

How can I make it work? From what I understand when reading the docs, I think it should be possible?

My application is targetting .NET Framework 4.6, I'm using EntityFramework6.Npgsql version 6.4.1.0 with Npgsql version 4.0.10.0.


问:
Convert String to boolean only if input is "true" or "false"
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

```<code>String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");
</code>```

答:
From java doc about method Boolean.valueOf(String):

Returns a Boolean with a value represented by the specified string.
  The Boolean returned represents a true value if the string argument is
  not null and is equal, ignoring case, to the string "true".

So you can use it in this way:

```<code>public static String getBoolean(String s) {
    if (!s.equals("true") && !s.equals("false")) {
            throw new InvalidInputException("true or false is allowed");
    }
    return Boolean.valueOf(s) ? "true": "false";
}
</code>```

Body:
How can I make sure that the input of a String is either "true" or "false" and then parse it to a boolean?

For example:

String input = "true"; -> boolean result = true;
String input = "false"; -> boolean result = false;
String input = "foobar"; -> throw new InvalidInputException("true or false is allowed");

Body:
From java doc about method Boolean.valueOf(String):

Returns a Boolean with a value represented by the specified string.
  The Boolean returned represents a true value if the string argument is
  not null and is equal, ignoring case, to the string "true".

So you can use it in this way:

public static String getBoolean(String s) {
    if (!s.equals("true") && !s.equals("false")) {
            throw new InvalidInputException("true or false is allowed");
    }
    return Boolean.valueOf(s) ? "true": "false";
}


问:
react filtering an object of arrays
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

```<code> this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}
</code>```

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

```<code>var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });
</code>```

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

答:
You can filter it this way with reduce method. Since it is an object, you have to combine object prototype .keys with array prototype .reduce to filter it.

const searchParams = {
  query: '',
  colors: [],
  text: '',
  legalities: '',
  setName: '',
  pageSize: 4
}

const notEmpty = Object.keys(searchParams).reduce((nonEmptyObj, currentKey) => {
  if (searchParams[currentKey] !== '') {
    nonEmptyObj[currentKey] = searchParams[currentKey];
  }
  return nonEmptyObj;
}, {})

console.log(notEmpty);```

Title: react filtering an object of arrays

Body:
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

 this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?


答:
filter only use for a array, not is a object.

You can try my code

```<code>let searchParams =
    Object.keys(this.state.searchParams)
          .filter( key => this.state.searchParams[key] !== '' );

this.setState({searchParams })
</code>```

Title: react filtering an object of arrays

Body:
filter only use for a array, not is a object.

You can try my code

let searchParams =
    Object.keys(this.state.searchParams)
          .filter( key => this.state.searchParams[key] !== '' );

this.setState({searchParams })


问:
How to replace a comma separated value in table column with user input value oracle

I have a table in oracle with a column with comma separated values. What i need is when a user enters a value and if that value is present in any of the rows, it should be removed.

eg.

COL

123,234

56,123

If user enters 123, the 1st column should have only 234 and second row should have only 56.

How do we do this in oracle??

Please help

Thanks

答:
```<code>delete from yourtable t
where
  instr(','||t.col||',', '123') > 0
</code>```

You can replace '123' with a parameter if you like.

But a better way would be not to store comma separated values, and create a detail table instead. If you need to look for a specific value within a comma separated list, you cannot make use of indices, amongst other limitations.

[edit]
Misunderstood the question. You meant this:

```<code>update YourTable t
set
  t.col = substr(substr(replace(','||t.col||',', ',123,', ','), 2), -2)
where
  instr(','||t.col||',', '123') > 0
</code>```

Add ',' before and after to match items at the beginning or end of the value.

Replace using the value ',123,' (within comma's) to prevent accidentally matching 1234 too.

Use substr twice to remove the first and last character (the added commas)

Use instr in the where to prevent updating records that don't need to be updated (better performance).

Body:
delete from yourtable t
where
  instr(','||t.col||',', '123') > 0

You can replace '123' with a parameter if you like.

But a better way would be not to store comma separated values, and create a detail table instead. If you need to look for a specific value within a comma separated list, you cannot make use of indices, amongst other limitations.

[edit]
Misunderstood the question. You meant this:

update YourTable t
set
  t.col = substr(substr(replace(','||t.col||',', ',123,', ','), 2), -2)
where
  instr(','||t.col||',', '123') > 0

Add ',' before and after to match items at the beginning or end of the value.

Replace using the value ',123,' (within comma's) to prevent accidentally matching 1234 too.

Use substr twice to remove the first and last character (the added commas)

Use instr in the where to prevent updating records that don't need to be updated (better performance).


问:
"Uncaught TypeError: $(...).autocomplete is not a function" and Oracle Apex
So I am tearing my hair out trying to figure out why this isn't working. I keep getting an Uncaught TypeError: $(...).autocomplete is not a function error. I've searched stack overflow and tried everything I can find but it simply refuses to work. I am trying to use this on an Oracle Apex application if that matters.

Does anyone have any suggestions as what to do?

```<code><head>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
    <table id="mytable" class="tg">
        <colgroup>
            <col>
            <col>
            <col>
            <col>
        </colgroup>
        <tr>
            <th class="tg-baqh"></th>
            <th id="A1" class="tg-baqh">Table Name ==></th>
            <th class="columnTypeCss"><div id = "TT00"  contenteditable></div></th>
            </td>
        </tr>
        <tr>
            <th id="A1" class="tg-baqh">Column Name</th>
            <th class="tg-baqh">Column Type</th>
            <th class="tg-baqh">Other Arguments</th>
        </tr>
        <tr>
            <td class="columnNameCss">
                <div  class="ui-widget">
  <input id='AA00'>
</div>
            </td>

            <td  class="columnTypeCss">
                <div class="ui-widget">
  <input id='BB00' >
</div>
            </td>
            <td class="otherArgumentsCss">
                <div class="ui-widget">
  <input id='CC00' >
</div>
            </td>
        </tr>
    </table>
<div style="text-align: center;">
<button id="myButten2" class="butten" type="button" value="button">Add Column</button>
</div>
    <div><br><br><br><br><br><br><br><br><br><br></div>
</body>
<script>

    function createCell(cell, text) {
        var div = document.createElement('div'), // create DIV element
            txt = document.createTextNode(text); // create text node
        //div.appendChild(txt); // append text node to the DIV
        //div.setAttribute('class', style); // set DIV class attribute
        cell.appendChild(div); // append DIV to the table cell
        cell.innerHTML = "<div contenteditable>" + text + "</div>";
    }

    var addRow = function (event) {
        var table = document.getElementById("mytable");
        var numcols = document.getElementById('mytable').rows[0].cells.length;
        var row = table.insertRow(-1);
        var counter = document.getElementById("mytable").rows.length - 1;
        if(counter<10){
        var padded_counter = '0'+counter}
        else{
        var padded_counter = counter}
        for (i = 0; i < numcols; i++) {
            var cell1 = row.insertCell(-1);
            if (i == 0) {
                cell1.setAttribute('class', 'columnNameCss')
                cell1.setAttribute('id', 'AA'+padded_counter)
                cell1.innerHTML = "<div contenteditable></div>"
            } else if (i == 1) {
                cell1.setAttribute('class', 'columnTypeCss')
                cell1.setAttribute('id', 'BB'+padded_counter)
                cell1.innerHTML = "<div contenteditable></div>";
            } else {
                cell1.setAttribute('class', 'otherArgumentsCss')
                cell1.setAttribute('id', 'CC'+padded_counter)
                cell1.innerHTML = "<div contenteditable></div>"
            }
            //if(i=0){cell1.className = "columnNameCss";}
            //if(i=3){cell1.className="columnNameCss"}
            //else if (i=1){cell1.className="columnTypeCss"}else{
            //    cell1.className="otherArgumentsCss"
            //}
        }

    }
document.getElementById("myButten2").addEventListener("click", addRow, false);
</script>  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>
</code>```

答:
It can be related to the different versions of JQuery conflict.
You can try to remove link to the jquery CDN or use apex.jQuery instead of $.

More:
https://docs.oracle.com/database/121/HTMDB/app_comp001.htm#HTMDB29028

Body:
So I am tearing my hair out trying to figure out why this isn't working. I keep getting an Uncaught TypeError: $(...).autocomplete is not a function error. I've searched stack overflow and tried everything I can find but it simply refuses to work. I am trying to use this on an Oracle Apex application if that matters.

Does anyone have any suggestions as what to do?

        <colgroup>
            <col>
            <col>
            <col>
            <col>
        </colgroup>

            Table Name ==>

            Column Name
            Column Type
            Other Arguments

  <input id='AA00'>

  <input id='BB00' >

  <input id='CC00' >

<button id="myButten2" class="butten" type="button" value="button">Add Column</button>


问:
Is there a native technique in PostgreSQL to force "timestamp without time zone" to not include milliseconds?
I am using PostgreSQL 9.6.17. (Migrating from MySQL)

A java program writes dates inside a table. The date formats is the following:
2019-01-01 09:00:00

But it can also be 2019-01-01 09:00:00.00 or 2019-01-01 09:00:00.000 when inserted in the database, which messes up my date management in my program when retrieved.

On insertion, I would like all the date to have the very same format: 2019-01-01 09:00:00. The datatype used by the column is timestamp without a time zone.

How can I tell postgresql to not input milliseconds in timestamp without timezone via configuration or SQL query ?

This data types doc does not provide any information about that.

答:
Retrieve as a timestamp and in the application querying the database, manage the precision however you want. eg. via JDBC you'll get a Java LocalDateTime object, in Python you'll get a datetime object.

If you want to retrieve timestamps as strings, there are lots of formatting options available

SELECT to_char(when, 'YYYY-MM-DD HH24:MI:SS') FROM mytable
```</li>
<li><p>Drop any milliseconds on input by specifying the precision option to your timestamp type:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE mytable (..., when TIMESTAMP(0));
</code>```

Body:
Retrieve as a timestamp and in the application querying the database, manage the precision however you want. eg. via JDBC you'll get a Java LocalDateTime object, in Python you'll get a datetime object.

If you want to retrieve timestamps as strings, there are lots of formatting options available

SELECT to_char(when, 'YYYY-MM-DD HH24:MI:SS') FROM mytable

Drop any milliseconds on input by specifying the precision option to your timestamp type:

CREATE TABLE mytable (..., when TIMESTAMP(0));


问:
R dplyr::Filter dataframe by group and numeric vector?
I have dataframe df1 containing data and groups, and df2 which stores the same groups, and one value per group.

I want to filter rows of df1 by df2 where lag by group is higher than indicated value.

Dummy example:

```<code>  # identify the first year of disturbance by lag by group
df1 <- data.frame(year = c(1:4, 1:4),
                 mort = c(5,16,40,4,5,6,10,108),
                 distance = rep(c("a", "b"), each = 4))

df2 = data.frame(distance = c("a", "b"),
                       my.median = c(12,1))
</code>```

Now calculate the lag between values (creates new column) and filter df1 based on column values of df2:

```<code># calculate lag between years
df1 %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  filter(yearLag > df2$my.median)  ##
</code>```

This however does not produce expected results:

```<code># A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     2    16 a             11
2     3    40 a             24
3     4   108 b             98
</code>```

Instead, I expect to get:

```<code># A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     3    40 a             24
2     1     5 b              5
3     3    10 b              4
</code>```

The filter works great while applied to single value, but how to adapt it to vector, and especially vector of groups (as the order of elements can potentially change?)

答:
here is a data.table approach

```<code>library( data.table )
#creatae data.tables
setDT(df1);setDT(df2)
#create yearLag variable
df1[, yearLag := mort - shift( mort, type = "lag", fill = 0 ), by = .(distance) ]
#update join and filter wanted rows
df1[ df2, median.value := i.my.median, on = .(distance)][ yearLag > median.value, ][]

#    year mort distance yearLag median.value
# 1:    3   40        a      24           12
# 2:    1    5        b       5            1
# 3:    3   10        b       4            1
# 4:    4  108        b      98            1
</code>```

Body:
I have dataframe df1 containing data and groups, and df2 which stores the same groups, and one value per group.

I want to filter rows of df1 by df2 where lag by group is higher than indicated value.

Dummy example:

  # identify the first year of disturbance by lag by group
df1 <- data.frame(year = c(1:4, 1:4),
                 mort = c(5,16,40,4,5,6,10,108),
                 distance = rep(c("a", "b"), each = 4))

df2 = data.frame(distance = c("a", "b"),
                       my.median = c(12,1))

Now calculate the lag between values (creates new column) and filter df1 based on column values of df2:

# calculate lag between years
df1 %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  filter(yearLag > df2$my.median)  ##

This however does not produce expected results:

# A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     2    16 a             11
2     3    40 a             24
3     4   108 b             98

Instead, I expect to get:

# A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     3    40 a             24
2     1     5 b              5
3     3    10 b              4

The filter works great while applied to single value, but how to adapt it to vector, and especially vector of groups (as the order of elements can potentially change?)

Body:
here is a data.table approach

library( data.table )
#creatae data.tables
setDT(df1);setDT(df2)
#create yearLag variable
df1[, yearLag := mort - shift( mort, type = "lag", fill = 0 ), by = .(distance) ]
#update join and filter wanted rows
df1[ df2, median.value := i.my.median, on = .(distance)][ yearLag > median.value, ][]

#    year mort distance yearLag median.value
# 1:    3   40        a      24           12
# 2:    1    5        b       5            1
# 3:    3   10        b       4            1
# 4:    4  108        b      98            1


问:
Openlayers: Vector Features instead of Markers
I want to place a symbol o a Map. E.g.

So far I have used OpenLayers with OpenLayers.Layer.Markers. The code looks like this:

```<code>    map = new OpenLayers.Map('map');
    layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
    map.addLayer(layer);
    map.setCenter(
        new OpenLayers.LonLat({{ location.lon }}, {{ location.lat }}).transform(
            new OpenLayers.Projection("EPSG:4326"),
            map.getProjectionObject()
        ), 15);

   var lonLat = new OpenLayers.LonLat({{ location.lon }}, {{ location.lat }})
             .transform(
               new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
               map.getProjectionObject() // to Spherical Mercator Projection
             );
   var markers = new OpenLayers.Layer.Markers( "Markers" );
   map.addLayer(markers);
   markers.addMarker(new OpenLayers.Marker(lonLat));
</code>```

This works as excepted and shows the map above. But I can't get it to work with Vectors replacing the last 3 lines with:

```<code>     vectors = new OpenLayers.Layer.Vector("Vector Layer");
     vectors.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat))]);
     map.addLayer(vectors);
</code>```

Is there any special magic needed to use OpenLayers.Feature.Vector?

答:
OpenLayers.Geometry.Point receives two coordinates in its constructor and not an OpenLayers.LonLat.

vectors = new OpenLayers.Layer.Vector("Vector Layer");
point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
vectors.addFeatures([new OpenLayers.Feature.Vector(point)]);
map.addLayer(vectors);
```

Body:
I want to place a symbol o a Map. E.g.

So far I have used OpenLayers with OpenLayers.Layer.Markers. The code looks like this:

    map = new OpenLayers.Map('map');
    layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
    map.addLayer(layer);
    map.setCenter(
        new OpenLayers.LonLat({{ location.lon }}, {{ location.lat }}).transform(
            new OpenLayers.Projection("EPSG:4326"),
            map.getProjectionObject()
        ), 15);

   var lonLat = new OpenLayers.LonLat({{ location.lon }}, {{ location.lat }})
             .transform(
               new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
               map.getProjectionObject() // to Spherical Mercator Projection
             );
   var markers = new OpenLayers.Layer.Markers( "Markers" );
   map.addLayer(markers);
   markers.addMarker(new OpenLayers.Marker(lonLat));

This works as excepted and shows the map above. But I can't get it to work with Vectors replacing the last 3 lines with:

     vectors = new OpenLayers.Layer.Vector("Vector Layer");
     vectors.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat))]);
     map.addLayer(vectors);

Is there any special magic needed to use OpenLayers.Feature.Vector?


问:
Web scraping according to user input form data
I surprised when I have asked to tell logic behind the website to scrape https://www.astroyogi.com/kundli/kundli-matching.I didnt How can I fill the details and goes to next page.</p>

答: You can do this in several ways. First of all, you can use selenium to control your web browser, fill out forms and then click on the button. Secondly, you can also use the requests library to send the necessary data using POST request. Finally, you can also use Scrapy as a library to help you scrape websites.</p>


问:
Trying to use Docker with Django but server not starting
I'm trying to start a Django app using Docker on Windows 10. I'm following the Quickstart Tutorial here:

https://docs.docker.com/compose/django/#connect-the-database

When it gets to the docker-compose up part, to actually start the app, it gets stuck.

This is the docker-compose.yml:

```<code>version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
</code>```

This is the Dockerfile:

```<code> FROM python:3.5
 ENV PYTHONUNBUFFERED 1
 RUN mkdir /code
 WORKDIR /code
 ADD requirements.txt /code/
 RUN pip install -r requirements.txt
 ADD . /code/
</code>```

when I use docker-compose up it gets stuck in:

```<code>web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
</code>```

答:
I had the same issue but I found a workaround to run it.

In your Django settings.py change ALLOWED_HOST to
ALLOWED_HOST = ['*'] so Django will allow every host to access the app.

Finally, when you start your Docker Quickstart Terminal it shows you default machine with IP 192.168.XX.XX. Run docker-compose up and you can find your Django app running on IP: 192.168.XX.XX:8000.

Don't worry docker-compose up isn't stuck but it's just not echoing any Django output.

Body:
I'm trying to start a Django app using Docker on Windows 10. I'm following the Quickstart Tutorial here:

https://docs.docker.com/compose/django/#connect-the-database

When it gets to the docker-compose up part, to actually start the app, it gets stuck.

This is the docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

This is the Dockerfile:

 FROM python:3.5
 ENV PYTHONUNBUFFERED 1
 RUN mkdir /code
 WORKDIR /code
 ADD requirements.txt /code/
 RUN pip install -r requirements.txt
 ADD . /code/

when I use docker-compose up it gets stuck in:

web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).


问:
Is there a way to find the list of Files accessed ( CRUD) by a Docker Container over its mounted volume
I am interested to find the list of files accessed ( create, read, update, delete) by a Docker container over its Mounted volume.

I can use File monitor over volume , would like to know is there any way it can be acheived or metrics extracted while Docker container access the volume and the directories or files present inside.

Volume mapping by -v hostdir:containerdir

答: On windows you can use process monitor. On linux you can use iotop.</p>


问:
Using CMake to create an executable that can run independently on other machines
I’m using LibTorch and OpenCV for a program in Cpp. The compilation and building is done on Linux using CMake. The program builds and runs as expected.

I want to use the executable that CMake created on another Linux machine.
The problem is that I don’t want to install either LibTorch nor OpenCV on the other machine. I’d rather supply the user with a single executable if possible.

How can CMake create a single independent executable?
If making just a single file is irrelevant, how can CMake copy all needed libraries to a single directory?

The current CMake file:

```<code>    cmake_minimum_required(VERSION 2.8)
    project(prediction)
    list(APPEND CMAKE_PREFIX_PATH “libtorch”) # the folder where libtorch in found
    set(CMAKE_BUILD_TYPE Release)

    find_package( OpenCV REQUIRED )
    find_package( Torch REQUIRED )

    if(NOT Torch_FOUND)
    message(FATAL_ERROR “Pytorch Not Found!”)
    endif(NOT Torch_FOUND)

    message(STATUS “Pytorch status:”)
    message(STATUS " libraries: ${TORCH_LIBRARIES}")

    message(STATUS “OpenCV library status:”)
    message(STATUS " version: ${OpenCV_VERSION}")
    message(STATUS " libraries: ${OpenCV_LIBS}")
    message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")

    file(GLOB SOURCES ".h" ".cpp") # Link all headers and sources in root dir

    include_directories( ${OpenCV_INCLUDE_DIRS} )
    add_executable(entrypoint ${SOURCES})
    target_link_libraries(entrypoint ${TORCH_LIBRARIES} ${OpenCV_LIBS})
    set_property(TARGET entrypoint PROPERTY CXX_STANDARD 14)
</code>```

####### EDIT

Thanks for the answers.
Following Phesho_T answer bellow, I got the static compilation of LibTorch, but it won't compile with the set() instruction. It throws C10_LIBRARY NOTFOUND.

I think I'll try to use the shared libraries. How can CMake be instructed to copy the releveant shared libraries to the "build" folder, so I can pack everything in a .zip file and send it to the user.

答: To create a single executable you need to statically link the dependencies into your executable. Check your libraries to see if they provide static-libs else you need to recompile libtorch or opencv to make static libraries.</p>

Body:
I’m using LibTorch and OpenCV for a program in Cpp. The compilation and building is done on Linux using CMake. The program builds and runs as expected.

I want to use the executable that CMake created on another Linux machine.
The problem is that I don’t want to install either LibTorch nor OpenCV on the other machine. I’d rather supply the user with a single executable if possible.

How can CMake create a single independent executable?
If making just a single file is irrelevant, how can CMake copy all needed libraries to a single directory?

The current CMake file:

    cmake_minimum_required(VERSION 2.8)
    project(prediction)
    list(APPEND CMAKE_PREFIX_PATH “libtorch”) # the folder where libtorch in found
    set(CMAKE_BUILD_TYPE Release)

    find_package( OpenCV REQUIRED )
    find_package( Torch REQUIRED )

    if(NOT Torch_FOUND)
    message(FATAL_ERROR “Pytorch Not Found!”)
    endif(NOT Torch_FOUND)

    message(STATUS “Pytorch status:”)
    message(STATUS " libraries: ${TORCH_LIBRARIES}")

    message(STATUS “OpenCV library status:”)
    message(STATUS " version: ${OpenCV_VERSION}")
    message(STATUS " libraries: ${OpenCV_LIBS}")
    message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")

    file(GLOB SOURCES ".h" ".cpp") # Link all headers and sources in root dir

    include_directories( ${OpenCV_INCLUDE_DIRS} )
    add_executable(entrypoint ${SOURCES})
    target_link_libraries(entrypoint ${TORCH_LIBRARIES} ${OpenCV_LIBS})
    set_property(TARGET entrypoint PROPERTY CXX_STANDARD 14)

####### EDIT

Thanks for the answers.
Following Phesho_T answer bellow, I got the static compilation of LibTorch, but it won't compile with the set() instruction. It throws C10_LIBRARY NOTFOUND.

I think I'll try to use the shared libraries. How can CMake be instructed to copy the releveant shared libraries to the "build" folder, so I can pack everything in a .zip file and send it to the user.


问:
Is there an extensible way to initialize a struct from an array in C++?
```<code>struct SomeStruct {
    int a;
    int b;
    int c;
    int d;
};

void main() {
    std::array<int, 4> arr {1, 2, 3, 4};
    SomeStruct someStruct { ??? }; // <------ Initialize with arr? (Ideal would be {arr})
}
</code>```

As seen in the code example, is there some shortcut to initialize someStruct with arr?
Instead of resorting to:

```<code>    SomeStruct someStruct {arr[0], arr[1], arr[2], arr[3]};
</code>```

答:
You can use one of the Memory Transfer functions. {memcpy, CopyMemory}

this is an example:

```<code>#include <iostream>
#include <array>
#include <string.h>

using namespace std;

int main()
{
   array<int,4> ar = {1,2,3,4};

   struct myStruct
   {
      int a;
      int b;
      int c;
      int d;
   };

 myStruct stc;

memcpy(&stc, ar.data(), sizeof(stc));

cout << "My struct elements are: " << stc.a << " - " << stc.b << " - "<< stc.c << " - " << stc.d << endl;
return 0;
}
</code>```

Body:
struct SomeStruct {
    int a;
    int b;
    int c;
    int d;
};

void main() {
    std::array<int, 4> arr {1, 2, 3, 4};
    SomeStruct someStruct { ??? }; // <------ Initialize with arr? (Ideal would be {arr})
}

As seen in the code example, is there some shortcut to initialize someStruct with arr?
Instead of resorting to:

    SomeStruct someStruct {arr[0], arr[1], arr[2], arr[3]};

Body:
You can use one of the Memory Transfer functions. {memcpy, CopyMemory}

this is an example:

#include <iostream>
#include <array>
#include <string.h>

using namespace std;

int main()
{
   array<int,4> ar = {1,2,3,4};

   struct myStruct
   {
      int a;
      int b;
      int c;
      int d;
   };

 myStruct stc;

memcpy(&stc, ar.data(), sizeof(stc));

cout << "My struct elements are: " << stc.a << " - " << stc.b << " - "<< stc.c << " - " << stc.d << endl;
return 0;
}


问:
Execution of do while loop in the Java Calculator program
In my Java Program, I have used a Boolean variable 'decision' which should execute the actual calculator code in the 'do loop code block' only when the variable is true, but the do while loop is executed anyways even when the decision variable is false. I am using Eclipse IDE for Java and JDK 10 (both are recent versions). Please help me with a solution. The code is as below</p>

```<code>import java.util.Scanner;

public class apples {

public static void main(String[] args) {

    int option,a,b,c;
    boolean decision;
    System.out.println("We are here to create a calculator");
    System.out.print("Do you want to switch on the calculator:");
    Scanner yogi = new Scanner(System.in);
    decision = yogi.nextBoolean();
    do {
        System.out.println("Following operations are available to perform:");
        System.out.println("1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Multiplication");
        System.out.println("4. Division");
        System.out.print("Enter the operations do you want to perform:");
        option = yogi.nextInt();
        System.out.println("Choice of operation is:"+option);

        switch(option) {

        case 1:
            System.out.println("Enter two numbers to be added:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a + b;
            System.out.print("Addition:"+c);
            break;

        case 2:
            System.out.println("Enter two numbers to be subtracted:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a - b;
            System.out.print("subtracted:"+c);
            break;

        case 3:
            System.out.println("Enter two numbers to be multiplied:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a * b;
            System.out.print("multiplied:"+c);
            break;

        case 4:
            System.out.println("Enter two numbers to be divided:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a / b;
            System.out.print("divided:"+c);
            break;

        default:
            System.out.println("This is a wrong choice");
            break;
        }
    }while(decision==true);
  }
}
</code>```

答:
You can add another case 5 and in that write System.exit(0) for the successful termination of the program.

In the while part pass (option != 5). This should run the program.
You don't need decision variable.

Body:
In my Java Program, I have used a Boolean variable 'decision' which should execute the actual calculator code in the 'do loop code block' only when the variable is true, but the do while loop is executed anyways even when the decision variable is false. I am using Eclipse IDE for Java and JDK 10 (both are recent versions). Please help me with a solution. The code is as below

import java.util.Scanner;

public class apples {

public static void main(String[] args) {

    int option,a,b,c;
    boolean decision;
    System.out.println("We are here to create a calculator");
    System.out.print("Do you want to switch on the calculator:");
    Scanner yogi = new Scanner(System.in);
    decision = yogi.nextBoolean();
    do {
        System.out.println("Following operations are available to perform:");
        System.out.println("1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Multiplication");
        System.out.println("4. Division");
        System.out.print("Enter the operations do you want to perform:");
        option = yogi.nextInt();
        System.out.println("Choice of operation is:"+option);

        switch(option) {

        case 1:
            System.out.println("Enter two numbers to be added:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a + b;
            System.out.print("Addition:"+c);
            break;

        case 2:
            System.out.println("Enter two numbers to be subtracted:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a - b;
            System.out.print("subtracted:"+c);
            break;

        case 3:
            System.out.println("Enter two numbers to be multiplied:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a * b;
            System.out.print("multiplied:"+c);
            break;

        case 4:
            System.out.println("Enter two numbers to be divided:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a / b;
            System.out.print("divided:"+c);
            break;

        default:
            System.out.println("This is a wrong choice");
            break;
        }
    }while(decision==true);
  }
}


问:
Collection View horizontal direction with dynamic height
I have a collection view with direction set to horizontal and paging enable. The things is, the height of my collection cell each page sometimes is higher than the phone screen size. What I want to achieve is user can scroll down the cell and swipe right to the next page.

Currently, I only able to display the collection cell one full page, without manage to scroll downward based on content height. Here some code:

```<code>extension EventListDetailsVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cat = dataArray[indexPath.row]

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "celldetails", for: indexPath) as? EventListDetailsCVC
        cell?.imageEvent.image = UIImage(named: cat.imageEvent)
        cell?.eventTitleLabel.text = cat.titleEvent
        cell?.eventDescriptionLabel.text = cat.content

        return cell!
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: self.collectionView.frame.size.width, height: self.collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
     }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}
</code>```

this how it should be

I tried to embed my collectionView into tableView, but it seems does not work because I have dynamic height in a cell.

Is it another way to achive this?

p/s I just started learning swift, thanks.

答:
Have you tried embedding a scroll view inside each collection view cell?

That would make sure that the collection view cell height never exceeds the phone height while the scroll view will work on displaying more content as you scroll down whether it be text or images or whatever view you decide to embed in the scroll view itself.

Body:
I have a collection view with direction set to horizontal and paging enable. The things is, the height of my collection cell each page sometimes is higher than the phone screen size. What I want to achieve is user can scroll down the cell and swipe right to the next page.

Currently, I only able to display the collection cell one full page, without manage to scroll downward based on content height. Here some code:

extension EventListDetailsVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cat = dataArray[indexPath.row]

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "celldetails", for: indexPath) as? EventListDetailsCVC
        cell?.imageEvent.image = UIImage(named: cat.imageEvent)
        cell?.eventTitleLabel.text = cat.titleEvent
        cell?.eventDescriptionLabel.text = cat.content

        return cell!
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: self.collectionView.frame.size.width, height: self.collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
     }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

this how it should be

I tried to embed my collectionView into tableView, but it seems does not work because I have dynamic height in a cell.

Is it another way to achive this?

p/s I just started learning swift, thanks.


问:
useContext() returns undefined
I'm running into an issue which is super frustrating and I can't figure out whats going on.
I have a simple context as shown here:

```<code>import React, { useState, createContext } from "react";

export const AppStateContext = createContext();

const AppStateContextProvider = props => {
  const [appState, setAppState] = useState({
    cartOpen: false
  });

  return <AppStateContext.Provider value={{ appState, setAppState }}>{props.children}</AppStateContext.Provider>;
};

export default AppStateContextProvider;
</code>```

I've also wrapped my App in the provider:

```<code>import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import CssBaseline from "@material-ui/core/CssBaseline";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
import { deepPurple, amber } from "@material-ui/core/colors";
import AppStateContextProvider from "./contexts/AppStateContext";

const theme = createMuiTheme({
  palette: {
    type: "dark",
    primary: {
      main: deepPurple[400]
    },
    secondary: {
      main: amber[800]
    }
  }
});

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <AppStateContextProvider>
      <App />
    </AppStateContextProvider>
  </ThemeProvider>,
  document.getElementById("root")
);

</code>```

and I'm consuming the context here:

```<code>import React, { useContext } from "react";
import {
  Grid,
  Card,
  CardHeader,
  CardContent,
  CardActions,
  Divider,
  Container,
  AppBar,
  Toolbar,
  IconButton,
  Tooltip
} from "@material-ui/core";
import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";
import AppStateContext from "../contexts/AppStateContext";

const TopAppBar = props => {
  console.log("context: ", AppStateContext);
  console.log("useContext(context): ", useContext(AppStateContext));

  //   const { appState, setAppState } = useContext(AppStateContext);

  return (
      <AppBar>
      <Toolbar>
        <Tooltip title="View Cart">
          <IconButton>
            <ShoppingCartIcon />
          </IconButton>
        </Tooltip>
      </Toolbar>
    </AppBar>
  );
};

export default TopAppBar;
</code>```

The line of code that is commented out throws an error because useContext(AppStateContext) is undefined.
The output of the two console logs are this:

```<code>context:  props => {
  const [appState, setAppState] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])({
    cartOpen: false
  });
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(App…
useContext(context):  undefined
</code>```

As you can see, the context looks okay, but calling useContext on the context returns undefined. So there must be some mistake somewhere but I'm struggling to find it.

Any help would be greatly appreciated! :)

答:
You are importing AppStateContextProvider

change import AppStateContext from "../contexts/AppStateContext";

to import { AppStateContext } from "../contexts/AppStateContext";

Title: useContext() returns undefined

Body:
I'm running into an issue which is super frustrating and I can't figure out whats going on.
I have a simple context as shown here:

import React, { useState, createContext } from "react";

export const AppStateContext = createContext();

const AppStateContextProvider = props => {
  const [appState, setAppState] = useState({
    cartOpen: false
  });

  return <AppStateContext.Provider value={{ appState, setAppState }}>{props.children}</AppStateContext.Provider>;
};

export default AppStateContextProvider;

I've also wrapped my App in the provider:

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import CssBaseline from "@material-ui/core/CssBaseline";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
import { deepPurple, amber } from "@material-ui/core/colors";
import AppStateContextProvider from "./contexts/AppStateContext";

const theme = createMuiTheme({
  palette: {
    type: "dark",
    primary: {
      main: deepPurple[400]
    },
    secondary: {
      main: amber[800]
    }
  }
});

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <AppStateContextProvider>
      <App />
    </AppStateContextProvider>
  </ThemeProvider>,
  document.getElementById("root")
);

and I'm consuming the context here:

import React, { useContext } from "react";
import {
  Grid,
  Card,
  CardHeader,
  CardContent,
  CardActions,
  Divider,
  Container,
  AppBar,
  Toolbar,
  IconButton,
  Tooltip
} from "@material-ui/core";
import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";
import AppStateContext from "../contexts/AppStateContext";

const TopAppBar = props => {
  console.log("context: ", AppStateContext);
  console.log("useContext(context): ", useContext(AppStateContext));

  //   const { appState, setAppState } = useContext(AppStateContext);

  return (
      <AppBar>
      <Toolbar>
        <Tooltip title="View Cart">
          <IconButton>
            <ShoppingCartIcon />
          </IconButton>
        </Tooltip>
      </Toolbar>
    </AppBar>
  );
};

export default TopAppBar;

The line of code that is commented out throws an error because useContext(AppStateContext) is undefined.
The output of the two console logs are this:

context:  props => {
  const [appState, setAppState] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])({
    cartOpen: false
  });
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(App…
useContext(context):  undefined

As you can see, the context looks okay, but calling useContext on the context returns undefined. So there must be some mistake somewhere but I'm struggling to find it.

Any help would be greatly appreciated! :)


问:
What is the reason to initialize or assign an empty string literal to a pointer to char in C, or a pointer to const char in C++?
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

```<code>char* p = "";
</code>```

or

```<code>char* p;
p = "";
</code>```

Or, as suggested in the comments, in C++:

```<code>const char* p = "";
</code>```

or

```<code>const char* p;
p = "";
</code>```

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

答:
I wouldn't necessarily go as far as to say that this is some kind of “coding technique”. Rather, I think that, in many cases, it is simply better than the alternatives.

Initializing to "" may sometimes be preferred because it is more safe. Let's suppose you have code like this:

```<code>const char* s;
if(some_condition) {
  s = something();
} else if(some_other_condition) {
  s = something_else();
}
for(const char* p = s; *p; ++p) {
  /* do something */
}
</code>```

Now, suppose you know with 95% certainty that either some_condition or some_other_condition will be true all the time, but this kind of code still looks scary to you (it does to me).

If you do not initialize s at all and none of conditions are true, the behaviour of your program is undefined. It may crash, it may not. You will never be able to check for the error condition later because s could be literally anything.

If you initialize s with NULL, you can now check for the error condition but your for loop still contains UB.

The safest way here would obviously be to include something like else { assert(0); } and explicitly check for the error condition, but if that's not necessary in your situation, you can initialize s to "" and the code will just do nothing if some_condition and some_other_condition are both false.

Body:
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

char* p = "";

or

char* p;
p = "";

Or, as suggested in the comments, in C++:

const char* p = "";

or

const char* p;
p = "";

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

Body:
I wouldn't necessarily go as far as to say that this is some kind of “coding technique”. Rather, I think that, in many cases, it is simply better than the alternatives.

Initializing to "" may sometimes be preferred because it is more safe. Let's suppose you have code like this:

const char* s;
if(some_condition) {
  s = something();
} else if(some_other_condition) {
  s = something_else();
}
for(const char* p = s; *p; ++p) {
  /* do something */
}

Now, suppose you know with 95% certainty that either some_condition or some_other_condition will be true all the time, but this kind of code still looks scary to you (it does to me).

If you do not initialize s at all and none of conditions are true, the behaviour of your program is undefined. It may crash, it may not. You will never be able to check for the error condition later because s could be literally anything.

If you initialize s with NULL, you can now check for the error condition but your for loop still contains UB.

The safest way here would obviously be to include something like else { assert(0); } and explicitly check for the error condition, but if that's not necessary in your situation, you can initialize s to "" and the code will just do nothing if some_condition and some_other_condition are both false.


问:
Return value from a deployed smart contract, via a smart contract, to a smart contract
I am trying to return a value using a function of a deployed smart contract on the blockchain.

```<code>pragma solidity 0.6.2;

contract Caller {

   address cont;

   function changeAdd(address _change) public {
     cont = _change;
   }

   function caller (bytes memory test) public returns(bool, bytes memory) {
      bytes memory payload = abi.encodeWithSignature("callMe(bytes)", test);
      (bool success, bytes memory result)= address(cont).call(payload);
      return (success, (result));

   }

   function viewCont() public view returns(address) {
       return cont;
   }
}
</code>```

And the deployed test contract is this:

```<code>pragma solidity 0.6.2;

contract Store {

  uint counter;

  function callMe(bytes calldata test) external returns(bytes memory) {
     counter++;
     return abi.encode(test);
  }

  function viewCounter () public view returns(uint256) {
     return(counter);
  }

  function clearCounter() public  {
     counter = 0 ;
  }
}
</code>```

In this example, I am deploying contract "Store" on the blockchain where it is assigned a random address, which can be pointed at via the Caller.changeAdd function in order to use Caller.caller function. Thus, I am trying to send data in the form of bytes to the Store contract, which is supposed to send back the same data to the Caller contract. I am trying to isolate -only- the data that is originally sent, so I can use it to test interaction between smart contracts on the blockchain. I tried in the beginning to send an integer, but I couldn't find a way to do it. So I used bytes and it worked, but still the data I receive isn't the same that I send in the first place(e.g. I send 0x0 and I receive a big bytes number, which isn't the same as 0x0).

I could appreciate any help on how to receive and handle data between two different, unlinked smart contracts, thank you in advance.

答:
Do you try to use abi.decode function of Solidity.

In the below example, contract B calls setName of contract A, then decodes the result by using abi.decode function.

```<code>contract A {
    string public name;
    constructor(string memory tokenName) public {
        name = tokenName;
    }

    function setName(string memory newName) public returns ( string memory){
        name = newName;
        return newName;
    }
}

contract B  {
    event Log(string msg);
    string public myName;
    function call(address addr, string memory newName) public {
        bytes memory payload = abi.encodeWithSignature("setName(string)", newName);
        (bool success, bytes memory result)= addr.call(payload);

        // Decode data
        string memory name = abi.decode(result, (string));

        myName = name;
        emit Log(name);
    }
}
</code>```

Body:
I am trying to return a value using a function of a deployed smart contract on the blockchain.

pragma solidity 0.6.2;

contract Caller {

   address cont;

   function changeAdd(address _change) public {
     cont = _change;
   }

   function caller (bytes memory test) public returns(bool, bytes memory) {
      bytes memory payload = abi.encodeWithSignature("callMe(bytes)", test);
      (bool success, bytes memory result)= address(cont).call(payload);
      return (success, (result));

   }

   function viewCont() public view returns(address) {
       return cont;
   }
}

And the deployed test contract is this:

pragma solidity 0.6.2;

contract Store {

  uint counter;

  function callMe(bytes calldata test) external returns(bytes memory) {
     counter++;
     return abi.encode(test);
  }

  function viewCounter () public view returns(uint256) {
     return(counter);
  }

  function clearCounter() public  {
     counter = 0 ;
  }
}

In this example, I am deploying contract "Store" on the blockchain where it is assigned a random address, which can be pointed at via the Caller.changeAdd function in order to use Caller.caller function. Thus, I am trying to send data in the form of bytes to the Store contract, which is supposed to send back the same data to the Caller contract. I am trying to isolate -only- the data that is originally sent, so I can use it to test interaction between smart contracts on the blockchain. I tried in the beginning to send an integer, but I couldn't find a way to do it. So I used bytes and it worked, but still the data I receive isn't the same that I send in the first place(e.g. I send 0x0 and I receive a big bytes number, which isn't the same as 0x0).

I could appreciate any help on how to receive and handle data between two different, unlinked smart contracts, thank you in advance.

Body:
Do you try to use abi.decode function of Solidity.

In the below example, contract B calls setName of contract A, then decodes the result by using abi.decode function.

contract A {
    string public name;
    constructor(string memory tokenName) public {
        name = tokenName;
    }

    function setName(string memory newName) public returns ( string memory){
        name = newName;
        return newName;
    }
}

contract B  {
    event Log(string msg);
    string public myName;
    function call(address addr, string memory newName) public {
        bytes memory payload = abi.encodeWithSignature("setName(string)", newName);
        (bool success, bytes memory result)= addr.call(payload);

        // Decode data
        string memory name = abi.decode(result, (string));

        myName = name;
        emit Log(name);
    }
}


问:
Sequel Pro and MySQL connection failed
I just installed mysql on mac from Homebrew

```<code>brew install mysql

mysql -V

mysql  Ver 8.0.11 for osx10.13 on x86_64 (Homebrew)
</code>```

from terminal it works and I can login to mysql but from Sequel Pro it says

Unable to connect to host 127.0.0.1, or the request timed out.

Be sure that the address is correct and that you have the necessary
  privileges, or try increasing the connection timeout (currently 10
  seconds).

MySQL said: Authentication plugin 'caching_sha2_password' cannot be
  loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2):
  image not found

can't figure out what I am missing

答:
If anyone facing this issue and installed MySQL version > 8 through .dmg file; downloaded it from the official link. In that case please use this guideline. I am adding the same details below in case the link will not be available in the future.

This issue is because you're using the new Strong Password Encryption which is a new feature in MySQL 8, if you installed MySQL 8 using the .dmg file, you can go to System Preferences > MySQL and then click on Initialize Database type your password and select the second option Use Legacy Password Encryption.

Title: Sequel Pro and MySQL connection failed

Body:
I just installed mysql on mac from Homebrew

brew install mysql

mysql -V

mysql  Ver 8.0.11 for osx10.13 on x86_64 (Homebrew)

from terminal it works and I can login to mysql but from Sequel Pro it says

Unable to connect to host 127.0.0.1, or the request timed out.

Be sure that the address is correct and that you have the necessary
  privileges, or try increasing the connection timeout (currently 10
  seconds).

MySQL said: Authentication plugin 'caching_sha2_password' cannot be
  loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2):
  image not found

can't figure out what I am missing


答:
Came to the same conclusion. You should left_join the data frames.</p>

```<code>df1 %>% left_join(df2, by="distance") %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  filter(yearLag > my.median)

# A tibble: 4 x 5
# Groups:   distance [2]
   year  mort distance my.median yearLag
  <int> <dbl> <fct>        <dbl>   <dbl>
1     3    40 a               12      24
2     1     5 b                1       5
3     3    10 b                1       4
4     4   108 b                1      98
</code>```

Title: R dplyr::Filter dataframe by group and numeric vector?

Body:
Came to the same conclusion. You should left_join the data frames.

df1 %>% left_join(df2, by="distance") %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  filter(yearLag > my.median)

# A tibble: 4 x 5
# Groups:   distance [2]
   year  mort distance my.median yearLag
  <int> <dbl> <fct>        <dbl>   <dbl>
1     3    40 a               12      24
2     1     5 b                1       5
3     3    10 b                1       4
4     4   108 b                1      98


问:
How do you pass FormGroups and FormArrays into a recursive mechanism of deep nested components?
I'm building a micro app for editing JSON objects before saving them to my database.  The JSON object comes from another micro app I made for parsing SVG code and creating a data object shaped like the interfaces bellow.

```<code>export interface OvaadSvgStyleProperty{
    property: string;
    setting: string;
  }

  export interface OvaadGraphicAttribute{
    attribute: string;
    setting: string;
    bind? : string;
  }

  export interface OvaadGraphicObject{
    element: string;
    selfClosing: boolean;
    attributes: OvaadGraphicAttribute[];
    styles?: OvaadSvgStyleProperty[];
    subElements?: OvaadGraphicObject[];
  }

  export interface ViewBoxParameters{
    x: string;
    y: string;
    width: string;
    height: string;
  }

  export interface OvaadSvgDataObject extends TitleCore{
      graphicId: string;
      viewBox: ViewBoxParameters;
      coreAttributes: OvaadGraphicAttribute[];
      coreStyles: OvaadSvgStyleProperty[];
      elements: OvaadGraphicObject[];
  }
</code>```

If you pay attention to the OvaadGraphicObject interface you'll see the subElements property is of type OvaadGraphicObject[] which is to handle instances of <g> tags and other svg elements that can potentially nest things thousands of layers deep if that were needed for some reason.

I've learned through my struggles so far with Angular Forms that it likes for the form to be a singular monolithic thing so I decided to create a family of functions for generating the form and passing in the values from the JSON object and passing the completed FormGroup into my form with [formGroup]="myFormVar".

This provides the FormGroup shaped accordingly with all the values passed in as expected.  If I treat the data like any other data and pass it into @Input()s everything breaks down and goes to where it needs to go, but unfortunately it breaks apart the communication within the form.  You can view a  stackblitz demo here to see the entire mechanism so far but for the sake of this post I'll be focusing on the elements aspect of the form which will pretty much crack the riddle of how to handle everything else.

To start, the function I use for creating the element FormGroup looks like this

```<code>export function CreateGraphicElementForm(data?: OvaadGraphicObject): FormGroup{
    let elementForm: FormGroup = new FormGroup({
      element     : new FormControl((data ? data.element    : ''), Validators.required),
      selfClosing : new FormControl((data? data.selfClosing : false), Validators.required),
      attributes  : new FormArray([]),
      styles      : new FormArray([]),
      subElements : new FormArray([])
    });

    if(data && data.attributes.length > 0){
      data.attributes.forEach((a: OvaadGraphicAttribute)=>{
        let attrArray: FormArray = elementForm.get('attributes') as FormArray;
        attrArray.push(CreateAttributeForm(a));
      });
    }

    if(data && data.styles.length > 0){
      data.styles.forEach((a: OvaadSvgStyleProperty)=>{
        let styleArray: FormArray = elementForm.get('styles') as FormArray;
        styleArray.push(CreateStylePropertyForm(a));
      });
    }

    if(data && data.subElements){
      data.subElements.forEach((a:OvaadGraphicObject)=>{
        let subElementArray: FormArray = elementForm.get('subElements') as FormArray;
        subElementArray.push(CreateGraphicElementForm(a));
      });

    }

    return elementForm as FormGroup;
  }
</code>```

So within this FormGroup there's 2 FormControls and 3 FormArrays that need to be passed down into their respective components.  The way I'm handling this part is with what I'm calling and Element List Component that takes an array of these FormGroups and is responsible for adding or deleting them.  Then I have an ElementFormComponent which receives a FormGroup from the ElementListComponent.  Then of course the ElementListComponent gets it's data from the parent component where the form is created which I call the SvgObjectFormComponent.  Here's what the ElementListComponent and ElementFormComponent looks like.

ElementList.component.ts

```<code>export class ElementListComponent implements OnInit {

  @Input() ElementListData: FormArray;

  constructor() { }

  ngOnInit() {
  }

  addElement(): void{
    const newElement: FormGroup = CreateGraphicElementForm();
    let elementList: FormArray = <FormArray>this.ElementListData as FormArray;
    console.log(newElement);
    elementList.push(newElement);
  }

  deleteElement(item: number): void{
    let elementList:FormArray = this.ElementListData as FormArray;

    console.log(item);

    elementList.removeAt(item);
  }

}
</code>```

ElementList.component.html

```<code><section [formGroup]="ElementListData">

    <article *ngIf="!ElementListData">
        <p>loading</p>
    </article>

    <article *ngIf="ElementListData">

        <h5 *ngIf="ElementListData.controls.length === 0" class="articleText">no elements</h5>

        <section *ngIf="ElementListData.controls.length > 0">

            <article *ngFor="let item of ElementListData.controls; let i = index" class="list-grid">

                <p class="index-area articleText">{{i}}</p>

       <!-- I removed attempts at passing in data to avoid discussing things we already know are wrong-->
                <element-form-component class="component-area"></element-form-component>

                <article class="delete-area">
                    <button (click)="deleteElement(i)">delete</button>
                </article>

            </article>

        </section>

    </article>

    <article>
        <button (click)="addElement()">add</button>
    </article>

</section>

</code>```

ElementForm.component.ts

```<code>export class ElementFormComponent implements OnInit, ControlValueAccessor {

  @Input() ElementFormData: FormGroup;

  constructor() { }

  ngOnInit() {}

}
</code>```

ElementForm.component.html

```<code><section [formGroup]="ElementFormData">
    <article class="text-control-section">
        <label class="control-label">
            element:
            <input type="text" class="text-control" formControlName="element" />
        </label>

        <label class="control-label">
            self closing:
            <input type="text" class="text-control" formControlName="selfClosing" />
        </label>
    </article>

    <!-- again I eliminated failed attempts at passing objects into components to reduce confusion -->
    <article>
        <h3>Attributes</h3>
        <attribute-list-component></attribute-list-component>
    </article>

    <article>
        <h3>Styles</h3>
        <style-list-component></style-list-component>
    </article>

    <section>

        <h3>Sub Elements</h3>

        <p *ngIf="ElementFormData.controls.subElements.length === 0">no sub elements</p>

        <article *ngFor="let item of ElementFormData.controls.subElements; let i = index" class="list-grid">

            <p class="index-area">{{i}}</p>

           <!-- this is where the recursive behavior begins if the element has nested elements -->
            <element-form-component class="component-area"></element-form-component>

            <article class="delete-area">
                <button>delete element</button>
            </article>

        </article>

    </section>

</section>
</code>```

I've been trying everything from using [(ngModel)] and [FormControl] vs. formControlName vs. [formControlName] and tinkering with the ControlValueAccessor just to discover it's only meant for single FormControls.  On another question I asked which was based around the ControlValueAccessor someone made the suggestion that I should add this to my component providers

```<code>viewProviders: [
   { provide: ControlContainer, useExisting: FormGroupDirective }
</code>```

which eliminates the need for the ControlValueAccesssorallowing all the controls to be accessed, but that assumes I'm only using my component in one place in the form syncing to only one FormGroup when as you see from this example I need to figure out how to provide a recursive connection to the top of the component tree.  How can this type of behavior be achieved with Angular Forms?

My stackblitz contains all the components, functions and a data object for demo as well as my most recent attempts at getting this behavior to work which was through the ControlValueAcessor.  Someone please help me figure out how to accomplish this because Angular Forms is the one thing I haven't been able to get a grasp on the entire time I've been using the platform due to not knowing whatever it is I can't seem to find my way in front of.

答:
I came across this article which covers how to accomplish this behavior by using ChangeDetectionStrategy.push on our components.  We add it to our component like this

```<code>@Component({
    selector       : 'element-list-component',
    templateUrl    : 'element-list.component.html',
    StyleUrls      : ['element-list.component.css'],
    // add change detection here
    changeDetection: ChangeDetectionStrategy.push
})

export class ElementListComponent {

    @Input() ElementListData : FormGroup;

    //.......
}
</code>```

Then in our Component class we can use a regular @Input() to pass in the form object as we do with any other piece of data. In the parent component we need to pass in the object like this

```<code><section [formGroup]="FormDataVar">

    <element-list-component [ElementListData]="FormDataVar.controls.elements"></element-list-component

</section>
</code>```

From there we connect the FormControls to our inputs with formControlName="yourControl" and everything stays synced to the top of the tree :).

Body:
I'm building a micro app for editing JSON objects before saving them to my database.  The JSON object comes from another micro app I made for parsing SVG code and creating a data object shaped like the interfaces bellow.

export interface OvaadSvgStyleProperty{
    property: string;
    setting: string;
  }

  export interface OvaadGraphicAttribute{
    attribute: string;
    setting: string;
    bind? : string;
  }

  export interface OvaadGraphicObject{
    element: string;
    selfClosing: boolean;
    attributes: OvaadGraphicAttribute[];
    styles?: OvaadSvgStyleProperty[];
    subElements?: OvaadGraphicObject[];
  }

  export interface ViewBoxParameters{
    x: string;
    y: string;
    width: string;
    height: string;
  }

  export interface OvaadSvgDataObject extends TitleCore{
      graphicId: string;
      viewBox: ViewBoxParameters;
      coreAttributes: OvaadGraphicAttribute[];
      coreStyles: OvaadSvgStyleProperty[];
      elements: OvaadGraphicObject[];
  }

If you pay attention to the OvaadGraphicObject interface you'll see the subElements property is of type OvaadGraphicObject[] which is to handle instances of <g> tags and other svg elements that can potentially nest things thousands of layers deep if that were needed for some reason.

I've learned through my struggles so far with Angular Forms that it likes for the form to be a singular monolithic thing so I decided to create a family of functions for generating the form and passing in the values from the JSON object and passing the completed FormGroup into my form with [formGroup]="myFormVar".

This provides the FormGroup shaped accordingly with all the values passed in as expected.  If I treat the data like any other data and pass it into @Input()s everything breaks down and goes to where it needs to go, but unfortunately it breaks apart the communication within the form.  You can view a  stackblitz demo here to see the entire mechanism so far but for the sake of this post I'll be focusing on the elements aspect of the form which will pretty much crack the riddle of how to handle everything else.

To start, the function I use for creating the element FormGroup looks like this

export function CreateGraphicElementForm(data?: OvaadGraphicObject): FormGroup{
    let elementForm: FormGroup = new FormGroup({
      element     : new FormControl((data ? data.element    : ''), Validators.required),
      selfClosing : new FormControl((data? data.selfClosing : false), Validators.required),
      attributes  : new FormArray([]),
      styles      : new FormArray([]),
      subElements : new FormArray([])
    });

    if(data && data.attributes.length > 0){
      data.attributes.forEach((a: OvaadGraphicAttribute)=>{
        let attrArray: FormArray = elementForm.get('attributes') as FormArray;
        attrArray.push(CreateAttributeForm(a));
      });
    }

    if(data && data.styles.length > 0){
      data.styles.forEach((a: OvaadSvgStyleProperty)=>{
        let styleArray: FormArray = elementForm.get('styles') as FormArray;
        styleArray.push(CreateStylePropertyForm(a));
      });
    }

    if(data && data.subElements){
      data.subElements.forEach((a:OvaadGraphicObject)=>{
        let subElementArray: FormArray = elementForm.get('subElements') as FormArray;
        subElementArray.push(CreateGraphicElementForm(a));
      });

    }

    return elementForm as FormGroup;
  }

So within this FormGroup there's 2 FormControls and 3 FormArrays that need to be passed down into their respective components.  The way I'm handling this part is with what I'm calling and Element List Component that takes an array of these FormGroups and is responsible for adding or deleting them.  Then I have an ElementFormComponent which receives a FormGroup from the ElementListComponent.  Then of course the ElementListComponent gets it's data from the parent component where the form is created which I call the SvgObjectFormComponent.  Here's what the ElementListComponent and ElementFormComponent looks like.

ElementList.component.ts

export class ElementListComponent implements OnInit {

  @Input() ElementListData: FormArray;

  constructor() { }

  ngOnInit() {
  }

  addElement(): void{
    const newElement: FormGroup = CreateGraphicElementForm();
    let elementList: FormArray = <FormArray>this.ElementListData as FormArray;
    console.log(newElement);
    elementList.push(newElement);
  }

  deleteElement(item: number): void{
    let elementList:FormArray = this.ElementListData as FormArray;

    console.log(item);

    elementList.removeAt(item);
  }

}

ElementList.component.html

loading

no elements

 0">

{{i}}

                <element-form-component class="component-area"></element-form-component>

                    <button (click)="deleteElement(i)">delete</button>

        <button (click)="addElement()">add</button>

ElementForm.component.ts

export class ElementFormComponent implements OnInit, ControlValueAccessor {

  @Input() ElementFormData: FormGroup;

  constructor() { }

  ngOnInit() {}

}

ElementForm.component.html

            element:
            <input type="text" class="text-control" formControlName="element" />

            self closing:
            <input type="text" class="text-control" formControlName="selfClosing" />

Attributes

        <attribute-list-component></attribute-list-component>

Styles

Sub Elements

no sub elements

{{i}}

            <element-form-component class="component-area"></element-form-component>

                <button>delete element</button>

I've been trying everything from using [(ngModel)] and [FormControl] vs. formControlName vs. [formControlName] and tinkering with the ControlValueAccessor just to discover it's only meant for single FormControls.  On another question I asked which was based around the ControlValueAccessor someone made the suggestion that I should add this to my component providers

viewProviders: [
   { provide: ControlContainer, useExisting: FormGroupDirective }

which eliminates the need for the ControlValueAccesssorallowing all the controls to be accessed, but that assumes I'm only using my component in one place in the form syncing to only one FormGroup when as you see from this example I need to figure out how to provide a recursive connection to the top of the component tree.  How can this type of behavior be achieved with Angular Forms?

My stackblitz contains all the components, functions and a data object for demo as well as my most recent attempts at getting this behavior to work which was through the ControlValueAcessor.  Someone please help me figure out how to accomplish this because Angular Forms is the one thing I haven't been able to get a grasp on the entire time I've been using the platform due to not knowing whatever it is I can't seem to find my way in front of.

Body:
I came across this article which covers how to accomplish this behavior by using ChangeDetectionStrategy.push on our components.  We add it to our component like this

@Component({
    selector       : 'element-list-component',
    templateUrl    : 'element-list.component.html',
    StyleUrls      : ['element-list.component.css'],
    // add change detection here
    changeDetection: ChangeDetectionStrategy.push
})

export class ElementListComponent {

    @Input() ElementListData : FormGroup;

    //.......
}

Then in our Component class we can use a regular @Input() to pass in the form object as we do with any other piece of data. In the parent component we need to pass in the object like this

<section [formGroup]="FormDataVar">

    <element-list-component [ElementListData]="FormDataVar.controls.elements"></element-list-component

</section>

From there we connect the FormControls to our inputs with formControlName="yourControl" and everything stays synced to the top of the tree :).


问:
Allow users to use custom domain to my cloudfront app
I have a cloud front app with domain xyz123.cloudfront.net.
This CloudFront is then mapped to domain sub1.mydomain.com. For this, I followed these steps.

Added SSL through AWS CloudFront pannel to *.mydomain.com

Added A Alias record in Route 53 to xyz123.cloudfront.net

This makes sub1.mydomain.com work perfectly over SSL.

Now, I want to allow my users to use their own domain (eg sub1.userdomain.com) to access the app.
This is similar to what UptimeRobot allows in its public status pages.

What I tried, but not working

Added CNAME to sub1.userdomain.com pointing to xyz123.cloudfront.net, I get SSL Error

Added CNAME to sub1.userdomain.com pointing to sub1.mydomain.com, I get SSL Error

Added CNAME to sub1.userdomain.com pointing to xyz123.s3-website.ap-south-1.amazonaws.com (S3 Static Hosting URL)

Question

How does UptimeRobot (or GitHub Pages) allow users to add a custom domain to their status page over SSL

What is the prerequisite to make this happen?

答:
From https://github.blog/2018-05-01-github-pages-custom-domains-https/:

We have partnered with the certificate authority Let’s Encrypt on
      this project. As supporters of Let’s Encrypt’s mission to make the
      web more secure for everyone, we’ve officially become Silver-level
      sponsors of the initiative.

Github pages create a single certificate, from Let's Encrypt, for both your custom userdomain.com and YOURNAME.github.io. This is possible with a SAN certificate (Subject Alternative Name, https://support.dnsimple.com/articles/what-is-ssl-san/).

You can't associate more than one SSL certificate to a CloudFront distribution but ACM (AWS Certificate Manager) supports up to 10 subject alternative names. To mimic Github Pages you have to know the user domains beforehand or create a new certificate each time you add a new domain to replace the old one.