问:
C - How scanf inputs work and how it iterates in loops?
I know the basics of scanf(); requiring a conversion specifier % and an address to the variable to store the input value &.

While doing an assignment, there was a task that involved inputting an arbitrary number of values, one example would be:
5 4 3 2 1

Into scanf, and then print out number of symbols corresponding to the integer typed (eg. '?'), so it would display the terminal as:

```<code>5 4 3 2 1
?????
????
???
??
?
</code>```

In this case I had put the scanf in a while loop as so:

```<code>int i, num;
while(scanf("%d",&num)==1){
   printf("%d",num);
   for (i=0; i<num; i++){
      printf("?");
   }
   printf("/n");
}
</code>```

I am totally confused how scanf reads multiple integers in one input line (5 4 3 2 1) when many sources has specified that scanf only takes one integer until it reads a whitespace. From looking at this, my understanding is that the whitespace separating the integers indicate a new iteration following the previous integer?
When I tried to trace how printing works, it printed as:

```<code>5 4 3 2 1
5?????
4????
3???
2??
1?
</code>```

...So my question is how does scanf 'save' all these integers in one line to 'num' and print EACH of the corresponding symbols to the values given AFTER input? Wouldn't integers be replacing the previous in the variable without an array?

Sorry if this question does not make sense - still quite new to coding. Thank you!

答:
Your understanding of scanf is true, scanf only takes one integer until it reads a whitespace.

What makes you confused here is how the algorithm works. Your algorithm first reads the integer 5 and prints "immediately" five ?. It continues to read 4, print four ?, read 3, print three ?, and so on.

Body:
I know the basics of scanf(); requiring a conversion specifier % and an address to the variable to store the input value &.

While doing an assignment, there was a task that involved inputting an arbitrary number of values, one example would be:
5 4 3 2 1

Into scanf, and then print out number of symbols corresponding to the integer typed (eg. '?'), so it would display the terminal as:

5 4 3 2 1
?????
????
???
??
?

In this case I had put the scanf in a while loop as so:

int i, num;
while(scanf("%d",&num)==1){
   printf("%d",num);
   for (i=0; i<num; i++){
      printf("?");
   }
   printf("/n");
}

I am totally confused how scanf reads multiple integers in one input line (5 4 3 2 1) when many sources has specified that scanf only takes one integer until it reads a whitespace. From looking at this, my understanding is that the whitespace separating the integers indicate a new iteration following the previous integer?
When I tried to trace how printing works, it printed as:

5 4 3 2 1
5?????
4????
3???
2??
1?

...So my question is how does scanf 'save' all these integers in one line to 'num' and print EACH of the corresponding symbols to the values given AFTER input? Wouldn't integers be replacing the previous in the variable without an array?

Sorry if this question does not make sense - still quite new to coding. Thank you!


来源: stackexchange

问:
UWP Manifest issue / restricted capability / inputForegroundObservation
I'm trying to follow this StackOverflow article, referring to this similar article on StackOverflow, and this from the UWP Windows Dev Center.

In my manifest XML, the <Package> tag was updated to include xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" and also IgnorableNamespaces="uap mp wincap rescap".

My <Capabilities> section looks like this:

<Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="inputForegroundObservation" />
  </Capabilities>

And <rescap:Capability is underlined with error:

"The element 'Capabilities'... has invalid child element...in...namespace.../windows10/restrictedcapabilities..."

(I snipped away much of the very long error message)

Any advice on how I can get the inputForegroundObservation Capability recognized?  VS Community 2015 sp3, Microsoft.NETCore.UniversalWindowsPlatform package installed.

Cheers,
Adam

答:
For Visual Studio 2019. The order is also important. I was putting the rescap:Capability last and kept getting the build error. It works if it's first, before other capabilities

From https://learn.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations#restricted-capabilities

All restricted capability elements must come before any CustomCapability and DeviceCapability elements under the Capabilities node in the package manifest.

For example

```<code><Package  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"

...
    <Capabilities>
        <rescap:Capability Name="extendedBackgroundTaskTime"/>
        <Capability Name="internetClient" />
        <DeviceCapability Name="location"/>
    </Capabilities>
</Package>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For Visual Studio 2019. The order is also important. I was putting the rescap:Capability last and kept getting the build error. It works if it's first, before other capabilities

From https://learn.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations#restricted-capabilities

All restricted capability elements must come before any CustomCapability and DeviceCapability elements under the Capabilities node in the package manifest.

For example

<Package  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"

...
    <Capabilities>
        <rescap:Capability Name="extendedBackgroundTaskTime"/>
        <Capability Name="internetClient" />
        <DeviceCapability Name="location"/>
    </Capabilities>
</Package>

ContentLicense: CC BY-SA 4.0


问:
xamarin: difference between Device.BeginInvokeOnMainThread and MainThread.BeginInvokeOnMainThread
I create a same custom controls, in some of them I use Device.BeginInvokeOnMainThread but in but sometimes it throws an error:

System.NullReferenceException: Object reference not set to an instance
  of an object

this error occurs when immediately after reading Device.BeginInvokeOnMainThread, but if I replace it with MainThread.BeginInvokeOnMainThread works ok.

The section code if this:

```<code>public class EntryRoundPassword : RelativeLayout
    {
             public EntryRoundPassword() : base()
            {
                  // throws an error
                  Device.BeginInvokeOnMainThread(() =>
                  {
                      ......
                  });

                   //works ok
                   MainThread.BeginInvokeOnMainThread(() =>
                   {
                      .....
                   });
            }
    }
</code>```

What is the difference between them, because one throws an error and the other does not ?

答: MainThread is part of Essentials, and is the newer implementation.  The Device implementation will eventually be deprecated.  If you want to know the specific implementation differences, you can check the source code

Body:
I create a same custom controls, in some of them I use Device.BeginInvokeOnMainThread but in but sometimes it throws an error:

System.NullReferenceException: Object reference not set to an instance
  of an object

this error occurs when immediately after reading Device.BeginInvokeOnMainThread, but if I replace it with MainThread.BeginInvokeOnMainThread works ok.

The section code if this:

public class EntryRoundPassword : RelativeLayout
    {
             public EntryRoundPassword() : base()
            {
                  // throws an error
                  Device.BeginInvokeOnMainThread(() =>
                  {
                      ......
                  });

                   //works ok
                   MainThread.BeginInvokeOnMainThread(() =>
                   {
                      .....
                   });
            }
    }

What is the difference between them, because one throws an error and the other does not ?


问:
RMarkdown: ggplot into a table
There are already a few questions considering ggplots in RMarkdown but none has answered my question as how to put a ggplot into a table with kable() by knitr.
I ve tried this link:

How can I embed a plot within a RMarkdown table?

But have not had any luck so far. Any ideas?

The idea was to put all plots into a list with

a<-list(p1,p2,p3...)

and then having the table with

{r}kable(a)

Additional text should also be able to be included

```<code>b<-("x","y","z",...)
kable (c(a,b),col.names=c())
</code>```

Thanks for your help

Frieder

答:
I experimented some with this and the following is the best I could come up with. This is a complete markdown document you should be able to paste into RStudio and hit the Knit button.

Two relevant notes here.

Setting the file links directly into kable doesn't work as it is wrapped in html such that it is interpreted as text, so we need to gsub() it in. An alternative is to set kable(..., escape = FALSE), but it is a risk that other text might cause problems.

Also, the chunk option results = 'asis' is necessary to have the print(kab) return raw html.

I don't know if these are problems for the real application.

```<code>---
title: "Untitled"
author: "me"
date: "02/06/2020"
output: html_document
---

```{r, results = 'asis'}
library(ggplot2)
library(svglite)

n <- length(unique(iris$Species))
data <- split(iris, iris$Species)

# Create list of plots
plots <- lapply(data, function(df) {
  ggplot(df, aes(Sepal.Width, Sepal.Length)) +
    geom_point()
})

# Create temporary files
tmpfiles <- replicate(n, tempfile(fileext = ".svg"))

# Save plots as files, get HTML links
links <- mapply(function(plot, file) {
  # Suit exact dimensions to your needs
  ggsave(file, plot, device = "svg", width = 4, height = 3)
  paste0('

')
}, plot = plots, file = tmpfiles)

# Table formatting
tab <- data.frame(name = names(plots), fig = paste0("dummy", LETTERS[seq_len(n)]))
kab <- knitr::kable(tab, "html")

# Substitute dummy column for figure links
for (i in seq_len(n)) {
  kab <- gsub(paste0("dummy", LETTERS[i]), links[i], kab, fixed = TRUE)
}
print(kab)
```
</code>```

Title: RMarkdown: ggplot into a table

Body:
There are already a few questions considering ggplots in RMarkdown but none has answered my question as how to put a ggplot into a table with kable() by knitr.
I ve tried this link:

How can I embed a plot within a RMarkdown table?

But have not had any luck so far. Any ideas?

The idea was to put all plots into a list with

a<-list(p1,p2,p3...)

and then having the table with

{r}kable(a)

Additional text should also be able to be included

b<-("x","y","z",...)
kable (c(a,b),col.names=c())

Thanks for your help

Frieder

Body:
I experimented some with this and the following is the best I could come up with. This is a complete markdown document you should be able to paste into RStudio and hit the Knit button.

Two relevant notes here.

Setting the file links directly into kable doesn't work as it is wrapped in html such that it is interpreted as text, so we need to gsub() it in. An alternative is to set kable(..., escape = FALSE), but it is a risk that other text might cause problems.

Also, the chunk option results = 'asis' is necessary to have the print(kab) return raw html.

I don't know if these are problems for the real application.

---
title: "Untitled"
author: "me"
date: "02/06/2020"
output: html_document
---

```{r, results = 'asis'}
library(ggplot2)
library(svglite)

n <- length(unique(iris$Species))
data <- split(iris, iris$Species)

# Create list of plots
plots <- lapply(data, function(df) {
  ggplot(df, aes(Sepal.Width, Sepal.Length)) +
    geom_point()
})

# Create temporary files
tmpfiles <- replicate(n, tempfile(fileext = ".svg"))

# Save plots as files, get HTML links
links <- mapply(function(plot, file) {
  # Suit exact dimensions to your needs
  ggsave(file, plot, device = "svg", width = 4, height = 3)
  paste0('<figure><img src="', file, '" style = "width:100%"></figure>')
}, plot = plots, file = tmpfiles)

# Table formatting
tab <- data.frame(name = names(plots), fig = paste0("dummy", LETTERS[seq_len(n)]))
kab <- knitr::kable(tab, "html")

# Substitute dummy column for figure links
for (i in seq_len(n)) {
  kab <- gsub(paste0("dummy", LETTERS[i]), links[i], kab, fixed = TRUE)
}
print(kab)
```


问:
App to run on startup for all users, but needs admin to close
I'm trying to build an application that would run on startup for all users, but non-admin users shouldn't be able to close it. I apologize if this has been answered, but I cannot find the answer even after googling it.</p>

答:
Sounds like it is a system level process, that is only marginally controlable by the Administrator. Controling System processes is one of the Admin tasks.

The two ways to start something with Windows are:

Make it a service. However do note that services operate under severe limitations, like not be able to create GUI themself. If you want to have any UI, you have to use a seperate process that talks with the service with IPC.

Have the Windows Task Sheduler start it on Windows Startup, using the Admin Account. The sheduler has replaced services in many cases, even for builtin processes like the automatic defragmentation.


问:
how to record .wav format file in android
I would like to record .wav files using android. is there any way to do this?</p>

答:
You have to use AudioRecord class and write the wav header data by yourself.
This code should include all you need.</p>
```<code>class WavRecorder(val context: Context) {
    private var recorder: AudioRecord? = null
    private var isRecording = false

    private var recordingThread: Thread? = null

    fun startRecording(_filename: String? = null, internalStorage: Boolean = false) {
        val filename = _filename ?: "recording-${System.currentTimeMillis()}.wav"

        val path = if (internalStorage) context.filesDir?.path + "/$filename"
        else context.externalCacheDir?.path + "/$filename"

        recorder = AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLE_RATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, 512)

        recorder?.startRecording()
        isRecording = true

        recordingThread = thread(true) {
            writeAudioDataToFile(path)
        }
    }

    fun stopRecording() {
        recorder?.run {
            isRecording = false;
            stop()
            release()
            recordingThread = null
            recorder = null
        }
    }

    private fun short2byte(sData: ShortArray): ByteArray {
        val arrSize = sData.size
        val bytes = ByteArray(arrSize * 2)
        for (i in 0 until arrSize) {
            bytes[i * 2] = (sData[i] and 0x00FF).toByte()
            bytes[i * 2 + 1] = (sData[i].toInt() shr 8).toByte()
            sData[i] = 0
        }
        return bytes
    }

    private fun writeAudioDataToFile(path: String) {
        val sData = ShortArray(BufferElements2Rec)
        var os: FileOutputStream? = null
        try {
            os = FileOutputStream(path)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        val data = arrayListOf<Byte>()

        for (byte in wavFileHeader()) {
            data.add(byte)
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format
            recorder?.read(sData, 0, BufferElements2Rec)
            try {
                val bData = short2byte(sData)
                for (byte in bData)
                    data.add(byte)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        updateHeaderInformation(data)

        os?.write(data.toByteArray())

        try {
            os?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * Constructs header for wav file format
     */
    private fun wavFileHeader(): ByteArray {
        val headerSize = 44
        val header = ByteArray(headerSize)

        header[0] = 'R'.toByte() // RIFF/WAVE header
        header[1] = 'I'.toByte()
        header[2] = 'F'.toByte()
        header[3] = 'F'.toByte()

        header[4] = (0 and 0xff).toByte() // Size of the overall file, 0 because unknown
        header[5] = (0 shr 8 and 0xff).toByte()
        header[6] = (0 shr 16 and 0xff).toByte()
        header[7] = (0 shr 24 and 0xff).toByte()

        header[8] = 'W'.toByte()
        header[9] = 'A'.toByte()
        header[10] = 'V'.toByte()
        header[11] = 'E'.toByte()

        header[12] = 'f'.toByte() // 'fmt ' chunk
        header[13] = 'm'.toByte()
        header[14] = 't'.toByte()
        header[15] = ' '.toByte()

        header[16] = 16 // Length of format data
        header[17] = 0
        header[18] = 0
        header[19] = 0

        header[20] = 1 // Type of format (1 is PCM)
        header[21] = 0

        header[22] = NUMBER_CHANNELS.toByte()
        header[23] = 0

        header[24] = (RECORDER_SAMPLE_RATE and 0xff).toByte() // Sampling rate
        header[25] = (RECORDER_SAMPLE_RATE shr 8 and 0xff).toByte()
        header[26] = (RECORDER_SAMPLE_RATE shr 16 and 0xff).toByte()
        header[27] = (RECORDER_SAMPLE_RATE shr 24 and 0xff).toByte()

        header[28] = (BYTE_RATE and 0xff).toByte() // Byte rate = (Sample Rate * BitsPerSample * Channels) / 8
        header[29] = (BYTE_RATE shr 8 and 0xff).toByte()
        header[30] = (BYTE_RATE shr 16 and 0xff).toByte()
        header[31] = (BYTE_RATE shr 24 and 0xff).toByte()

        header[32] = (NUMBER_CHANNELS * BITS_PER_SAMPLE / 8).toByte() //  16 Bits stereo
        header[33] = 0

        header[34] = BITS_PER_SAMPLE.toByte() // Bits per sample
        header[35] = 0

        header[36] = 'd'.toByte()
        header[37] = 'a'.toByte()
        header[38] = 't'.toByte()
        header[39] = 'a'.toByte()

        header[40] = (0 and 0xff).toByte() // Size of the data section.
        header[41] = (0 shr 8 and 0xff).toByte()
        header[42] = (0 shr 16 and 0xff).toByte()
        header[43] = (0 shr 24 and 0xff).toByte()

        return header
    }

    private fun updateHeaderInformation(data: ArrayList<Byte>) {
        val fileSize = data.size
        val contentSize = fileSize - 44

        data[4] = (fileSize and 0xff).toByte() // Size of the overall file
        data[5] = (fileSize shr 8 and 0xff).toByte()
        data[6] = (fileSize shr 16 and 0xff).toByte()
        data[7] = (fileSize shr 24 and 0xff).toByte()

        data[40] = (contentSize and 0xff).toByte() // Size of the data section.
        data[41] = (contentSize shr 8 and 0xff).toByte()
        data[42] = (contentSize shr 16 and 0xff).toByte()
        data[43] = (contentSize shr 24 and 0xff).toByte()
    }

    companion object {
        const val RECORDER_SAMPLE_RATE = 8000
        const val RECORDER_CHANNELS: Int = android.media.AudioFormat.CHANNEL_IN_MONO
        const val RECORDER_AUDIO_ENCODING: Int = android.media.AudioFormat.ENCODING_PCM_16BIT
        const val BITS_PER_SAMPLE: Short = 16
        const val NUMBER_CHANNELS: Short = 1
        const val BYTE_RATE = RECORDER_SAMPLE_RATE * NUMBER_CHANNELS * 16 / 8

        var BufferElements2Rec = 1024
    }
}
</code>```

Body:
You have to use AudioRecord class and write the wav header data by yourself.
This code should include all you need.

class WavRecorder(val context: Context) {
    private var recorder: AudioRecord? = null
    private var isRecording = false

    private var recordingThread: Thread? = null

    fun startRecording(_filename: String? = null, internalStorage: Boolean = false) {
        val filename = _filename ?: "recording-${System.currentTimeMillis()}.wav"

        val path = if (internalStorage) context.filesDir?.path + "/$filename"
        else context.externalCacheDir?.path + "/$filename"

        recorder = AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLE_RATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, 512)

        recorder?.startRecording()
        isRecording = true

        recordingThread = thread(true) {
            writeAudioDataToFile(path)
        }
    }

    fun stopRecording() {
        recorder?.run {
            isRecording = false;
            stop()
            release()
            recordingThread = null
            recorder = null
        }
    }

    private fun short2byte(sData: ShortArray): ByteArray {
        val arrSize = sData.size
        val bytes = ByteArray(arrSize * 2)
        for (i in 0 until arrSize) {
            bytes[i * 2] = (sData[i] and 0x00FF).toByte()
            bytes[i * 2 + 1] = (sData[i].toInt() shr 8).toByte()
            sData[i] = 0
        }
        return bytes
    }

    private fun writeAudioDataToFile(path: String) {
        val sData = ShortArray(BufferElements2Rec)
        var os: FileOutputStream? = null
        try {
            os = FileOutputStream(path)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        val data = arrayListOf<Byte>()

        for (byte in wavFileHeader()) {
            data.add(byte)
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format
            recorder?.read(sData, 0, BufferElements2Rec)
            try {
                val bData = short2byte(sData)
                for (byte in bData)
                    data.add(byte)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        updateHeaderInformation(data)

        os?.write(data.toByteArray())

        try {
            os?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * Constructs header for wav file format
     */
    private fun wavFileHeader(): ByteArray {
        val headerSize = 44
        val header = ByteArray(headerSize)

        header[0] = 'R'.toByte() // RIFF/WAVE header
        header[1] = 'I'.toByte()
        header[2] = 'F'.toByte()
        header[3] = 'F'.toByte()

        header[4] = (0 and 0xff).toByte() // Size of the overall file, 0 because unknown
        header[5] = (0 shr 8 and 0xff).toByte()
        header[6] = (0 shr 16 and 0xff).toByte()
        header[7] = (0 shr 24 and 0xff).toByte()

        header[8] = 'W'.toByte()
        header[9] = 'A'.toByte()
        header[10] = 'V'.toByte()
        header[11] = 'E'.toByte()

        header[12] = 'f'.toByte() // 'fmt ' chunk
        header[13] = 'm'.toByte()
        header[14] = 't'.toByte()
        header[15] = ' '.toByte()

        header[16] = 16 // Length of format data
        header[17] = 0
        header[18] = 0
        header[19] = 0

        header[20] = 1 // Type of format (1 is PCM)
        header[21] = 0

        header[22] = NUMBER_CHANNELS.toByte()
        header[23] = 0

        header[24] = (RECORDER_SAMPLE_RATE and 0xff).toByte() // Sampling rate
        header[25] = (RECORDER_SAMPLE_RATE shr 8 and 0xff).toByte()
        header[26] = (RECORDER_SAMPLE_RATE shr 16 and 0xff).toByte()
        header[27] = (RECORDER_SAMPLE_RATE shr 24 and 0xff).toByte()

        header[28] = (BYTE_RATE and 0xff).toByte() // Byte rate = (Sample Rate * BitsPerSample * Channels) / 8
        header[29] = (BYTE_RATE shr 8 and 0xff).toByte()
        header[30] = (BYTE_RATE shr 16 and 0xff).toByte()
        header[31] = (BYTE_RATE shr 24 and 0xff).toByte()

        header[32] = (NUMBER_CHANNELS * BITS_PER_SAMPLE / 8).toByte() //  16 Bits stereo
        header[33] = 0

        header[34] = BITS_PER_SAMPLE.toByte() // Bits per sample
        header[35] = 0

        header[36] = 'd'.toByte()
        header[37] = 'a'.toByte()
        header[38] = 't'.toByte()
        header[39] = 'a'.toByte()

        header[40] = (0 and 0xff).toByte() // Size of the data section.
        header[41] = (0 shr 8 and 0xff).toByte()
        header[42] = (0 shr 16 and 0xff).toByte()
        header[43] = (0 shr 24 and 0xff).toByte()

        return header
    }

    private fun updateHeaderInformation(data: ArrayList<Byte>) {
        val fileSize = data.size
        val contentSize = fileSize - 44

        data[4] = (fileSize and 0xff).toByte() // Size of the overall file
        data[5] = (fileSize shr 8 and 0xff).toByte()
        data[6] = (fileSize shr 16 and 0xff).toByte()
        data[7] = (fileSize shr 24 and 0xff).toByte()

        data[40] = (contentSize and 0xff).toByte() // Size of the data section.
        data[41] = (contentSize shr 8 and 0xff).toByte()
        data[42] = (contentSize shr 16 and 0xff).toByte()
        data[43] = (contentSize shr 24 and 0xff).toByte()
    }

    companion object {
        const val RECORDER_SAMPLE_RATE = 8000
        const val RECORDER_CHANNELS: Int = android.media.AudioFormat.CHANNEL_IN_MONO
        const val RECORDER_AUDIO_ENCODING: Int = android.media.AudioFormat.ENCODING_PCM_16BIT
        const val BITS_PER_SAMPLE: Short = 16
        const val NUMBER_CHANNELS: Short = 1
        const val BYTE_RATE = RECORDER_SAMPLE_RATE * NUMBER_CHANNELS * 16 / 8

        var BufferElements2Rec = 1024
    }
}


问:
Android Kotlin: Getting a FileNotFoundException with filename chosen from file picker?
I'm working on an Android application where one of the features is to let the user choose a file to open (I'm wanting to open a plain text .txt file).  I've worked on Android apps before with Java, but for this one, I'm using Kotlin, and it's my first time using Kotlin.

I currently have the app display a file chooser and let the user tap the file they want to open.  Then I'm trying to use a File object to open the file and do a forEachLine loop.  But for some reason, it's throwing a java.io.FileNotFoundException (No such file or directory) with the file chosen from the file picker.  I'm not sure what's wrong, and if I have to do some conversion to convert the file path?

The code for my 'load' button:

```<code>val btn_load: Button = findViewById<Button>(R.id.btn_load_puzzle)
    btn_load.setOnClickListener {
        val intent = Intent()
            .setType("*/*")
            .setAction(Intent.ACTION_GET_CONTENT)

        startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
    }
</code>```

My function to respond to the file selection:

```<code>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // Selected a file to load
    if ((requestCode == 111) && (resultCode == RESULT_OK)) {
        val selectedFilename = data?.data //The uri with the location of the file
        if (selectedFilename != null) {
            val filenameURIStr = selectedFilename.toString()
            if (filenameURIStr.endsWith(".txt", true)) {
                val msg = "Chosen file: " + filenameURIStr
                val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT)
                toast.show()
                File(selectedFilename.getPath()).forEachLine {
                    val toast = Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT)
                    toast.show()
                }
            }
            else {
                val msg = "The chosen file is not a .txt file!"
                val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
                toast.show()
            }
        }
        else {
            val msg = "Null filename data received!"
            val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
            toast.show()
        }
    }
}
</code>```

The FileNotFound exception is thrown on the line where it creates the File object to do the forEachLine loop:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=111, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/0000-0000:Sudoku puzzles/hard001.txt flg=0x1 }} to activity {com.example.sudokusolver/com.example.sudokusolver.MainActivity}: java.io.FileNotFoundException: /document/0000-0000:Sudoku puzzles/hard001.txt (No such file or directory)

答:
If you are getting "msf:xxx" in URI, use below solution where I have created temp file in app cache directory and deleted same file after completion of my task:

```<code>if (id != null && id.startsWith("msf:")) {
                    final File file = new File(mContext.getCacheDir(), Constant.TEMP_FILE + Objects.requireNonNull(mContext.getContentResolver().getType(imageUri)).split("/")[1]);
                    try (final InputStream inputStream = mContext.getContentResolver().openInputStream(imageUri); OutputStream output = new FileOutputStream(file)) {
                        final byte[] buffer = new byte[4 * 1024]; // or other buffer size
                        int read;

                        while ((read = inputStream.read(buffer)) != -1) {
                            output.write(buffer, 0, read);
                        }

                        output.flush();
                        return file;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    return null;
                }
</code>```

I have fixed this issue and it's working 100% for msf. :)

Also Delete the temp file after the completion of your work:

```<code>private void deleteTempFile() {
        final File[] files = requireContext().getCacheDir().listFiles();
        if (files != null) {
            for (final File file : files) {
                if (file.getName().contains(Constant.TEMP_FILE)) {
                    file.delete();
                }
            }
        }
    }
</code>```

Here TEMP_FILE value is "temp."

Body:
I'm working on an Android application where one of the features is to let the user choose a file to open (I'm wanting to open a plain text .txt file).  I've worked on Android apps before with Java, but for this one, I'm using Kotlin, and it's my first time using Kotlin.

I currently have the app display a file chooser and let the user tap the file they want to open.  Then I'm trying to use a File object to open the file and do a forEachLine loop.  But for some reason, it's throwing a java.io.FileNotFoundException (No such file or directory) with the file chosen from the file picker.  I'm not sure what's wrong, and if I have to do some conversion to convert the file path?

The code for my 'load' button:

val btn_load: Button = findViewById<Button>(R.id.btn_load_puzzle)
    btn_load.setOnClickListener {
        val intent = Intent()
            .setType("*/*")
            .setAction(Intent.ACTION_GET_CONTENT)

        startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
    }

My function to respond to the file selection:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // Selected a file to load
    if ((requestCode == 111) && (resultCode == RESULT_OK)) {
        val selectedFilename = data?.data //The uri with the location of the file
        if (selectedFilename != null) {
            val filenameURIStr = selectedFilename.toString()
            if (filenameURIStr.endsWith(".txt", true)) {
                val msg = "Chosen file: " + filenameURIStr
                val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT)
                toast.show()
                File(selectedFilename.getPath()).forEachLine {
                    val toast = Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT)
                    toast.show()
                }
            }
            else {
                val msg = "The chosen file is not a .txt file!"
                val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
                toast.show()
            }
        }
        else {
            val msg = "Null filename data received!"
            val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
            toast.show()
        }
    }
}

The FileNotFound exception is thrown on the line where it creates the File object to do the forEachLine loop:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=111, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/0000-0000:Sudoku puzzles/hard001.txt flg=0x1 }} to activity {com.example.sudokusolver/com.example.sudokusolver.MainActivity}: java.io.FileNotFoundException: /document/0000-0000:Sudoku puzzles/hard001.txt (No such file or directory)

Body:
If you are getting "msf:xxx" in URI, use below solution where I have created temp file in app cache directory and deleted same file after completion of my task:

if (id != null && id.startsWith("msf:")) {
                    final File file = new File(mContext.getCacheDir(), Constant.TEMP_FILE + Objects.requireNonNull(mContext.getContentResolver().getType(imageUri)).split("/")[1]);
                    try (final InputStream inputStream = mContext.getContentResolver().openInputStream(imageUri); OutputStream output = new FileOutputStream(file)) {
                        final byte[] buffer = new byte[4 * 1024]; // or other buffer size
                        int read;

                        while ((read = inputStream.read(buffer)) != -1) {
                            output.write(buffer, 0, read);
                        }

                        output.flush();
                        return file;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    return null;
                }

I have fixed this issue and it's working 100% for msf. :)

Also Delete the temp file after the completion of your work:

private void deleteTempFile() {
        final File[] files = requireContext().getCacheDir().listFiles();
        if (files != null) {
            for (final File file : files) {
                if (file.getName().contains(Constant.TEMP_FILE)) {
                    file.delete();
                }
            }
        }
    }

Here TEMP_FILE value is "temp."


问:
Google Smart Home - TemperatureSetting Temperature Range not working
I made a google Smart Home able to control a water heater pump with google smarthome touch control. What it need to control is desired temperature and mode (on off).

I was not able to make that work with the "heater" device so instead I use the "thermostat" device.

Everything work except one thing : the temperature range.

In my onSync request I enter a range between 60F° and 104F°, but it doesn't work on the device.

My min is 50F° and My max is 90F°

Here my onSync request.

```<code>function onSync(firebaseRef) { return async (body, headers) => {

    return {
        requestId: body.requestId,
        payload: {
            agentUserId: uId,
            devices: [{
                id: pId,
                type: 'action.devices.types.THERMOSTAT',
                traits: [
                    'action.devices.traits.TemperatureSetting',
                ],
                name: {
                    defaultNames: ['My Heat Pump'],
                    name: 'Heat Pump',
                    nicknames: ['Pump'],
                },
                deviceInfo: {
                    manufacturer: 'test',
                    model: '1',
                    hwVersion: '1.0',
                    swVersion: '1.0.1',
                },
                willReportState: true,
                attributes: {

                    // TemperatureSetting
                    availableThermostatModes: 'off,heat',
                    thermostatTemperatureRange: {
                        minThresholdCelsius: 15.555,
                        maxThresholdCelsius: 40.0
                    },
                    thermostatTemperatureUnit: 'F'

                },
            }],
        },
    };
}
}
</code>```

Do you know how to get the good temperature range ?

Bonus : It is possible to have a temperature touch control working with something else like a heater ?

答:
I had this answer from u/devunwired on Reddit:

In my onSync request I enter a range between 60F° and 104F°, but it
    doesn't work on the device.

This is a known issue that the Google Home app does not currently render the temperature range provided (the value is respected in voice
  queries). You can follow (and start) the feature request here:
  b/154169625

Permalink: https://www.reddit.com/r/GoogleAssistantDev/comments/guoyih/temperaturesetting_temperature_range/fskfx4f/

Body:
I made a google Smart Home able to control a water heater pump with google smarthome touch control. What it need to control is desired temperature and mode (on off).

I was not able to make that work with the "heater" device so instead I use the "thermostat" device.

Everything work except one thing : the temperature range.

In my onSync request I enter a range between 60F° and 104F°, but it doesn't work on the device.

My min is 50F° and My max is 90F°

Here my onSync request.

function onSync(firebaseRef) { return async (body, headers) => {

    return {
        requestId: body.requestId,
        payload: {
            agentUserId: uId,
            devices: [{
                id: pId,
                type: 'action.devices.types.THERMOSTAT',
                traits: [
                    'action.devices.traits.TemperatureSetting',
                ],
                name: {
                    defaultNames: ['My Heat Pump'],
                    name: 'Heat Pump',
                    nicknames: ['Pump'],
                },
                deviceInfo: {
                    manufacturer: 'test',
                    model: '1',
                    hwVersion: '1.0',
                    swVersion: '1.0.1',
                },
                willReportState: true,
                attributes: {

                    // TemperatureSetting
                    availableThermostatModes: 'off,heat',
                    thermostatTemperatureRange: {
                        minThresholdCelsius: 15.555,
                        maxThresholdCelsius: 40.0
                    },
                    thermostatTemperatureUnit: 'F'

                },
            }],
        },
    };
}
}

Do you know how to get the good temperature range ?

Bonus : It is possible to have a temperature touch control working with something else like a heater ?


答:
Here's how you could convert an int like 0422 to a time value:

```<code>SELECT CAST('00:00' AS time)
     + INTERVAL (@IntValue DIV 60) HOUR
     + INTERVAL (@IntValue % 60) MINUTE
</code>```

Without seeing your import query it's impossible to say how you could actually apply it.

Title: SQL Convert Int to Time

Body:
i'm trying to import data from a text file to an SQL database.  The file is using TAB not , to separate fields.  My issue on import has been that when I write the Time which is given as an Int it completely messes up on import.

Part of the text file:

North   Felix   2011-07-01  0422    0.47    0012    0.69    2109    0.55    1311    1.44
North   Felix   2011-07-02  0459    0.43    0048    0.72    2140    0.55    1342    1.47
North   Felix   2011-07-03  0533    0.41    0123    0.75    2213    0.57    1412    1.46
North   Felix   2011-07-04  0605    0.41    0158    0.79    2244    0.59    1441    1.41

My query result:

INSERT INTO `dbc`.`history_long` (`Region`,`Location`,`Date`,`LT1-time`,`LT1-height`,`HT1-time`,`HT1-height`,`LT2-time`,`LT2-height`,`HT2-time`,`HT2-height`)
values ('North','Felix','2011:00:00','422:00:00','0.47','12:00:00','0.69','2109:00:00','0.55','1311:00:00','1.44'),
('North','Felix','2011:00:00','459:00:00','0.43','48:00:00','0.72','2140:00:00','0.55','1342:00:00','1.47'),
('North','Felix','2011:00:00','533:00:00','0.41','123:00:00','0.75','2213:00:00','0.57','1412:00:00','1.46'),
('North','Felix','2011:00:00','605:00:00','0.41','158:00:00','0.79','2244:00:00','0.59','1441:00:00','1.41'),

The issue is for example L2-time becomes 2109:00:00 in the time column.  Is there a way to convert this from Int to Time?

Body:
Here's how you could convert an int like 0422 to a time value:

SELECT CAST('00:00' AS time)
     + INTERVAL (@IntValue DIV 60) HOUR
     + INTERVAL (@IntValue % 60) MINUTE

Without seeing your import query it's impossible to say how you could actually apply it.


问:
Download all Twilio Call logs?
I'm trying to download all my twilio call logs (as it's explained here https://support.twilio.com/hc/en-us/articles/223183588-Exporting-SMS-and-Call-Logs) but the problem is that this method is limited to 1000 logs.
Any idea how can I download them all (csv)?

Thanks in advance

答:
From the documentation:

PageSize argument is limited to 1000 pages.

When fetching multiple pages of API results, use the provided
  nextpageuri parameter to retrieve the next page of results. All of the
  Twilio Helper Libraries use the nextpageuri to page through resources.

You should use the Twilio Helper Libraries or nextpageuri and previouspageuri to navigate
  through the resources.

Title: Download all Twilio Call logs?


问:
Can I get the SQL string from a JPA Query object?
May I know how can I get the sql from a JPA query? or let's say, convert the JPA query to a SQL string? Thank you very much!</p>

答:
JPA Specification

While there is not standard JPA functionality to achieve this goal, you can still extract the SQL query from a JPQL or Criteria API Query using the JPA provider-specific API.

Hibernate Types

Starting with the 2.9.11 version, the Hibernate Types open-source project offers the SQLExtractor utility that allows you to get the SQL query from any JPQL or Criteria API query, no matter you are using Hibernate 5.4, 5.3, 5.2, 5.1, 5.0, 4.3, 4.2, or 4.1.

Get the SQL statement from a JPQL Query

Let's assume we have the following JPQL query:

```<code>Query jpql = entityManager.createQuery("""
    select
       YEAR(p.createdOn) as year,
       count(p) as postCount
    from
       Post p
    group by
       YEAR(p.createdOn)
    """, Tuple.class
);
</code>```

With Hibernate Types, extracting the Hibernate-generated SQL query is as simple as that:

```<code>String sql = SQLExtractor.from(jpql);
</code>```

And, if we log the extracted SQL query:

```<code>LOGGER.info("""
    The JPQL query: [
        {}
    ]
    generates the following SQL query: [
        {}
    ]
    """,
    jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
    sql
);
</code>```

We get the following output:

```<code>- The JPQL query: [
    select
        YEAR(p.createdOn) as year,
        count(p) as postCount
    from
        Post p
    group by
        YEAR(p.createdOn)
]
generates the following SQL query: [
    SELECT
        extract(YEAR FROM sqlextract0_.created_on) AS col_0_0_,
        count(sqlextract0_.id) AS col_1_0_
    FROM
        post p
    GROUP BY
        extract(YEAR FROM p.created_on)
]
</code>```

Notice that we unwrapped the JPA Query to the Hibernate org.hibernate.query.Query interface which provided the getQueryString method we can use to log the associated JPQL query string.

Get the SQL statement from a JPA Criteria API Query

The SQLExtractor is not limited to JPQL queries. You can use it with Criteria API queries as well, as illustrated by the following example:

```<code>CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class);

Root<PostComment> postComment = criteria.from(PostComment.class);
Join<PostComment, Post> post = postComment.join("post");

criteria.where(
    builder.like(post.get("title"), "%Java%")
);

criteria.orderBy(
    builder.asc(postComment.get("id"))
);

Query criteriaQuery = entityManager.createQuery(criteria);

String sql = SQLExtractor.from(criteriaQuery);

assertNotNull(sql);

LOGGER.info("""
    The Criteria API, compiled to this JPQL query: [
        {}
    ]
    generates the following SQL query: [
        {}
    ]
    """,
    jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
    sql
);
</code>```

When running the above test case, we get the following SQL query:

```<code>- The Criteria API, compiled to this JPQL query: [
    select
        pc
    from
        PostComment as pc
    inner join
        pc.post as p
    where
        p.title like :param0
    order by
        pc.id asc
]
generates the following SQL query: [
    SELECT
        pc.id AS id1_1_,
        pc.post_id AS post_id3_1_,
        pc.review AS review2_1_
    FROM
        post_comment pc
    INNER JOIN
        post p ON pc.post_id=p.id
    WHERE
        p.title LIKE ?
    ORDER BY
        pc.id ASC
]
</code>```

The Criteria API is first compiled to a JPQL query, as illustrated by the getQueryString() method call.

The intermediary JPQL query is further translated to an SQL query, which is properly resolved by the SQLExtractor utility.

Body:
JPA Specification

While there is not standard JPA functionality to achieve this goal, you can still extract the SQL query from a JPQL or Criteria API Query using the JPA provider-specific API.

Hibernate Types

Starting with the 2.9.11 version, the Hibernate Types open-source project offers the SQLExtractor utility that allows you to get the SQL query from any JPQL or Criteria API query, no matter you are using Hibernate 5.4, 5.3, 5.2, 5.1, 5.0, 4.3, 4.2, or 4.1.

Get the SQL statement from a JPQL Query

Let's assume we have the following JPQL query:

Query jpql = entityManager.createQuery("""
    select
       YEAR(p.createdOn) as year,
       count(p) as postCount
    from
       Post p
    group by
       YEAR(p.createdOn)
    """, Tuple.class
);

With Hibernate Types, extracting the Hibernate-generated SQL query is as simple as that:

String sql = SQLExtractor.from(jpql);

And, if we log the extracted SQL query:

LOGGER.info("""
    The JPQL query: [
        {}
    ]
    generates the following SQL query: [
        {}
    ]
    """,
    jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
    sql
);

We get the following output:

- The JPQL query: [
    select
        YEAR(p.createdOn) as year,
        count(p) as postCount
    from
        Post p
    group by
        YEAR(p.createdOn)
]
generates the following SQL query: [
    SELECT
        extract(YEAR FROM sqlextract0_.created_on) AS col_0_0_,
        count(sqlextract0_.id) AS col_1_0_
    FROM
        post p
    GROUP BY
        extract(YEAR FROM p.created_on)
]

Notice that we unwrapped the JPA Query to the Hibernate org.hibernate.query.Query interface which provided the getQueryString method we can use to log the associated JPQL query string.

Get the SQL statement from a JPA Criteria API Query

The SQLExtractor is not limited to JPQL queries. You can use it with Criteria API queries as well, as illustrated by the following example:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class);

Root<PostComment> postComment = criteria.from(PostComment.class);
Join<PostComment, Post> post = postComment.join("post");

criteria.where(
    builder.like(post.get("title"), "%Java%")
);

criteria.orderBy(
    builder.asc(postComment.get("id"))
);

Query criteriaQuery = entityManager.createQuery(criteria);

String sql = SQLExtractor.from(criteriaQuery);

assertNotNull(sql);

LOGGER.info("""
    The Criteria API, compiled to this JPQL query: [
        {}
    ]
    generates the following SQL query: [
        {}
    ]
    """,
    jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
    sql
);

When running the above test case, we get the following SQL query:

- The Criteria API, compiled to this JPQL query: [
    select
        pc
    from
        PostComment as pc
    inner join
        pc.post as p
    where
        p.title like :param0
    order by
        pc.id asc
]
generates the following SQL query: [
    SELECT
        pc.id AS id1_1_,
        pc.post_id AS post_id3_1_,
        pc.review AS review2_1_
    FROM
        post_comment pc
    INNER JOIN
        post p ON pc.post_id=p.id
    WHERE
        p.title LIKE ?
    ORDER BY
        pc.id ASC
]

The Criteria API is first compiled to a JPQL query, as illustrated by the getQueryString() method call.

The intermediary JPQL query is further translated to an SQL query, which is properly resolved by the SQLExtractor utility.


问:
React-Leaflet: Placing map control components outside of map?
This is a more generalized version of my other question: Remove Zoom control from map in react-leaflet.  React-leaflet comes with a handful of components which control the map - i.e. the <ZoomControl />, <LayersControl />, etc.  But in order for these components to properly communicate with a map instance, they must be written as a child of the <Map /> component, like so:

<Map center={...} zoom={...}>

  <ZoomControl />
  <LayersControl />
  <MyCustomComponent />

</Map>
```

<p>What I am trying to create is a situation where map components that are not direct children of the map can properly communicate with the map.  For example:</p>

<pre class="lang-js prettyprint-override"><code><App>
  <Map />
  <Sibling>
    <Niece>
      <ZoomControl />
      <OtherControls />
    </Niece>
  </Sibling>
</App>
</code>```

Obviously the trouble here is that when these controls are no longer children or descendants of the <Map />, they don't receive the map instance through a provider.  As you can see in my other question, I tried creating a new Context object and using it to provide the map to the displaced controls.  That didn't work, and I'm not sure why.  So far, my solution has been to use vanilla javascript to rehome these controls in the componentDidMount of their intended parent, like so:

// Niece.js
componentDidMount(){
  const newZoomHome = document.querySelector('#Niece')
  const leafletZoomControl= document.querySelector('.leaflet-control-zoom')
  newZoomHome.appendChild(leafletZoomControl)
}
```

<p>I really hate this because now my general component structure does not reflect the application structure.  My Zoom needs to be written as part of my map, but ends up in my Neice component.</p>

<p>Kboul's solution in my other question was simply to rebuild the zoom component from scratch and feed it the map context.  This works fine for a simple zoom component, but for more complex components, I can't be rebuilding entire frameworks.  For example, I made a quick react-leaflet component version of esri-leaflet's geosearch:</p>

<pre class="lang-js prettyprint-override"><code>import { withLeaflet, MapControl } from "react-leaflet";
import * as ELG from "esri-leaflet-geocoder";

class GeoSearch extends MapControl {
  createLeafletElement(props) {
    const searchOptions = {
       ...props,
      providers: props.providers ? props.providers.map( provider => ELG[provider]()) : null
    };

    const GeoSearch = new ELG.Geosearch(searchOptions);
    // Author can specify a callback function for the results event
    if (props.onResult){
      GeoSearch.addEventListener('results', props.onResult)
    }
    return GeoSearch;
  }

  componentDidMount() {
    const { map } = this.props.leaflet;
    this.leafletElement.addTo(map);
  }
}

export default withLeaflet(GeoSearch);
</code>```

Its relatively simple and works great when declared inside the <Map /> component.  But I want to move it to a separate place in the app, and I don't want to have to recode the entire esri Geosearch.  How can I use functioning react-leaflet control components outside of the <Map /> component while properly linking it to the map instance?

Here's a quick codsandbox template to start messing with if you're so inclined.  Thanks for reading.

答:
Might not be helpful in this instance but I used redux to define the state of the map and then used normal actions and reducers to update the map from anywhere in the application.

So your action would look something like this

```<code>export const setCenterMap = (payload) => ({
  type: CENTER_MAP,
  payload,
})
</code>```

and a basic reducer:

```<code>const initialState = {
centerMap: false,
}

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case (CENTER_MAP) : {
            return ({
                ...state,
                centerMap: action.payload
            })
        }
        default: return state
    }
}
</code>```

Then you connect it to your map component

```<code>const mapStateToProps = state => ({
  centerMap: state.app.centerMap,
})

const mapDispatchToProps = dispatch => ({
  setCenterMap: (centerMap) => dispatch(setCenterMap(centerMap)),
})
</code>```

You can now manipulate the map outside of the Leaflet component.

```<code>        <LeafletMap
            center={centerMap}
            sites={event.sites && [...event.sites, ...event.workingGroups]}
        />
        <button onClick={() => setCenterMap([5.233, 3.342])} >SET MAP CENTER</button>
</code>```

Most of this is pseudo code so you would have to adopt it for your own use but I found it a fairly painless way to add some basic map controls from outside of the LeafletMap component especially if you are already using redux.

Body:
This is a more generalized version of my other question: Remove Zoom control from map in react-leaflet.  React-leaflet comes with a handful of components which control the map - i.e. the <ZoomControl />, <LayersControl />, etc.  But in order for these components to properly communicate with a map instance, they must be written as a child of the <Map /> component, like so:

<Map center={...} zoom={...}>

  <ZoomControl />
  <LayersControl />
  <MyCustomComponent />

</Map>

What I am trying to create is a situation where map components that are not direct children of the map can properly communicate with the map.  For example:

<App>
  <Map />
  <Sibling>
    <Niece>
      <ZoomControl />
      <OtherControls />
    </Niece>
  </Sibling>
</App>

Obviously the trouble here is that when these controls are no longer children or descendants of the <Map />, they don't receive the map instance through a provider.  As you can see in my other question, I tried creating a new Context object and using it to provide the map to the displaced controls.  That didn't work, and I'm not sure why.  So far, my solution has been to use vanilla javascript to rehome these controls in the componentDidMount of their intended parent, like so:

// Niece.js
componentDidMount(){
  const newZoomHome = document.querySelector('#Niece')
  const leafletZoomControl= document.querySelector('.leaflet-control-zoom')
  newZoomHome.appendChild(leafletZoomControl)
}

I really hate this because now my general component structure does not reflect the application structure.  My Zoom needs to be written as part of my map, but ends up in my Neice component.

Kboul's solution in my other question was simply to rebuild the zoom component from scratch and feed it the map context.  This works fine for a simple zoom component, but for more complex components, I can't be rebuilding entire frameworks.  For example, I made a quick react-leaflet component version of esri-leaflet's geosearch:

import { withLeaflet, MapControl } from "react-leaflet";
import * as ELG from "esri-leaflet-geocoder";

class GeoSearch extends MapControl {
  createLeafletElement(props) {
    const searchOptions = {
       ...props,
      providers: props.providers ? props.providers.map( provider => ELG[provider]()) : null
    };

    const GeoSearch = new ELG.Geosearch(searchOptions);
    // Author can specify a callback function for the results event
    if (props.onResult){
      GeoSearch.addEventListener('results', props.onResult)
    }
    return GeoSearch;
  }

  componentDidMount() {
    const { map } = this.props.leaflet;
    this.leafletElement.addTo(map);
  }
}

export default withLeaflet(GeoSearch);

Its relatively simple and works great when declared inside the <Map /> component.  But I want to move it to a separate place in the app, and I don't want to have to recode the entire esri Geosearch.  How can I use functioning react-leaflet control components outside of the <Map /> component while properly linking it to the map instance?

Here's a quick codsandbox template to start messing with if you're so inclined.  Thanks for reading.

Body:
Might not be helpful in this instance but I used redux to define the state of the map and then used normal actions and reducers to update the map from anywhere in the application.

So your action would look something like this

export const setCenterMap = (payload) => ({
  type: CENTER_MAP,
  payload,
})

and a basic reducer:

const initialState = {
centerMap: false,
}

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case (CENTER_MAP) : {
            return ({
                ...state,
                centerMap: action.payload
            })
        }
        default: return state
    }
}

Then you connect it to your map component

const mapStateToProps = state => ({
  centerMap: state.app.centerMap,
})

const mapDispatchToProps = dispatch => ({
  setCenterMap: (centerMap) => dispatch(setCenterMap(centerMap)),
})

You can now manipulate the map outside of the Leaflet component.

        <LeafletMap
            center={centerMap}
            sites={event.sites && [...event.sites, ...event.workingGroups]}
        />
        <button onClick={() => setCenterMap([5.233, 3.342])} >SET MAP CENTER</button>

Most of this is pseudo code so you would have to adopt it for your own use but I found it a fairly painless way to add some basic map controls from outside of the LeafletMap component especially if you are already using redux.


问:
I'm trying to learn how to make a discord bot and the example code it said to run doesn't work, what might be wrong?
I'm learning how to use the discord.py API and this example code (from here: https://discordpy.readthedocs.io/en/latest/quickstart.html) does not work. I think it has something to do with the async syntax, but I have no idea what could be wrong with it.
Any help would be appreciated!

```<code>import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('private token that is filled in in the actual code')
</code>```

On line 7, “async def on_ready():”, the error is an invalid syntax on async. I’m using 3.8.3

答:
client = commands.Bot(command_prefix = '!') instead of client = commands.Client()
You should import commands too

```<code>import discord
from discord.ext import commands
</code>```

Body:
I'm learning how to use the discord.py API and this example code (from here: https://discordpy.readthedocs.io/en/latest/quickstart.html) does not work. I think it has something to do with the async syntax, but I have no idea what could be wrong with it.
Any help would be appreciated!

import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('private token that is filled in in the actual code')

On line 7, “async def on_ready():”, the error is an invalid syntax on async. I’m using 3.8.3

Body:
client = commands.Bot(command_prefix = '!') instead of client = commands.Client()
You should import commands too

import discord
from discord.ext import commands


问:
I always get a Kernel Dead when using "pd.read_parquet()". (No matter which file size)
As you can guess by the title, the kernel always dies when using pd.read_parquet().
I already tried it with different sizes but it wont work.

here the code... (I am using jupyter (without anaconda, because it always takes to long to start) in Python 3.7 with a i5 & 16GB RAM)

```<code>outfp = PurePath(data_dir+'/interim/IVE_tickbidask.parq')
#df = df.head(10)
df.to_parquet(outfp)

from pathlib import PurePath, Path
import pandas as pd
data_dir = "../../../Adv_Fin_ML_Exercises-master/Adv_Fin_ML_Exercises-master/data"
infp=PurePath(data_dir+'/interim/IVE_tickbidask.parq')
df = pd.read_parquet(data_dir+'/interim/IVE_tickbidask.parq')
cprint(df)
</code>```

What can i do to still make it work?

答: I had the same problem, adding engine = 'fastparquet' worked for me. Otherwise it defaults to engine = 'pyarrow' and that seems to make the kernel die.

Body:
As you can guess by the title, the kernel always dies when using pd.read_parquet().
I already tried it with different sizes but it wont work.

here the code... (I am using jupyter (without anaconda, because it always takes to long to start) in Python 3.7 with a i5 & 16GB RAM)

outfp = PurePath(data_dir+'/interim/IVE_tickbidask.parq')
#df = df.head(10)
df.to_parquet(outfp)

from pathlib import PurePath, Path
import pandas as pd
data_dir = "../../../Adv_Fin_ML_Exercises-master/Adv_Fin_ML_Exercises-master/data"
infp=PurePath(data_dir+'/interim/IVE_tickbidask.parq')
df = pd.read_parquet(data_dir+'/interim/IVE_tickbidask.parq')
cprint(df)

What can i do to still make it work?


问:
How to change referenced numpy arrays to a slice of itself?
Consider the following operation and slicing applied to two numpy arrays:

```<code>In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])
</code>```

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

```<code>In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]
</code>```

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

```<code>In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])
</code>```

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

答:
Sounds like you want a dictionary:

```<code>import numpy as np

arrs = {'a': np.array([1,2,3,4]), 'b': np.array([5,6,7,8])}
arrs = {k: v[::2] for k, v in arrs.items()}
print(arrs)
</code>```

output:

```<code>{'a': array([1, 3]), 'b': array([5, 7])}
</code>```

Body:
Consider the following operation and slicing applied to two numpy arrays:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

Body:
Sounds like you want a dictionary:

import numpy as np

arrs = {'a': np.array([1,2,3,4]), 'b': np.array([5,6,7,8])}
arrs = {k: v[::2] for k, v in arrs.items()}
print(arrs)

output:

{'a': array([1, 3]), 'b': array([5, 7])}


问:
I can't install basemap package
I tried to work with Basemap packages in Python 3.x but, when I try to install the packages in my IDE Pycharm, it gives me this error:

```<code>Could not find a version that satisfies the requirement Basemap (from versions: )
No matching distribution found for Basemap
You are using pip version 10.0.1, however version 19.0.3 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
</code>```

Anyone knows how can I do to install that packages correctly?

(Python 3.x, Pycharm, Windows 10)

答:
I also ran into a similar problem and the above two solutions did not work for me.
And as you can see here https://github.com/jakevdp/PythonDataScienceHandbook/issues/72#issuecomment-301008464
It is no longer possible to install it via pip, rather try this:</p>

```<code>conda install -c conda-forge basemap
</code>```

Title: I can't install basemap package

Body:
I tried to work with Basemap packages in Python 3.x but, when I try to install the packages in my IDE Pycharm, it gives me this error:

Could not find a version that satisfies the requirement Basemap (from versions: )
No matching distribution found for Basemap
You are using pip version 10.0.1, however version 19.0.3 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

Anyone knows how can I do to install that packages correctly?

(Python 3.x, Pycharm, Windows 10)

Body:
I also ran into a similar problem and the above two solutions did not work for me.
And as you can see here https://github.com/jakevdp/PythonDataScienceHandbook/issues/72#issuecomment-301008464
It is no longer possible to install it via pip, rather try this:

conda install -c conda-forge basemap


问:
working of range for loop and C-style arrays in C++
C-style Arrays are not self-describing as it doesn't has any information about it's size, so for iterating it's elements we need size information somehow. I'm confused as how range-for loop gets the size information. It is expected to fail. Consider 2 conflicting examples,

```<code>#include <iostream>
using namespace std;

int main() {
    int a[] = { 1, 2, 3, 4, 5, 6 };
    for(auto x : a)
        cout<<x<<" ";
    cout<<endl;
    return 0;
}
</code>```

It ran successfully(unexpected), but

```<code>#include <iostream>
using namespace std;

void print_a(int*);

void print_a(int a[])
{
    for(auto x : a)
        cout<<x<<" ";
    cout<<endl;
}
int main() {
    int a[] = { 1, 2, 3, 4, 5, 6 };
    print_a(a);
    return 0;
}

</code>```

This produced errors(expected).

Can someone explain as how range-for loop actually works ?

答:
range-for loop run from start to end that says it needs to know the length.
of statically allocated arrays AKA int array[10] the compiler know the length on compile-time  so he knows to terminate them,
but on the dynamically allocated array, the compiler doesn't know the length of the array so he cants rang loop them

Body:
C-style Arrays are not self-describing as it doesn't has any information about it's size, so for iterating it's elements we need size information somehow. I'm confused as how range-for loop gets the size information. It is expected to fail. Consider 2 conflicting examples,

#include <iostream>
using namespace std;

int main() {
    int a[] = { 1, 2, 3, 4, 5, 6 };
    for(auto x : a)
        cout<<x<<" ";
    cout<<endl;
    return 0;
}

It ran successfully(unexpected), but

#include <iostream>
using namespace std;

void print_a(int*);

void print_a(int a[])
{
    for(auto x : a)
        cout<<x<<" ";
    cout<<endl;
}
int main() {
    int a[] = { 1, 2, 3, 4, 5, 6 };
    print_a(a);
    return 0;
}

This produced errors(expected).

Can someone explain as how range-for loop actually works ?


问:
Flutter Caching
How to save network data in cash and then implement it have any resource or example, I use flutter_cashe_manager but I can't implement it in my code

there I call the API API return data and save it in cash, whene i call this future method its returns the list from the cache JSON file.. this is the code where return the data list from the cache.

```<code>TopicHab _topicHab;
  Future<List<Topic>> fetchTopicList(String api) async {
    try {
//      var file = await DefaultCacheManager().getSingleFile(url+api);
      var file = await DefaultCacheManager().getSingleFile(url+api);
      print('files ${file.readAsStringSync()}');
      print('files ${file.path}');
//      var tempDir = await getTemporaryDirectory();
//      String tempPath = tempDir.path;
//      print('path ${tempPath}');
      _topicHab = TopicHab.fromJson(jsonDecode(file.readAsStringSync()));
      print('Topic Length ${_topicHab.cats.length}');
      return _topicHab.cats;
    } catch (e) {
      return List<Topic>();
    }
  }
</code>```

their whare the snapshot.haseData is false but its use streamside first time its work but next time it does not work. I can't find what the proper problems

```<code>drawer: Drawer(
          child: Container(
            color: drawerBackgroundColors,
            child: StreamBuilder(
              stream: newsBloc.allTopic,
              builder:
                  (BuildContext context, AsyncSnapshot<List<Topic>> snapshot) {
                print('newsBloc.allTopic ${newsBloc.allTopic}' );
                print('snapshot data ${snapshot.hasData}');
                if (snapshot.hasData) {
                  print('snapshot topic ${snapshot.data.length}');
                  return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        decoration: BoxDecoration(
                          color: childMenuBackgroundColor,
                          border: Border(
                            bottom: BorderSide(
                              color: Colors.white,
                            )
                          ),
                        ),
                        padding: EdgeInsets.all(2),
                        height: 50,
                        child: ListTile(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => TopicsNewsScreen(
                                        parentTopic: true,
                                          topicId: snapshot.data[index].topicId,
                                          topicName: snapshot
                                              .data[index].topicName
                                              .toUpperCase())));
                            },
                            title: Text(
                              snapshot.data[index].topicName,
                              style: childMenuStyle,
                            ))
                      );
                    },
                  );
                } else if (snapshot.hasError) {
                  return Text(snapshot.error.toString());
                } else {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
              },
            ),
          ),
        ),
</code>```

答:
The package used is Hive

Another way of caching is by using hive a No-SQL database it is faster to retrieve documents and is easy to use. And it retrieves data faster

For more details check:https://github.com/shashiben/Anime-details to know how to cache using hive from rest api

Title: Flutter Caching

Body:
How to save network data in cash and then implement it have any resource or example, I use flutter_cashe_manager but I can't implement it in my code

there I call the API API return data and save it in cash, whene i call this future method its returns the list from the cache JSON file.. this is the code where return the data list from the cache.

TopicHab _topicHab;
  Future<List<Topic>> fetchTopicList(String api) async {
    try {
//      var file = await DefaultCacheManager().getSingleFile(url+api);
      var file = await DefaultCacheManager().getSingleFile(url+api);
      print('files ${file.readAsStringSync()}');
      print('files ${file.path}');
//      var tempDir = await getTemporaryDirectory();
//      String tempPath = tempDir.path;
//      print('path ${tempPath}');
      _topicHab = TopicHab.fromJson(jsonDecode(file.readAsStringSync()));
      print('Topic Length ${_topicHab.cats.length}');
      return _topicHab.cats;
    } catch (e) {
      return List<Topic>();
    }
  }

their whare the snapshot.haseData is false but its use streamside first time its work but next time it does not work. I can't find what the proper problems

drawer: Drawer(
          child: Container(
            color: drawerBackgroundColors,
            child: StreamBuilder(
              stream: newsBloc.allTopic,
              builder:
                  (BuildContext context, AsyncSnapshot<List<Topic>> snapshot) {
                print('newsBloc.allTopic ${newsBloc.allTopic}' );
                print('snapshot data ${snapshot.hasData}');
                if (snapshot.hasData) {
                  print('snapshot topic ${snapshot.data.length}');
                  return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        decoration: BoxDecoration(
                          color: childMenuBackgroundColor,
                          border: Border(
                            bottom: BorderSide(
                              color: Colors.white,
                            )
                          ),
                        ),
                        padding: EdgeInsets.all(2),
                        height: 50,
                        child: ListTile(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => TopicsNewsScreen(
                                        parentTopic: true,
                                          topicId: snapshot.data[index].topicId,
                                          topicName: snapshot
                                              .data[index].topicName
                                              .toUpperCase())));
                            },
                            title: Text(
                              snapshot.data[index].topicName,
                              style: childMenuStyle,
                            ))
                      );
                    },
                  );
                } else if (snapshot.hasError) {
                  return Text(snapshot.error.toString());
                } else {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
              },
            ),
          ),
        ),


问:
format the dates of several columns

dt <- data.table(date1 = c("14.01.2009", "9/2/2005",  "24/1/2010", "28.01.2014"),
                 var1 = rnorm(4,2,1),
                 date2 = c("09.01.2009", "23/8/2005","17.01.2000", "04.01.2005"),
                 d = c("2020-02-23", "2015-05-26", "2002-02-04"))
```

<p>I tried with this script </p>

<pre class="lang-r prettyprint-override"><code>for (j in seq_along(dt)) if (all(grepl('\\d+(\\.|/|-)\\d+(\\.|/|-)\\d+',dt[,j]))) set(dt,j = j, value = dmy(dt[[j]]))
</code>```

I have the following error:

Error in [.data.table(dt, , j) : j (the 2nd argument inside [...]) is a single symbol but column name 'j' is not found. Perhaps you intended DT[, ..j]. This difference to data.frame is deliberate and explained in FAQ 1.1.

Title: format the dates of several columns

Body:
dt <- data.table(date1 = c("14.01.2009", "9/2/2005",  "24/1/2010", "28.01.2014"),
                 var1 = rnorm(4,2,1),
                 date2 = c("09.01.2009", "23/8/2005","17.01.2000", "04.01.2005"),
                 d = c("2020-02-23", "2015-05-26", "2002-02-04"))

I tried with this script

for (j in seq_along(dt)) if (all(grepl('\\d+(\\.|/|-)\\d+(\\.|/|-)\\d+',dt[,j]))) set(dt,j = j, value = dmy(dt[[j]]))

I have the following error:

Error in [.data.table(dt, , j) : j (the 2nd argument inside [...]) is a single symbol but column name 'j' is not found. Perhaps you intended DT[, ..j]. This difference to data.frame is deliberate and explained in FAQ 1.1.

Body:
here is data.table + lubridate solution.

library(data.table)
library(lubridate)
cols = names(dt)[ dt[, sapply( .SD, function(x) {
    all( grepl( "\\d+(\\.|/|-)\\d+(\\.|/|-)\\d+", x ) )
  } ) ] ]
possible.date.formats <- c("d.m.Y", "d/m/Y", "Y-m-d") #possible data-formats
dt[, (cols) := lapply( .SD,
                       lubridate::parse_date_time,
                       orders =  possible.date.formats ),
   .SDcols = cols][]

#         date1      var1      date2          d
# 1: 2009-01-14 1.9459372 2009-01-09 2020-02-23
# 2: 2005-02-09 3.7666378 2005-08-23 2015-05-26
# 3: 2010-01-24 0.6207715 2000-01-17 2002-02-04
# 4: 2014-01-28 2.8800135 2005-01-04 2020-02-23


问:
local variable 'context' referenced before assignment in django
```<code>from django.shortcuts import render
from main import (models,forms)
from django.http import HttpResponseRedirect

# Create your views here.

def index(request):
    return render (request, 'index.txt')

def about(request):
    return render (request, 'about.txt')

def contact(request):
    contactform = forms.ContactForm()

    if request.method == "POST":
        contactform = forms.ContactForm(request.POST)
        if contactform.is_valid():
            contact = contactform.save()
            return HttpResponseRedirect('/contact')
        context = {
        "contactform" : contactform

        }
    return render(request, 'contact.txt', context)

def post(request):
    return render (request, 'post.txt')
</code>```

答:
You're sending context without declaring it when requesting with a GET method.</p>

```<code>from django.shortcuts import render
from main import (models,forms)
from django.http import HttpResponseRedirect

# Create your views here.

def index(request):
    return render (request, 'index.txt')

def about(request):
    return render (request, 'about.txt')

def contact(request):
    if request.method == "GET":
        context = {
            "contactform" : forms.ContactForm()
        }
    if request.method == "POST":
        contactform = forms.ContactForm(request.POST)
        if contactform.is_valid():
            contact = contactform.save()
            return HttpResponseRedirect('/contact')
        context = {
            "contactform" : contactform
        }
    return render(request, 'contact.txt', context)

def post(request):
    return render (request, 'post.txt')

</code>```

Body:
You're sending context without declaring it when requesting with a GET method.

from django.shortcuts import render
from main import (models,forms)
from django.http import HttpResponseRedirect

# Create your views here.

def index(request):
    return render (request, 'index.txt')

def about(request):
    return render (request, 'about.txt')

def contact(request):
    if request.method == "GET":
        context = {
            "contactform" : forms.ContactForm()
        }
    if request.method == "POST":
        contactform = forms.ContactForm(request.POST)
        if contactform.is_valid():
            contact = contactform.save()
            return HttpResponseRedirect('/contact')
        context = {
            "contactform" : contactform
        }
    return render(request, 'contact.txt', context)

def post(request):
    return render (request, 'post.txt')


问:
API Json response to C# Object with capital case properties first letter
I've made an API where after an Entity Framework elaboration I send an object serialized in Json.

My Object:

```<code>public class Package
{
    public int Items { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    public double? Weight { get; set; }
    public string Size { get; set; }
    public string PackageType { get; set; }
}
</code>```

The problem start when after recieve it (Xamarin app) the Json have the first letter lowercase, but I want deserialize it in the exact same class and it can't because the class have properties in capitalcase (C# standard).
Now I'm using a horrible 'helper' class that have the properties in lowercase for translating it.

Any idea how to handle this and send the Json directly with capital case first letter?

Edit

I use ASP.NET web API Core and Newtonsoft.Json

In Xamarin app I use System.Text.Json

答:
You have to change the default property naming policy on the json serialization options.

By default it's set to camel case but if you set it to null, the property names are to remain unchanged (or remain as you wrote on your class).

Simply add this to your Startup.cs:

```<code>services.AddControllers()
.AddJsonOptions(options =>
{
   options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
</code>```

Body:
I've made an API where after an Entity Framework elaboration I send an object serialized in Json.

My Object:

public class Package
{
    public int Items { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    public double? Weight { get; set; }
    public string Size { get; set; }
    public string PackageType { get; set; }
}

The problem start when after recieve it (Xamarin app) the Json have the first letter lowercase, but I want deserialize it in the exact same class and it can't because the class have properties in capitalcase (C# standard).
Now I'm using a horrible 'helper' class that have the properties in lowercase for translating it.

Any idea how to handle this and send the Json directly with capital case first letter?

Edit

I use ASP.NET web API Core and Newtonsoft.Json

In Xamarin app I use System.Text.Json

Body:
You have to change the default property naming policy on the json serialization options.

By default it's set to camel case but if you set it to null, the property names are to remain unchanged (or remain as you wrote on your class).

Simply add this to your Startup.cs:

services.AddControllers()
.AddJsonOptions(options =>
{
   options.JsonSerializerOptions.PropertyNamingPolicy = null;
});


问:
Need to Give Fined grained access to Developers to access the Specific KMS key which belongs to his project
Need to get a better solution for the below problem statement:-

my secrets and config are encrypted via Mozilla sops and let's say the first time Devops team will do this at there end, but DevOps team will NoT encrypt the config all the time for the developer. To solve this problem we want to give access to Developer and when we think to give access to them we need to put the security in the first place. Currently, we are thinking of creating a master box and give access to the selective 2 members of the team who have this kind of access. But as per current situation if both the two developers are not available we need to give them access to 3rd and eventually one day everybody in the team has that access which we don’t want, what we want is without giving any kind other access to the developer, Means he can only play with his KMS keys, not the other available KMS keys which not belongs to him, Is this possible?

Because when we give KMS resource access to that person, eventually all the key access he has which is in KMS Portal, So for that, we Need to Give Fined grained access to Developers to access the Specific KMS key which belongs to his project. No permission more than that !

答:
One way to restrict access of KMS keys for each user (or developer) is to use key policies for your customer master keys (CMKs) in AWS KMS. This documentation goes through how key policies can be used: https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html

```<code>{
  "Sid": "Allow root account full access",
  "Effect": "Allow",
  "Principal": {"AWS": "arn:aws:iam::444455556666:root"},
  "Action": "kms:*",
  "Resource": "*"
},
{
  "Sid": "Allow specific permissions to dev user",
  "Effect": "Allow",
  "Principal": {"AWS": [
    "arn:aws:iam::444455556666:user/dev1"
  ]},
  "Action": [
    "kms:Encrypt",
    "kms:Decrypt",
    "kms:ReEncrypt*",
    "kms:GenerateDataKey*",
    "kms:DescribeKey"
  ],
  "Resource": "*"
}
</code>```

Note: In a key policy, you use * for the resource, which means "this CMK". A key policy applies only to the CMK it is attached to.

Body:
One way to restrict access of KMS keys for each user (or developer) is to use key policies for your customer master keys (CMKs) in AWS KMS. This documentation goes through how key policies can be used: https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html

{
  "Sid": "Allow root account full access",
  "Effect": "Allow",
  "Principal": {"AWS": "arn:aws:iam::444455556666:root"},
  "Action": "kms:*",
  "Resource": "*"
},
{
  "Sid": "Allow specific permissions to dev user",
  "Effect": "Allow",
  "Principal": {"AWS": [
    "arn:aws:iam::444455556666:user/dev1"
  ]},
  "Action": [
    "kms:Encrypt",
    "kms:Decrypt",
    "kms:ReEncrypt*",
    "kms:GenerateDataKey*",
    "kms:DescribeKey"
  ],
  "Resource": "*"
}

Note: In a key policy, you use * for the resource, which means "this CMK". A key policy applies only to the CMK it is attached to.


问:
How to manage time zones across multiple systems in java?
I have a web application that returns a booking time based on the country where the event was performed.

Eg: If the booking was created in India at 02-JUNE-2020 1700 IST,then time returned is:

```<code>2020-06-02T17:00:00+0530
</code>```

If the booking was created in Thailand at 02-JUNE-2020 1700 Thai Time,then time returned is:

```<code>2020-06-02T17:00:00+0700
</code>```

Now I have to store all this in a system in UK time,so the data would be:

for India,in UK system:  2020-06-02T12:30:00+0100

for Thailand,in UK system:  2020-06-02T11:00:00+0100

I know I can use the zone indicator of +0530 to convert to milliseconds offset by using

```<code>TimeZone.getAvailableIDs(milliseconds);
</code>```

and find the corresponding timezone to do a reverse integration.

But is there an easy way to translate the IST to UK time directly in java ?

答:
+0530 is not actually indicative of any particular time zone. A time zone could be, say, Europe/Amsterdam. This is +0100 in winter and +0200 in summer, and the zone Europe/Paris has the exact same offset at the exact same dates. Whilst unlikely, it is entirely possible that 5 years from now this is no longer the case. Note that +0100 does not accurately describe Europe/Amsterdam (it'd be wrong in summer), and cannot disambiguate between amsterdam and paris, which is why it's not good enough, generally. If this is just what you've been given and you can't change it, yea, getAvailableIDs is one way to at least attempt to convert +0530 into a zone, but note that usually you get many answers, so I don't know how you'd figure out how to pick the 'right' zone. Consider changing the system so that you get this timezone, the full ID, as part of the input instead.

Let's say you have obtained the zone, somehow.

Given 2020-06-02T17:00:00+0530 - you can translate this to the exact moment in time that the event being described by this timestamp has/will occur. That's presumably important; if you want an alarm to go off at that time anywhere on the planet you can now make that happen. That you store this 'in UK time' is just an implementation detail, that doesn't matter: You're storing the instant in time this event occurs, and not the way the human-oriented system that created this timestamp would refer to it (which is, presumably: '5 in the evening, on the second of june in 2020, in india').

But, you indicate a need to convert back from this 'exact instant in time' back to the zoned time.

Why?

If the answer is: So that it is familiar to the human, because the human I will end up printing this string to is definitely in india, you potentially have some issues if you go with the not-human-relevant zone ID of '+0530'; you optimally want to go with the more human-relevant zone ID of 'Asia/Kolkata', for example.

Okay, and now in java please!

an instant in time is best represented with an instance of java.time.Instant. This has no timezone info; it just marks a moment in time. (internally it stores as UTC, but that is an implementation detail. these things are timezoneless).

Once you have an Instant, and you have a TimeZone, you can do:

```<code>Instant x = ....; // obtain an instance somehow.
ZoneId zone = ZoneId.of("Asia/Kolkata"); // get a zone somehow.
ZonedDateTime zdt = x.atZone(zone);
</code>```

You can print a zdt, for example with a java.time.format.DateTimeFormatter instance, and it'll render it as somebody in india would prefer.

If you have instead stored, say, a string containing the text 2020-06-02T12:30:00+0100, you can go from there to an instant rather easily, and then you can .atZone your way back to indian time.

Body:
I have a web application that returns a booking time based on the country where the event was performed.

Eg: If the booking was created in India at 02-JUNE-2020 1700 IST,then time returned is:

2020-06-02T17:00:00+0530

If the booking was created in Thailand at 02-JUNE-2020 1700 Thai Time,then time returned is:

2020-06-02T17:00:00+0700

Now I have to store all this in a system in UK time,so the data would be:

for India,in UK system:  2020-06-02T12:30:00+0100

for Thailand,in UK system:  2020-06-02T11:00:00+0100

I know I can use the zone indicator of +0530 to convert to milliseconds offset by using

TimeZone.getAvailableIDs(milliseconds);

and find the corresponding timezone to do a reverse integration.

But is there an easy way to translate the IST to UK time directly in java ?

Body:
+0530 is not actually indicative of any particular time zone. A time zone could be, say, Europe/Amsterdam. This is +0100 in winter and +0200 in summer, and the zone Europe/Paris has the exact same offset at the exact same dates. Whilst unlikely, it is entirely possible that 5 years from now this is no longer the case. Note that +0100 does not accurately describe Europe/Amsterdam (it'd be wrong in summer), and cannot disambiguate between amsterdam and paris, which is why it's not good enough, generally. If this is just what you've been given and you can't change it, yea, getAvailableIDs is one way to at least attempt to convert +0530 into a zone, but note that usually you get many answers, so I don't know how you'd figure out how to pick the 'right' zone. Consider changing the system so that you get this timezone, the full ID, as part of the input instead.

Let's say you have obtained the zone, somehow.

Given 2020-06-02T17:00:00+0530 - you can translate this to the exact moment in time that the event being described by this timestamp has/will occur. That's presumably important; if you want an alarm to go off at that time anywhere on the planet you can now make that happen. That you store this 'in UK time' is just an implementation detail, that doesn't matter: You're storing the instant in time this event occurs, and not the way the human-oriented system that created this timestamp would refer to it (which is, presumably: '5 in the evening, on the second of june in 2020, in india').

But, you indicate a need to convert back from this 'exact instant in time' back to the zoned time.

Why?

If the answer is: So that it is familiar to the human, because the human I will end up printing this string to is definitely in india, you potentially have some issues if you go with the not-human-relevant zone ID of '+0530'; you optimally want to go with the more human-relevant zone ID of 'Asia/Kolkata', for example.

Okay, and now in java please!

an instant in time is best represented with an instance of java.time.Instant. This has no timezone info; it just marks a moment in time. (internally it stores as UTC, but that is an implementation detail. these things are timezoneless).

Once you have an Instant, and you have a TimeZone, you can do:

Instant x = ....; // obtain an instance somehow.
ZoneId zone = ZoneId.of("Asia/Kolkata"); // get a zone somehow.
ZonedDateTime zdt = x.atZone(zone);

You can print a zdt, for example with a java.time.format.DateTimeFormatter instance, and it'll render it as somebody in india would prefer.

If you have instead stored, say, a string containing the text 2020-06-02T12:30:00+0100, you can go from there to an instant rather easily, and then you can .atZone your way back to indian time.


问:
How to add pivot header into pandas dataframe?
I'm tring to collect some data from my db, and using pandas to make a excel file.
The dataframe structure I got like below:

```<code>>>> df

                                            2020-05-21~2020-05-27
input_cost   jim    bob     companyc            17770.65                17770.65
                            companye            3392.73                 3392.73
                            companyd            2892.30                 2892.30
                            companyf            22843.67                22843.67
             casy   dave    company_a           160.93                  160.93
                            company_b           160.93                  160.93
</code>```

And then I want to add a header to it , then export it to excel file by using df.to_excel

```<code># expected output
                                                date
data_source  sale   leader  entity_name       2020-05-21~2020-05-27       sum
input_cost   jim    bob     companyc            17770.65                17770.65
                            companye            3392.73                 3392.73
                            companyd            2892.30                 2892.30
                            companyf            22843.67                22843.67
             casy   dave    company_a           160.93                  160.93
                            company_b           160.93                  160.93
</code>```

Sorry that I'm a new bee to pandas, how can I make it work?

Thanks.

答:
You can use rename_axis:

```<code># rename index
df = df.rename_axis(['data_source', 'sale', 'leader', 'entity_name'])

# add level to columns
df.columns = pd.MultiIndex.from_product([['date'], df.columns])
</code>```

Body:
I'm tring to collect some data from my db, and using pandas to make a excel file.
The dataframe structure I got like below:

>>> df

                                            2020-05-21~2020-05-27
input_cost   jim    bob     companyc            17770.65                17770.65
                            companye            3392.73                 3392.73
                            companyd            2892.30                 2892.30
                            companyf            22843.67                22843.67
             casy   dave    company_a           160.93                  160.93
                            company_b           160.93                  160.93

And then I want to add a header to it , then export it to excel file by using df.to_excel

# expected output
                                                date
data_source  sale   leader  entity_name       2020-05-21~2020-05-27       sum
input_cost   jim    bob     companyc            17770.65                17770.65
                            companye            3392.73                 3392.73
                            companyd            2892.30                 2892.30
                            companyf            22843.67                22843.67
             casy   dave    company_a           160.93                  160.93
                            company_b           160.93                  160.93

Sorry that I'm a new bee to pandas, how can I make it work?

Thanks.

Body:
You can use rename_axis:

# rename index
df = df.rename_axis(['data_source', 'sale', 'leader', 'entity_name'])

# add level to columns
df.columns = pd.MultiIndex.from_product([['date'], df.columns])


问:
Cannot use Using Statement
I am using Visual Studio 2005 and am unable to use the "Using" statement. I have just moved some code over from a .net 4 application, but that does not seem to be the problem as it is still not usable in a new app.

```<code>Using sw as StreamWriter = new StreamWriter(userFile2)
    For each blah as blahblah in blah()
        sw.WriteLine(blah)
    sw.Close()
End Using
</code>```

Error = Using is not declared
I am lead to believe that it should work the exact same as in VB 2010.

答: You mention that you are doing this in Visual Studio 2005.  Are you working in .NET 1.1 or .NET 2.0?  I don't believe that the USING keyword is available in .NET 1.1.</p>

Title: Cannot use Using Statement

Body:
I am using Visual Studio 2005 and am unable to use the "Using" statement. I have just moved some code over from a .net 4 application, but that does not seem to be the problem as it is still not usable in a new app.

Using sw as StreamWriter = new StreamWriter(userFile2)
    For each blah as blahblah in blah()
        sw.WriteLine(blah)
    sw.Close()
End Using

Error = Using is not declared
I am lead to believe that it should work the exact same as in VB 2010.


问:
perl command line parameter -MIO flag
You can create a perl oneliner like this:

```<code>perl -MIO -e 'some_perl_code'
</code>```

Can someone explain what this -MIO means? Couldn't find any useful information about this
(On https://perldoc.perl.org/perl.html there are flags -I and -M, but this makes no sense for me).

答:
Refer to perldoc perlrun for Perl command line switches:

-Mmodule executes use module; before executing your program. This loads the module and calls its import method, causing the module to
  have its default effect, typically importing subroutines or giving
  effect to a pragma.

-MIO is interpreted as the -M option where the module name is IO.  This is equivalent to using:

```<code>perl -e 'use IO; some_perl_code'
</code>```

It does not use the -I option.

Title: perl command line parameter -MIO flag

Body:
You can create a perl oneliner like this:

perl -MIO -e 'some_perl_code'

Can someone explain what this -MIO means? Couldn't find any useful information about this
(On https://perldoc.perl.org/perl.html there are flags -I and -M, but this makes no sense for me).

Body:
Refer to perldoc perlrun for Perl command line switches:

-Mmodule executes use module; before executing your program. This loads the module and calls its import method, causing the module to
  have its default effect, typically importing subroutines or giving
  effect to a pragma.

-MIO is interpreted as the -M option where the module name is IO.  This is equivalent to using:

perl -e 'use IO; some_perl_code'

It does not use the -I option.