问:
How to use NetworkBoundResource with suspend fun in Retorfit
I am using Retrofit, LiveData, Room (Android AAC). NetworkBoundResource is a great helper to combine network source and room provided by googlesimple.

Since Retrofit 2.6.0 introduced built-in support for suspend, I tried to modify NetworkBoundResource to use suspend funciton instaed of LiveDataCallAdapter but  encountered a lot of troubles.

Here's my modification:

```<code>abstract class NetworkBondResource<ResultType, RequestType>
@MainThread constructor() {
    private val result = MediatorLiveData<Resource<ResultType>>()

    private val supervisorJob = SupervisorJob()

    init {
        result.value = Resource.loading(null)
    }

    fun asLiveData() = result as LiveData<Resource<ResultType>>

    suspend fun load() {
        withContext(Dispatchers.Main) {
            val dbSource = loadFromDb()
            result.addSource(dbSource) { data ->
                result.removeSource(dbSource)
                if (shouldFetch(data)) {
                    // ! HERE--------------
                    GlobalScope.launch(Dispatchers.IO) {
                        fetchFromNetwork(dbSource)
                    }
                } else {
                    result.addSource(dbSource) { newData ->
                        setValue(Resource.success(newData))
                    }
                }
            }
        }
    }

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

The question is code within result.addSource(dbSource) unable to inherit external scope. I have to use GlobalScope to launch a new coroutine which will causing a 'Coroutine Leak' since it is not controlled by the viewModel scope.

Also I found another way. But this scheme violates the principle of a single trusted source, lost the core role of NetworkBoundResource.

Any ideas will be appreciated.

答:
I also had the same problem, my solution was this. I recommend that you do not use GlobalScope for these reasons. Make it clear that result.addSoruce can only be declared within the main thread. I hope it helps you, if there is a better solution please let me know.</p>

```<code> private val result = MediatorLiveData<Resource<ResultType>>()
private val supervisorJob = SupervisorJob()

suspend fun load(): NetworkBoundResource<ResultType, RequestType> {

    val context = Dispatchers.IO
    context + supervisorJob

    withContext(Dispatchers.Main) {
            result.value = Resource.loading(null)
            val dbResult = loadFromDb()
            result.addSource(dbResult){data->
                result.removeSource(dbResult)
                if (shouldFetch(data)){
                   try {
                       CoroutineScope(context).launch {
                           fetchFromNetwork(dbResult)
                       }
                   }catch (e:Exception){
                       Timber.i("NetworkBoundResource: An error happened: $e")
                       result.addSource(dbResult){newData->
                           setValue(Resource.error(e.message!!, newData))
                       }
                   }
                }else{
                    Timber.i("NetworkBoundResource: Return data from local database")
                    result.addSource(dbResult){newData->
                        setValue(Resource.success(newData))
                    }

                }
            }

    }

    return this

}
</code>```

Body:
I am using Retrofit, LiveData, Room (Android AAC). NetworkBoundResource is a great helper to combine network source and room provided by googlesimple.

Since Retrofit 2.6.0 introduced built-in support for suspend, I tried to modify NetworkBoundResource to use suspend funciton instaed of LiveDataCallAdapter but  encountered a lot of troubles.

Here's my modification:

abstract class NetworkBondResource<ResultType, RequestType>
@MainThread constructor() {
    private val result = MediatorLiveData<Resource<ResultType>>()

    private val supervisorJob = SupervisorJob()

    init {
        result.value = Resource.loading(null)
    }

    fun asLiveData() = result as LiveData<Resource<ResultType>>

    suspend fun load() {
        withContext(Dispatchers.Main) {
            val dbSource = loadFromDb()
            result.addSource(dbSource) { data ->
                result.removeSource(dbSource)
                if (shouldFetch(data)) {
                    // ! HERE--------------
                    GlobalScope.launch(Dispatchers.IO) {
                        fetchFromNetwork(dbSource)
                    }
                } else {
                    result.addSource(dbSource) { newData ->
                        setValue(Resource.success(newData))
                    }
                }
            }
        }
    }

    // others code...
}

The question is code within result.addSource(dbSource) unable to inherit external scope. I have to use GlobalScope to launch a new coroutine which will causing a 'Coroutine Leak' since it is not controlled by the viewModel scope.

Also I found another way. But this scheme violates the principle of a single trusted source, lost the core role of NetworkBoundResource.

Any ideas will be appreciated.

Body:
I also had the same problem, my solution was this. I recommend that you do not use GlobalScope for these reasons. Make it clear that result.addSoruce can only be declared within the main thread. I hope it helps you, if there is a better solution please let me know.

 private val result = MediatorLiveData<Resource<ResultType>>()
private val supervisorJob = SupervisorJob()

suspend fun load(): NetworkBoundResource<ResultType, RequestType> {

    val context = Dispatchers.IO
    context + supervisorJob

    withContext(Dispatchers.Main) {
            result.value = Resource.loading(null)
            val dbResult = loadFromDb()
            result.addSource(dbResult){data->
                result.removeSource(dbResult)
                if (shouldFetch(data)){
                   try {
                       CoroutineScope(context).launch {
                           fetchFromNetwork(dbResult)
                       }
                   }catch (e:Exception){
                       Timber.i("NetworkBoundResource: An error happened: $e")
                       result.addSource(dbResult){newData->
                           setValue(Resource.error(e.message!!, newData))
                       }
                   }
                }else{
                    Timber.i("NetworkBoundResource: Return data from local database")
                    result.addSource(dbResult){newData->
                        setValue(Resource.success(newData))
                    }

                }
            }

    }

    return this

}


来源: stackexchange

问:
How to fetch data from database before rendering in a function componment in React?
Below is my code:

```<code>function Profile() {
    const {userInfo} = useSelector(state => state.user);
    let user = {};

    useEffect(() => {
        const populateUserInfo = async () => {
            const {data} = await axios.get("api/users/" + userInfo._id);
            user = data

            // this line works if I comment out {user.shipping.address} in the "return" section.
            console.log(user.shipping.address)
        }
        populateUserInfo();
    }, [])

    return <div>{user.shipping.address}</div>
}
</code>```

I want to fetch data from DB and store it into user variable before rendering, but when the page renders, TypeError: Cannot read property 'address' of undefined occurred.

I guess the user variable is still empty when the page renders?
Could anyone teach me how to do it?

答:
You can't use async-await inside useEffect()

instead, you can use this.

and I edited some parts of your code.

```<code>function Profile() {
    const {userInfo} = useSelector(state => state.user);
    const [user, setUser] = React.useState({});
    async function populateUserInfo(){
       let user = {};
       const {data} = await axios.get("api/users/" + userInfo._id);
       setUser(data);
       console.log(data.shipping.address)
    }
    useEffect(() => {
        populateUserInfo();
    }, [])

    return <div>{user.shipping.address}</div>
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Below is my code:

function Profile() {
    const {userInfo} = useSelector(state => state.user);
    let user = {};

    useEffect(() => {
        const populateUserInfo = async () => {
            const {data} = await axios.get("api/users/" + userInfo._id);
            user = data

            // this line works if I comment out {user.shipping.address} in the "return" section.
            console.log(user.shipping.address)
        }
        populateUserInfo();
    }, [])

    return
{user.shipping.address}

}

I want to fetch data from DB and store it into user variable before rendering, but when the page renders, TypeError: Cannot read property 'address' of undefined occurred.

I guess the user variable is still empty when the page renders?
Could anyone teach me how to do it?

Body:
You can't use async-await inside useEffect()

instead, you can use this.

and I edited some parts of your code.

function Profile() {
    const {userInfo} = useSelector(state => state.user);
    const [user, setUser] = React.useState({});
    async function populateUserInfo(){
       let user = {};
       const {data} = await axios.get("api/users/" + userInfo._id);
       setUser(data);
       console.log(data.shipping.address)
    }
    useEffect(() => {
        populateUserInfo();
    }, [])

    return <div>{user.shipping.address}</div>
}


问:
React Js Context Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
I am using React and request data from api, but it seems like my 'data' is getting error

My class as below:

```<code>class Login extends Component {
  constructor() {
    super();

this.state = {
  UserName: '',
  Password: '',
  var:'',
}
this.Login = this.Login.bind(this);

  }

  Login(event) {
    debugger;
    api.post('/api/login', {
      UserName: this.state.UserName,
      Password: this.state.Password,
    })
      .then((result) => {
        if (result.data.Status === 'Success') {
          this.setState({var: result.data.status});
          alert("User login Successfully");
        } else {
          alert('Invalid User');
        }
        debugger;
      })
  }
</code>```

I am trying to make a login.
After user make a request, I will get some data from api and setState my var

The error prompt that the my result.data.Success was error. I dig some research on stack overflow, it mentioned about the Arrow Function which I used. Or is it any snytax error?

答: I think that result.data.data.Status is the correct way. Or you can print it with console.log(), or debugger to see what format the result is</p>

Body:
I am using React and request data from api, but it seems like my 'data' is getting error

My class as below:

class Login extends Component {
  constructor() {
    super();

this.state = {
  UserName: '',
  Password: '',
  var:'',
}
this.Login = this.Login.bind(this);

  }

  Login(event) {
    debugger;
    api.post('/api/login', {
      UserName: this.state.UserName,
      Password: this.state.Password,
    })
      .then((result) => {
        if (result.data.Status === 'Success') {
          this.setState({var: result.data.status});
          alert("User login Successfully");
        } else {
          alert('Invalid User');
        }
        debugger;
      })
  }

I am trying to make a login.
After user make a request, I will get some data from api and setState my var

The error prompt that the my result.data.Success was error. I dig some research on stack overflow, it mentioned about the Arrow Function which I used. Or is it any snytax error?


问:
How do I retrieve the response.URL using Faraday gem?
I'm using Faraday to check for broken links, and I want to retrieve the response.URL of the links I'm querying, however, I am not able to find any documentation and examples to do so.

I was able to do this on the front-end using Javascript's Fetch API (Response.url: https://developer.mozilla.org/en-US/docs/Web/API/Response/url) but that is not an option now as I am required to do this on the backend using Faraday only.

Is this even possible with Faraday? If so, how do I implement it? Or kindly point me to the right documentation.

答:
There are lots of class variables instantiated in the response object: response.env
You might be looking at:

```<code>response.env.url.to_s
</code>```

Body:
There are lots of class variables instantiated in the response object: response.env
You might be looking at:

response.env.url.to_s


问:
Sort a list using awk (idiomatically)
I'm trying to arrange some entries in the Arch mkinitcpio.conf with awk.
I have come up with a working solution, but honestly it makes me kind of sick, so I wondered, there must be a better way to achieve something like this, right?

Basically there is a line somewhere in the file like this:

```<code>HOOKS=(base udev autodetect modconf block filesystems keyboard fsck)
</code>```

and I want to rearrange it so block and keyboard come before autodetect.

```<code>#! /usr/bin/awk -f
/^\s*HOOKS/ {
    start_list = index ($0, "(" ) + 1
    end_list = index ($0, ")" )
    l = end_list - start_list
    listo = substr($0, start_list, l)
    split(listo, arr, " ")
    j = 1
    for (i in arr)
    {
        if (arr[i] == "keyboard" || arr[i] == "block")
        { }
        else if (arr[i] != "autodetect")
            juck[j++] = arr[i]

        else
        {
            juck[j++] = "keyboard"
            juck[j++] = "block"
            juck[j++] = arr[i]
        }
    }
    for (k in juck)
        print juck[k]
}
</code>```

As per request in the comments: the desired result is a line like:

```<code>HOOKS=(base udev keyboard block autodetect modconf filesystems fsck)
</code>```

答:
something like this should work, also can be extended for more keywords

```<code>$ awk -v order="keyboard block autodetect" '
     BEGIN{n=split(order,o)}
     {gsub("[()]",FS)}
     {if($0 ~ FS o[n] FS)
        {for(i=1;i<n;i++)
          if($0 ~ FS o[i] FS)
           {sub(FS o[i] FS, FS)
            sub(FS o[n] FS, FS o[i] FS o[n] FS)}}}
     {sub("= ","=(")
      sub(/ $/,")")}1' hooks_line
</code>```

I didn't add guard against other types of input, but should work with the sample input and regardless of the previous keywords exist or not.

Title: Sort a list using awk (idiomatically)

Body:
I'm trying to arrange some entries in the Arch mkinitcpio.conf with awk.
I have come up with a working solution, but honestly it makes me kind of sick, so I wondered, there must be a better way to achieve something like this, right?

Basically there is a line somewhere in the file like this:

HOOKS=(base udev autodetect modconf block filesystems keyboard fsck)

and I want to rearrange it so block and keyboard come before autodetect.

#! /usr/bin/awk -f
/^\s*HOOKS/ {
    start_list = index ($0, "(" ) + 1
    end_list = index ($0, ")" )
    l = end_list - start_list
    listo = substr($0, start_list, l)
    split(listo, arr, " ")
    j = 1
    for (i in arr)
    {
        if (arr[i] == "keyboard" || arr[i] == "block")
        { }
        else if (arr[i] != "autodetect")
            juck[j++] = arr[i]

        else
        {
            juck[j++] = "keyboard"
            juck[j++] = "block"
            juck[j++] = arr[i]
        }
    }
    for (k in juck)
        print juck[k]
}

As per request in the comments: the desired result is a line like:

HOOKS=(base udev keyboard block autodetect modconf filesystems fsck)

Body:
something like this should work, also can be extended for more keywords

$ awk -v order="keyboard block autodetect" '
     BEGIN{n=split(order,o)}
     {gsub("[()]",FS)}
     {if($0 ~ FS o[n] FS)
        {for(i=1;i<n;i++)
          if($0 ~ FS o[i] FS)
           {sub(FS o[i] FS, FS)
            sub(FS o[n] FS, FS o[i] FS o[n] FS)}}}
     {sub("= ","=(")
      sub(/ $/,")")}1' hooks_line

I didn't add guard against other types of input, but should work with the sample input and regardless of the previous keywords exist or not.


问:
if cardNumberArray[0] == 4: IndexError: list index out of range
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

```<code>    if cardNumberArray[0] == 4:
    IndexError: list index out of range
</code>```

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

```<code>cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")
</code>```

答:
Your array is empty because you put the user's response on cardNumber variable.

Before using your Ifs, you must check if your array is not empty and if these indexes exist.

Body:
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

    if cardNumberArray[0] == 4:
    IndexError: list index out of range

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")


问:
Windows CE vs Embedded Linux
Now I'm sure we're all well aware of the relative merits of Linux vs Windows Desktop. However I've heard much less about the world of embedded development. I'm mainly interested in solutions for industry and am therefore uninterested about the IPhone or Android and more interested in these two OSes.

What are the relative trade-offs between the two platforms in the embedded world? If you were considering building a box for a specific project with custom hardware, a partially customised OS and a custom app then which would you choose and why?

I would assume that Windows CE wins on tools and Linux wins on both cost and possibly performance. However this is just utter speculation. Does anyone have any facts or experience of the two?

答:
With Linux you are never on you own and you are never dependent on one single entity to provide permissions. There are many support options and you have the freedom to choose your support options for any part of the system through many competing sources.

With Windows CE you must adhere to the license and restrictions as set forth in the complex license agreements that must be agreed to. Get a lawyer. With windows CE you have only one proprietary source for OS support and you will proceed only as they see fit to support and provide what you need. You may not agree with their position, but will not have any recourse but to bend to what they prescribe. The costs of incremental components, modules, development kits, licensing, and support tend to pile up with proprietary platforms. In the longer term, what happens when the vendor no longer desires to support the platform and you do not have the rights to support and distribute it yourself? What happens when the vendor moves to newer technology and wants you to move along with them even though you may not be ready to make the move? $$$

Our experience with Windows solutions in general is that they tend to become more expensive over time. What was originally considered lowest TCO gravitates quickly towards and solution that is encumbered and costly to maintain and support. Licenses have to be re-negotiated over time and the new technologies, often unneeded, are forced into the picture at the whim of the provider for the sake of THEIR business needs. On top of that, the license agreements are CONTINUALLY changing--get a lawyer.

With Linux you have the freedom to provide in-house support and expertise without being encumbered against distributing the solution as you need. You also have the freedom to continue to use and support technology that original providers no longer want to support. Having the source code and the RIGHTs to do with it what you want (GPL, LGPL) is a powerful attractor when it comes to business continuity and containing costs while providing access to the very latest technologies or technologies that fit your needs.

OwnerDisplayName: Quarrelsome

ContentLicense: CC BY-SA 2.5

Title: Windows CE vs Embedded Linux

LastEditorDisplayName: ctacke

ContentLicense: CC BY-SA 3.0


问:
How does Python ConfigParser Interpolate values with '${ }'?
I am following a youtube tutorial detailing how to create and read a .ini file with configparser.

In the tutorial, there is a files section like this:

```<code>[files]
images_path = /my_app/images
python_path=${settings:packages_path}/bin/python${settings:python_version}
</code>```

He is reading the data with these lines of code:

```<code>from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('dev.ini')
print(parser.get('files', 'python_path'))
</code>```

In his example, it prints out '/usr/local/bin/python3'

I am not able to replicate his example or able to figure out how it is working. I am able to grab other values from the config, but get this error when trying to grab python_path.

```<code>Traceback (most recent call last):
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/ticket_tracking_system/objects/config_file_read.py", line 12, in <module>
    print(x.getPythonPath())
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/ticket_tracking_system/objects/config_file_read.py", line 8, in getPythonPath
    return self.parser.get('files', 'python_path')
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 799, in get
    return self._interpolation.before_get(self, section, option, value,
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 456, in before_get
    self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 507, in _interpolate_some
    raise InterpolationMissingOptionError(
configparser.InterpolationMissingOptionError: Bad value substitution: option 'python_path' in section 'files' contains an interpolation key 'settings:packages_path' which is not a valid option name. Raw value: '${settings:packages_path}/bin/python${settings:python_version}'
</code>```

I am trying to understand how the ${settings.packages_path} value is being interpreted and where the is value coming from. If someone could please explain this or point me in the right direction, I would greatly appreciate it.

Thanks!

答:
As @wim posted in the comments, this value is coming from another section in the .ini file. You can access other values inside the file by using ${sectionName: optionName}.

This will only work if you pass ExtendedInterpolation class to ConfigParser.

```<code>from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
</code>```

Body:
I am following a youtube tutorial detailing how to create and read a .ini file with configparser.

In the tutorial, there is a files section like this:

[files]
images_path = /my_app/images
python_path=${settings:packages_path}/bin/python${settings:python_version}

He is reading the data with these lines of code:

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('dev.ini')
print(parser.get('files', 'python_path'))

In his example, it prints out '/usr/local/bin/python3'

I am not able to replicate his example or able to figure out how it is working. I am able to grab other values from the config, but get this error when trying to grab python_path.

Traceback (most recent call last):
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/ticket_tracking_system/objects/config_file_read.py", line 12, in <module>
    print(x.getPythonPath())
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/ticket_tracking_system/objects/config_file_read.py", line 8, in getPythonPath
    return self.parser.get('files', 'python_path')
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 799, in get
    return self._interpolation.before_get(self, section, option, value,
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 456, in before_get
    self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 507, in _interpolate_some
    raise InterpolationMissingOptionError(
configparser.InterpolationMissingOptionError: Bad value substitution: option 'python_path' in section 'files' contains an interpolation key 'settings:packages_path' which is not a valid option name. Raw value: '${settings:packages_path}/bin/python${settings:python_version}'

I am trying to understand how the ${settings.packages_path} value is being interpreted and where the is value coming from. If someone could please explain this or point me in the right direction, I would greatly appreciate it.

Thanks!

Body:
As @wim posted in the comments, this value is coming from another section in the .ini file. You can access other values inside the file by using ${sectionName: optionName}.

This will only work if you pass ExtendedInterpolation class to ConfigParser.

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())


问:
Restricting css selectors to one class without repeating the class name
I am looking for some way to not repeat a class name within css. For example if I have

.class1 div { color: red }
.class1 h2 { color: blue }
.class1 p { color: yellow }
```

<p>is there some way I can group the 3 rules under the one class, something like</p>

<pre class="lang-css prettyprint-override"><code>.class1 {
    div { color: red }
    h2 { color: blue }
    p { color: yellow }
}
</code>```

答: Rule nesting is not possible in CSS. You've to use SASS for this.</p>

Body:
I am looking for some way to not repeat a class name within css. For example if I have

.class1 div { color: red }
.class1 h2 { color: blue }
.class1 p { color: yellow }

is there some way I can group the 3 rules under the one class, something like

.class1 {
    div { color: red }
    h2 { color: blue }
    p { color: yellow }
}


问:
Logic Apps skip SQL new row trigger after I created SQL table
I have SQL item is created triggered and it worked fine for weeks.
There is SQL table with Id column, which primary key

Now I have removed table in SQL and recreated with same name. There is new one new column.

I have updated "Compose" in Logic Apps to add new column in compose json. Obviously LogicApps finds table and columns.

My problem is now that Logic Apps does not get triggered anymore even new row is created. Why???

答:
As far as I know, the new sql table can't trigger the logic although they have the same name just as Joel mentioned in the comment. Each sql table has its unique identity and when we create the trigger in logic app, the trigger will associates the table by the unique identity. So you need to re-create the trigger when you remove the table and re-create a table with same name.

But here provide a workaround which can help you simplify the steps, in this way we do not need to remove the trigger and create a new trigger in logic app. Please refer to the steps below:

1. After you delete the original table and create a new one with same table name, you can go to your logic app trigger and choose the "Enter custom value".

2. Then type any letters for the "Table name" such as "test" and click "Save" button(click "Save" button" is necessary).

3. After that, choose your sql table in the trigger again and click "Save" button.

Now, the trigger will associates to the new sql table. It will be triggered when an item is created in your sql table.

Hope it helps~


问:
Kotlin: open new Activity inside of a Fragment
How can I open a new Activity inside of a fragment when using a button?

I tried this

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    LogOut_btn.setOnClickListener {
        //FirebaseAuth.getInstance().signOut()
        val intent = Intent (this, Main::class.java)
        startActivity(intent)
    }
}
</code>```

val intent = Intent doesn't seem to work in a fragment.

Any idea how I can start a new activity inside a fragment?

答: FirebaseAuth.getInstance().signOut() before the intent.</p>

Body:
How can I open a new Activity inside of a fragment when using a button?

I tried this

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    LogOut_btn.setOnClickListener {
        //FirebaseAuth.getInstance().signOut()
        val intent = Intent (this, Main::class.java)
        startActivity(intent)
    }
}

val intent = Intent doesn't seem to work in a fragment.

Any idea how I can start a new activity inside a fragment?


问:
Using CSS :target with Javascript
Not sure if this can be done or not, but I'm banging my head trying to figure it out. So I have a pure CSS modal that utilizes :target to fire. However, I would like to use Javascript to add/remove a class to my Body when it is fired so I can prevent page scrolling behind the modal.

[data-am-modal] {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  z-index: 999;
  width: 0;
  height: 0;
  opacity: 0;
}
[data-am-modal]:target {
  width: auto;
  height: auto;
  opacity: 1;
  -webkit-transition: opacity 400ms ease;
  transition: opacity 400ms ease;
}
[data-am-modal]:target .modal-overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  cursor: default;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 1;
}
[data-am-modal] .modal-dialog {
  position: relative;
  width: calc(100% - 30px);
  max-width: 600px;
  margin: 15px auto;
  z-index: 2;
}
[data-am-modal] .modal-content {
  background-color: white;
  padding: 30px;
}
[data-am-modal] .modal-close {
  position: absolute;
  top: 15px;
  right: 15px;
}

/* Base Styling */
body {
  margin: 0;
  font-family: 'Open Sans', sans-serif;
}

.link {
  display: inline-block;
  padding: 15px;
  background-color: #1e91c7;
  color: #fff;
  border-radius: 5px;
  text-decoration: none;
}

```

<pre class="lang-html prettyprint-override"><code>Open Modal

<p>
filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>
</p>

<div data-am-modal id="modal-1">

    <div class="modal-dialog">
        <div class="modal-content">
            Close
            <h1>CSS Modal</h1>
            <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p> <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p> <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        </div>
    </div>
</div>
</code>```

https://jsfiddle.net/gpjcauye/6/

答:
You can listen to the hashchange event:

window.addEventListener('hashchange', (evt) =>
  document.body.classList.toggle('modal-on', location.hash === "#modal-1")
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal-on {
  color: green;
}

[data-am-modal] {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  z-index: 999;
  width: 0;
  height: 0;
  opacity: 0;
}

[data-am-modal]:target {
  width: auto;
  height: auto;
  opacity: 1;
  -webkit-transition: opacity 400ms ease;
  transition: opacity 400ms ease;
}

[data-am-modal]:target .modal-overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  cursor: default;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 1;
}

[data-am-modal] .modal-dialog {
  position: relative;
  width: calc(100% - 30px);
  max-width: 600px;
  margin: 15px auto;
  z-index: 2;
}

[data-am-modal] .modal-content {
  background-color: white;
  padding: 30px;
}

[data-am-modal] .modal-close {
  position: absolute;
  top: 15px;
  right: 15px;
}

/* Base Styling */

body {
  margin: 0;
  font-family: 'Open Sans', sans-serif;
}

.link {
  display: inline-block;
  padding: 15px;
  background-color: #1e91c7;
  color: #fff;
  border-radius: 5px;
  text-decoration: none;
}</code>```

Open Modal

  filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler
  text
filler text
filler text
filler text
filler text
filler text
filler text
filler text

      Close

CSS Modal

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

```

Title: Using CSS :target with Javascript

Body:
Not sure if this can be done or not, but I'm banging my head trying to figure it out. So I have a pure CSS modal that utilizes :target to fire. However, I would like to use Javascript to add/remove a class to my Body when it is fired so I can prevent page scrolling behind the modal.

[data-am-modal] {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  z-index: 999;
  width: 0;
  height: 0;
  opacity: 0;
}
[data-am-modal]:target {
  width: auto;
  height: auto;
  opacity: 1;
  -webkit-transition: opacity 400ms ease;
  transition: opacity 400ms ease;
}
[data-am-modal]:target .modal-overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  cursor: default;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 1;
}
[data-am-modal] .modal-dialog {
  position: relative;
  width: calc(100% - 30px);
  max-width: 600px;
  margin: 15px auto;
  z-index: 2;
}
[data-am-modal] .modal-content {
  background-color: white;
  padding: 30px;
}
[data-am-modal] .modal-close {
  position: absolute;
  top: 15px;
  right: 15px;
}

/* Base Styling */
body {
  margin: 0;
  font-family: 'Open Sans', sans-serif;
}

.link {
  display: inline-block;
  padding: 15px;
  background-color: #1e91c7;
  color: #fff;
  border-radius: 5px;
  text-decoration: none;
}

Open Modal

filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text
filler text

            Close

CSS Modal

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

https://jsfiddle.net/gpjcauye/6/

Body:
You can listen to the hashchange event:

window.addEventListener('hashchange', (evt) =>
  document.body.classList.toggle('modal-on', location.hash === "#modal-1")
);

.modal-on {
  color: green;
}

[data-am-modal] {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  z-index: 999;
  width: 0;
  height: 0;
  opacity: 0;
}

[data-am-modal]:target {
  width: auto;
  height: auto;
  opacity: 1;
  -webkit-transition: opacity 400ms ease;
  transition: opacity 400ms ease;
}

[data-am-modal]:target .modal-overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  cursor: default;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 1;
}

[data-am-modal] .modal-dialog {
  position: relative;
  width: calc(100% - 30px);
  max-width: 600px;
  margin: 15px auto;
  z-index: 2;
}

[data-am-modal] .modal-content {
  background-color: white;
  padding: 30px;
}

[data-am-modal] .modal-close {
  position: absolute;
  top: 15px;
  right: 15px;
}

/* Base Styling */

body {
  margin: 0;
  font-family: 'Open Sans', sans-serif;
}

.link {
  display: inline-block;
  padding: 15px;
  background-color: #1e91c7;
  color: #fff;
  border-radius: 5px;
  text-decoration: none;
}

<a href="#modal-1" class="link">Open Modal</a>

<p>
  filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler
  text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>filler text<br>
</p>

<div data-am-modal id="modal-1">
  <a href="#!" class="modal-overlay"></a>
  <div class="modal-dialog">
    <div class="modal-content">
      <a href="#!" class="modal-close">Close</a>
      <h1>CSS Modal</h1>
      <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
      <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
      <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
      <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
      <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
      <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
      <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
    </div>
  </div>
</div>


问:
How to add class to header element if its href is contained within window href?
My current code applies a class to the proper header element if its href is an indexOf the window.location.href

```<code>$(function() {
    $('.sidebar-links li.active').removeClass("active");
    $('.sidebar-links li a').filter(function(){
        return this.href.indexOf(window.location.href) !== -1;
            }).parent().addClass("active");
});
</code>```

An example header href would be

http://localhost:8090/website/jobs.php

If my window.location.href matches that exactly, it works great. The issue that I am running into is, if I click on something that produces a query string like

http://localhost:8090/website/jobs.php?info=54

Then refresh the page, the header element no longer has the class.
Is it possible to change the function so that if the header element's href  is contained within the window.location.href that it will add the class? Or without the query string at all?

http://localhost:8090/website/jobs.php

http://localhost:8090/website/jobs.php?info=54

答:
You can use window.location.href.split('?')[0] for a quick hack,

or https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

If you want a more fancy solution

$('.sidebar-links li.active').removeClass("active");
$('.sidebar-links li a').filter(function () {
    return this.href.indexOf(window.location.href.split('?')[0]) !== -1;
}).parent().addClass("active");
```

Body:
My current code applies a class to the proper header element if its href is an indexOf the window.location.href

$(function() {
    $('.sidebar-links li.active').removeClass("active");
    $('.sidebar-links li a').filter(function(){
        return this.href.indexOf(window.location.href) !== -1;
            }).parent().addClass("active");
});

An example header href would be

http://localhost:8090/website/jobs.php

If my window.location.href matches that exactly, it works great. The issue that I am running into is, if I click on something that produces a query string like

http://localhost:8090/website/jobs.php?info=54

Then refresh the page, the header element no longer has the class.
Is it possible to change the function so that if the header element's href  is contained within the window.location.href that it will add the class? Or without the query string at all?

http://localhost:8090/website/jobs.php

http://localhost:8090/website/jobs.php?info=54


问:
Empty List LXML XPATH
I'm having a problem, from the link provided (https://www.avisosdeocasion.com/Resultados-Inmuebles.aspx?n=venta-casas-nuevo-leon&PlazaBusqueda=2&Plaza=2.html) I'm trying to get the first information from every table ('2 plantas...3 plantas, etc.) but I'm receiving an empty lis from the code below:

```<code>from lxml import html
import requests
mark=2
page = requests.get('https://www.avisosdeocasion.com/Resultados-Inmuebles.aspx?n=venta-casas-nuevo-leon&PlazaBusqueda=2&Plaza=2.html')
tree = html.fromstring(page.content)
while mark<25:
    plantas=tree.xpath('//*[@id="divDetalleResultados"]/table/tbody/tr/td/table[mark]/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr[1]/td[1]/text()')
    mark=mark+1
print(plantas)
</code>```

Does someone knows how to fix this?

答:
You need to fix your XPath expression. Something like this should work :

```<code>from lxml import html
import requests
page = requests.get('https://www.avisosdeocasion.com/Resultados-Inmuebles.aspx?n=venta-casas-nuevo-leon&PlazaBusqueda=2&Plaza=2.html')
tree = html.fromstring(page.content)
plantas = tree.xpath('//td[contains(text(),"terreno")]/preceding-sibling::td/text()')
plantas2 = [item.strip() for item in plantas]
print(plantas2)
</code>```

Output :

```<code>['2 plantas', '3 plantas', '3 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '3 plantas', '2 plantas', '2 plantas']
</code>```

Title: Empty List LXML XPATH

Body:
I'm having a problem, from the link provided (https://www.avisosdeocasion.com/Resultados-Inmuebles.aspx?n=venta-casas-nuevo-leon&PlazaBusqueda=2&Plaza=2.html) I'm trying to get the first information from every table ('2 plantas...3 plantas, etc.) but I'm receiving an empty lis from the code below:

from lxml import html
import requests
mark=2
page = requests.get('https://www.avisosdeocasion.com/Resultados-Inmuebles.aspx?n=venta-casas-nuevo-leon&PlazaBusqueda=2&Plaza=2.html')
tree = html.fromstring(page.content)
while mark<25:
    plantas=tree.xpath('//*[@id="divDetalleResultados"]/table/tbody/tr/td/table[mark]/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr[1]/td[1]/text()')
    mark=mark+1
print(plantas)

Does someone knows how to fix this?

Body:
You need to fix your XPath expression. Something like this should work :

from lxml import html
import requests
page = requests.get('https://www.avisosdeocasion.com/Resultados-Inmuebles.aspx?n=venta-casas-nuevo-leon&PlazaBusqueda=2&Plaza=2.html')
tree = html.fromstring(page.content)
plantas = tree.xpath('//td[contains(text(),"terreno")]/preceding-sibling::td/text()')
plantas2 = [item.strip() for item in plantas]
print(plantas2)

Output :

['2 plantas', '3 plantas', '3 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '2 plantas', '3 plantas', '2 plantas', '2 plantas']


问:
How do you initialize values in SwiftUI before view is loaded?
I want to take say a stock price and then generate values within .05% in a 2D array.

I am passing the stock information such as stock name and stock price.

But when I try and run a method that creates the 2D array of values I am met with a "Cannot use instance member '' within property initializer; property initializers run before 'self' is available"

I was looking how to get around this.

Say Amazon stock is 2400. This data passes into the new view. What I want to do is create a 2D array of values near 2400, perhaps 2405 and 2395. I want a 2D array of these values generated in the new view. But I am getting an error that I cannot generate the values until the view is loaded, but I need them to generate the view.

I think I have to use init method but I am not sure how.

This is the line that is throwing the error above.

```<code>var new_prices = generateValues(price: position.stock_price)
</code>```

Here is the method

```<code>func generateValues(price: Double) -> [[Double]] {
    var values = [[Double]]()
     for x in 1...5 {
        values[0][x-1] = (price + price * 0.005 * Double(x))
    }
    return values
}
</code>```

This is what is being passed in the stock postion

```<code>struct Position : Identifiable {
    var id = UUID()
    var stock_name: String
    var stock_ticker: String
    var stock_price: Double
    var price_paid: Double

}
</code>```

Arguments passed throwing an error for no argument init().

```<code>struct PositionDetail_Previews: PreviewProvider {
    static var previews: some View {
        PositionDetail(position: Position(stock_name: "Amazon",
stock_ticker: "AMZN", stock_price : 2400, price_paid : 2300))
    }
}
</code>```

答:
This is how you call dynamic functions to initialize the current version of SwiftUI View data. (Note: no .init() needed):

```<code>import SwiftUI

struct Position : Identifiable {
    var id = UUID()
    var stock_name: String
    var stock_ticker: String
    var stock_price: Double
    var price_paid: Double
}

struct PositionDetail: View {
    var position: Position

    func generateValues(price: Double) -> [[Double]] {
        var values: [[Double]] = Array(repeating: Array(repeating: 0, count: 5), count: 1)

        for x in 1...5 {
            values[0][x-1] = (price + price * 0.005 * Double(x))
        }

        return values
    }

    var body: some View {
        let values   = generateValues(price: position.stock_price)

        return HStack {
            ForEach(values, id:\.self) { row in
                HStack {
                    ForEach(row, id: \.self) { value in
                        Text("\(value)")
                    }
                }
            }
        }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

struct PositionDetail_Previews: PreviewProvider {
    static var previews: some View {
        PositionDetail(position: Position(stock_name: "Amazon", stock_ticker: "AMZN", stock_price : 2400, price_paid : 2300))
    }
}
</code>```

Note: The generateValues function, as specified, was broken...

Body:
I want to take say a stock price and then generate values within .05% in a 2D array.

I am passing the stock information such as stock name and stock price.

But when I try and run a method that creates the 2D array of values I am met with a "Cannot use instance member '' within property initializer; property initializers run before 'self' is available"

I was looking how to get around this.

Say Amazon stock is 2400. This data passes into the new view. What I want to do is create a 2D array of values near 2400, perhaps 2405 and 2395. I want a 2D array of these values generated in the new view. But I am getting an error that I cannot generate the values until the view is loaded, but I need them to generate the view.

I think I have to use init method but I am not sure how.

This is the line that is throwing the error above.

var new_prices = generateValues(price: position.stock_price)

Here is the method

func generateValues(price: Double) -> [[Double]] {
    var values = [[Double]]()
     for x in 1...5 {
        values[0][x-1] = (price + price * 0.005 * Double(x))
    }
    return values
}

This is what is being passed in the stock postion

struct Position : Identifiable {
    var id = UUID()
    var stock_name: String
    var stock_ticker: String
    var stock_price: Double
    var price_paid: Double

}

Arguments passed throwing an error for no argument init().

struct PositionDetail_Previews: PreviewProvider {
    static var previews: some View {
        PositionDetail(position: Position(stock_name: "Amazon",
stock_ticker: "AMZN", stock_price : 2400, price_paid : 2300))
    }
}

Body:
This is how you call dynamic functions to initialize the current version of SwiftUI View data. (Note: no .init() needed):

import SwiftUI

struct Position : Identifiable {
    var id = UUID()
    var stock_name: String
    var stock_ticker: String
    var stock_price: Double
    var price_paid: Double
}

struct PositionDetail: View {
    var position: Position

    func generateValues(price: Double) -> [[Double]] {
        var values: [[Double]] = Array(repeating: Array(repeating: 0, count: 5), count: 1)

        for x in 1...5 {
            values[0][x-1] = (price + price * 0.005 * Double(x))
        }

        return values
    }

    var body: some View {
        let values   = generateValues(price: position.stock_price)

        return HStack {
            ForEach(values, id:\.self) { row in
                HStack {
                    ForEach(row, id: \.self) { value in
                        Text("\(value)")
                    }
                }
            }
        }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

struct PositionDetail_Previews: PreviewProvider {
    static var previews: some View {
        PositionDetail(position: Position(stock_name: "Amazon", stock_ticker: "AMZN", stock_price : 2400, price_paid : 2300))
    }
}

Note: The generateValues function, as specified, was broken...


问:
Get domain the server was reached over?
In general on any non-HTTP server. Would there be a way to detect what domain was used to reach the IP?

I know HTTP servers get the domain passed within the request header, but would this be possible with any other server that does not require this information to be received from the client?

I'm especially looking for a way to do this with the minecraft server (Bukkit) so my preferred language (if needed for you to answer) would be Java. But I'd like to not have the theories about this language specific.

答:
In general, no, which is why the HTTP protocol includes it in the headers.

In order to reach your server, first a DNS lookup is performed to resolve your IP, which is then followed by the connection itself. These two steps are separate, and hard to link together.

Logging what domain was last requested by a client is tricky, too, as DNS information is often cached, so the DNS request may not even reach your DNS server before being answered.

If it isn't cached, it also often isn't directly looked up by the end client, but rather by a caching DNS server operated, for instance, by the ISP.

Title: Get domain the server was reached over?


问:
TimePicker spinner mode change color of colon
I use TimePicker class with Spinner Mode. I was wondering if it would be possible to change the color of the colon between the NumberPickers.

I'm not looking for two independent NumberPickers and a TextView between them.

答:
If you take a look at the layout used for the spinner-style Material TimePicker, you'll see that the divider is a simple TextView:

```<code><TextView
    android:id="@+id/divider"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="6dip"
    android:layout_marginEnd="6dip"
    android:layout_gravity="center_vertical"
    android:importantForAccessibility="no" />
</code>```

A simple way to change it would be to create a style for your picker:

```<code><style name="MyPickerTheme" parent="Theme.MaterialComponents...">
    ...
    <item name="android:textColor">@color/myColor</item>
    ...
</style>
</code>```

After that, set the theme for your TimePicker:

```<code><TimePicker
    android:id="@+id/my_picker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MyPickerTheme"
    android:timePickerMode="spinner" />
</code>```

Body:
If you take a look at the layout used for the spinner-style Material TimePicker, you'll see that the divider is a simple TextView:

<TextView
    android:id="@+id/divider"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="6dip"
    android:layout_marginEnd="6dip"
    android:layout_gravity="center_vertical"
    android:importantForAccessibility="no" />

A simple way to change it would be to create a style for your picker:

<style name="MyPickerTheme" parent="Theme.MaterialComponents...">
    ...
    <item name="android:textColor">@color/myColor</item>
    ...
</style>

After that, set the theme for your TimePicker:

<TimePicker
    android:id="@+id/my_picker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MyPickerTheme"
    android:timePickerMode="spinner" />


问:
chrome said server's IP address could not be found
Im trying to browse my project in laravel using chrome

but chrome said server's IP address could not be found

Does anyone encounter the same problem?

I'm running a server on windows 10 with laragon
apache
mysql

答:
Try to flush DNS:</p>

```<code>ipconfig /release
ipconfig /renew
ipconfig /flushdns
</code>```

Body:
Try to flush DNS:

ipconfig /release
ipconfig /renew
ipconfig /flushdns


问:
Redirecting stdout to tkinter immediately (without waiting for the process to complete)
I am writing a python app to take some inputs from the user and call a shell script based on these inputs.

This shell script can run for quite sometime, and I want to redirect the output it produces (in realtime) to tkinter.
I managed to do that, but it only happens after the shell script is completely finished, not as soon as the shell script "echos" something for example.

So main problem:
1. Output appears in the text widget only after shellScript.sh is exited (although if I run the same in the terminal manually, I see continuous output).
2. Side problem: all the "\n" printed in the output are just printed as "\n" and no new lines are added in the text widget.

here is what I have:

```<code>class RedirectText(object):
   def __init__(self, text_ctrl):
       """Constructor"""
       self.output = text_ctrl

   def write(self, string):
       self.output.insert(tk.END, string[2:])

class Gui(GuiApp):
   def __init__(self, master=None):
      redir = RedirectText(self.text_Output)
      sys.stdout = redir

  def testRun(self, event=None):
     p = subprocess.Popen(["./shellScript.sh"], stdout=subprocess.PIPE)
     print(p.communicate()[0])
</code>```

答:
As p.communicate() will wait for the process to complete, so use p.poll() and p.stdout.readline() instead.  Also put the process in a thread to avoid blocking the main thread:

```<code>import threading
...
class Gui(GuiApp):
    ...
    def runScript(self):
        print('started')
        p = subprocess.Popen(['./shellScript.sh'], stdout=subprocess.PIPE, bufsize=1, text=True)
        while p.poll() is None: # check whether process is still running
            msg = p.stdout.readline().strip() # read a line from the process output
            if msg:
                print(msg)
        print('finished')

    def testRun(self, event=None):
        # create a thread to run the script
        threading.Thread(target=self.runScript, daemon=True).start()
</code>```

Body:
I am writing a python app to take some inputs from the user and call a shell script based on these inputs.

This shell script can run for quite sometime, and I want to redirect the output it produces (in realtime) to tkinter.
I managed to do that, but it only happens after the shell script is completely finished, not as soon as the shell script "echos" something for example.

So main problem:
1. Output appears in the text widget only after shellScript.sh is exited (although if I run the same in the terminal manually, I see continuous output).
2. Side problem: all the "\n" printed in the output are just printed as "\n" and no new lines are added in the text widget.

here is what I have:

class RedirectText(object):
   def __init__(self, text_ctrl):
       """Constructor"""
       self.output = text_ctrl

   def write(self, string):
       self.output.insert(tk.END, string[2:])

class Gui(GuiApp):
   def __init__(self, master=None):
      redir = RedirectText(self.text_Output)
      sys.stdout = redir

  def testRun(self, event=None):
     p = subprocess.Popen(["./shellScript.sh"], stdout=subprocess.PIPE)
     print(p.communicate()[0])

Body:
As p.communicate() will wait for the process to complete, so use p.poll() and p.stdout.readline() instead.  Also put the process in a thread to avoid blocking the main thread:

import threading
...
class Gui(GuiApp):
    ...
    def runScript(self):
        print('started')
        p = subprocess.Popen(['./shellScript.sh'], stdout=subprocess.PIPE, bufsize=1, text=True)
        while p.poll() is None: # check whether process is still running
            msg = p.stdout.readline().strip() # read a line from the process output
            if msg:
                print(msg)
        print('finished')

    def testRun(self, event=None):
        # create a thread to run the script
        threading.Thread(target=self.runScript, daemon=True).start()


问:
materializeCSS label is not working properly with React

The code inside the signing container something look like this

the label is not moving or getting hide after start typing in the text field

```<code> <div className="container">
            <form className="while" onSubmit={this.onSubmit}>
                <h5 className="grey-text text-darken-3"> Sign In</h5>
                <div className="input-field">
                    <label htmlFor="email">Email</label>
                    <input type="email" id="email" onChange={this.onChange} />
                </div>
                <div className="input-field">
                    <label htmlFor="password">Password</label>
                    <input type="password" id="password" onChange={this.onChange} />
                </div>
                <div className="input-field">
                    <button className="btn pink lighten-1 z-depth-0">Login</button>
                </div>
            </form>

        </div>
</code>```

答: Try adding class="active" to the label. it works for me!</p>

Body:
The code inside the signing container something look like this

the label is not moving or getting hide after start typing in the text field

            <form className="while" onSubmit={this.onSubmit}>

 Sign In

                    Email
                    <input type="email" id="email" onChange={this.onChange} />

                    Password
                    <input type="password" id="password" onChange={this.onChange} />

                    <button className="btn pink lighten-1 z-depth-0">Login</button>

            </form>


问:
What is wrong with the following for loop? It runs into syntax error
```<code>import openpyxl

wb = openpyxl.load_workbook('ISOQuestionnaire_Format (1).xlsx')
sheet = wb['Sheet1']

while True:
    row = 2
    column = 6
    a = sheet.cell(row = row + 1, column = column-2).value
    for a == None:
        print(sheet.cell(row,column).value)
        row+=1
</code>```

It shows syntax error at first line of for loop. What is wrong with it?

Error like:

```<code>File "xljson.py", line 11
   for a == None:
          ^
SyntaxError: invalid syntax
</code>```

答:
This statement:

```<code>    for a == None:
</code>```

is basically nonsensical.  A for in Python is supposed to iterate over something, and you haven't supplied an iterable.

I'm going to take a wild stab and guess that you might be aiming for something more like this...?

```<code>row = 2
column = 6
while True:
    a = sheet.cell(row = row + 1, column = column-2).value
    if a is None:
        break
    print(sheet.cell(row,column).value)
    row+=1
</code>```

Body:
import openpyxl

wb = openpyxl.load_workbook('ISOQuestionnaire_Format (1).xlsx')
sheet = wb['Sheet1']

while True:
    row = 2
    column = 6
    a = sheet.cell(row = row + 1, column = column-2).value
    for a == None:
        print(sheet.cell(row,column).value)
        row+=1

It shows syntax error at first line of for loop. What is wrong with it?

Error like:

File "xljson.py", line 11
   for a == None:
          ^
SyntaxError: invalid syntax

Body:
This statement:

    for a == None:

is basically nonsensical.  A for in Python is supposed to iterate over something, and you haven't supplied an iterable.

I'm going to take a wild stab and guess that you might be aiming for something more like this...?

row = 2
column = 6
while True:
    a = sheet.cell(row = row + 1, column = column-2).value
    if a is None:
        break
    print(sheet.cell(row,column).value)
    row+=1


问:
Master/detail (activity/fragment) layout, porting from Android to Codename One
I am porting my Android app to Codename One project, my immediate goal is to create an iOS version.

My app has a master/detail structure and has different layout when used on phones or tablets.

Indeed when the app runs on a tablet in landscape mode, it is possible to edit an element of the list with a fragment on the right, that is, the activity list is on the left while the editing happens on the right in the fragment.

When the app is in portrait mode, both on tablets and phones, the list is displayed.

On phones the editing happens in a separate activity, but the fragment is the same, just its layout is large as the activity's one.

I was suggested to have a look at the KitchenSink example. I see that its structure is master/detail but the layout is the same in both landscape and portrait mode, that is the list on the left and the "fragment" are both visible in both orientations.

I think it is not difficult to reproduce my app layout by customizing the KitchenSink layout and setting the size of the list and of the editing pane programmatically, according to the orientation and the control flow.

Is it the right path to follow or there is something similar to Android activity/fragment code that has to be followed?

答:
Codename One doesn't have an explicit master-detail abstraction since it doesn't really need it as much.

Kitchen sink is a bit simplistic and makes only the menu a part of the master detail. In your case you would just use a couple of Containers to represent the master and the detail. You can think of those as fragments but really they're just view groups in android terminology.

Here you can rely on code in the kitchen sink to implement this behavior for the form. When the form loads just write the logic you described similarly to the kitchen sink e.g.:

```<code>// I assume form has a BorderLayout and we have a static import of CN.*
if(isTablet() && !isPortrait()) {
   form.add(WEST, master);
   form.add(CENTER, detail);
} else {
   form.add(CENTER, master);
}

form.addOrientationListener(e -> {
   detail.remove();
   master.remove();
   findCommandComponent(
   if(isPortrait()) {
       form.add(CENTER, master);
   } else {
       form.add(CENTER, detail);
       form.add(WEST, master);
   }
   form.getContentPane().animateLayout(150);
});
</code>```

There's some logic here I removed e.g. for event handling/navigation but the gist of it is similar.

Also see related discussions here: How to structure the CN1 code for a tablet form layout?

Body:
Codename One doesn't have an explicit master-detail abstraction since it doesn't really need it as much.

Kitchen sink is a bit simplistic and makes only the menu a part of the master detail. In your case you would just use a couple of Containers to represent the master and the detail. You can think of those as fragments but really they're just view groups in android terminology.

Here you can rely on code in the kitchen sink to implement this behavior for the form. When the form loads just write the logic you described similarly to the kitchen sink e.g.:

// I assume form has a BorderLayout and we have a static import of CN.*
if(isTablet() && !isPortrait()) {
   form.add(WEST, master);
   form.add(CENTER, detail);
} else {
   form.add(CENTER, master);
}

form.addOrientationListener(e -> {
   detail.remove();
   master.remove();
   findCommandComponent(
   if(isPortrait()) {
       form.add(CENTER, master);
   } else {
       form.add(CENTER, detail);
       form.add(WEST, master);
   }
   form.getContentPane().animateLayout(150);
});

There's some logic here I removed e.g. for event handling/navigation but the gist of it is similar.

Also see related discussions here: How to structure the CN1 code for a tablet form layout?