问:
How to convert string to double in PowerShell?
I have a script in PowerShell that I am using to import data from a CSV. I am receiving an error

Cannot convert value "Journal Amount" to type "System.Double". Error: "Input string was not in a correct format."
At C:\TestPowerShell\TestPowerShell1.ps1:98 char:1
+ $JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Va ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToDoubleOrSingle

Here is my code:

```<code>Get-Content "config.txt" | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }

$FileBrowserInitialDir = $h.FileBrowserInitialDir
$Header = 'Terminal','Company','Journal Account Code','Project','Task','Line of Business','Date','Journal Amount','Report Entry Vendor Description'

$TIDataFilePath = $h.TIDataFilePath
$TIDataFileBaseName = $h.TIDataFileBaseName

$TIScreenID = $h.TIScreenID
$TIControlFile = $h.TIControlFile
$TIErrLog = $h.TIErrLog

$ResultsFilePath = $h.ResultsFilePath
$ResultsFileBaseName = $h.ResultsFileBaseName

$dt = Get-Date -Format "MMddyyyyHHmmss"
$TIDataFile = "$($TIDataFileBaseName)$($dt).txt"
$ResultsFile = "$($ResultsFileBaseName)$($dt).txt"

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = $FileBrowserInitialDir
    Filter = 'CSV (*.csv)|*.csv'
    Title = "Select Expense csv file"
}
$null = $FileBrowser.ShowDialog()

if($FileBrowser.FileName -eq ""){
    exit
}

 $EXPENSECSV = Import-CSV $FileBrowser.FileName -Header $Header
 New-Item -path $TIDataFilePath -name $TIDataFile -type "file"
 $EXPENSECSV |foreach-object{

$Terminal =  $_.PSObject.Properties['Terminal'].Value
$Terminal = $Terminal.Insert(0,'0')

$CompanyTemp =  $_.PSObject.Properties['Company'].Value
$CompanyTemp = $CompanyTemp.Insert(0,'0')
#$Company= [String]::Concat($_.Terminal,$CompanyTemp)
$Company= [String]::Concat($Terminal,$CompanyTemp)
$LineofB =  $_.PSObject.Properties['Line of Business'].Value
#$JournalAmount = [double] $_.PSObject.Properties["Journal Amount"].Value
 $LineofB = $LineofB.Insert(0,'0')

 $Account = $_.PSObject.Properties['Journal Account Code'].Value
$Sub = $LineofB

$TranDateStr =  $_.PSObject.Properties['Date'].Value
$JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Value
$Description =  $_.PSObject.Properties['Report Entry Vendor Description'].Value

    $row = ""
    $row +=  "`"Level1`","
    $row +=  "`"$($Company)`","
    $row +=  "`"$($Account)`","
    $row +=  "`"$($Sub)`","
    $row +=  "`"$($TranDateStr)`","

    # Convert Concur Amount to Credit/Debit Amount
    # Postive Amount  --> Debit Amount
    # Negative Amount --> Credit Amount
    if($JournalAmount -lt 0){
        $JournalAmount*= -1
        $row += "`"$($JournalAmount)`","   #Credit Amount
        $row += "`"`","             #Debit Amount
    }
    else {
        $row += "`"`","             #Credit Amount
        $row += "`"$($JournalAmount)`","   #Debit Amount
    }

    $row += "`"$($Description)`""

   Add-Content -Path "$($TIDataFilePath)$($TIDataFile)" -Value $row
 }

 #Results
 New-Item -path $ResultsFilePath -name $ResultsFile -type "file"

 $ResultsStr =   "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "                             Concur to Dynamics SL                                   `n"
$ResultsStr +=  "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "Copy and paste the following into the Transaction Import screen.`n"
$ResultsStr += "Line 1: Data File Name`n"
$ResultsStr += "Line 2: Screen ID`n"
$ResultsStr += "Line 3: Control File Name`n"
$ResultsStr += "Line 4: Output Log File`n`n`n"
$ResultsStr += "$($TIDataFilePath)$($TIDataFile)`n"
$ResultsStr += "$($TIScreenID)`n"
$ResultsStr += "$($TIControlFile)`n"
$ResultsStr += "$($TIErrLog)"

 Add-Content -path "$($ResultsFilePath)$($ResultsFile)" -value $ResultsStr

Start-Process "$($ResultsFilePath)$($ResultsFile)"
</code>```

答:
To answer the question as asked:

Casting a string to [double] - as you've attempted yourself - does work, but only if the string is recognized as a (floating-point) number.

Caveat: Since PowerShell's casts are culture-invariant, only . is recognized as the decimal mark, and , is always interpreted as the thousands-grouping separator.

To parse culture-sensitively, use [double]::Parse($string) to parse based on the rules of the current culture (as reflected in $PSCulture); pass a [cultureinfo] instance as the second argument to parse based on the rules of a given culture (e.g., to parse based on the rules of the French culture, use [double]::Parse($string, [cultureinfo] 'fr-FR'))

If the string value is not recognized, you can use one of the following approaches to handle that case:

Use try / catch to handle the error; e.g., to quietly default to 0:

[double] $double = try { $string } catch { 0 }

Use -as, the conditional type conversion operator, which either returns an instance of the specified type or, if the conversion fails, $null:

$double = $string -as [double]; if ($null -eq $double) { ... }

As for what you tried:

As Mathias R. Jessen points out, the likely cause of your problem is that your CSV file does a have a header row itself, yet you also supplied headers via the -Header parameter.

This results in the CSV file's header line to be misread as the first data row, as a result of which the first object returned by Import-Csv then contains the column (header) names as property values - which then causes the [double] cast to fail, given that you're effectively executing the following:

[double] 'Journal Amount'

Therefore:

Omit the -Header parameter in your Import-Csv call.

As an optimization, simplify the property-value retrieval by using normal dot notation; simply use quoting to specify property name Journal Amount, because it contains a space:

```<code>Import-CSV $FileBrowser.FileName | # !! No -Header argument
  ForEach-Object {
    # Simpler and more efficient than:
    #   $JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Value
    $JournalAmount = [double] $_.'Journal Amount'
  }
# ...

</code>```

Body:
I have a script in PowerShell that I am using to import data from a CSV. I am receiving an error

Cannot convert value "Journal Amount" to type "System.Double". Error: "Input string was not in a correct format."
At C:\TestPowerShell\TestPowerShell1.ps1:98 char:1
+ $JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Va ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToDoubleOrSingle

Here is my code:

Get-Content "config.txt" | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }

$FileBrowserInitialDir = $h.FileBrowserInitialDir
$Header = 'Terminal','Company','Journal Account Code','Project','Task','Line of Business','Date','Journal Amount','Report Entry Vendor Description'

$TIDataFilePath = $h.TIDataFilePath
$TIDataFileBaseName = $h.TIDataFileBaseName

$TIScreenID = $h.TIScreenID
$TIControlFile = $h.TIControlFile
$TIErrLog = $h.TIErrLog

$ResultsFilePath = $h.ResultsFilePath
$ResultsFileBaseName = $h.ResultsFileBaseName

$dt = Get-Date -Format "MMddyyyyHHmmss"
$TIDataFile = "$($TIDataFileBaseName)$($dt).txt"
$ResultsFile = "$($ResultsFileBaseName)$($dt).txt"

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = $FileBrowserInitialDir
    Filter = 'CSV (*.csv)|*.csv'
    Title = "Select Expense csv file"
}
$null = $FileBrowser.ShowDialog()

if($FileBrowser.FileName -eq ""){
    exit
}

 $EXPENSECSV = Import-CSV $FileBrowser.FileName -Header $Header
 New-Item -path $TIDataFilePath -name $TIDataFile -type "file"
 $EXPENSECSV |foreach-object{

$Terminal =  $_.PSObject.Properties['Terminal'].Value
$Terminal = $Terminal.Insert(0,'0')

$CompanyTemp =  $_.PSObject.Properties['Company'].Value
$CompanyTemp = $CompanyTemp.Insert(0,'0')
#$Company= [String]::Concat($_.Terminal,$CompanyTemp)
$Company= [String]::Concat($Terminal,$CompanyTemp)
$LineofB =  $_.PSObject.Properties['Line of Business'].Value
#$JournalAmount = [double] $_.PSObject.Properties["Journal Amount"].Value
 $LineofB = $LineofB.Insert(0,'0')

 $Account = $_.PSObject.Properties['Journal Account Code'].Value
$Sub = $LineofB

$TranDateStr =  $_.PSObject.Properties['Date'].Value
$JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Value
$Description =  $_.PSObject.Properties['Report Entry Vendor Description'].Value

    $row = ""
    $row +=  "`"Level1`","
    $row +=  "`"$($Company)`","
    $row +=  "`"$($Account)`","
    $row +=  "`"$($Sub)`","
    $row +=  "`"$($TranDateStr)`","

    # Convert Concur Amount to Credit/Debit Amount
    # Postive Amount  --> Debit Amount
    # Negative Amount --> Credit Amount
    if($JournalAmount -lt 0){
        $JournalAmount*= -1
        $row += "`"$($JournalAmount)`","   #Credit Amount
        $row += "`"`","             #Debit Amount
    }
    else {
        $row += "`"`","             #Credit Amount
        $row += "`"$($JournalAmount)`","   #Debit Amount
    }

    $row += "`"$($Description)`""

   Add-Content -Path "$($TIDataFilePath)$($TIDataFile)" -Value $row
 }

 #Results
 New-Item -path $ResultsFilePath -name $ResultsFile -type "file"

 $ResultsStr =   "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "                             Concur to Dynamics SL                                   `n"
$ResultsStr +=  "----------------------------------------------------------------------------------`n"
$ResultsStr +=  "Copy and paste the following into the Transaction Import screen.`n"
$ResultsStr += "Line 1: Data File Name`n"
$ResultsStr += "Line 2: Screen ID`n"
$ResultsStr += "Line 3: Control File Name`n"
$ResultsStr += "Line 4: Output Log File`n`n`n"
$ResultsStr += "$($TIDataFilePath)$($TIDataFile)`n"
$ResultsStr += "$($TIScreenID)`n"
$ResultsStr += "$($TIControlFile)`n"
$ResultsStr += "$($TIErrLog)"

 Add-Content -path "$($ResultsFilePath)$($ResultsFile)" -value $ResultsStr

Start-Process "$($ResultsFilePath)$($ResultsFile)"

Body:
To answer the question as asked:

Casting a string to [double] - as you've attempted yourself - does work, but only if the string is recognized as a (floating-point) number.

Caveat: Since PowerShell's casts are culture-invariant, only . is recognized as the decimal mark, and , is always interpreted as the thousands-grouping separator.

To parse culture-sensitively, use [double]::Parse($string) to parse based on the rules of the current culture (as reflected in $PSCulture); pass a [cultureinfo] instance as the second argument to parse based on the rules of a given culture (e.g., to parse based on the rules of the French culture, use [double]::Parse($string, [cultureinfo] 'fr-FR'))

If the string value is not recognized, you can use one of the following approaches to handle that case:

Use try / catch to handle the error; e.g., to quietly default to 0:

[double] $double = try { $string } catch { 0 }

Use -as, the conditional type conversion operator, which either returns an instance of the specified type or, if the conversion fails, $null:

$double = $string -as [double]; if ($null -eq $double) { ... }

As for what you tried:

As Mathias R. Jessen points out, the likely cause of your problem is that your CSV file does a have a header row itself, yet you also supplied headers via the -Header parameter.

This results in the CSV file's header line to be misread as the first data row, as a result of which the first object returned by Import-Csv then contains the column (header) names as property values - which then causes the [double] cast to fail, given that you're effectively executing the following:

[double] 'Journal Amount'

Therefore:

Omit the -Header parameter in your Import-Csv call.

As an optimization, simplify the property-value retrieval by using normal dot notation; simply use quoting to specify property name Journal Amount, because it contains a space:

Import-CSV $FileBrowser.FileName | # !! No -Header argument
  ForEach-Object {
    # Simpler and more efficient than:
    #   $JournalAmount = [double] $_.PSObject.Properties['Journal Amount'].Value
    $JournalAmount = [double] $_.'Journal Amount'
  }
# ...


来源: stackexchange

问:
Is there a library that allows checking if a 24-hour time is valid?
I am trying to check if a given time is valid, using any of python's multiple datetime libraries. This given time would be in 24hr format, and examples of valid inputs are 2359, 0000, 1330, while examples of invalid inputs would be 2400, 2360, 2500.

May I ask if there is a better way to check the validity of the input, without parsing through the strings to check individually?

Preferably using python libraries, if possible

If there are no such libraries, may I instead ask how this should be done in regex?

答:
You might get along with a regular expression:

```<code>\b(?:[01][0-9]|2[0-3])[0-5][0-9]\b
</code>```

See a demo on regex101.com.

ContentLicense: CC BY-SA 4.0

Body:
You might get along with a regular expression:

\b(?:[01][0-9]|2[0-3])[0-5][0-9]\b

See a demo on regex101.com.


问:
What does bitwise_and operator exactly do in openCV?
I did not exactly understand what the "bitwise_and" operator does when used in openCV.
I would also like to know about it's parameters.</p>

答:
The answer by @mannyglover with the US flag example is a great one! I would also just quickly add that for actual images, any pixel value at 0 (pitch black) would be 'false'. Since false & anything = false, any other pixel with value above 0 would become 0.

This means that after applying bitwise_and, pitch black pixels of the mask would turn respective pixels in the original image pitch black.

Here is an example, done in OpenCV:

Original image: stack.jpg

Mask: mask.jpg

After applying result = cv2.bitwise_and(stack, stack, mask=mask) : result.jpg

ContentLicense: CC BY-SA 3.0


问:
Typescript doesn't have a function type?
I need to clone an already existing javascript code into Typescript. The javascript is :

```<code>object.getsomething( function(err, result) {
    // async
});
</code>```

How can I type the parameter function(err,result) ?

I tried retrieve(func: function(err:string, result:string) : any){}

but the my intellisense says "err" and "result" name can't be found. And I can't find any documentation about the "function" type.

答:
You can use the "fat arrow" notation as follows:</p>

```<code>retrieve(func: (err: string, result: string) => any) { ... }
</code>```

Body:
I need to clone an already existing javascript code into Typescript. The javascript is :

object.getsomething( function(err, result) {
    // async
});

How can I type the parameter function(err,result) ?

I tried retrieve(func: function(err:string, result:string) : any){}

but the my intellisense says "err" and "result" name can't be found. And I can't find any documentation about the "function" type.

Body:
You can use the "fat arrow" notation as follows:

retrieve(func: (err: string, result: string) => any) { ... }


问:
Relative performance of std::atomic and std::mutex
I am considering options for implementation of a queue for a project, a requirement of which is that the producer, at least, must be as low latency as possibe. To this end, I have been investigating "lock free" queues using std::atomic to control access to the data structure by the producer and consumer threads.  It was my hope that this would avoid overheads in std::mutex, and specifically std::unique_lock, which the code currently uses.

To this end, I have written a simple test program to assess the relative performance of std::mutex (coupled with std::unique_lock) and std::atomic.  The program also does a check to ensure the atomic object is lock free, which it is.

```<code>#include <mutex>
#include <atomic>
#include <thread>
#include <chrono>
#include <iostream>

#define CYCLES 100000000

void testAtomic()
{
   bool var(true);
   std::atomic_bool _value(true);

   std::cout << "atomic bool is ";

   if(!_value.is_lock_free())
      std::cout << "not ";
   std::cout << "lock free" << std::endl;
   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      var = _value.load();
      var = !var;
      _value.store(var);
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

void testMutex()
{
   bool var(true);
   std::mutex _mutex;
   std::chrono::high_resolution_clock _clock;

   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      std::unique_lock<std::mutex> lock(_mutex);
      var = !var;
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

int main()
{
   std::thread t1(testAtomic);
   t1.join();
   std::thread t2(testMutex);
   t2.join();
   return 0;
}
</code>```

When running this program, I get the following output:

```<code>atomic bool is lock free
3.49434 s
2.31755 s
</code>```

This would indicate to me that std::mutex (and std::unique_lock) is significantly faster, which is the opposite of what I've come to expect from reading up about atomics vs mutexes. Are my findings correct? Is there a problem with my test program? Is my understanding about the differences between the two incorrect?

The code was compiled with GCC 4.8.5 on CentOS7

答:
I was told, on some implementations of mutex initially it will spin lock internally first.

This could be why it seems faster.

If a system call would be made I doubt you would have the same results.

(I can't verify this but I thought this could be a reason)

Body:
I am considering options for implementation of a queue for a project, a requirement of which is that the producer, at least, must be as low latency as possibe. To this end, I have been investigating "lock free" queues using std::atomic to control access to the data structure by the producer and consumer threads.  It was my hope that this would avoid overheads in std::mutex, and specifically std::unique_lock, which the code currently uses.

To this end, I have written a simple test program to assess the relative performance of std::mutex (coupled with std::unique_lock) and std::atomic.  The program also does a check to ensure the atomic object is lock free, which it is.

#include <mutex>
#include <atomic>
#include <thread>
#include <chrono>
#include <iostream>

#define CYCLES 100000000

void testAtomic()
{
   bool var(true);
   std::atomic_bool _value(true);

   std::cout << "atomic bool is ";

   if(!_value.is_lock_free())
      std::cout << "not ";
   std::cout << "lock free" << std::endl;
   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      var = _value.load();
      var = !var;
      _value.store(var);
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

void testMutex()
{
   bool var(true);
   std::mutex _mutex;
   std::chrono::high_resolution_clock _clock;

   const auto _start_time = std::chrono::high_resolution_clock::now();

   for(size_t counter = 0; counter < CYCLES; counter++)
   {
      std::unique_lock<std::mutex> lock(_mutex);
      var = !var;
   }

   const auto _end_time = std::chrono::high_resolution_clock::now();

   std::cout << 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>
      (_end_time - _start_time).count() << " s" << std::endl;
}

int main()
{
   std::thread t1(testAtomic);
   t1.join();
   std::thread t2(testMutex);
   t2.join();
   return 0;
}

When running this program, I get the following output:

atomic bool is lock free
3.49434 s
2.31755 s

This would indicate to me that std::mutex (and std::unique_lock) is significantly faster, which is the opposite of what I've come to expect from reading up about atomics vs mutexes. Are my findings correct? Is there a problem with my test program? Is my understanding about the differences between the two incorrect?

The code was compiled with GCC 4.8.5 on CentOS7


问:
Max value of for each column for distinct rows of data frame in r
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

```<code>ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77
</code>```

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

```<code>my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]
</code>```

To finally give me:

```<code>all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94
</code>```

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

```<code>#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D
</code>```

答:
I see that some solutions do not handle duplicated IDs. For instance, we have ID 123 for both groups A and C.

To get an output similar to the final results in your question, another solution that handles duplicated IDs is the following

```<code># initialization
variables <- c("A", "B", "C", "D")
df_max <- data.frame(ID = numeric(length(variables)), Group = variables)

for(column in variables){
  temp_id <- df %>%
    filter(!(ID %in% df_max$ID)) %>%
    arrange(desc(!!rlang::sym(column)), desc(Rating)) %>%
    slice(1) %>%
    select(ID) %>%
    as.numeric(ID)
  df_max[df_max$Group == column, "ID"] <- temp_id
}
</code>```

Basically, the filter step makes sure that we do not consider the already selected IDs.

Output

```<code># > df_max
#
#    ID Group
# 1 123     A
# 2 721     B
# 3 142     C
# 4  21     D
</code>```

Body:
Let’s say there is an ordered df with an ID column, and other columns containing numeral data, ordered by the last column.

ID <- c(123, 142, 21, 562, 36, 721, 847, 321)
A <- c(96, 83, 73, 47, 88, 65, 72, 67)
B <- c(72, 69, 88, 75, 63, 89, 48, 80)
C <- c(95, 94, 94, 94, 65, 81, 75, 75)
D <- c(63, 88, 89, 88, 89, 79, 88, 79)
Rating <- c(97, 95, 92, 87, 85, 83, 79, 77)
df <- data.frame(ID, A, B, C, D, Rating)
df
#   ID  A  B  C  D Rating
#1 123 96 72 95 63     97
#2 142 83 69 94 88     95
#3  21 73 88 94 89     92
#4 562 47 75 94 88     87
#5  36 88 63 65 89     85
#6 721 65 89 81 79     83
#7 847 72 48 75 88     79
#8 321 67 80 75 79     77

The aim is to get the max value for each group/column, with its ID, and each pair needs to be from a distinct row (unique ID). For two IDs with the same value for a column, pick the one with the better Rating.

What I did is use the apply() function to get the max from each column, extract the IDs that have that value, and join them all into a data frame. Because I was still missing an ID for the 4th column, I used an anti join to take out the previous IDs and repeated the process to get this data frame:

my_max <- data.frame(apply(df, 2, max))
A2 <- df[which(df$A == my_max[2,1]),]%>% dplyr::select(ID, A)
B2 <- df[which(df$B == my_max[3,1]),]%>% dplyr::select(ID, B)
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
D2 <- df[which(df$D == my_max[5,1]),]%>% dplyr::select(ID, D)
all <- full_join(A2, B2, by='ID') %>% full_join(C2, by='ID') %>% full_join(D2, by='ID')
all <- all[-c(4),]
df <- anti_join(df, all, by='ID')
my_max <- data.frame(apply(df, 2, max))
C2 <- df[which(df$C == my_max[4,1]),]%>% dplyr::select(ID, C)
all <- all %>% full_join(C2, by='ID')
all <- all[-c(5),-c(4)]

To finally give me:

all
#   ID  A  B  D C.y
#1 123 96 NA NA  NA
#2 721 NA 89 NA  NA
#3  21 NA NA 89  NA
#4 142 NA NA NA  94

Is there a more clean or concise/efficient way of doing this? Not necessarily the same way, perhaps just the ID and role like:

#   ID  Group
#1 123    A
#2 721    B
#3 142    C
#4 21     D

Body:
I see that some solutions do not handle duplicated IDs. For instance, we have ID 123 for both groups A and C.

To get an output similar to the final results in your question, another solution that handles duplicated IDs is the following

# initialization
variables <- c("A", "B", "C", "D")
df_max <- data.frame(ID = numeric(length(variables)), Group = variables)

for(column in variables){
  temp_id <- df %>%
    filter(!(ID %in% df_max$ID)) %>%
    arrange(desc(!!rlang::sym(column)), desc(Rating)) %>%
    slice(1) %>%
    select(ID) %>%
    as.numeric(ID)
  df_max[df_max$Group == column, "ID"] <- temp_id
}

Basically, the filter step makes sure that we do not consider the already selected IDs.

Output

# > df_max
#
#    ID Group
# 1 123     A
# 2 721     B
# 3 142     C
# 4  21     D


问:
how do i get a list of all combinations for both words given?
i was trying to come up with a way to get a list of words like "yes" in all possible (but common) ways like lower cased and upper case and capitalized .
and then i found out you cant put two words in this function (the words "sup" & "hello") .
is there a way possible to be able to have all the words in one list with this function or should start over ?</p>

```<code>def case_insensetive(text) :
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    print (insensetive_string)

try :
   case_insensetive("sup","hello")
except :
   raise Exception ("you screwed something")
</code>```

答:
Just pass an arbitrary parameter(*args)..then take it can any numbers of arguments..

```<code>def case_insensetive(*texts):
    insensetive_string = []
    for text in texts:
        insensetive_string+=[text.lower(),text.upper(),text.capitalize()]
    print(insensetive_string)

case_insensetive("sup",'hello')
</code>```

Output: ['sup', 'SUP', 'Sup', 'hello', 'HELLO', 'Hello']

Body:
i was trying to come up with a way to get a list of words like "yes" in all possible (but common) ways like lower cased and upper case and capitalized .
and then i found out you cant put two words in this function (the words "sup" & "hello") .
is there a way possible to be able to have all the words in one list with this function or should start over ?

def case_insensetive(text) :
    insensetive_string = [text.lower(),text.upper(),text.capitalize()]
    print (insensetive_string)

try :
   case_insensetive("sup","hello")
except :
   raise Exception ("you screwed something")

Body:
Just pass an arbitrary parameter(*args)..then take it can any numbers of arguments..

def case_insensetive(*texts):
    insensetive_string = []
    for text in texts:
        insensetive_string+=[text.lower(),text.upper(),text.capitalize()]
    print(insensetive_string)

case_insensetive("sup",'hello')

Output: ['sup', 'SUP', 'Sup', 'hello', 'HELLO', 'Hello']


问:
How to sort on multiple columns using JavaScript sort?
I have following array that needs to be sorted with respect to search text 'John'.

```<code>  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 5, firstName: 'John', lastName: 'Doe'},

];
</code>```

Expected Output:

Array should be first sorted with nickName (with search text) then lastName(with search text). If nickName is not present then it should sorted with respect to firstName(with search text) with ASC sorting order.
Note: It should consider search text word as 'John'

This sort resembles like Search with Sort in your mobile's contact app

```<code>[
  // sort with nickName as higher relevance considering search text as John
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  // sort with lastName considering search text
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  // sort  with firstName as nickName is null
  {id: 5, firstName: 'John', lastName: 'Doe'},

];
</code>```

I tried localeMethod

```<code>function sortByLocale(user1, user2) {
   var sortByNickName = user1.nickName.toLowerCase().localeCompare(user2.nickName.toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortByNickName || sortByLastName;
}
</code>```

But the result is not considering search text while sorting.
One approach, I can see is creating three different arrays and sort them and combined those sorted array
Any helps would be appreciated.

Edit: Not considering the non-matched object with search text value

答:
You could take two iterations for the wanted order

one for the wanted string

for the order of the rest

var data = [{ id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith' },
  { id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew' },
  { id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John' },
  { id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John' },
  { id: 5, firstName: 'John', lastName: 'Doe' }
],
    search = 'john',
    check = (s => (o, k) => (o[k] || '').toLowerCase() === search)(search),
    keys = ['nickName', 'lastName', 'firstName'];

data.sort((a, b) => {
    const
        fns = [
            k => d = check(b, k) - check(a, k),
            k => d = (a[k] || '').localeCompare(b[k] || '')
        ];
    let d = 0;
    fns.some(fn => keys.some(fn));
    return d;
});

console.log(data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have following array that needs to be sorted with respect to search text 'John'.

  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 5, firstName: 'John', lastName: 'Doe'},

];

Expected Output:

Array should be first sorted with nickName (with search text) then lastName(with search text). If nickName is not present then it should sorted with respect to firstName(with search text) with ASC sorting order.
Note: It should consider search text word as 'John'

This sort resembles like Search with Sort in your mobile's contact app

[
  // sort with nickName as higher relevance considering search text as John
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  // sort with lastName considering search text
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  // sort  with firstName as nickName is null
  {id: 5, firstName: 'John', lastName: 'Doe'},

];

I tried localeMethod

function sortByLocale(user1, user2) {
   var sortByNickName = user1.nickName.toLowerCase().localeCompare(user2.nickName.toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortByNickName || sortByLastName;
}

But the result is not considering search text while sorting.
One approach, I can see is creating three different arrays and sort them and combined those sorted array
Any helps would be appreciated.

Edit: Not considering the non-matched object with search text value

Body:
You could take two iterations for the wanted order

one for the wanted string

for the order of the rest

var data = [{ id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith' },
  { id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew' },
  { id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John' },
  { id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John' },
  { id: 5, firstName: 'John', lastName: 'Doe' }
],
    search = 'john',
    check = (s => (o, k) => (o[k] || '').toLowerCase() === search)(search),
    keys = ['nickName', 'lastName', 'firstName'];

data.sort((a, b) => {
    const
        fns = [
            k => d = check(b, k) - check(a, k),
            k => d = (a[k] || '').localeCompare(b[k] || '')
        ];
    let d = 0;
    fns.some(fn => keys.some(fn));
    return d;
});

console.log(data);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Center all text in PHPSpreadsheet and make the cells expand to fill up with context
I struggle a bit to make all the cells set the context to center and to autoexpand so it doesnt overlap each other.

So what I try to do is:

Set the info in every cell to be centered since it makes better for printing to PDF/etc.

Make the cells expand based on how much text there is in the cell. I dont want the the information in A to go over in cell B.

Ive tried this code but it doesnt seem to work:

```<code>$styleArray = array(
            'borders' => array(
                'outline' => array(
                    'style' => Alignment::HORIZONTAL_CENTER,
                ),
            ),
        );

        $sheet ->getStyle('A1:D30')->applyFromArray($styleArray);
</code>```

Tho if I do it for one single cell (center context), it works. Did it like this:

```<code>$sheet->setCellValue('A2', $activitiesCount)->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
</code>```

For the cells expanding tho I havent found a solution for that to try yet.

I would love to do both on all my cells with only 1 command if possible.

答:
Set the info in every cell to be centered since it makes better for printing to PDF/etc.

As $sheet->getStyle('A:B') didn't work with me so here is an alternative.

 $lastColumn = $sheet->getHighestColumn();
 $lastRow = $sheet->getHighestRow();
 $sheet->getStyle("A1:$lastColumn$lastRow")->applyFromArray($styleArray); // "A1:$lastColumn$lastRow" this is basically means apply style from the first cell to last cell (last column)
```

<blockquote>
  <ol start="2">
  <li>Make the cells expand based on how much text there is in the cell. I dont want the the information in A to go over in cell B.</li>
  </ol>
</blockquote>

```$sheet->getColumnDimension('B')->setAutoSize(true);
```

you can also loop on columns and apply autosize to every column.

Body:
I struggle a bit to make all the cells set the context to center and to autoexpand so it doesnt overlap each other.

So what I try to do is:

Set the info in every cell to be centered since it makes better for printing to PDF/etc.

Make the cells expand based on how much text there is in the cell. I dont want the the information in A to go over in cell B.

Ive tried this code but it doesnt seem to work:

$styleArray = array(
            'borders' => array(
                'outline' => array(
                    'style' => Alignment::HORIZONTAL_CENTER,
                ),
            ),
        );

        $sheet ->getStyle('A1:D30')->applyFromArray($styleArray);

Tho if I do it for one single cell (center context), it works. Did it like this:

$sheet->setCellValue('A2', $activitiesCount)->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

For the cells expanding tho I havent found a solution for that to try yet.

I would love to do both on all my cells with only 1 command if possible.

Body:
Set the info in every cell to be centered since it makes better for printing to PDF/etc.

As $sheet->getStyle('A:B') didn't work with me so here is an alternative.

 $lastColumn = $sheet->getHighestColumn();
 $lastRow = $sheet->getHighestRow();
 $sheet->getStyle("A1:$lastColumn$lastRow")->applyFromArray($styleArray); // "A1:$lastColumn$lastRow" this is basically means apply style from the first cell to last cell (last column)

Make the cells expand based on how much text there is in the cell. I dont want the the information in A to go over in cell B.

$sheet->getColumnDimension('B')->setAutoSize(true);

you can also loop on columns and apply autosize to every column.


问:
Refresh indicator without scrollview
I know with a ListView or SingleChildScrollView RefreshIndicator just works natively but I want to use a RefreshIndicator on a page that doesn't scroll. Is this even possible and if so, how?

答:
Most of the other answers will work but they all have some downsides:

Using a SingleChildScrollView without adjusting the height will cause the scrolling glow effect to be not at the bottom of the page.

Setting the height to the maximum height of the current view (by using MediaQuery or a LayoutBuilder) will fix that, but there will be a render overflow when your content's height is bigger than the height of the available space.

Eventually, the following solution works perfectly without any problems:

LayoutBuilder(
  builder: (context, constraints) => RefreshIndicator(
    onRefresh: () {},
    child: SingleChildScrollView(
      physics: AlwaysScrollableScrollPhysics(),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: constraints.maxHeight
        ),
        child: Text("My Widget")
      )
    )
  )
)
```

Title: Refresh indicator without scrollview


问:
insert 0 rows without error
Can an insert ever execute without error but not insert anything?  I am using sql server 2008 and wondering if I can get away with just checking @@error or is there something I am missing.  For an update I check @@error and @@rowcount.  Having @@rowcount = 0 for an insert just seems strange to me.

edit
@Gregory  I basically wondering how I should error check an insert statement.  Are there any strange boundary cases where an insert execute and @@error is 0?

答: Additionally, an insert could end up inserting no rows without an error if there is an instead of trigger involved. </p>

Title: insert 0 rows without error


问:
Trying to get property 'name' of non-object in Laravel (View: D:\...\resources\views\home.blade.php
I have this little problem here where the code isn't getting the proper form of the name I guess...
This is the place where it shows me a mistake:

```<code>                <div class="rank-label-container">
                    <span class="label label-default rank-label">{{$user ?? ''->name}}</span>
                </div>
</code>```

Someone tried to convince me that my mistake is here in the create_user_table:

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('avatar')->default('user.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

But I didn't find any problem in here.
Any suggestions on how to fix it?
And if you need something else from the code tell me please, I didn't know what else should I give you so you can help me.
Thanks in advance!

答:
try this ..

```<code>{{dd($user)}}
</code>```

if you gat property name
then you can just call like this ..

```<code>{{$user['name']}}
</code>```

get it as array not object

Body:
I have this little problem here where the code isn't getting the proper form of the name I guess...
This is the place where it shows me a mistake:

                    {{$user ?? ''->name}}

Someone tried to convince me that my mistake is here in the create_user_table:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('avatar')->default('user.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

But I didn't find any problem in here.
Any suggestions on how to fix it?
And if you need something else from the code tell me please, I didn't know what else should I give you so you can help me.
Thanks in advance!

Body:
try this ..

{{dd($user)}}

if you gat property name
then you can just call like this ..

{{$user['name']}}

get it as array not object


问:
Uber Eats API scopes
I'm following the Uber Eats API documentation and i'm having trouble with it. I want it to work with my point of sale web app.

The documentation say:

To generate a client credentials token, retrieve your client_id and client_secret for your app from the developer dashboard...

But when trying to generate client credentials it shows:

Sorry, Can't generate an access token, make sure you have checked at least one scope which is allowed to generate access token using client credentials.

But there are no items available for selection in the developers dashboard.

Documentation: https://developer.uber.com/docs/eats/guides/authentication#example-request

Dashboard: https://developer.uber.com/dashboard/

答: You have to contact the person who provided the accounts to activate them. I think only they can do it.</p>

Title: Uber Eats API scopes


问:
Should I handle exception with Closable.use{...} in Kotlin?
According to the source of Closable.use, if an error occurs, an exception will be thrown.

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        when {
            apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
            this == null -> {}
            exception == null -> close()
            else ->
                try {
                    close()
                } catch (closeException: Throwable) {
                    // cause.addSuppressed(closeException) // ignored here
                }
        }
    }
```

<p>In most examples of <code>Closable.use</code>, try-catch is not used as shown below.
Why isn't error handling needed? Is it safe?</p>

<pre class="lang-kotlin prettyprint-override"><code>    BufferedReader(FileReader("test.file")).use { return it.readLine() }
</code>```

答:
This line

```<code> BufferedReader(FileReader("test.file")).use { return it.readLine() }
</code>```

is not safe. Reading and closing the reader can both throw IOExceptions, which are not RuntimeExceptions (caused by programming errors). That means leaving them uncaught exposes your app to crashing from things outside your control.

Since Kotlin doesn't have checked exceptions, the compiler won't warn you about this. To do this safely, you need to wrap it in try/catch. And if you want to handle read errors differently than close errors, you either need to have inner and outer try/catch statements:

```<code>try {
    BufferedReader(FileReader("test.file")).use {
        try {
            return it.readLine()
        catch (e: IOException) {
            println("Failed to read line")
        }
    }
} catch (e: IOException) {
    println("Failed to close reader")
}
</code>```

or wrap the whole thing and extract any suppressed exceptions, but then its cumbersome to distinguish between them:

```<code>try {
    BufferedReader(FileReader("test.file")).use { return it.readLine() }
} catch (e: IOException) {
    val throwables = listOf(e, *e.suppressed)
    for (throwable in throwables)
        println(throwable.message)
}
</code>```

But in practice, you're probably not going to react differently to various IOExceptions, so you can just put the one try/catch outside.

Body:
According to the source of Closable.use, if an error occurs, an exception will be thrown.

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        when {
            apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
            this == null -> {}
            exception == null -> close()
            else ->
                try {
                    close()
                } catch (closeException: Throwable) {
                    // cause.addSuppressed(closeException) // ignored here
                }
        }
    }

In most examples of Closable.use, try-catch is not used as shown below.
Why isn't error handling needed? Is it safe?

    BufferedReader(FileReader("test.file")).use { return it.readLine() }

Body:
This line

 BufferedReader(FileReader("test.file")).use { return it.readLine() }

is not safe. Reading and closing the reader can both throw IOExceptions, which are not RuntimeExceptions (caused by programming errors). That means leaving them uncaught exposes your app to crashing from things outside your control.

Since Kotlin doesn't have checked exceptions, the compiler won't warn you about this. To do this safely, you need to wrap it in try/catch. And if you want to handle read errors differently than close errors, you either need to have inner and outer try/catch statements:

try {
    BufferedReader(FileReader("test.file")).use {
        try {
            return it.readLine()
        catch (e: IOException) {
            println("Failed to read line")
        }
    }
} catch (e: IOException) {
    println("Failed to close reader")
}

or wrap the whole thing and extract any suppressed exceptions, but then its cumbersome to distinguish between them:

try {
    BufferedReader(FileReader("test.file")).use { return it.readLine() }
} catch (e: IOException) {
    val throwables = listOf(e, *e.suppressed)
    for (throwable in throwables)
        println(throwable.message)
}

But in practice, you're probably not going to react differently to various IOExceptions, so you can just put the one try/catch outside.


问:
Uncaught ReferenceError: initializeApp is not defined
I'm trying to connect a contact us form on my web app to firebase and I get this error.

These are my JS scripts in the head tag;

```<code><!--<script src="presentation.js"></script>-->
<!--<script src="home1.js"></script>-->
<script type="module" src="contact.js"></script>

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>

<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>

<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
</head>
<body onload="initializeApp()">
</code>```

And this is the contact.js file:

//import 'firebase';
//import firebase from 'firebase';
//import 'firebase/firestore';
// Initialize Firebase
function initializeApp() {

var firebaseConfig ={
    apiKey: "AIzaSyBlKtHSHez53z6LqZ4GyljzBk5Dq6G95oM",
    authDomain: "white-web-cac.firebaseapp.com",
    databaseURL: "https://white-web-cac.firebaseio.com",
    projectId: "white-web-cac",
    storageBucket: "white-web-cac.appspot.com",
    messagingSenderId: "16825950723472",
    appId: "1:168259507672:web:f352b0c66828d746b06d7904ead",
    measurementId: "G-KXTSR34654V"
};
// Initialize Firebase

firebase.initializeApp(firebaseConfig);
firebase.analytics();

// Reference messages collection
var messagesRef = firebase.database().ref('messages');

// Listen for form submit
document.getElementById('ContactFormData');
document.addEventListener('submit', submitForm);
const db = firebase.collection("ContactFormData");

// Submit form
function submitForm(e){
    e.preventDefault();

    //Get value
    let name = getInputVal('name');
    let company = getInputVal('company');
    let email = getInputVal('email');
    let phone = getInputVal('phone')
    let message = getInputVal('message');

    // Save message
    saveMessage(name, company, email, phone, message);

    // Show alert
    document.querySelector('.alert').style.display = 'block';

    // Hide alert after 3 seconds
    setTimeout(function(){
        document.querySelector('.alert').style.display = 'none';
    },3000);

    // Clear form
    document.getElementById('contactForm').reset();
}

// Function to get form value
function getInputVal(id){
    return document.getElementById(id).value;
}

// Save message to firebase
function saveMessage(name, company, email, phone, message){
    var newMessageRef = messagesRef.push();
    newMessageRef.set({
        name: name,
        company: company,
        email: email,
        phone: phone,
        message: message
    });
}
}```
</div>
</div>
</p>

<p>When I inspect my code, I get this error: "Uncaught ReferenceError: initializeApp is not defined"<br>
Please help me with what I might be doing wrong.</p>

<p>EDIT: I am uploading my html code for the form here:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contact-c" id="Contact">
    <!--<h1 class="title">Contact Us</h1>-->
    <h2 class="title"><b>We'd love to hear from you!</b></h2>
    <div class="wrapper animated bounceInLeft">
        <div class="contact">
            <h3 class="contact-us" style="text-align: center"><b>Contact Us</b></h3>
            <div class="alert">Your message has been sent!</div>
             <form id="contactForm" method="post">
                <p class="name-field">
                    <label>Name <span>*</span></label>
                    <input type="text" name="name" id="name" required>
                </p>
                <p class="company-field">
                    <label>Company</label>
                    <input type="text" name="company" id="company">
                </p>
                <p class="email-field">
                    <label>Email <span>*</span></label>
                    <input name="email" required type="email">
                </p>
                <p class="phone-field">
                    <label>Phone</label>
                    <input type="text" name="phone" id="phone">
                </p>
                <p class="message-field full">
                    <label>Message <span>*</span></label>
                    <textarea name="message" rows="5" id="message" required></textarea>
                </p>
                <p class="required-field">Required field <span>*</span></p>
                <p class="submit-button">
                    <button type="submit">Submit</button>
                </p>
            </form>
        </div>
    </div>
</div></code>```

答:
html:

```<code><html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="contact.js"></script>

    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>

    <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>

    <!-- Add Firebase products that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
</head>

<body onload="initializeApp()">
    <div class="contact-c" id="Contact">
        <!--<h1 class="title">Contact Us</h1>-->
        <h2 class="title"><b>We'd love to hear from you!</b></h2>
        <div class="wrapper animated bounceInLeft">
            <div class="contact">
                <h3 class="contact-us" style="text-align: center"><b>Contact Us</b></h3>
                <div class="alert">Your message has been sent!</div>
                <form id="contactForm" method="post">
                    <p class="name-field">
                        <label>Name <span>*</span></label>
                        <input type="text" name="name" id="name" required>
                    </p>
                    <p class="company-field">
                        <label>Company</label>
                        <input type="text" name="company" id="company">
                    </p>
                    <p class="email-field">
                        <label>Email <span>*</span></label>
                        <input id="email" name="email" required type="email">
                    </p>
                    <p class="phone-field">
                        <label>Phone</label>
                        <input type="text" name="phone" id="phone">
                    </p>
                    <p class="message-field full">
                        <label>Message <span>*</span></label>
                        <textarea name="message" rows="5" id="message" required></textarea>
                    </p>
                    <p class="required-field">Required field <span>*</span></p>
                    <p class="submit-button">
                        <input type="submit" value="Submit">
                </form>
            </div>
        </div>
    </div>
</body>

</html>
</code>```

js:

```<code>function initializeApp() {

var firebaseConfig ={
    apiKey: "AIzaSyBlKtHSHez53z6LqZ4GyljzBk5Dq6G95oM",
    authDomain: "white-web-cac.firebaseapp.com",
    databaseURL: "https://white-web-cac.firebaseio.com",
    projectId: "white-web-cac",
    storageBucket: "white-web-cac.appspot.com",
    messagingSenderId: "16825950723472",
    appId: "1:168259507672:web:f352b0c66828d746b06d7904ead",
    measurementId: "G-KXTSR34654V"
};
// Initialize Firebase

firebase.initializeApp(firebaseConfig);
firebase.analytics();
const firestore= firebase.firestore()

// Listen for form submit
const form= document.getElementById('contactForm');
form.addEventListener('submit', submitForm);
const db = firestore.collection("ContactFormData");

// Submit form
function submitForm(e){
    e.preventDefault();

    //Get value
    var name = getInputVal('name');
    var company = getInputVal('company');
    var email = getInputVal('email');
    var phone = getInputVal('phone')
    var message = getInputVal('message');

    // Save message
    saveMessage(name, company, email, phone, message);

    // Show alert
    document.querySelector('.alert').style.display = 'block';

    // Hide alert after 3 seconds
    setTimeout(function(){
        document.querySelector('.alert').style.display = 'none';
    },3000);

    // Clear form
    document.getElementById('contactForm').reset();
}

// Function to get form value
function getInputVal(id){
    return document.getElementById(id).value;
}

// Save message to firebase
const saveMessage= function(name, company, email, phone, message){
    firestore.collection("ContactFormData").add({
        name,
        company,
        email,
        phone,
        message
    })
}
}
</code>```

if it doesn't work, check the rules in your firestore database.

Body:
I'm trying to connect a contact us form on my web app to firebase and I get this error.

These are my JS scripts in the head tag;

And this is the contact.js file:

//import 'firebase';
//import firebase from 'firebase';
//import 'firebase/firestore';
// Initialize Firebase
function initializeApp() {

var firebaseConfig ={
    apiKey: "AIzaSyBlKtHSHez53z6LqZ4GyljzBk5Dq6G95oM",
    authDomain: "white-web-cac.firebaseapp.com",
    databaseURL: "https://white-web-cac.firebaseio.com",
    projectId: "white-web-cac",
    storageBucket: "white-web-cac.appspot.com",
    messagingSenderId: "16825950723472",
    appId: "1:168259507672:web:f352b0c66828d746b06d7904ead",
    measurementId: "G-KXTSR34654V"
};
// Initialize Firebase

firebase.initializeApp(firebaseConfig);
firebase.analytics();

// Reference messages collection
var messagesRef = firebase.database().ref('messages');

// Listen for form submit
document.getElementById('ContactFormData');
document.addEventListener('submit', submitForm);
const db = firebase.collection("ContactFormData");

// Submit form
function submitForm(e){
    e.preventDefault();

    //Get value
    let name = getInputVal('name');
    let company = getInputVal('company');
    let email = getInputVal('email');
    let phone = getInputVal('phone')
    let message = getInputVal('message');

    // Save message
    saveMessage(name, company, email, phone, message);

    // Show alert
    document.querySelector('.alert').style.display = 'block';

    // Hide alert after 3 seconds
    setTimeout(function(){
        document.querySelector('.alert').style.display = 'none';
    },3000);

    // Clear form
    document.getElementById('contactForm').reset();
}

// Function to get form value
function getInputVal(id){
    return document.getElementById(id).value;
}

// Save message to firebase
function saveMessage(name, company, email, phone, message){
    var newMessageRef = messagesRef.push();
    newMessageRef.set({
        name: name,
        company: company,
        email: email,
        phone: phone,
        message: message
    });
}
}

When I inspect my code, I get this error: "Uncaught ReferenceError: initializeApp is not defined"

Please help me with what I might be doing wrong.

EDIT: I am uploading my html code for the form here:

We'd love to hear from you!

Contact Us

Your message has been sent!

             <form id="contactForm" method="post">

                    Name *
                    <input type="text" name="name" id="name" required>

                    Company
                    <input type="text" name="company" id="company">

                    Email *
                    <input name="email" required type="email">

                    Phone
                    <input type="text" name="phone" id="phone">

                    Message *
                    <textarea name="message" rows="5" id="message" required></textarea>

Required field *

                    <button type="submit">Submit</button>

            </form>

Body:
html:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="contact.js"></script>

    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>

    <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>

    <!-- Add Firebase products that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
</head>

<body onload="initializeApp()">
    <div class="contact-c" id="Contact">
        <!--<h1 class="title">Contact Us</h1>-->
        <h2 class="title"><b>We'd love to hear from you!</b></h2>
        <div class="wrapper animated bounceInLeft">
            <div class="contact">
                <h3 class="contact-us" style="text-align: center"><b>Contact Us</b></h3>
                <div class="alert">Your message has been sent!</div>
                <form id="contactForm" method="post">
                    <p class="name-field">
                        <label>Name <span>*</span></label>
                        <input type="text" name="name" id="name" required>
                    </p>
                    <p class="company-field">
                        <label>Company</label>
                        <input type="text" name="company" id="company">
                    </p>
                    <p class="email-field">
                        <label>Email <span>*</span></label>
                        <input id="email" name="email" required type="email">
                    </p>
                    <p class="phone-field">
                        <label>Phone</label>
                        <input type="text" name="phone" id="phone">
                    </p>
                    <p class="message-field full">
                        <label>Message <span>*</span></label>
                        <textarea name="message" rows="5" id="message" required></textarea>
                    </p>
                    <p class="required-field">Required field <span>*</span></p>
                    <p class="submit-button">
                        <input type="submit" value="Submit">
                </form>
            </div>
        </div>
    </div>
</body>

</html>

js:

function initializeApp() {

var firebaseConfig ={
    apiKey: "AIzaSyBlKtHSHez53z6LqZ4GyljzBk5Dq6G95oM",
    authDomain: "white-web-cac.firebaseapp.com",
    databaseURL: "https://white-web-cac.firebaseio.com",
    projectId: "white-web-cac",
    storageBucket: "white-web-cac.appspot.com",
    messagingSenderId: "16825950723472",
    appId: "1:168259507672:web:f352b0c66828d746b06d7904ead",
    measurementId: "G-KXTSR34654V"
};
// Initialize Firebase

firebase.initializeApp(firebaseConfig);
firebase.analytics();
const firestore= firebase.firestore()

// Listen for form submit
const form= document.getElementById('contactForm');
form.addEventListener('submit', submitForm);
const db = firestore.collection("ContactFormData");

// Submit form
function submitForm(e){
    e.preventDefault();

    //Get value
    var name = getInputVal('name');
    var company = getInputVal('company');
    var email = getInputVal('email');
    var phone = getInputVal('phone')
    var message = getInputVal('message');

    // Save message
    saveMessage(name, company, email, phone, message);

    // Show alert
    document.querySelector('.alert').style.display = 'block';

    // Hide alert after 3 seconds
    setTimeout(function(){
        document.querySelector('.alert').style.display = 'none';
    },3000);

    // Clear form
    document.getElementById('contactForm').reset();
}

// Function to get form value
function getInputVal(id){
    return document.getElementById(id).value;
}

// Save message to firebase
const saveMessage= function(name, company, email, phone, message){
    firestore.collection("ContactFormData").add({
        name,
        company,
        email,
        phone,
        message
    })
}
}

if it doesn't work, check the rules in your firestore database.


问:
Sending USSD codes in React native
I'm trying to create an app with React Native to sending some USSD codes and Manage SMSs.

actually, I need to do two operations in my app:

USSD

SMS

I Googled it but there are not many resources about this topic, so If someone knows how to do it, I'll appreciate a lot your help, Thanks!

答:
This can be done using react-native-ussd library, for dialing and receiving USSD responses.
But currently only Android is supported.</p>

Title: Sending USSD codes in React native


问:
R Plot: spead out axis labels evenly
I'm currently struggling with finding out, how to spread the axis labels evenly.

Here is the code I'm using:

```<code>plot(1:10, type = "p", xlab = "", ylab = "")
axis(1, at = c(1:10))
axis(2, at = c(1:10))
grid(nx = 10, ny = 10)
</code>```

What I'm trying to achieve is to have the data points in the center of the respective grid box and to have the labels (1-10) to be in the center. How can I achieve this?

Any help or direction would be greatly appreciated, thank you!

答:
As the help file for grid tells you, when you need more control of the grid lines, you should draw them directly with abline. When you want precise control of the axis limits rather than allowing R to choose pretty limits, you specify xaxs = "i" and yaxs = "i" in your initial plot command.

plot(1:10, type = "p", xlab = "", ylab = "",
     xlim = c(0.5, 10.5), ylim = c(0.5, 10.5), yaxs = "i", xaxs = "i")
abline(h = 2:10 - 0.5, v = 2:10 - 0.5, lty = "dotted", col = "lightgray")
axis(1, at = c(0:11))
axis(2, at = c(1:10))
```

Title: R Plot: spead out axis labels evenly

Body:
I'm currently struggling with finding out, how to spread the axis labels evenly.

Here is the code I'm using:

plot(1:10, type = "p", xlab = "", ylab = "")
axis(1, at = c(1:10))
axis(2, at = c(1:10))
grid(nx = 10, ny = 10)

What I'm trying to achieve is to have the data points in the center of the respective grid box and to have the labels (1-10) to be in the center. How can I achieve this?

Any help or direction would be greatly appreciated, thank you!


问:
React state variable updates automatically without calling setState
I am facing the following issue and not able to figure it out.

I have two variables inside the state called userDetails & userDetailsCopy. In componentDidMount I am making an API call and saving the data in both userDetails & userDetailsCopy.

I am maintaining another copy called userDetailsCopy for comparison purposes.

I am updating only userDetails inside setState but even userDetailsCopy is also getting updated instead of have old API data.

Below is the code :

```<code>constructor(){
    super()
    this.state={
        userDetails:{},
        userDetailsCopy: {}
    }
}

componentDidMount(){
     // API will return the following data
       apiUserDetails : [
            {
                 'name':'Tom',
                 'age' : '28'
            },
            {
                 'name':'Jerry',
                 'age' : '20'

            }
        ]

       resp.data is nothing but apiUserDetails
    /////

     apiCall()
     .then((reps) => {
         this.setState({
             userDetails: resp.data,
             userDetailsCopy: resp.data
         })
     })
}

updateValue = (text,i) => {
     let userDetail = this.state.userDetails
     userDetail[i].name = text
     this.setState({
         userDetails: userDetail
     })
}

submit = () => {
     console.log(this.state.userDetials) // returns updated values
     console.log(this.state.userDetailsCopy) // also return updated values instead of returning old API data
}

Need a quick solution on this.
</code>```

答:
React state and its data should be treated as immutable.

From the React documentation:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

Here are five ways how to treat state as immutable:

Approach #1: Object.assign and Array.concat

```<code>updateValue = (text, index) => {
  const { userDetails } = this.state;

  const userDetail = Object.assign({}, userDetails[index]);

  userDetail.name = text;

  const newUserDetails = []
    .concat(userDetails.slice(0, index))
    .concat(userDetail)
    .concat(userDetails.slice(index + 1));

  this.setState({
    userDetails: newUserDetails
  });
}
</code>```

Approach #2: Object and Array Spread

```<code>updateValue = (text, index) => {
  const { userDetails } = this.state;

  const userDetail = { ...userDetails[index], name: text };

  this.setState({
    userDetails: [
      ...userDetails.slice(0, index),
      userDetail,
      ...userDetails.slice(index + 1)
    ]
  });
}
</code>```

Approach #3: Immutability Helper

import update from 'immutability-helper';

updateValue = (text, index) => {
  const userDetails = update(this.state.userDetails, {
    [index]: {
      $merge: {
        name: text
      }
    }
  });

  this.setState({ userDetails });
};
```

<p><strong>Approach #4: Immutable.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { Map, List } from 'immutable';

updateValue = (text, index) => {
  const userDetails = this.state.userDetails.setIn([index, 'name'], text);

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

Approach #5: Immer

import produce from "immer";

updateValue = (text, index) => {
  this.setState(
    produce(draft => {
        draft.userDetails[index].name = text;
    })
  );
};
```

<p><em>Note:</em>
Option #1 and #2 only do a shallow clone. So if your object contains nested objects, those nested objects will be copied by reference instead of by value. So if you change the nested object, you’ll mutate the original object.</p>

<p>To maintain the <code>userDetailsCopy</code> unchanged you need to maintain the immutability of <code>state</code> (and <code>state.userDetails</code> of course). </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getUserDerails() {
  return new Promise(resolve => setTimeout(
    () => resolve([
      { id: 1, name: 'Tom', age : 40 },
      { id: 2, name: 'Jerry', age : 35 }
    ]),
    300
  ));
}

class App extends React.Component {
  state = {
    userDetails: [],
    userDetailsCopy: []
  };

  componentDidMount() {
    getUserDerails().then(users => this.setState({
      userDetails: users,
      userDetailsCopy: users
    }));
  }

  createChangeHandler = userDetailId => ({ target: { value } }) => {
    const { userDetails } = this.state;

    const index = userDetails.findIndex(({ id }) => id === userDetailId);
    const userDetail = { ...userDetails[index], name: value };

    this.setState({
      userDetails: [
        ...userDetails.slice(0, index),
        userDetail,
        ...userDetails.slice(index + 1)
      ]
    });
  };

  render() {
    const { userDetails, userDetailsCopy } = this.state;

    return (
      <React.Fragment>
        {userDetails.map(userDetail => (
          <input
            key={userDetail.id}
            onChange={this.createChangeHandler(userDetail.id)}
            value={userDetail.name}
          />
        ))}

        ```userDetails: {JSON.stringify(userDetails)}```
        ```userDetailsCopy: {JSON.stringify(userDetailsCopy)}```
      </React.Fragment>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);</code>```

```

Body:
I am facing the following issue and not able to figure it out.

I have two variables inside the state called userDetails & userDetailsCopy. In componentDidMount I am making an API call and saving the data in both userDetails & userDetailsCopy.

I am maintaining another copy called userDetailsCopy for comparison purposes.

I am updating only userDetails inside setState but even userDetailsCopy is also getting updated instead of have old API data.

Below is the code :

constructor(){
    super()
    this.state={
        userDetails:{},
        userDetailsCopy: {}
    }
}

componentDidMount(){
     // API will return the following data
       apiUserDetails : [
            {
                 'name':'Tom',
                 'age' : '28'
            },
            {
                 'name':'Jerry',
                 'age' : '20'

            }
        ]

       resp.data is nothing but apiUserDetails
    /////

     apiCall()
     .then((reps) => {
         this.setState({
             userDetails: resp.data,
             userDetailsCopy: resp.data
         })
     })
}

updateValue = (text,i) => {
     let userDetail = this.state.userDetails
     userDetail[i].name = text
     this.setState({
         userDetails: userDetail
     })
}

submit = () => {
     console.log(this.state.userDetials) // returns updated values
     console.log(this.state.userDetailsCopy) // also return updated values instead of returning old API data
}

Need a quick solution on this.

Body:
React state and its data should be treated as immutable.

From the React documentation:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

Here are five ways how to treat state as immutable:

Approach #1: Object.assign and Array.concat

updateValue = (text, index) => {
  const { userDetails } = this.state;

  const userDetail = Object.assign({}, userDetails[index]);

  userDetail.name = text;

  const newUserDetails = []
    .concat(userDetails.slice(0, index))
    .concat(userDetail)
    .concat(userDetails.slice(index + 1));

  this.setState({
    userDetails: newUserDetails
  });
}

Approach #2: Object and Array Spread

updateValue = (text, index) => {
  const { userDetails } = this.state;

  const userDetail = { ...userDetails[index], name: text };

  this.setState({
    userDetails: [
      ...userDetails.slice(0, index),
      userDetail,
      ...userDetails.slice(index + 1)
    ]
  });
}

Approach #3: Immutability Helper

import update from 'immutability-helper';

updateValue = (text, index) => {
  const userDetails = update(this.state.userDetails, {
    [index]: {
      $merge: {
        name: text
      }
    }
  });

  this.setState({ userDetails });
};

Approach #4: Immutable.js

import { Map, List } from 'immutable';

updateValue = (text, index) => {
  const userDetails = this.state.userDetails.setIn([index, 'name'], text);

  this.setState({ userDetails });
};

Approach #5: Immer

import produce from "immer";

updateValue = (text, index) => {
  this.setState(
    produce(draft => {
        draft.userDetails[index].name = text;
    })
  );
};

Note:
Option #1 and #2 only do a shallow clone. So if your object contains nested objects, those nested objects will be copied by reference instead of by value. So if you change the nested object, you’ll mutate the original object.

To maintain the userDetailsCopy unchanged you need to maintain the immutability of state (and state.userDetails of course).

function getUserDerails() {
  return new Promise(resolve => setTimeout(
    () => resolve([
      { id: 1, name: 'Tom', age : 40 },
      { id: 2, name: 'Jerry', age : 35 }
    ]),
    300
  ));
}

class App extends React.Component {
  state = {
    userDetails: [],
    userDetailsCopy: []
  };

  componentDidMount() {
    getUserDerails().then(users => this.setState({
      userDetails: users,
      userDetailsCopy: users
    }));
  }

  createChangeHandler = userDetailId => ({ target: { value } }) => {
    const { userDetails } = this.state;

    const index = userDetails.findIndex(({ id }) => id === userDetailId);
    const userDetail = { ...userDetails[index], name: value };

    this.setState({
      userDetails: [
        ...userDetails.slice(0, index),
        userDetail,
        ...userDetails.slice(index + 1)
      ]
    });
  };

  render() {
    const { userDetails, userDetailsCopy } = this.state;

    return (
      <React.Fragment>
        {userDetails.map(userDetail => (
          <input
            key={userDetail.id}
            onChange={this.createChangeHandler(userDetail.id)}
            value={userDetail.name}
          />
        ))}

        <pre>userDetails: {JSON.stringify(userDetails)}</pre>
        <pre>userDetailsCopy: {JSON.stringify(userDetailsCopy)}</pre>
      </React.Fragment>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


问:
Can SVM method deal with 1 dimensional data for forecasting?
I am working on using SVM to predict the future values of one particular 1D data. The data contains 54 month sales values and with their month indexes from 1 to 54. The first problem is that I think the SVM could do the prediction but I am not quit sure about it. As I know, SVM could do the classification but how about the regression? Could anyone tell me about why SVM can do the regression?

And in my problem, I tried to set the X as month indexes and y as the value for each month. I am not quite sure if I was doing right as there is no label(or the label I've tired using the value) and feature is only the month index.

I tried to fit it by from sklearn import svm and get the result that the accuracy for training  set is 100% and 0 for testing set. I do not know where is wrong.

Here's the code:

```<code>import pandas as pd
import numpy as np

df = pd.read_csv('11.csv', header=None, names = ['a', 'b', 'c'])

X = df['b'].values.reshape(-1,1)
y = df['c'].values.reshape(-1,1)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

from sklearn import svm

clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')
clf.fit(X_train, y_train.ravel())

print("training result：",clf.score(X_train, y_train))

print("testing result：",clf.score(X_test,y_test))
</code>```

The dataset looks like this X = [1, 2, 3, 4,...,53, 54] and y = [90, 18, 65, 150.... 289], 1D dataset.

答:
SVM for regression purposes is called Support Vector Regression (SVR) and it's available in the sklearn module.

Instead of svm.SVC() you need to use svm.SVR() with the appropriate parameters. And yes, 1D data should be fine.

Here is a more complete example.

Body:
I am working on using SVM to predict the future values of one particular 1D data. The data contains 54 month sales values and with their month indexes from 1 to 54. The first problem is that I think the SVM could do the prediction but I am not quit sure about it. As I know, SVM could do the classification but how about the regression? Could anyone tell me about why SVM can do the regression?

And in my problem, I tried to set the X as month indexes and y as the value for each month. I am not quite sure if I was doing right as there is no label(or the label I've tired using the value) and feature is only the month index.

I tried to fit it by from sklearn import svm and get the result that the accuracy for training  set is 100% and 0 for testing set. I do not know where is wrong.

Here's the code:

import pandas as pd
import numpy as np

df = pd.read_csv('11.csv', header=None, names = ['a', 'b', 'c'])

X = df['b'].values.reshape(-1,1)
y = df['c'].values.reshape(-1,1)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

from sklearn import svm

clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')
clf.fit(X_train, y_train.ravel())

print("training result：",clf.score(X_train, y_train))

print("testing result：",clf.score(X_test,y_test))

The dataset looks like this X = [1, 2, 3, 4,...,53, 54] and y = [90, 18, 65, 150.... 289], 1D dataset.


问:
scala - count every line in which a word occurs
I want to find create a Map that has a word as a key and a List of integers as a value.
The Integers in the list should represent the line numbers as indices. Like so:

```<code>Map("test" -> List(0, 2), "test2"->List(1),"foo" -> List(0, 3), "bar" -> List(2))
</code>```

This would mean that the word test occurred in line 0&2, foo in line 0&3 and bar only in line 2.

I already managed to create a list of all words that occur in one line of text and read them to a list e.g.

```<code>val wordsWithLine= List((0,"test"), (0,"foo"), (1,"test2"), (2,"test"), (2,"bar"), (0,"test"), (3,"foo"))
</code>```

Now I'm stuck and have no Idea how I can create this map. I know that the function definition has to look like this, but I have no idea how to implement it:

```<code>def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] = {???}
</code>```

My idea was to use groupMapReduce() ? But I can't wrap my head around how this works.

I'm very new to Scala and functional programming in general so any tips would be highly appreciated

答:
At first you need to group by word, then map the result so that key is still a word but value is a distinct list of line numbers:

```<code>listwithIndices.groupBy(wWI => wWI._2).map(group => group._1 -> group._2.map(item => item._1).distinct)
</code>```

I suggest to play with this code in scala interactive shell to figure out how exactly it works.

It is possible to do it may other (more succinct) ways (using groupMap or groupBy and mapValues).

Body:
I want to find create a Map that has a word as a key and a List of integers as a value.
The Integers in the list should represent the line numbers as indices. Like so:

Map("test" -> List(0, 2), "test2"->List(1),"foo" -> List(0, 3), "bar" -> List(2))

This would mean that the word test occurred in line 0&2, foo in line 0&3 and bar only in line 2.

I already managed to create a list of all words that occur in one line of text and read them to a list e.g.

val wordsWithLine= List((0,"test"), (0,"foo"), (1,"test2"), (2,"test"), (2,"bar"), (0,"test"), (3,"foo"))

Now I'm stuck and have no Idea how I can create this map. I know that the function definition has to look like this, but I have no idea how to implement it:

def createIndexMap(listwithIndices: List[(Int, String)]): Map[String, List[Int]] = {???}

My idea was to use groupMapReduce() ? But I can't wrap my head around how this works.

I'm very new to Scala and functional programming in general so any tips would be highly appreciated

Body:
At first you need to group by word, then map the result so that key is still a word but value is a distinct list of line numbers:

listwithIndices.groupBy(wWI => wWI._2).map(group => group._1 -> group._2.map(item => item._1).distinct)

I suggest to play with this code in scala interactive shell to figure out how exactly it works.

It is possible to do it may other (more succinct) ways (using groupMap or groupBy and mapValues).


问:
C# Mongo BsonSerializer.Deserialize Ignore elements that do not exist
Is there a flat that will tell the C# Mongo BsonSerializer to ignore elements that do not exist in the poco class

Example collection

```<code>Animal {"Type" : "Cat", "Skill" : "Jump"}
Animal {"Type" : "Dog", "Skill" : "Bark", "Owner" : "Jimmy"}
</code>```

If the cat C# class only has

```<code>public string Type {get;set;}
public string Skill {get;set;}
</code>```

When I attempt to execute the following

```<code> var test = BsonSerializer.Deserialize<Animal>(result);
</code>```

The first item will work fine, the second one will throw an exception that Owner does not exist.

答:
Or you can use Convention to do it for all types at once

var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionPack, _ => true);
```

Body:
Is there a flat that will tell the C# Mongo BsonSerializer to ignore elements that do not exist in the poco class

Example collection

Animal {"Type" : "Cat", "Skill" : "Jump"}
Animal {"Type" : "Dog", "Skill" : "Bark", "Owner" : "Jimmy"}

If the cat C# class only has

public string Type {get;set;}
public string Skill {get;set;}

When I attempt to execute the following

 var test = BsonSerializer.Deserialize<Animal>(result);

The first item will work fine, the second one will throw an exception that Owner does not exist.


问:
Load data into std::vector<char> efficiently
My understanding is that you can access the data in a std::vector using pointers. For example:

```<code>char *ptr;
std::vector<char> v1 {'A', 'B', 'C'};
ptr = &v1[0]
if (*(ptr+1) == 'B')
    std::cout << "Addressing via pointer works\n";
</code>```

How about loading a std::vector directly? For example:

```<code>std::vector<char> v2;
v2.reserve(3); // allocate memory in the vector
ptr = &v2[0]
*ptr = 'A';
*(ptr+1) = 'B';
*(ptr+2) = 'C';
if (v2[1] == 'B')
    std::cout << "Data is in vector buffer!\n";
</code>```

but

```<code>if (!v2.size())
    std::cout << "But the vector doesn't know about it!\n";
</code>```

My question: Is there any way to tell the v2 vector that its internal memory buffer is loaded with data? This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.

I look forward to your comments.

答:
Is there any way to tell the v2 vector that its internal memory buffer is loaded with data?

No.

The behaviour of your second example is undefined.

This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.

You can read a file into vector like this:

```<code>std::vector<char> v3(count);
ifs.read(v3.data(), count);
</code>```

Or like this:

```<code>using It = std::istreambuf_iterator<char>;
std::vector<char> v4(It{ifs}, It{});
</code>```

Body:
My understanding is that you can access the data in a std::vector using pointers. For example:

char *ptr;
std::vector<char> v1 {'A', 'B', 'C'};
ptr = &v1[0]
if (*(ptr+1) == 'B')
    std::cout << "Addressing via pointer works\n";

How about loading a std::vector directly? For example:

std::vector<char> v2;
v2.reserve(3); // allocate memory in the vector
ptr = &v2[0]
*ptr = 'A';
*(ptr+1) = 'B';
*(ptr+2) = 'C';
if (v2[1] == 'B')
    std::cout << "Data is in vector buffer!\n";

but

if (!v2.size())
    std::cout << "But the vector doesn't know about it!\n";

My question: Is there any way to tell the v2 vector that its internal memory buffer is loaded with data? This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.

I look forward to your comments.

Body:
Is there any way to tell the v2 vector that its internal memory buffer is loaded with data?

No.

The behaviour of your second example is undefined.

This would be useful when you want to use a std::vector to hold data that is sourced from a file stream.

You can read a file into vector like this:

std::vector<char> v3(count);
ifs.read(v3.data(), count);

Or like this:

using It = std::istreambuf_iterator<char>;
std::vector<char> v4(It{ifs}, It{});


问:
Is it possible to run iis6 and iis7 in parallel?
We have a huge amount of webApplications running on IIS6. Because we want to run an MS MVC2 or MVC3 Webapp we have to use IIS7. Migrating these huge amount of IIS6 webapps is way to time intensive for us.

is it possible to run IIS6 and IIS7 on one machine?

Thanks!

答:
You can use IIS 7 / 7.5 but just run the application pools in the "classic" pipeline mode, which is the same as running your application in IIS6.

That way you can handle legacy applications and still be free to leverage the advantages of IIS7.  Here's an article on the pipeline differences.

http://learn.iis.net/page.aspx/243/aspnet-integration-with-iis-7/


问:
How to Install Deno on Ubuntu
The command I run is:

```<code>curl -fsSL https://deno.land/x/install/install.sh | sh
</code>```

The output is:

```<code>######################################################################## 100.0%
Archive:  /root/.deno/bin/deno.zip
  inflating: deno
Deno was installed successfully to /root/.deno/bin/deno
Manually add the directory to your $HOME/.bash_profile (or similar)
  export DENO_INSTALL="/root/.deno"
  export PATH="$DENO_INSTALL/bin:$PATH"
Run '/root/.deno/bin/deno --help' to get started
</code>```

After this, I run deno in the terminal and it gives me an error.

Can anyone explain how to install Deno in Ubuntu properly?

答:
I was also facing the same issue but below command worked for me:</p>

```<code>curl -fsSL https://deno.land/x/install/install.sh | sudo DENO_INSTALL=/usr/local sh
</code>```

Title: How to Install Deno on Ubuntu

Body:
The command I run is:

curl -fsSL https://deno.land/x/install/install.sh | sh

The output is:

######################################################################## 100.0%
Archive:  /root/.deno/bin/deno.zip
  inflating: deno
Deno was installed successfully to /root/.deno/bin/deno
Manually add the directory to your $HOME/.bash_profile (or similar)
  export DENO_INSTALL="/root/.deno"
  export PATH="$DENO_INSTALL/bin:$PATH"
Run '/root/.deno/bin/deno --help' to get started

After this, I run deno in the terminal and it gives me an error.

Can anyone explain how to install Deno in Ubuntu properly?

Body:
I was also facing the same issue but below command worked for me:

curl -fsSL https://deno.land/x/install/install.sh | sudo DENO_INSTALL=/usr/local sh


问:
Postgresql: Joining TimeSeries data with different time scaled: Weekly, Daily and Monthly
I've got data that comes in from the same sources at different rates. I'd like to plot the data (and do some thresholding etc) and the easiest way to do it would be treating it as timeseries data.

My data looks like:

```<code>SourceID, SubmissionTime,  Daily_Data
-------------------------------
ABC,    2020-01-01 10h32,  100
ABC,    2020-01-01 10h45,  101
ABC,    2020-01-02 09h01,  120
DEF,    2020-01-01 15h30,  123
</code>```

and

```<code>SourceID, SubmissionTime,  Weekly_Data
-------------------------------
ABC,    2020-01-01 09h00,  Joe
ABC,    2020-01-08 09h21,  Soap
ABC,    2020-01-14 15h20,  Bill
</code>```

The daily and weekly submissions are roughly a day or a week apart and are user inputs so there are gaps, delay, bad data etc. What I'd like to get out is something like:

```<code>SourceID, Daily_Date, Weekly_date, Weekly_datatime, Weekly_Data
-------------------------------
ABC,    2020-01-01, 2020-01-01 09h00,  101, Joe
ABC,    2020-01-02, 2020-01-01 09h00,  120, Joe
ABC,    2020-01-03, 2020-01-01 09h00,  122, Joe
...
ABC,    2020-01-07, 2020-01-01 09h00,  133, Joe
ABC,    2020-01-07, 2020-01-14 15h20,  145, Soap
</code>```

Extracting the date is pretty trivial but how do I do a nearest datetime join for rows only after the weekly submission has occured. I've been doing something similar in TimscaleDB but this is on someone else's DB now who doesn't want extra extensions...

答:
I figured it out. It's basically a "last object carried forward" problem where I did a straight up join of the daily/weekly/monthly tables and carried the last monthly/weekly observations forward to the daily time samples.

More info here

I created a function, an aggregate, and then ran the table through those:

```<code>CREATE OR REPLACE FUNCTION fun(a FLOAT, b FLOAT)
RETURNS FLOAT
LANGUAGE SQL
AS '
  SELECT COALESCE(b, a)
';

select a,b,t,v,
    fun(t,v) as v_or_t
from tbl
order by a,b,t
;
</code>```

and

```<code>create or replace function locf_s(a float, b float)
returns float
language sql
as '
  select coalesce(b, a)
';

drop aggregate if exists locf(float);
CREATE AGGREGATE locf(FLOAT) (
  SFUNC = locf_s,
  STYPE = FLOAT
);
</code>```

and finally:

```<code>with weekly_data as (SELECT source_id, submissiontime, weekly_data from weekly_table)
select distinct on (source_id, submissiontime)
    source_id,
    submissiontime,
    daily_data,
    locf(weekly_data) over (PARTITION by source_id ORDER by submissiontime) as weekly_data,

from daily_table
join weekly_table on daily_table.source_id = weekly_table.source_id
order by source_id, submissiontime desc;
</code>```

this is just pseudo code, not exactly what I was using (since I multiple tables and weird data) so please forgive any faults, I'm hoping the idea comes across.

Body:
I've got data that comes in from the same sources at different rates. I'd like to plot the data (and do some thresholding etc) and the easiest way to do it would be treating it as timeseries data.

My data looks like:

SourceID, SubmissionTime,  Daily_Data
-------------------------------
ABC,    2020-01-01 10h32,  100
ABC,    2020-01-01 10h45,  101
ABC,    2020-01-02 09h01,  120
DEF,    2020-01-01 15h30,  123

and

SourceID, SubmissionTime,  Weekly_Data
-------------------------------
ABC,    2020-01-01 09h00,  Joe
ABC,    2020-01-08 09h21,  Soap
ABC,    2020-01-14 15h20,  Bill

The daily and weekly submissions are roughly a day or a week apart and are user inputs so there are gaps, delay, bad data etc. What I'd like to get out is something like:

SourceID, Daily_Date, Weekly_date, Weekly_datatime, Weekly_Data
-------------------------------
ABC,    2020-01-01, 2020-01-01 09h00,  101, Joe
ABC,    2020-01-02, 2020-01-01 09h00,  120, Joe
ABC,    2020-01-03, 2020-01-01 09h00,  122, Joe
...
ABC,    2020-01-07, 2020-01-01 09h00,  133, Joe
ABC,    2020-01-07, 2020-01-14 15h20,  145, Soap

Extracting the date is pretty trivial but how do I do a nearest datetime join for rows only after the weekly submission has occured. I've been doing something similar in TimscaleDB but this is on someone else's DB now who doesn't want extra extensions...

Body:
I figured it out. It's basically a "last object carried forward" problem where I did a straight up join of the daily/weekly/monthly tables and carried the last monthly/weekly observations forward to the daily time samples.

More info here

I created a function, an aggregate, and then ran the table through those:

CREATE OR REPLACE FUNCTION fun(a FLOAT, b FLOAT)
RETURNS FLOAT
LANGUAGE SQL
AS '
  SELECT COALESCE(b, a)
';

select a,b,t,v,
    fun(t,v) as v_or_t
from tbl
order by a,b,t
;

and

create or replace function locf_s(a float, b float)
returns float
language sql
as '
  select coalesce(b, a)
';

drop aggregate if exists locf(float);
CREATE AGGREGATE locf(FLOAT) (
  SFUNC = locf_s,
  STYPE = FLOAT
);

and finally:

with weekly_data as (SELECT source_id, submissiontime, weekly_data from weekly_table)
select distinct on (source_id, submissiontime)
    source_id,
    submissiontime,
    daily_data,
    locf(weekly_data) over (PARTITION by source_id ORDER by submissiontime) as weekly_data,

from daily_table
join weekly_table on daily_table.source_id = weekly_table.source_id
order by source_id, submissiontime desc;

this is just pseudo code, not exactly what I was using (since I multiple tables and weird data) so please forgive any faults, I'm hoping the idea comes across.


问:
How to whitelist the Function app in Azure SQL Database
I need to configure Azure SQL Database firewall settings so that it can only be accessed by my Azure Function app. The problem is I'm running the app in a consumption plan, and as far as I know, the outbound IP address(es) can change even when I don't take any actions.

Is there a way to whitelist the app so that I protect the database from unwanted connections?

I thought of whitelisting by Azure region since everything is hosted in the same region, but then how do I guard against other apps in the same region? That's why I'm thinking of using specific IP addresses. My only concern with this approach is, I don't know if other function apps can share the same outbound IP addresses as my own.

P.S. Currently, my firewall settings deny public network access and allow Azure services to connect only.

答:
You can do this by assigning a static IP to the function app and whitelist at the SQL Server -INbound Networking side and Deny all requests. However you have to change the consumption plan to Appservice to assign a static IP.

https://learn.microsoft.com/en-us/azure/azure-functions/ip-addresses#dedicated-ip-addresses

Also, you can try creating a Vnet peering for those services and block other requests.