问:
How to pass params from one screen to another via reactnavigation v5
I have an issue: thre is a list of users, and I want to add appointment to any user, so on user screen a PlusButton sending user on the add appointment screen (the PlusButton rendered from headerRight of the user screen). BUT I dont know how to pass to AddAppointmentScreen users id, because link to screen not via button, its via react-navigation v5.

here is a link to my project on github

App.js

```<code>const HeaderRight = ({ navigation, target }) => {
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}

<Stack.Screen
                name='Patient'
                component={PatientScreen}
                options={{
                    title: 'Карта пациента',
                    headerTintColor: '#2A86FF',
                    headerTitleAlign: 'center',
                    headerTitleStyle: {
                        fontWeight: 'bold',
                        fontSize: 20,
                    },
                    headerBackTitleVisible: false,
                    headerRight: () => <HeaderRight navigation={navigation} target={'AddAppointment'} />,
                }}
/>
</code>```

AddAppointmentScreen.js

```<code>import React, { useState } from 'react'
import { Keyboard } from 'react-native'
import { Container, Content, Form, Item, Input, Label, Icon, Text, Button } from 'native-base'
import DateTimePicker from '@react-native-community/datetimepicker'
import styled from 'styled-components/native'

import { appointmentsApi } from '../utils/api'

const AddAppointmentScreen = ({ route, navigation }) => {
    const [values, setValues] = useState({ patientId: route.params?.patientId._id ?? 'defaultValue' })
    const [date, setDate] = useState(new Date())
    const [mode, setMode] = useState('date')
    const [show, setShow] = useState(false)

    console.log(values.patientId)
    //I need to get patientId in this screen to create appointment to THIS user with its ID

    const setFieldValue = (name, value) => {
        setValues({
            ...values,
            [name]: value,
        })
    }

    const handleChange = (name, e) => {
        const text = e.nativeEvent.text
        setFieldValue(name, text)
    }

    const submitHandler = () => {
        appointmentsApi
            .add(values)
            .then(() => {
                navigation.navigate('Patient')
            })
            .catch((e) => {
                alert(e)
            })
        /* alert(JSON.stringify(values)) */
    }

    const formatDate = (date) => {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear()

        if (month.length < 2) month = '0' + month
        if (day.length < 2) day = '0' + day

        return [year, month, day].join('-')
    }

    const onChange = (event, selectedDate) => {
        Keyboard.dismiss()
        const currentDate = selectedDate || date
        const date = formatDate(currentDate)
        const time = currentDate.toTimeString().split(' ')[0].slice(0, 5)
        setShow(Platform.OS === 'ios')
        setDate(currentDate)
        setValues({
            ...values,
            ['date']: date,
            ['time']: time,
        })
    }

    const showMode = (currentMode) => {
        show ? setShow(false) : setShow(true)
        setMode(currentMode)
    }

    const showDatepicker = () => {
        Keyboard.dismiss()
        showMode('datetime')
    }

    return (
        <Container>
            <Content style={{ paddingLeft: 20, paddingRight: 20 }}>
                <Form>
                    <Item picker style={{ borderWidth: 0 }} /* floatingLabel */>
                        <Input
                            onChange={handleChange.bind(this, 'dentNumber')}
                            value={values.dentNumber}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Номер зуба'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'diagnosis')}
                            value={values.diagnosis}
                            clearButtonMode='while-editing'
                            placeholder='* Диагноз'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'description')}
                            value={values.description}
                            multiline
                            clearButtonMode='while-editing'
                            placeholder='Подробное описание или заметка'
                            style={{ paddingTop: 15, paddingBottom: 15 }}
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'price')}
                            value={values.price}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Цена'
                        />
                    </Item>

                    <ButtonRN onPress={showDatepicker}>
                        <Text style={{ fontSize: 18, fontWeight: '400' }}>
                            Дата: {formatDate(date)}, время: {date.toTimeString().split(' ')[0].slice(0, 5)}
                        </Text>
                    </ButtonRN>

                    {show && (
                        <DateTimePicker
                            timeZoneOffsetInSeconds={21600}
                            minimumDate={new Date()}
                            value={date}
                            mode={mode}
                            is24Hour={true}
                            display='default'
                            locale='ru-RU'
                            minuteInterval={10}
                            onChange={onChange}
                        />
                    )}

                    <ButtonView>
                        <Button
                            onPress={submitHandler}
                            rounded
                            block
                            iconLeft
                            style={{ backgroundColor: '#84D269' }}
                        >
                            <Icon type='Entypo' name='plus' style={{ color: '#fff' }} />
                            <Text style={{ color: '#fff' }}>Добавить прием</Text>
                        </Button>
                    </ButtonView>
                    <Label style={{ marginTop: 10, fontSize: 16 }}>
                        Поля помеченные звездочкой <TomatoText>*</TomatoText> обязательны для заполнения
                    </Label>
                </Form>
            </Content>
        </Container>
    )
}

const ButtonRN = styled.TouchableOpacity({
    paddingTop: 15,
    paddingLeft: 5,
})

const ButtonView = styled.View({
    marginTop: 15,
})

const TomatoText = styled.Text({
    color: 'tomato',
})

export default AddAppointmentScreen
</code>```

答:
I have not gone through your code but I can tell you how can you pass params to next screen as per your heading.

```<code>  toNavigate = (user) => {

    this.setState({ isLoading: false },
        () => { this.props.navigation.push('Main', { userData: user }) })
//I am sending user into userData to my Main screen
}
</code>```

And I am receive it like

```<code>render(){
 user = this.props.route.params.userData;
 }
</code>```

If any issue let me know.

Hope it helps!!!

Body:
I have an issue: thre is a list of users, and I want to add appointment to any user, so on user screen a PlusButton sending user on the add appointment screen (the PlusButton rendered from headerRight of the user screen). BUT I dont know how to pass to AddAppointmentScreen users id, because link to screen not via button, its via react-navigation v5.

here is a link to my project on github

App.js

const HeaderRight = ({ navigation, target }) => {
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}

<Stack.Screen
                name='Patient'
                component={PatientScreen}
                options={{
                    title: 'Карта пациента',
                    headerTintColor: '#2A86FF',
                    headerTitleAlign: 'center',
                    headerTitleStyle: {
                        fontWeight: 'bold',
                        fontSize: 20,
                    },
                    headerBackTitleVisible: false,
                    headerRight: () => <HeaderRight navigation={navigation} target={'AddAppointment'} />,
                }}
/>

AddAppointmentScreen.js

import React, { useState } from 'react'
import { Keyboard } from 'react-native'
import { Container, Content, Form, Item, Input, Label, Icon, Text, Button } from 'native-base'
import DateTimePicker from '@react-native-community/datetimepicker'
import styled from 'styled-components/native'

import { appointmentsApi } from '../utils/api'

const AddAppointmentScreen = ({ route, navigation }) => {
    const [values, setValues] = useState({ patientId: route.params?.patientId._id ?? 'defaultValue' })
    const [date, setDate] = useState(new Date())
    const [mode, setMode] = useState('date')
    const [show, setShow] = useState(false)

    console.log(values.patientId)
    //I need to get patientId in this screen to create appointment to THIS user with its ID

    const setFieldValue = (name, value) => {
        setValues({
            ...values,
            [name]: value,
        })
    }

    const handleChange = (name, e) => {
        const text = e.nativeEvent.text
        setFieldValue(name, text)
    }

    const submitHandler = () => {
        appointmentsApi
            .add(values)
            .then(() => {
                navigation.navigate('Patient')
            })
            .catch((e) => {
                alert(e)
            })
        /* alert(JSON.stringify(values)) */
    }

    const formatDate = (date) => {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear()

        if (month.length < 2) month = '0' + month
        if (day.length < 2) day = '0' + day

        return [year, month, day].join('-')
    }

    const onChange = (event, selectedDate) => {
        Keyboard.dismiss()
        const currentDate = selectedDate || date
        const date = formatDate(currentDate)
        const time = currentDate.toTimeString().split(' ')[0].slice(0, 5)
        setShow(Platform.OS === 'ios')
        setDate(currentDate)
        setValues({
            ...values,
            ['date']: date,
            ['time']: time,
        })
    }

    const showMode = (currentMode) => {
        show ? setShow(false) : setShow(true)
        setMode(currentMode)
    }

    const showDatepicker = () => {
        Keyboard.dismiss()
        showMode('datetime')
    }

    return (
        <Container>
            <Content style={{ paddingLeft: 20, paddingRight: 20 }}>
                <Form>
                    <Item picker style={{ borderWidth: 0 }} /* floatingLabel */>
                        <Input
                            onChange={handleChange.bind(this, 'dentNumber')}
                            value={values.dentNumber}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Номер зуба'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'diagnosis')}
                            value={values.diagnosis}
                            clearButtonMode='while-editing'
                            placeholder='* Диагноз'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'description')}
                            value={values.description}
                            multiline
                            clearButtonMode='while-editing'
                            placeholder='Подробное описание или заметка'
                            style={{ paddingTop: 15, paddingBottom: 15 }}
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'price')}
                            value={values.price}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Цена'
                        />
                    </Item>

                    <ButtonRN onPress={showDatepicker}>
                        <Text style={{ fontSize: 18, fontWeight: '400' }}>
                            Дата: {formatDate(date)}, время: {date.toTimeString().split(' ')[0].slice(0, 5)}
                        </Text>
                    </ButtonRN>

                    {show && (
                        <DateTimePicker
                            timeZoneOffsetInSeconds={21600}
                            minimumDate={new Date()}
                            value={date}
                            mode={mode}
                            is24Hour={true}
                            display='default'
                            locale='ru-RU'
                            minuteInterval={10}
                            onChange={onChange}
                        />
                    )}

                    <ButtonView>
                        <Button
                            onPress={submitHandler}
                            rounded
                            block
                            iconLeft
                            style={{ backgroundColor: '#84D269' }}
                        >
                            <Icon type='Entypo' name='plus' style={{ color: '#fff' }} />
                            <Text style={{ color: '#fff' }}>Добавить прием</Text>
                        </Button>
                    </ButtonView>

                        Поля помеченные звездочкой <TomatoText>*</TomatoText> обязательны для заполнения

                </Form>
            </Content>
        </Container>
    )
}

const ButtonRN = styled.TouchableOpacity({
    paddingTop: 15,
    paddingLeft: 5,
})

const ButtonView = styled.View({
    marginTop: 15,
})

const TomatoText = styled.Text({
    color: 'tomato',
})

export default AddAppointmentScreen

Body:
I have not gone through your code but I can tell you how can you pass params to next screen as per your heading.

  toNavigate = (user) => {

    this.setState({ isLoading: false },
        () => { this.props.navigation.push('Main', { userData: user }) })
//I am sending user into userData to my Main screen
}

And I am receive it like

render(){
 user = this.props.route.params.userData;
 }

If any issue let me know.

Hope it helps!!!


来源: stackexchange

问:
could strange UINavigationController nav bar behavior be due to memory leaks?
I'm getting strange navigation bar behaviour, for example when I hit back button the screen displayed is the previous screen, however the Navigation Bar items do change.  So I'm left with screen A, but with nav bar buttons for screen B.

Could this be due to memory leaks?  I do note with my app still:

This behavior seems to happen:

immediately if I trigger memory
warning via the simulator menu, or

on a device after it has been on
for a while [without being killed
and then restarted as an app].

I do have some memory leaks I'm
trying to clean up (i.e. Profiler
highlights items in "leaked blocks"
section)

Any tips on fault finding root cause of why pushing a back button would end up in a weird state? e.g. screen on previous parent view, but nav bar items don't change...

UPDATE - I have finally removed the memory leaks in my app, however I note the nav bar issue still remains.  I guess this doesn't confirm the answer to my question is NO in general, but in my specific case it wasn't the memork leak...

答:
From Apple:

The navigation controller updates the
  navigation bar each time the top view
  controller changes. Thus, these
  changes occur each time a view
  controller is pushed onto the stack or
  popped from it. When you animate a
  push or pop operation, the navigation
  controller similarly animates the
  change in navigation bar content.

Based on this, I would start by looking for a bug or misconfiguration in your view definitions. Check for any InterfaceBuilder warnings if you defined your views via NIBs. Make sure your view hierarchies are correct in both UIViewControllers. Also check for possible bugs in your view life-cycle methods: viewWillAppear:, viewWillDisappear:, etc,.

Actually, it would be nice if you could post some screenshots and/or code. Thanks!

ContentLicense: CC BY-SA 3.0


问:
How to generate an array of objects, having an array with keys and having another array with objects?
The first array is the one containing the keys, the second is the array of objects.

Then it should generate an array of the objects that contain those keys.
Then it should generate an array of the objects that contain those keys, that is, the keys of the first array.

I'm trying

```<code>this.fields.filter((index) => {
  const newValue = this.data.filter((data, indexData)=>{
     index = indexData;
   });
 });
</code>```

this.fields contains the keys and this.data contains the array of objects in which I want to extract them according to the key.

答:
Using a Set() and .has to check if one of the keys is a a key in fields.</p>

```<code>const fields = new Set(this.fields)
const newValue = this.data.filter(data =>
     Object.keys(data).some(key=>fields.has(key)))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The first array is the one containing the keys, the second is the array of objects.

Then it should generate an array of the objects that contain those keys.
Then it should generate an array of the objects that contain those keys, that is, the keys of the first array.

I'm trying

this.fields.filter((index) => {
  const newValue = this.data.filter((data, indexData)=>{
     index = indexData;
   });
 });

this.fields contains the keys and this.data contains the array of objects in which I want to extract them according to the key.

Body:
Using a Set() and .has to check if one of the keys is a a key in fields.

const fields = new Set(this.fields)
const newValue = this.data.filter(data =>
     Object.keys(data).some(key=>fields.has(key)))


问:
how to use many condition in aggregate mongo db
I have a transactions collection as:

```<code>{
  _id:ObjecId("5286f7c1f873cc89108b6898"),
  type:"sms",
  amount:NumberInt(1000),
  input_vendor:"a"
},
{
  _id:ObjecId("5286f7c1f873cc89108b6898"),
  type:"sms",
  amount:NumberInt(2000),
  input_vendor:"a"
},
{
  _id:ObjecId("5286f7c1f873cc89108b6898"),
  type:"sms",
  amount:NumberInt(5000),
  input_vendor:"b"
}
</code>```

I want to use aggregate in mongo to count total sms, and total amount each sms type, please help me.
Result as:

```<code>total_sms_a:2
amount_sms_a:3000
total_sms_b:1,
amount_sms_b:500
</code>```

答:
You have to group by "$input_vendor", sum +1 to count total sms and sum "$amount" to get total amount. This will get you count and sum for each input_vendor.

```<code>db.transactions.aggregate([
    {
        "$group": {
            "_id": "$input_vendor",
            "total_sms": { "$sum": 1 },
            "amount_sms": { "$sum": "$amount" }
        }
    }
])
</code>```

If you have documents with other "$type" values, you also have to add a match stage before this group, like this:

```<code>db.transactions.aggregate([
    {
        "$match": {
            "type": "sms"
        }
    },
    {
        "$group": {
            "_id": "$input_vendor",
            "total_sms": { "$sum": 1 },
            "amount_sms": { "$sum": "$amount" }
        }
    }
])
</code>```

Body:
I have a transactions collection as:

{
  _id:ObjecId("5286f7c1f873cc89108b6898"),
  type:"sms",
  amount:NumberInt(1000),
  input_vendor:"a"
},
{
  _id:ObjecId("5286f7c1f873cc89108b6898"),
  type:"sms",
  amount:NumberInt(2000),
  input_vendor:"a"
},
{
  _id:ObjecId("5286f7c1f873cc89108b6898"),
  type:"sms",
  amount:NumberInt(5000),
  input_vendor:"b"
}

I want to use aggregate in mongo to count total sms, and total amount each sms type, please help me.
Result as:

total_sms_a:2
amount_sms_a:3000
total_sms_b:1,
amount_sms_b:500

Body:
You have to group by "$input_vendor", sum +1 to count total sms and sum "$amount" to get total amount. This will get you count and sum for each input_vendor.

db.transactions.aggregate([
    {
        "$group": {
            "_id": "$input_vendor",
            "total_sms": { "$sum": 1 },
            "amount_sms": { "$sum": "$amount" }
        }
    }
])

If you have documents with other "$type" values, you also have to add a match stage before this group, like this:

db.transactions.aggregate([
    {
        "$match": {
            "type": "sms"
        }
    },
    {
        "$group": {
            "_id": "$input_vendor",
            "total_sms": { "$sum": 1 },
            "amount_sms": { "$sum": "$amount" }
        }
    }
])


问:
Function returns wrong value for certain arrays
I have recently started coding and was working on a function that returns the 3 largest numbers in a given array. The function works for most arrays, but not for others. Below is the code:

```<code>def findThreeLargestNumbers(array):
  list = []
  if len(set(array)) != 1:
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
    list.reverse()
    return list
  else:
    for element in array:
      newlist = [element, element, element]
      return newlist
</code>```

For instance, when I input the array [1,2,3,4,5] the function returns [3,4,5]. However, when I input [55, 43, 11, 3, -3, 10], the function returns 4 values: [10, 11, 43, 55].

Why is this?

Thank you so much!

答:
Add a break in the end of the for </p>

```<code>  def findThreeLargestNumbers(array):
      list = []
      if len(set(array)) != 1:
        while len(list) <= 2:
          for element in array:
            if element == max(array):
              list.append(element)
              array.remove(element)
              break
        list.reverse()
        return list
      else:
        for element in array:
          newlist = [element, element, element]
          return newlist
</code>```

Body:
I have recently started coding and was working on a function that returns the 3 largest numbers in a given array. The function works for most arrays, but not for others. Below is the code:

def findThreeLargestNumbers(array):
  list = []
  if len(set(array)) != 1:
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
    list.reverse()
    return list
  else:
    for element in array:
      newlist = [element, element, element]
      return newlist

For instance, when I input the array [1,2,3,4,5] the function returns [3,4,5]. However, when I input [55, 43, 11, 3, -3, 10], the function returns 4 values: [10, 11, 43, 55].

Why is this?

Thank you so much!

Body:
Add a break in the end of the for

  def findThreeLargestNumbers(array):
      list = []
      if len(set(array)) != 1:
        while len(list) <= 2:
          for element in array:
            if element == max(array):
              list.append(element)
              array.remove(element)
              break
        list.reverse()
        return list
      else:
        for element in array:
          newlist = [element, element, element]
          return newlist


问:
why my github account s connecting to the command line?
for this wonderful community that inspired me to start my learning journey.

My name is Lina and I just started teaching myself about web-development few days ago.
I am learning about Git and Github for few days.
My basic understanding of Git and Github is that Git is a tool that we use to track the history of our folder or repository at the local machine where Github is a website where we can share our code with other collaborators(remotely).

Here what I did step by step until I stick with the issue:

I created a Github account.

I checked the command line(terminator)if I have git install in my laptop (I am using Mack laptop).
Open the command Line: then type (git --version) and here what I got back in the command line

```<code>git version 2.26.2
[(base) lealas-MacBook-Pro:~ username$ git --version
git version 2.26.2
(base) lealas-MacBook-Pro:~ username$ git --version
git version 2.26.2
(base) lealas-MacBook-Pro:~ username$
</code>```

I downloaded visual studio code (VSC) on my laptop; then in my local machine created a folder called git. I opened that folder in VSC.
When I try to connect VSC with Github through the following step:

open my folder in my local machine (this folder called git).

press view on vsc and click on terminal; then write git clone following by the SHH from github:

```<code>The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
(base) lealas-MacBook-Pro:git username$ git clone git@github.com:lina-aleean/demo-repo.git
Cloning into 'demo-repo'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
(base) lealas-MacBook-Pro:git username$
</code>```

Please can someone help? I have been trying to solve this issue for more than 7 hours; but I am new in this world of technology and teaching myself from the scratch.

I really appreciate your help.
I am watching this video to learn git and GitHub

https://www.youtube.com/watch?v=RGOj5yH7evk

答:
It looks like you are trying to clone a repo over SSH without having SSH keys. If you want to add SSH keys, you can try to follow the instructions here.

Note that depending on your OS, how you generate and use SSH keys will vary.

Alternatively, if you do not mind typing username and password when pushing, you can use HTTP instead:

```<code>git clone https://github.com/lina-aleean/demo-repo.git

</code>```

Body:
for this wonderful community that inspired me to start my learning journey.

My name is Lina and I just started teaching myself about web-development few days ago.
I am learning about Git and Github for few days.
My basic understanding of Git and Github is that Git is a tool that we use to track the history of our folder or repository at the local machine where Github is a website where we can share our code with other collaborators(remotely).

Here what I did step by step until I stick with the issue:

I created a Github account.

I checked the command line(terminator)if I have git install in my laptop (I am using Mack laptop).
Open the command Line: then type (git --version) and here what I got back in the command line

git version 2.26.2
[(base) lealas-MacBook-Pro:~ username$ git --version
git version 2.26.2
(base) lealas-MacBook-Pro:~ username$ git --version
git version 2.26.2
(base) lealas-MacBook-Pro:~ username$

I downloaded visual studio code (VSC) on my laptop; then in my local machine created a folder called git. I opened that folder in VSC.
When I try to connect VSC with Github through the following step:

open my folder in my local machine (this folder called git).

press view on vsc and click on terminal; then write git clone following by the SHH from github:

The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
(base) lealas-MacBook-Pro:git username$ git clone git@github.com:lina-aleean/demo-repo.git
Cloning into 'demo-repo'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
(base) lealas-MacBook-Pro:git username$

Please can someone help? I have been trying to solve this issue for more than 7 hours; but I am new in this world of technology and teaching myself from the scratch.

I really appreciate your help.
I am watching this video to learn git and GitHub

https://www.youtube.com/watch?v=RGOj5yH7evk

Body:
It looks like you are trying to clone a repo over SSH without having SSH keys. If you want to add SSH keys, you can try to follow the instructions here.

Note that depending on your OS, how you generate and use SSH keys will vary.

Alternatively, if you do not mind typing username and password when pushing, you can use HTTP instead:

git clone https://github.com/lina-aleean/demo-repo.git


问:
R: calculate variance for data$V1 for each different value in data$V2
I have data frame looking like this

```<code>V1   V2
..   1
..   2
..   1
..   3
</code>```

etc.

For each distinct V2 value i would like to calculate variance of data in V1. I have just started my adventure with R, any hints how to do this? for my specific case i guess i can do manually something like

```<code> var1 = var(data[data$V2==1, "V1"])
 var2 = ...
</code>```

etc because I know all possible V2 values ( there are not many ), however I am curious what would be more generic solutions. Any ideas?

答:
Using dplyr you can do

```<code>library(dplyr)
data %>%
  group_by(V2) %>%
  summarize(var = var(V1))
</code>```

Here we group by the unique values of V2 and find the variance of V1 for each group.

Body:
I have data frame looking like this

V1   V2
..   1
..   2
..   1
..   3

etc.

For each distinct V2 value i would like to calculate variance of data in V1. I have just started my adventure with R, any hints how to do this? for my specific case i guess i can do manually something like

 var1 = var(data[data$V2==1, "V1"])
 var2 = ...

etc because I know all possible V2 values ( there are not many ), however I am curious what would be more generic solutions. Any ideas?

Body:
Using dplyr you can do

library(dplyr)
data %>%
  group_by(V2) %>%
  summarize(var = var(V1))

Here we group by the unique values of V2 and find the variance of V1 for each group.


问:
NavigationActions.reset is not a function?
I created a project has a Welcome screen navigate to MainActivity screen. I want that when the user clicks the back button it will close the app in MainActivity not back to Welcome screen.  I use the library react-navigation, so I looked for some solution from Github.

When I use the code from https://github.com/react-navigation/react-navigation/issues/295. I get the error:

```<code>NavigationActions.reset is not a function
</code>```

I console.log(NavigationActions);

There is no reset obviously.  But why can everybody else use the code?

I can't figure it out. Any help would be appreciated. Thanks in advance.

Here is my Welcome.js:

```<code>import React, { Component } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import { ColorSetting } from './common/ColorSetting';
import { fetchMainMovieList } from '../actions';

class Welcome extends Component {
  static navigationOptions = {
    header: null,
  };

  componentDidMount() {
    // call main page data first
    this.props.fetchMainMovieList();

    this.timer = setTimeout(() => {
      this.navigateToMainActivity();
    }, 3000);
  }
  componentWillUnmount() {
    // if this.timer existed，then use clearTimeout to remove it.
    this.timer && clearTimeout(this.timer);
  }

  navigateToMainActivity() {
    console.log(NavigationActions);
    const resetAction = NavigationActions.reset({
      index: 1,
      actions: [
        NavigationActions.navigate({ routeName: 'MainActivity' })
      ]
    });

    this.props.navigation.dispatch(resetAction);
  }

  render() {
    return (
      <View>
        <Text>Three !</Text>
      </View>
    );
  }
}

export default connect(null, { fetchMainMovieList })(Welcome);
</code>```

答:
```<code>navigateToMainActivity(){
this.props.navigation.dispatch(StackActions.reset({
  index:0,
  actions:[
    NavigationActions.navigate({routeName:'MainActivity'})
  ]
   })
  );
 }
</code>```

Body:
I created a project has a Welcome screen navigate to MainActivity screen. I want that when the user clicks the back button it will close the app in MainActivity not back to Welcome screen.  I use the library react-navigation, so I looked for some solution from Github.

When I use the code from https://github.com/react-navigation/react-navigation/issues/295. I get the error:

NavigationActions.reset is not a function

I console.log(NavigationActions);

There is no reset obviously.  But why can everybody else use the code?

I can't figure it out. Any help would be appreciated. Thanks in advance.

Here is my Welcome.js:

import React, { Component } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import { ColorSetting } from './common/ColorSetting';
import { fetchMainMovieList } from '../actions';

class Welcome extends Component {
  static navigationOptions = {
    header: null,
  };

  componentDidMount() {
    // call main page data first
    this.props.fetchMainMovieList();

    this.timer = setTimeout(() => {
      this.navigateToMainActivity();
    }, 3000);
  }
  componentWillUnmount() {
    // if this.timer existed，then use clearTimeout to remove it.
    this.timer && clearTimeout(this.timer);
  }

  navigateToMainActivity() {
    console.log(NavigationActions);
    const resetAction = NavigationActions.reset({
      index: 1,
      actions: [
        NavigationActions.navigate({ routeName: 'MainActivity' })
      ]
    });

    this.props.navigation.dispatch(resetAction);
  }

  render() {
    return (
      <View>
        <Text>Three !</Text>
      </View>
    );
  }
}

export default connect(null, { fetchMainMovieList })(Welcome);


问:
DACPAC pre-pre script avilale?
I am facing an issue while publishing DACPAC. (SQL 2012)
I have table in production that is having null,not null values column.
I need to make this column not nullable and drop another column.
Since that may not be using in the application.

I tried pre-deployment script to update null column with values, alter column and delete column, but getting error-
"Rows were detected. The schema update is terminating because data loss might occur."

Since this is a sensitive production, I don't want to uncheck the publish option 'Block incremental deployment
if data loss might occur'.

Please let me know if anyone have any idea?

答:
Let us first understand how DACPACs are deployed, These are the order of tasks

1.Build a empty DB using the schema from *.dacpack file, call it "vNextDB"

2.Compare the production DB to vNextDB, and generate a script that will deploy changes, let us call it deploy.sql (you can actually write this to a file and inspect it manually, look for documentation on "SqlPackage.exe")

3.Run Pre-Deployment Script

4.Run deploy.sql from step (2)

5.Run Post-Deployment Script

Looking at the sequence above, you probably already figured the issue. if not, look at when the deploy.sql script is generated, it is done before the pre-deplyment script is executed, so obviously it does see the NULL values and generates script that backs off from deployment.

You can see 'how' it backs off if you make sqlproject.exe write the deploy.sql to disk and open it in a text editor (i can't say how it does the backing off because each version of sqlpackage.exe does it differently. they keep improving it).

Here are couple of options

A) Split your deployment into two, First deploymentwill have no schema change, it just runs "UPDATE MyTable SET theColumn = '' WHERE theColumn IS NULL" in post/pre deployment step,  and the second deployment will have the actual changes

B) Take a step back and think comprehensively about how you are going to handle versioning of your DB schema, you should have a versioning strategy, you should think of backward compatibility and such stuff. (i.e You can introduce new column that is NOT NULL with default values and the DB clients can start using that column, while a old client that cant be updated will still be supported because you are not removing the old column right away)

Even if you choose option A to work around the current issue, long term you should establish a versioning startegy. Every self respecting data store has a versioning strategy :-), you should give one to your DB.

Title: DACPAC pre-pre script avilale?


问:
Passing Active Profile through command line arguments for main
I am trying to call  Spring boot main application from my junit test case as below and setting profile as an argument as below.

```<code>MyApplication.main(new String[] {"-Dspring.profiles.active=local"});
</code>```

And I have @Value configuration which reads from yml file.

yml

```<code>spring:
  profiles: local

subdivisions: test
</code>```

java

```<code>@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class);
  }
}
</code>```

Test case

```<code>@RunWith(SpringJUnit4ClassRunner.class)
public class MyApplicationTest {

  @Test
  public void testMainApplication() {

    MyApplication.main(new String[] {"-Dspring.profiles.active=local"});

  }
}
</code>```

When I ran my test case, I am getting this error  Could not resolve placeholder 'subdivisions' in value "${subdivisions}".

I am guessing the active profile is not set which is causing this error.

I tried below option to pass the active profile for Spring boot main application

```<code>MyApplication.main(new String[] {"spring.profiles.active=local"});
</code>```

Thanks in advance. Any help on this is appreciated..

答:
You can see which spring profile is set from the startup logs.
Also, if you have a test class why not just use @ActiveProfiles("local")
Also use @SpringBootTest to startup the spring boot test rather than calling main class directly</p>

Body:
I am trying to call  Spring boot main application from my junit test case as below and setting profile as an argument as below.

MyApplication.main(new String[] {"-Dspring.profiles.active=local"});

And I have @Value configuration which reads from yml file.

yml

spring:
  profiles: local

subdivisions: test

java

@SpringBootApplication
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class);
  }
}

Test case

@RunWith(SpringJUnit4ClassRunner.class)
public class MyApplicationTest {

  @Test
  public void testMainApplication() {

    MyApplication.main(new String[] {"-Dspring.profiles.active=local"});

  }
}

When I ran my test case, I am getting this error  Could not resolve placeholder 'subdivisions' in value "${subdivisions}".

I am guessing the active profile is not set which is causing this error.

I tried below option to pass the active profile for Spring boot main application

MyApplication.main(new String[] {"spring.profiles.active=local"});

Thanks in advance. Any help on this is appreciated..


问:
Deserialize a binary tree breadth-first in Functional Programming
I had an imperative program which deserializes to a Binary Tree from an array. Its a BFS algorithm. I was wondering how to do this in Scala with functional programming concepts.

```<code>class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
  val value: Int = _value
  val left: TreeNode = _left
  val right: TreeNode = _right
}
def createTree(list: Array[Int]): TreeNode = ???
</code>```

For reference this is the imperative version in Javascript. The algorithm is described here. https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-

```<code>class TreeNode {
  constructor(val){
    this.val = val;
    this.left = this.right = null;
  }
}

function makeTree(arr){
  let root = new TreeNode(arr[0]);
  let q = [root];

  let index = 1;
  while(q.length){
    let node = q.splice(0,1)[0];
    if(arr[index] != null){
      node.left = new TreeNode(arr[index]);
      q.push(node.left);
    }
    index++;

    if(arr[index] != null){
      node.right = new TreeNode(arr[index]);
      q.push(node.right);
    }
    index++;
  }
  return root;
}
</code>```

答:
As has been noted, Scala avoids null whenever possible, preferring Option to indicate the absence of a value.

Mutable variables are also shunned, which makes it much easier to construct a B-tree in a depth-first manner rather than breadth-first.

So all you really need is an easy-to-use breadth-first-serialization --to--> depth-first-serialization translator.

I did it in two steps.

```<code>//from Breadth-First-Serialization to full tree representation
def BFS2full[A](bfs:IndexedSeq[Option[A]]) :List[List[Option[A]]] = {
  val bfsLen = bfs.length
  if (bfs.isEmpty) Nil
  else
    List(bfs.head) :: List.unfold((List(bfs.head),1)){case (pr,idx) =>
      Option.when(bfsLen > idx){
        val ns = pr.foldLeft((List.empty[Option[A]],idx)){
          case ((acc,x), None) => (acc ++ List(None,None), x)
          case ((acc,x), _) => (acc ++ List(bfs.lift(x).flatten
                                           ,bfs.lift(x+1).flatten), x+2)
        }
        (ns._1, ns)
      }
    }
}

//from full tree representation to Depth-First-Serialization
def toDFS[A](lloa :List[List[Option[A]]]
            ,lvl :Int = 0) :List[Option[A]] = lloa match {
  case Nil => List(None, None)
  case List(None) :: Nil => List(None)
  case List( oa ) :: tl  => oa :: toDFS(tl, lvl)
  case row :: tl => row.drop(lvl*2) match {
    case List(None,None,_*) => List(None, None)
    case List(None, ob ,_*) => None :: (ob::toDFS(tl,2*lvl + 1))
    case List( oa ,None,_*) => (oa::toDFS(tl,2*lvl)) ++ List(None)
    case List( oa , ob ,_*) => (oa :: toDFS(tl, 2*lvl)) ++
                                (ob :: toDFS(tl,2*lvl + 1))
  }
}
</code>```

Now let's parameterize the tree so that we can build Int trees, Float trees, String trees, etc.

We're also going to make the constructor private so that node creation is only done via factory methods.

```<code>case class Tree[A] private (value : A
                           ,left  : Option[Tree[A]]
                           ,right : Option[Tree[A]])
</code>```

All that's left is to supply the factory methods.

```<code>object Tree {
  private def BFS2full[A]( . . . //as above
  private def toDFS[A]( . . . //as above

  def fromDFS[A](dfs :IterableOnce[Option[A]]) :Option[Tree[A]] = {
    val itr = dfs.iterator
    def loop(): Option[Tree[A]] =
      Option.when(itr.hasNext)(itr.next())
            .flatten
            .map(new Tree(_,loop(),loop()))
    loop()
  }
  def fromBFS[A](bfs:IndexedSeq[Option[A]]) :Option[Tree[A]] =
    fromDFS(toDFS(BFS2full(bfs)))
}
</code>```

testing:

```<code>Tree.fromBFS(Vector(Some('A'),None,Some('B'),Some('C'))).get
//res0: Tree[Char] = Tree(A,None,Some(Tree(B,Some(Tree(C,None,None)),None)))
</code>```

Body:
I had an imperative program which deserializes to a Binary Tree from an array. Its a BFS algorithm. I was wondering how to do this in Scala with functional programming concepts.

class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
  val value: Int = _value
  val left: TreeNode = _left
  val right: TreeNode = _right
}
def createTree(list: Array[Int]): TreeNode = ???

For reference this is the imperative version in Javascript. The algorithm is described here. https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-

class TreeNode {
  constructor(val){
    this.val = val;
    this.left = this.right = null;
  }
}

function makeTree(arr){
  let root = new TreeNode(arr[0]);
  let q = [root];

  let index = 1;
  while(q.length){
    let node = q.splice(0,1)[0];
    if(arr[index] != null){
      node.left = new TreeNode(arr[index]);
      q.push(node.left);
    }
    index++;

    if(arr[index] != null){
      node.right = new TreeNode(arr[index]);
      q.push(node.right);
    }
    index++;
  }
  return root;
}

Body:
As has been noted, Scala avoids null whenever possible, preferring Option to indicate the absence of a value.

Mutable variables are also shunned, which makes it much easier to construct a B-tree in a depth-first manner rather than breadth-first.

So all you really need is an easy-to-use breadth-first-serialization --to--> depth-first-serialization translator.

I did it in two steps.

//from Breadth-First-Serialization to full tree representation
def BFS2full[A](bfs:IndexedSeq[Option[A]]) :List[List[Option[A]]] = {
  val bfsLen = bfs.length
  if (bfs.isEmpty) Nil
  else
    List(bfs.head) :: List.unfold((List(bfs.head),1)){case (pr,idx) =>
      Option.when(bfsLen > idx){
        val ns = pr.foldLeft((List.empty[Option[A]],idx)){
          case ((acc,x), None) => (acc ++ List(None,None), x)
          case ((acc,x), _) => (acc ++ List(bfs.lift(x).flatten
                                           ,bfs.lift(x+1).flatten), x+2)
        }
        (ns._1, ns)
      }
    }
}

//from full tree representation to Depth-First-Serialization
def toDFS[A](lloa :List[List[Option[A]]]
            ,lvl :Int = 0) :List[Option[A]] = lloa match {
  case Nil => List(None, None)
  case List(None) :: Nil => List(None)
  case List( oa ) :: tl  => oa :: toDFS(tl, lvl)
  case row :: tl => row.drop(lvl*2) match {
    case List(None,None,_*) => List(None, None)
    case List(None, ob ,_*) => None :: (ob::toDFS(tl,2*lvl + 1))
    case List( oa ,None,_*) => (oa::toDFS(tl,2*lvl)) ++ List(None)
    case List( oa , ob ,_*) => (oa :: toDFS(tl, 2*lvl)) ++
                                (ob :: toDFS(tl,2*lvl + 1))
  }
}

Now let's parameterize the tree so that we can build Int trees, Float trees, String trees, etc.

We're also going to make the constructor private so that node creation is only done via factory methods.

case class Tree[A] private (value : A
                           ,left  : Option[Tree[A]]
                           ,right : Option[Tree[A]])

All that's left is to supply the factory methods.

object Tree {
  private def BFS2full[A]( . . . //as above
  private def toDFS[A]( . . . //as above

  def fromDFS[A](dfs :IterableOnce[Option[A]]) :Option[Tree[A]] = {
    val itr = dfs.iterator
    def loop(): Option[Tree[A]] =
      Option.when(itr.hasNext)(itr.next())
            .flatten
            .map(new Tree(_,loop(),loop()))
    loop()
  }
  def fromBFS[A](bfs:IndexedSeq[Option[A]]) :Option[Tree[A]] =
    fromDFS(toDFS(BFS2full(bfs)))
}

testing:

Tree.fromBFS(Vector(Some('A'),None,Some('B'),Some('C'))).get
//res0: Tree[Char] = Tree(A,None,Some(Tree(B,Some(Tree(C,None,None)),None)))


问:
If else if shortening
I can see there are so many related questions to this. Could not find anything specific addressing my query. Here is my question:

How can i shorten the below if else condition:

```<code>If (condition1)
{
    If(condition2)
    {
        Logic A
    }
}
Else if (condition3)
{
    Logic A
}
</code>```

One way i could come up was as below:

```<code>If (condition1 && condition2  ||  !condition1 && condition3)
{
    Logic A
}
</code>```

Just wondering if there is a better way of doing it?

答:
you can do this

(condition1 && condition2  ||  !condition1 && condition3) ?  logic(a) : logic(b)
```

<p>Its called Ternary operator, It would make your code shorter and you can also use it to set a variable, for example </p>

```const isTrue = 4 > 3 ? true : false
```

Title: If else if shortening

Body:
I can see there are so many related questions to this. Could not find anything specific addressing my query. Here is my question:

How can i shorten the below if else condition:

If (condition1)
{
    If(condition2)
    {
        Logic A
    }
}
Else if (condition3)
{
    Logic A
}

One way i could come up was as below:

If (condition1 && condition2  ||  !condition1 && condition3)
{
    Logic A
}

Just wondering if there is a better way of doing it?

Body:
you can do this

(condition1 && condition2  ||  !condition1 && condition3) ?  logic(a) : logic(b)

Its called Ternary operator, It would make your code shorter and you can also use it to set a variable, for example

const isTrue = 4 > 3 ? true : false


问:
Oracle sql - How do I get the most updated value?
I'm trying to pull in the most recently updated lines. I tried using the MAX function in the select statement but am just getting the same results as I do when just doing a select *:

```<code>select max(last_update_date),vendor_id, last_update_date, last_updated_by , VENDOR_SITE_CODE
from POZ_SUPPLIER_SITES_ALL_M
group by vendor_id, last_update_date, last_updated_by, VENDOR_SITE_CODE
</code>```

This is the table:

This is the result I want:

What condition or function do I have to use to get the results I want?

答:
One method uses a correlated subquery:

```<code>select t.*
from t
where t.lastupdateddate = (select max(t2.lastupdateddate)
                           from t t2
                           where t2.vendor = t.vendor and t2.vendorsite = t.vendorsite
                          );
</code>```

Another method uses aggregation and keep:

```<code>select vendor, vendorsite, max(lastupdateddate),
       max(lastupdatedby) keep (dense_rank first order by lastupdateddate desc) as lastupdatedby
from t
group by vendor, vendorsite;
</code>```

The keep expression is Oracle's (rather verbose) way of saying "first".

Of course, there is also the row_number() approach as well.

Body:
I'm trying to pull in the most recently updated lines. I tried using the MAX function in the select statement but am just getting the same results as I do when just doing a select *:

select max(last_update_date),vendor_id, last_update_date, last_updated_by , VENDOR_SITE_CODE
from POZ_SUPPLIER_SITES_ALL_M
group by vendor_id, last_update_date, last_updated_by, VENDOR_SITE_CODE

This is the table:

This is the result I want:

What condition or function do I have to use to get the results I want?

Body:
One method uses a correlated subquery:

select t.*
from t
where t.lastupdateddate = (select max(t2.lastupdateddate)
                           from t t2
                           where t2.vendor = t.vendor and t2.vendorsite = t.vendorsite
                          );

Another method uses aggregation and keep:

select vendor, vendorsite, max(lastupdateddate),
       max(lastupdatedby) keep (dense_rank first order by lastupdateddate desc) as lastupdatedby
from t
group by vendor, vendorsite;

The keep expression is Oracle's (rather verbose) way of saying "first".

Of course, there is also the row_number() approach as well.


问:
React element name as a string variable
While skimming through source code of one of the React UI libraries, I've come across this code pattern (I simplify):

```<code>function Test() {
  let Button = "button";
  // ...
  return <Button>Click me</Button>;
}
</code>```

What's going on here - why does this work?:)

答:
The JSX above is interpreted by React as:

```<code>function Test() {
  let Button = "button";
  return React.createElement(
    Button,
    null,
    "Click me"
  );
}
</code>```

Button is just a string variable, set to "button", that gets passed to React.createElement(...).

Title: React element name as a string variable

Body:
While skimming through source code of one of the React UI libraries, I've come across this code pattern (I simplify):

function Test() {
  let Button = "button";
  // ...
  return <Button>Click me</Button>;
}

What's going on here - why does this work?:)

Body:
The JSX above is interpreted by React as:

function Test() {
  let Button = "button";
  return React.createElement(
    Button,
    null,
    "Click me"
  );
}

Button is just a string variable, set to "button", that gets passed to React.createElement(...).


问:
Issue while connecting Node service with Office365 mail exchange server
I'm facing issues while trying to read mail from Office 365 account. Below is the code I'm using:</p>

```<code>const EWS = require('node-ews');

// exchange server connection info
const ewsConfig = { username: 'myuser@myDomain.com', password: 'mypassword', host: 'https://outlook.office365.com/owa/myDomain.com/', auth: 'basic' };

// initialize node-ews
const ews = new EWS(ewsConfig);

// define ews api function
const ewsFunction = 'ExpandDL';

// define ews api function args
const ewsArgs = { 'Mailbox': { 'EmailAddress':'publiclist@domain.com' } };

// query EWS and print resulting JSON to console
ews.run(ewsFunction, ewsArgs).then(result => {
  console.log(JSON.stringify(result)); }).catch(err => {
  console.log(err.message); });
</code>```

答:
Your EWS config is wrong for Office365, the EWS endpoint for Office365 is https://outlook.office365.com/ews/exchange.asmx so you should just have</p>

```<code>const ewsConfig = { username: 'myuser@myDomain.com', password: 'mypassword', host: 'https://outlook.office365.com', auth: 'basic' };
</code>```

Body:
I'm facing issues while trying to read mail from Office 365 account. Below is the code I'm using:

const EWS = require('node-ews');

// exchange server connection info
const ewsConfig = { username: 'myuser@myDomain.com', password: 'mypassword', host: 'https://outlook.office365.com/owa/myDomain.com/', auth: 'basic' };

// initialize node-ews
const ews = new EWS(ewsConfig);

// define ews api function
const ewsFunction = 'ExpandDL';

// define ews api function args
const ewsArgs = { 'Mailbox': { 'EmailAddress':'publiclist@domain.com' } };

// query EWS and print resulting JSON to console
ews.run(ewsFunction, ewsArgs).then(result => {
  console.log(JSON.stringify(result)); }).catch(err => {
  console.log(err.message); });

Body:
Your EWS config is wrong for Office365, the EWS endpoint for Office365 is https://outlook.office365.com/ews/exchange.asmx so you should just have

const ewsConfig = { username: 'myuser@myDomain.com', password: 'mypassword', host: 'https://outlook.office365.com', auth: 'basic' };


问:
How do I get the next line from a file
I am implemting a program using c++, and i have a problem of geting the next line from an input file. I used:

```<code>   const MAX 300;
   char oneline[MAX];
   ifstream in;
   in.open("input.txt);
   in.getline(oneline,MAX);
</code>```

The function getline always gets me the first line in the file. The thing is, how can I get the next line in the file?

答:
```<code>std::string line;
while(in.good())
{
    getline(in, line);

    //do something with line
}
</code>```

Since you're using C++ you should use std::string to read your lines.

Title: How do I get the next line from a file

Body:
I am implemting a program using c++, and i have a problem of geting the next line from an input file. I used:

   const MAX 300;
   char oneline[MAX];
   ifstream in;
   in.open("input.txt);
   in.getline(oneline,MAX);

The function getline always gets me the first line in the file. The thing is, how can I get the next line in the file?

Body:
std::string line;
while(in.good())
{
    getline(in, line);

    //do something with line
}

Since you're using C++ you should use std::string to read your lines.


问:
ReactNative TouchableOpacity makes view dissapear?
Consider the following example:

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

import snackicon from './assets/snack-icon.png';

export default function App() {
  return (
    <>
    {/*<TouchableOpacity onPress={() => console.log("View clicked")}>*/}
    <View style={{flex: 1, flexDirection: 'row', backgroundColor: '#00000050', marginRight: 5, borderRadius: 15}}>
        <View style={{flex: 1}}>
            <Image style={{alignSelf: 'stretch', flex: 1, resizeMode: 'contain', width: 'auto' }} source={snackicon}></Image>
        </View>
        <View style={{flex: 3}}>
        </View>
    </View>
    {/*</TouchableOpacity>*/}
    <View style={{flex: 10, flexDirection: 'column'}}></View>
    </>
  );
}
</code>```

This shows a view with an Image in it; However if you uncomment the TouchableOpacity the entire view disappears. What exactly is causing this?

Expo link if anyone wants to try live: https://snack.expo.io/qt_gAkTaM

答:
You are using flex: 1 to define the height of your nested View component. Since it has a flex: 1 and your other View has flex: 10, it takes 1/10 of the screen.

Your TouchableOpacity doesn't have a height nor flex property, so it doesn't grow.

I suggest trying to put flex: 1 in the styles of TouchableOpacity.

Body:
Consider the following example:

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

import snackicon from './assets/snack-icon.png';

export default function App() {
  return (
    <>
    {/*<TouchableOpacity onPress={() => console.log("View clicked")}>*/}
    <View style={{flex: 1, flexDirection: 'row', backgroundColor: '#00000050', marginRight: 5, borderRadius: 15}}>
        <View style={{flex: 1}}>
            <Image style={{alignSelf: 'stretch', flex: 1, resizeMode: 'contain', width: 'auto' }} source={snackicon}></Image>
        </View>
        <View style={{flex: 3}}>
        </View>
    </View>
    {/*</TouchableOpacity>*/}
    <View style={{flex: 10, flexDirection: 'column'}}></View>
    </>
  );
}

This shows a view with an Image in it; However if you uncomment the TouchableOpacity the entire view disappears. What exactly is causing this?

Expo link if anyone wants to try live: https://snack.expo.io/qt_gAkTaM


问:
string representation of dictionary without quotes in values
I am trying to create a string that can be evaluated to a dictionary such as:

```<code>'{"key1": val1, "key2": val2}'
</code>```

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})
```

This mostly works except instead of val1 I get 'val1'. I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.

答:
Not pretty, but accomplishes what you're looking for:</p>

```<code>args = ["key1", "key2"]

your_attempt = str({key: "val%d" % i for i, key in enumerate(args)})
# outputs: "{'key2': 'val1', 'key1': 'val0'}"

your_attempt.replace("': '","': ").replace("', '",", '").replace("'}","}")
# outputs: "{'key2': val1, 'key1': val0}"
</code>```

Body:
I am trying to create a string that can be evaluated to a dictionary such as:

'{"key1": val1, "key2": val2}'

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})

This mostly works except instead of val1 I get 'val1'. I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.

Body:
Not pretty, but accomplishes what you're looking for:

args = ["key1", "key2"]

your_attempt = str({key: "val%d" % i for i, key in enumerate(args)})
# outputs: "{'key2': 'val1', 'key1': 'val0'}"

your_attempt.replace("': '","': ").replace("', '",", '").replace("'}","}")
# outputs: "{'key2': val1, 'key1': val0}"


问:
Background fetch working in simulator but not working in real device
I am calling API to get data and show local push based on the response of API so I am using background fetch service of Apple which is introduce in iOS 13 and above.

But when try to test this scenario in simulator and it works fine but when I checked this app in real device then it is not working and lost the connection when it tries to call api in background.

I am not killing my app from device just put back by click on home button.

I am not sure why it is not running in real device.

What I did till now. Steps are here:

I have enable background fetch from capabilities of app project.

then I have added this code in AppDelegate

```<code>extension AppDelegate {

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

  print("Bg Fetch from App Delegate 1")

  DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

  BroadCastManager.sharedInstance.fetchNewDataWithCompletionHandler(completionHandler: completionHandler)

}
}
}
</code>```

This will call one method from service class where one API will be call and then based on response api it will fire one local push.

So here problem is that when API is call in real device and app is in background then i am getting below error.

error screenshot.

答:
The code you have is iOS12 and earlier.  Try the new process.  I just gave an example (my app's working code) here:

BGAppRefreshTask Background Task Not Executing

Body:
I am calling API to get data and show local push based on the response of API so I am using background fetch service of Apple which is introduce in iOS 13 and above.

But when try to test this scenario in simulator and it works fine but when I checked this app in real device then it is not working and lost the connection when it tries to call api in background.

I am not killing my app from device just put back by click on home button.

I am not sure why it is not running in real device.

What I did till now. Steps are here:

I have enable background fetch from capabilities of app project.

then I have added this code in AppDelegate

extension AppDelegate {

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

  print("Bg Fetch from App Delegate 1")

  DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

  BroadCastManager.sharedInstance.fetchNewDataWithCompletionHandler(completionHandler: completionHandler)

}
}
}

This will call one method from service class where one API will be call and then based on response api it will fire one local push.

So here problem is that when API is call in real device and app is in background then i am getting below error.

error screenshot.


问:
Firebase - sort posts by number of keys and show in TableView
I have made app that save users message and its username to Firebase with childByAutoID key. Inside there are childs that saves Username, message, likes and PostID (as you can see on image below).

After a lot of research and a lot of trying writing code by myself, I figure out that likes need to be saved as autoID keys inside separate child and then you have to count that keys to get number of likes (you'll see that child also on image under and that child is named "Liked")

Everything is displayed in tableView cell.
But all of them are displayed randomly which is OK (I would prefer to be ordered by date added), but what would really like is that loaded data in next next VC to be displayed as:

TOP 10 of the week
TOP 10 of the month
ALL BEST etc...

There'll be separate button for menu and when you press it, you'll be presented with next VC that contain Table View with same data, but this time sorted by most liked post.

This is code that writes keys to LIKED child path (when like is pressed on already loaded data from Firebase database):

```<code>    @IBAction func likePressed(_ sender: Any) {

    let ref = Database.database().reference()
    self.likeButton.isEnabled = false
    let key = ref.child("Frusters").childByAutoId().key

    ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

                let updateLikes = ["Liked/\(key)" : key] as [String : Any]
                    ref.child("Frusters").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in

                        if error == nil {
                            ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                        if let properties = snap.value as? [String : AnyObject] {
                        if let likes = properties["Liked"] as? [String : AnyObject] {

                        let count = likes.count
                        self.likeLabel.text = "\(count) Likes"

                        let update = ["likes" : count]
                        ref.child("Frusters").child(self.postID).updateChildValues(update)

                        self.likeButton.isHidden = true
                        self.unlikeButton.isHidden = false
                        self.likeButton.isEnabled = true
                        }
                    }
                })
            }
        })
    })

    ref.removeAllObservers()
}
</code>```

and this is the code that loads data and put it in my table view:

```<code>    func loadData() {
    self.fetchPosts.removeAll()
    let ref = Database.database().reference()
    ref.child("Frusters").observeSingleEvent(of: .value, with: { (snapshot) in
        if let postDict = snapshot.value as? [String:AnyObject] {
            for (_,postElement) in postDict {
                print(postElement);
                let post = Post()
                post.username = postElement["Username"] as? String
                post.message = postElement["Message"] as? String
                post.likes = postElement["likes"] as? Int
                post.postID = postElement["postID"] as? String
                self.fetchPosts.append(post)
            }
        }
        self.tableView.reloadData()

    }) { (error) in
        print(error.localizedDescription)
    }
    ref.removeAllObservers()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.fetchPosts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")  as! PostTableViewCell

    cell.messageLabel.text = self.fetchPosts[indexPath.row].message
    cell.usernameLabel.text = self.fetchPosts[indexPath.row].username

    cell.likeLabel.text = "\(self.fetchPosts[indexPath.row].likes!) Likes"
    cell.postID = self.fetchPosts[indexPath.row].postID

    cell.bckgView.layer.cornerRadius = 0

    cell.bckgView.layer.shadowOffset = CGSize(width: 0, height: 1)
    cell.bckgView.layer.masksToBounds = false
    cell.bckgView.layer.shadowColor = UIColor.black.cgColor
    cell.bckgView.layer.shadowOpacity = 0.3
    cell.bckgView.layer.shadowRadius = 4

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}
</code>```

Well, problem is that I do not know how to insert inside my new UITableView top 10 post with most likes, to sort them from most liked post to next 9 of them with most likes.

Also, is it possible to sort them most liked this month or this week?
Does this keys that Firebase database makes (by autoID) contain date of created post or do I have to insert new child with date inside and then in code combine "date" child and "liked" child to be presented as top 10 liked post between 1st and last of this month?

Thanks in advance. ;)

答:
1-You don't have to store each like separately, if all you care about is the number. You can just update the number.

```<code>    @IBAction func likePressed(_ sender: Any) {

    let ref = Database.database().reference()
    self.likeButton.isEnabled = false
    let key = ref.child("Frusters").childByAutoId().key

    ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

    let counted = snapshot.value as? Int
    self.ref.child("Flusters".child(self.postID).child("likes").setValue(counted! + 1)
})
</code>```

2- Yes, you can sort by likes. you'd need to use the .queryOrdered function. Update the code as follows

```<code>func loadData() {
    self.fetchPosts.removeAll()
    let ref = Database.database().reference()
    ref.child("Frusters").queryOrdered(byChild: "likes").observeSingleEvent(of: .value, with: { (snapshot) in
        if let postDict = snapshot.value as? [String:AnyObject] {
            for (_,postElement) in postDict {
                print(postElement);
                let post = Post()
                post.username = postElement["Username"] as? String
                post.message = postElement["Message"] as? String
                post.likes = postElement["likes"] as? Int
                post.postID = postElement["postID"] as? String
                self.fetchPosts.append(post)
            }
        }
        self.tableView.reloadData()
</code>```

3- To order by top week, month, you'd have to keep track of a timestamp.

Body:
I have made app that save users message and its username to Firebase with childByAutoID key. Inside there are childs that saves Username, message, likes and PostID (as you can see on image below).

After a lot of research and a lot of trying writing code by myself, I figure out that likes need to be saved as autoID keys inside separate child and then you have to count that keys to get number of likes (you'll see that child also on image under and that child is named "Liked")

Everything is displayed in tableView cell.
But all of them are displayed randomly which is OK (I would prefer to be ordered by date added), but what would really like is that loaded data in next next VC to be displayed as:

TOP 10 of the week
TOP 10 of the month
ALL BEST etc...

There'll be separate button for menu and when you press it, you'll be presented with next VC that contain Table View with same data, but this time sorted by most liked post.

This is code that writes keys to LIKED child path (when like is pressed on already loaded data from Firebase database):

    @IBAction func likePressed(_ sender: Any) {

    let ref = Database.database().reference()
    self.likeButton.isEnabled = false
    let key = ref.child("Frusters").childByAutoId().key

    ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

                let updateLikes = ["Liked/\(key)" : key] as [String : Any]
                    ref.child("Frusters").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in

                        if error == nil {
                            ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                        if let properties = snap.value as? [String : AnyObject] {
                        if let likes = properties["Liked"] as? [String : AnyObject] {

                        let count = likes.count
                        self.likeLabel.text = "\(count) Likes"

                        let update = ["likes" : count]
                        ref.child("Frusters").child(self.postID).updateChildValues(update)

                        self.likeButton.isHidden = true
                        self.unlikeButton.isHidden = false
                        self.likeButton.isEnabled = true
                        }
                    }
                })
            }
        })
    })

    ref.removeAllObservers()
}

and this is the code that loads data and put it in my table view:

    func loadData() {
    self.fetchPosts.removeAll()
    let ref = Database.database().reference()
    ref.child("Frusters").observeSingleEvent(of: .value, with: { (snapshot) in
        if let postDict = snapshot.value as? [String:AnyObject] {
            for (_,postElement) in postDict {
                print(postElement);
                let post = Post()
                post.username = postElement["Username"] as? String
                post.message = postElement["Message"] as? String
                post.likes = postElement["likes"] as? Int
                post.postID = postElement["postID"] as? String
                self.fetchPosts.append(post)
            }
        }
        self.tableView.reloadData()

    }) { (error) in
        print(error.localizedDescription)
    }
    ref.removeAllObservers()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.fetchPosts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")  as! PostTableViewCell

    cell.messageLabel.text = self.fetchPosts[indexPath.row].message
    cell.usernameLabel.text = self.fetchPosts[indexPath.row].username

    cell.likeLabel.text = "\(self.fetchPosts[indexPath.row].likes!) Likes"
    cell.postID = self.fetchPosts[indexPath.row].postID

    cell.bckgView.layer.cornerRadius = 0

    cell.bckgView.layer.shadowOffset = CGSize(width: 0, height: 1)
    cell.bckgView.layer.masksToBounds = false
    cell.bckgView.layer.shadowColor = UIColor.black.cgColor
    cell.bckgView.layer.shadowOpacity = 0.3
    cell.bckgView.layer.shadowRadius = 4

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}

Well, problem is that I do not know how to insert inside my new UITableView top 10 post with most likes, to sort them from most liked post to next 9 of them with most likes.

Also, is it possible to sort them most liked this month or this week?
Does this keys that Firebase database makes (by autoID) contain date of created post or do I have to insert new child with date inside and then in code combine "date" child and "liked" child to be presented as top 10 liked post between 1st and last of this month?

Thanks in advance. ;)

Body:
1-You don't have to store each like separately, if all you care about is the number. You can just update the number.

    @IBAction func likePressed(_ sender: Any) {

    let ref = Database.database().reference()
    self.likeButton.isEnabled = false
    let key = ref.child("Frusters").childByAutoId().key

    ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

    let counted = snapshot.value as? Int
    self.ref.child("Flusters".child(self.postID).child("likes").setValue(counted! + 1)
})

2- Yes, you can sort by likes. you'd need to use the .queryOrdered function. Update the code as follows

func loadData() {
    self.fetchPosts.removeAll()
    let ref = Database.database().reference()
    ref.child("Frusters").queryOrdered(byChild: "likes").observeSingleEvent(of: .value, with: { (snapshot) in
        if let postDict = snapshot.value as? [String:AnyObject] {
            for (_,postElement) in postDict {
                print(postElement);
                let post = Post()
                post.username = postElement["Username"] as? String
                post.message = postElement["Message"] as? String
                post.likes = postElement["likes"] as? Int
                post.postID = postElement["postID"] as? String
                self.fetchPosts.append(post)
            }
        }
        self.tableView.reloadData()

3- To order by top week, month, you'd have to keep track of a timestamp.


问:
Shared item producers and consumer problem
I have a flavor of producer consumer problem (I couldn't find any similar questions and ran out of search keywords) where

Consumers are themselves are producers.

The items produced can be shared.

If some thread is producing, the other threads wait for it to complete and use the same produced item.

I came up with a solution, but I am stuck on how to test it. Is there a theoretical framework to verify the correctness of solutions to these kind of problems. Also is it possible to test these solutions without modifying the source

In case you are interested in the code, it's listed below

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class SharedItemProducer {

    /* testing parameters */
    static final int randMax = 1;
    static final Random R = new Random();
    static final int numThreads = 8;
    static final long produceDelay = 0;
    static final long maxRunTime = 5000;

    Integer item = 0;
    final Object waitingRoom = new Object();
    AtomicInteger wantToBeProducer = new AtomicInteger(0);

    public void produce() {
        log("entering produce");

        if (wantToBeProducer.compareAndSet(0, 1)) {
            log("i'm the producer. cur=%d", item);
            try {
                Thread.sleep(produceDelay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            item = item + 1;
            synchronized (waitingRoom) {
                waitingRoom.notifyAll();
            }
            wantToBeProducer.set(0);
            log("done producing");
        } else {
            log("someone else is producing, waiting..");
            synchronized (waitingRoom) {
                try {
                    waitingRoom.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log("wait complete");
        }
    }

    public static void main(String[] args) {

        long start = System.currentTimeMillis();

        /* run the tests */
        SharedItemProducer1 P = new SharedItemProducer1();
        for (int i = 0; i < numThreads; i++) {
            new Thread(() -> {
                while (true) {
                    P.produce();
                    try {
                        Thread.sleep(R.nextInt(randMax));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        /* limit time for tests */
        new Thread(() -> {
            try {
                Thread.sleep(maxRunTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.exit(0);
        }).start();
    }

    static boolean enableLog = false;
    static final String FMT = "[%s] [%s] ";

    public static void log(String info, Object... params) {
        if (!enableLog)
            return;
        Object[] pfParams = new Object[params.length + 2];
        System.arraycopy(params, 0, pfParams, 2, params.length);
        pfParams[0] = new Date();
        pfParams[1] = Thread.currentThread().getName();
        System.out.printf(FMT + info + "\n", pfParams);
    }
}
```

答:
If I understood correctly, you are asking for a way to control thread interleaving so that you can verify possible edge cases and weird scenarios.

I'd recommend you to have a look at Baeldung - Testing Multi-Threaded Code in Java and see if it helps.

It talks not only about concepts and strategies for testing concurrency code, but also refers to some tools that might be helpful, including:

Tempus Fugit

Thread Weaver

MultithreadedTC

Please have a look and give them a try.

To better test your code, I'd also suggest you modularize it a bit more, so you can test the producer and the consumer in isolation.

EDIT: To come up with test cases, it might be helpful a list of typical concurrency problems that you may want to verify in your code. Please have a look this blog post from the CMU SEI called Testing Concurrent Systems: Concurrency Defects, Testing Techniques, and Recommendations for an extensive list.


问:
Uppercase specific words in EditText
Inside EditText I want to know how to capitalize on specific words. The code is below.

```<code> editText.addTextChangedListener(new TextWatcher() {

        private static final String KEYWORD = "rain";
        private static final String KEYWORD1 = "music";

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onSaveNote();
        }

        @Override
        public void afterTextChanged(Editable s) {
            onSaveNote();

            try {

                for (StyleSpan span : s.getSpans(0, s.length(), StyleSpan.class)) {
                    s.removeSpan(span);
                }

                // Add new spans for every occurrence of the keyword.
                int i = 0;
                while (i != -1) {
                    i = editText.getText().toString().indexOf(KEYWORD, i);
                    if (i != -1) {
                        s.setSpan(new InputFilter[]{new InputFilter.AllCaps()}, i, i + KEYWORD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
</code>```

I tried searching for this but not found any. InputFilter doesn't work. How to do this?

答:
In afterTextChanged(), do the following:

```<code>@Override
public void afterTextChanged(Editable s) {
    onSaveNote();
    String[] words = s.toString().split("\\s+");
    String output = "";
    for (String word : words) {
        if (word.equalsIgnoreCase(KEYWORD) || word.equalsIgnoreCase(KEYWORD1)) {
            output += word.toUpperCase(Locale.getDefault()) + " ";
        } else {
            output += word + " ";
        }
    }
    editText.setText(output.trim());
}
</code>```

Title: Uppercase specific words in EditText

Body:
Inside EditText I want to know how to capitalize on specific words. The code is below.

 editText.addTextChangedListener(new TextWatcher() {

        private static final String KEYWORD = "rain";
        private static final String KEYWORD1 = "music";

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onSaveNote();
        }

        @Override
        public void afterTextChanged(Editable s) {
            onSaveNote();

            try {

                for (StyleSpan span : s.getSpans(0, s.length(), StyleSpan.class)) {
                    s.removeSpan(span);
                }

                // Add new spans for every occurrence of the keyword.
                int i = 0;
                while (i != -1) {
                    i = editText.getText().toString().indexOf(KEYWORD, i);
                    if (i != -1) {
                        s.setSpan(new InputFilter[]{new InputFilter.AllCaps()}, i, i + KEYWORD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

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

I tried searching for this but not found any. InputFilter doesn't work. How to do this?

Body:
In afterTextChanged(), do the following:

@Override
public void afterTextChanged(Editable s) {
    onSaveNote();
    String[] words = s.toString().split("\\s+");
    String output = "";
    for (String word : words) {
        if (word.equalsIgnoreCase(KEYWORD) || word.equalsIgnoreCase(KEYWORD1)) {
            output += word.toUpperCase(Locale.getDefault()) + " ";
        } else {
            output += word + " ";
        }
    }
    editText.setText(output.trim());
}


问:
Disable AJAX Caching
I am in a bit of a pickle right now. I am building a web page that will get data from a CGI backend. I have no control over the CGI backend, nor the server (so no mod_headers or mod_expires). Also, because of the parameters to the script, I cannot append a unique value (like '&089u0af0d98) to each request. The requests are AJAX using the XmlHttpRequest object. I have tried to set the 'If-Modified-Since' and 'Cache-Control' request headers unsuccessfully. Does anybody have any other ideas for how I can prevent the AJAX response from being cached by the browser?</p>

答:
You can send random parameters using POST, while sending the important vars using GET if you need to.

If you have problems with IE, I know that sending something with POST makes it to stop caching server responses

Title: Disable AJAX Caching


问:
Xamarin forms: Display Alert is not working in XF version 4.6 on UWP platform
For implementing expander on my project I have updated my XF version to 4.6.0.726. After that, the displayalert is not working on the xamarin UWP project. Working fine on android and ios platforms.

My Code:

```<code>await DisplayAlert("Alert","Hiiiii","Ok");
</code>```

This is an issue with the XF new version, How can I solve this? I have uploaded a sample project here.

答:
I will post this additional answer for anyone else having this problem. I also had the problem with the display alert not working, it was working fine on my Android project but on my UWP testing it would just freeze up. I searched the internet for hours and hours, no posted answers I found would work for me. I tried changing the Windows target version from Fall Creators update to version 1809 and finally the issue went away! Here is how to do it in Visual Studio:

Right-click on your UWP project and select properties

The properties window will come up. Select the Assemblies tab. Select the target version.

Body:
For implementing expander on my project I have updated my XF version to 4.6.0.726. After that, the displayalert is not working on the xamarin UWP project. Working fine on android and ios platforms.

My Code:

await DisplayAlert("Alert","Hiiiii","Ok");

This is an issue with the XF new version, How can I solve this? I have uploaded a sample project here.


答:
You can use row_number to achieve your expected result.

```<code>select
    vendor,
    vendor_site
    last_update_date,
    last_updated_by
from
(
    select
        vendor,
        vendor_site
        last_update_date,
        last_updated_by,
        row_number() over (partition by vendor, vendor_site order by last_update_date desc) as rnk
    from POZ_SUPPLIER_SITES_ALL_M
) val
where rnk = 1
</code>```

Title: Oracle sql - How do I get the most updated value?

Body:
I'm trying to pull in the most recently updated lines. I tried using the MAX function in the select statement but am just getting the same results as I do when just doing a select *:

select max(last_update_date),vendor_id, last_update_date, last_updated_by , VENDOR_SITE_CODE
from POZ_SUPPLIER_SITES_ALL_M
group by vendor_id, last_update_date, last_updated_by, VENDOR_SITE_CODE

This is the table:

This is the result I want:

What condition or function do I have to use to get the results I want?

Body:
You can use row_number to achieve your expected result.

select
    vendor,
    vendor_site
    last_update_date,
    last_updated_by
from
(
    select
        vendor,
        vendor_site
        last_update_date,
        last_updated_by,
        row_number() over (partition by vendor, vendor_site order by last_update_date desc) as rnk
    from POZ_SUPPLIER_SITES_ALL_M
) val
where rnk = 1


问:
Is there a "test room" for Twilio Programmable Video?
I'm building a web app that uses Twilio Programmable Video to connect users.  Works great on all my computers and browsers!  When I tested it with 12 people this morning I got a 40% success rate.  "I couldn't see any video" was the most common response.  Browser permissions, browser versions... who knows why.

Does Twilio have a recommended flow for allowing users to test the video features?  Perhaps a test room with an always-on video stream.  I could test getUserMedia myself, but I'd prefer some sort of end-to-end test that ensures when a user is ready to connect to a real person, everything is good to go.

Zoom has this feature in their app.  I realize it's not a fair comparison, but this feature has reduced the time spent dealing with "video's not working!" tech issues at the start of a meeting.

答:
Not exactly today.

Twilio has a more exhaustive testing tool located here, https://networktest.twilio.com/.


问:
Add some variables to an array in a foreach loop
1 / I read a table X with multiple Join and where clause (Result is in $query1).

```<code>            $query1= DB::select(DB::raw(....)
</code>```

2 / After, I do a FOREACH loop. For each selected row, I do a sum of some fields coming from a table X where columns = $ values coming from $query1.

```<code>    $query2 = DB::table('paris')
    ->WHERE('bet_grille_id', '=', $pari->bet_grille_id)
    ->WHERE('bet_match_id','=',$pari->bet_match_id)
    ->WHERE('bet_groupe_id','=',$pari->bet_groupe_id )
    ->WHERE('bet_status','<>','I')
    ->GROUPBY('bet_grille_id','bet_match_id')
    ->get(array(
    DB::raw('SUM(CASE WHEN bet_sens="1" THEN 1 ELSE 0 END) AS parieur1'),
    DB::raw('SUM(CASE WHEN bet_sens="N" THEN 1 ELSE 0 END) AS parieurn'),
    DB::raw('SUM(CASE WHEN bet_sens="2" THEN 1 ELSE 0 END) AS parieur2')));
</code>```

How I can move the result of my query 2 to the the result of query 1 ?

I have
$query1 = A, B, C

$query 2 = D, E, F

At the end, I want to have $query1 = A, B, C, D, E, F

Thanks a lot for you help

答:
```<code>$query1 = array_merge($query1, $query2);
</code>```

Body:
1 / I read a table X with multiple Join and where clause (Result is in $query1).

            $query1= DB::select(DB::raw(....)

2 / After, I do a FOREACH loop. For each selected row, I do a sum of some fields coming from a table X where columns = $ values coming from $query1.

    $query2 = DB::table('paris')
    ->WHERE('bet_grille_id', '=', $pari->bet_grille_id)
    ->WHERE('bet_match_id','=',$pari->bet_match_id)
    ->WHERE('bet_groupe_id','=',$pari->bet_groupe_id )
    ->WHERE('bet_status','<>','I')
    ->GROUPBY('bet_grille_id','bet_match_id')
    ->get(array(
    DB::raw('SUM(CASE WHEN bet_sens="1" THEN 1 ELSE 0 END) AS parieur1'),
    DB::raw('SUM(CASE WHEN bet_sens="N" THEN 1 ELSE 0 END) AS parieurn'),
    DB::raw('SUM(CASE WHEN bet_sens="2" THEN 1 ELSE 0 END) AS parieur2')));

How I can move the result of my query 2 to the the result of query 1 ?

I have
$query1 = A, B, C

$query 2 = D, E, F

At the end, I want to have $query1 = A, B, C, D, E, F

Thanks a lot for you help


答:
There are some aspects that you must keep in mind.

It's possible that a shorter code be faster in some script languages (like JavaScript, PHP...).

But it worth? Is your if inside a loop long enough to make any difference in your code execution time?

Do your shortened code makes easier or harder to understand your code? Sometimes joining some if conditions inside a boolean logic makes it easier to understand, but sometimes it's so complicated that is very hard to understand.

Title: If else if shortening

Body:
I can see there are so many related questions to this. Could not find anything specific addressing my query. Here is my question:

How can i shorten the below if else condition:

If (condition1)
{
    If(condition2)
    {
        Logic A
    }
}
Else if (condition3)
{
    Logic A
}

One way i could come up was as below:

If (condition1 && condition2  ||  !condition1 && condition3)
{
    Logic A
}

Just wondering if there is a better way of doing it?