问:
PowerShell: Iterate Through Directory List, Copy Files with Duplicate Handling
EDIT: So after some research, since what I had wasn't quite doing the trick and the advice and comments from before got me further along than I was previously, I am back with a bit more research and a more complete script.

```<code>Import-CSV C:\saveme\file_path3.csv | ForEach-Object {
Get-ChildItem $_.path -Recurse  | ForEach-Object {
$split = $_.FullName  -split '\\'
$DestFile =  $split[1..($split.Length - 1)] -join '\'
$DestFile =  "G:\Recuva2\$DestFile"
$null = New-Item -Path $DestFile -Type File -Force
If (Test-Path $DestFile) {
$i = 0
While (Test-Path $DestFile) {
$i += 1
$DestFile = $DestFile+$i
}
} Else {
$null
}
Copy-Item -Path  $_.FullName -Destination $DestFile -Verbose -Force
}
}
</code>```

This seems to be breaking due to an inability to find the destination directory. It seems to be breaking on this line

```<code>$null = New-Item -Path $DestFile -Type File -Force
</code>```

and this line

```<code>Copy-Item -Path  $_.FullName -Destination $DestFile -Verbose -Force
</code>```

The common denominator here seems to be the $DestFile. I understand I am doing a good bit to the $DestFile, but I can't seem to nail down what is causing it to break.

My desired end-result here is that the folder structure be maintained when copying the specific files over in the csv list from which I am importing.

What actually seems to be happening is that it is throwing errors whenever I attempt to copy. Error text below.

```<code>Copy-Item : Could not find a part of the path 'G:\Recuva2\HR_VIOLATORS\REPORTS\REPORT_Storage2\199452\1.3.6.1.4.1.11157.2011.3.21.8.12.5.52516\1.3.51.5156.1369.20110321.1190709\1.3.51.0.7.3750462839.61413.18976.39828.11247.2380.39394'.
At line:16 char:5
+     Copy-Item -Path  $_.FullName -Destination $DestFile -Verbose -Force
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItem
Command
</code>```

-- END EDIT

ORIGNAL POST:

Similar to but not quite the same as

Keep rename duplicate items with copy

Essentially I am being forced to grab a list of directories from a csv file and copy their contents. However the problem I am having is that some of the directories and files are duplicated.

I am attempting to use this script to import from the csv, copy the files with directory structure intact, while renaming any duplicates, ideally at the file level so that the duplicate directories are merged.

```<code>Import-CSV C:\COPYME\file_path.csv | foreach($_.path) {
ls $_.path -recurse  | foreach($_) {
$SourceFile = $_.FullName
$DestinationFile = "G:\Recuva2\"+$_
If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = "G:\Recuva2\"+$_+$i
    }
} Else {
    New-Item -ItemType File -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -verbose -Force
}
}
</code>```

I am receiving an error that says that line 2 character 24 cannot be resolved to a method? What am I missing/doing wrong here?

答:
As it turned out, I was causing my own problems by trying to pass data I had already gotten. A working version of the scripting is below. This worked flawlessly for every test I put it through thus far large and small. Thank you to the answers above for contributing to my knowledge and understanding of powershell.</p>

```<code>Import-CSV C:\COPYME\file_path.csv | ForEach-Object {
Get-ChildItem $_.path -recurse | ForEach {
$split = $_.FullName  -split '\\'
$DestinationFile = $split[1..($split.Length - 1)] -join '\'
$DestinationFile = "D:\HUBICOPY\$DestinationFile"
#$DestinationFile = (Resolve-Path $DestinationFile).Path
#$null = New-Item -Path $DestinationFile -Type File -Force
If (Test-Path $DestinationFile)
{
$i = 0
While (Test-Path $DestinationFile)
{
$i += 1
$DestinationFile = $DestinationFile+$i
}
}
Else {New-Item -ItemType File -Path $DestinationFile -Force}
Copy-Item -Path $_ -Destination $DestinationFile -verbose -Force
}
}
</code>```

Body:
EDIT: So after some research, since what I had wasn't quite doing the trick and the advice and comments from before got me further along than I was previously, I am back with a bit more research and a more complete script.

Import-CSV C:\saveme\file_path3.csv | ForEach-Object {
Get-ChildItem $_.path -Recurse  | ForEach-Object {
$split = $_.FullName  -split '\\'
$DestFile =  $split[1..($split.Length - 1)] -join '\'
$DestFile =  "G:\Recuva2\$DestFile"
$null = New-Item -Path $DestFile -Type File -Force
If (Test-Path $DestFile) {
$i = 0
While (Test-Path $DestFile) {
$i += 1
$DestFile = $DestFile+$i
}
} Else {
$null
}
Copy-Item -Path  $_.FullName -Destination $DestFile -Verbose -Force
}
}

This seems to be breaking due to an inability to find the destination directory. It seems to be breaking on this line

$null = New-Item -Path $DestFile -Type File -Force

and this line

Copy-Item -Path  $_.FullName -Destination $DestFile -Verbose -Force

The common denominator here seems to be the $DestFile. I understand I am doing a good bit to the $DestFile, but I can't seem to nail down what is causing it to break.

My desired end-result here is that the folder structure be maintained when copying the specific files over in the csv list from which I am importing.

What actually seems to be happening is that it is throwing errors whenever I attempt to copy. Error text below.

Copy-Item : Could not find a part of the path 'G:\Recuva2\HR_VIOLATORS\REPORTS\REPORT_Storage2\199452\1.3.6.1.4.1.11157.2011.3.21.8.12.5.52516\1.3.51.5156.1369.20110321.1190709\1.3.51.0.7.3750462839.61413.18976.39828.11247.2380.39394'.
At line:16 char:5
+     Copy-Item -Path  $_.FullName -Destination $DestFile -Verbose -Force
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItem
Command

-- END EDIT

ORIGNAL POST:

Similar to but not quite the same as

Keep rename duplicate items with copy

Essentially I am being forced to grab a list of directories from a csv file and copy their contents. However the problem I am having is that some of the directories and files are duplicated.

I am attempting to use this script to import from the csv, copy the files with directory structure intact, while renaming any duplicates, ideally at the file level so that the duplicate directories are merged.

Import-CSV C:\COPYME\file_path.csv | foreach($_.path) {
ls $_.path -recurse  | foreach($_) {
$SourceFile = $_.FullName
$DestinationFile = "G:\Recuva2\"+$_
If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = "G:\Recuva2\"+$_+$i
    }
} Else {
    New-Item -ItemType File -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -verbose -Force
}
}

I am receiving an error that says that line 2 character 24 cannot be resolved to a method? What am I missing/doing wrong here?

Body:
As it turned out, I was causing my own problems by trying to pass data I had already gotten. A working version of the scripting is below. This worked flawlessly for every test I put it through thus far large and small. Thank you to the answers above for contributing to my knowledge and understanding of powershell.

Import-CSV C:\COPYME\file_path.csv | ForEach-Object {
Get-ChildItem $_.path -recurse | ForEach {
$split = $_.FullName  -split '\\'
$DestinationFile = $split[1..($split.Length - 1)] -join '\'
$DestinationFile = "D:\HUBICOPY\$DestinationFile"
#$DestinationFile = (Resolve-Path $DestinationFile).Path
#$null = New-Item -Path $DestinationFile -Type File -Force
If (Test-Path $DestinationFile)
{
$i = 0
While (Test-Path $DestinationFile)
{
$i += 1
$DestinationFile = $DestinationFile+$i
}
}
Else {New-Item -ItemType File -Path $DestinationFile -Force}
Copy-Item -Path $_ -Destination $DestinationFile -verbose -Force
}
}


来源: stackexchange

问:
Golang compile environment variable into binary
If I compile this program

```<code>package main

import (
    "fmt"
    "os"
)

var version = os.Getenv("VERSION")

func main() {
    fmt.Println(version)
}
</code>```

It prints the env var when I run it

```<code>VERSION="0.123" ./example
> 0.123
</code>```

Is there a way to compile the env var into the binary, for example:

```<code>VERSION="0.123" go build example.go
</code>```

Then get the same output when I run

```<code>./example
</code>```

答:
Ainer-G's answer led me to the right place, but it wasn't a full code sample answering the question. A couple of changes were required:

Declare the version as var version string

Compile with -X main.version=$VERSION

Here's the full code:

```<code>package main

import (
    "fmt"
)

var version string

func main() {
    fmt.Println(version)
}
</code>```

Now compile with

```<code>go build -ldflags "-X main.version=$VERSION"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I compile this program

package main

import (
    "fmt"
    "os"
)

var version = os.Getenv("VERSION")

func main() {
    fmt.Println(version)
}

It prints the env var when I run it

VERSION="0.123" ./example
> 0.123

Is there a way to compile the env var into the binary, for example:

VERSION="0.123" go build example.go

Then get the same output when I run

./example

Body:
Ainer-G's answer led me to the right place, but it wasn't a full code sample answering the question. A couple of changes were required:

Declare the version as var version string

Compile with -X main.version=$VERSION

Here's the full code:

package main

import (
    "fmt"
)

var version string

func main() {
    fmt.Println(version)
}

Now compile with

go build -ldflags "-X main.version=$VERSION"


问:
button value undefined when passing
I am trying to pass the value of my button to a function that just logs that value for now. The function is in a functions class that is imported in my welcome.ts file.
Welcome.html

```<code>  <ion-content padding id="page1">
<h1 id="welcome-heading4" style="color:#000000;text-align:center;">
Question-CF
</h1>
<div class="spacer" style="width:320px;height:427px;" id="welcome-spacer1"></div>
<button  value='0' (click)=barrierClick(this.value)   id="welcome-button1" ion-button color="positive" block style="font-weight:500;border-radius:50px 50px 50px 50px;">
Begin
</button>
</ion-content>
</code>```

Welcome.ts

```<code>import { Component } from '@angular/core';
import { NavController, IonicPage, NavParams } from 'ionic-angular';
import {functions} from '../functions';
import {BarriersQ1Page} from '../barriers-q1/barriers-q1';

@Component({
selector: 'page-welcome',
templateUrl: 'welcome.html'
})

export class WelcomePage {
nextPage = BarriersQ1Page;

barrierClick(val){

functions.barrierClick(val);
}

constructor(public navCtrl: NavController) {

}

}
</code>```

Functions.ts

```<code> export class functions
 {
 public static barrierClick(val: string)
 {
 console.log(val);

 }

 }
</code>```

Currently, the console logs undefined and I want it to log the button value currently "0".

答:
There is no this reference in the html.
You can pass the entire click event to the function like,

```<code>(click) = barrierClick($event)
</code>```

This will contain all the information including the value of the button.

And in your ts file,

```<code>barrierClick(event) {
   functions.barrierClick(event.target.value); // Should pass button's value to functions.barrierClick
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: button value undefined when passing

Body:
I am trying to pass the value of my button to a function that just logs that value for now. The function is in a functions class that is imported in my welcome.ts file.
Welcome.html

  <ion-content padding id="page1">

Question-CF

<button  value='0' (click)=barrierClick(this.value)   id="welcome-button1" ion-button color="positive" block style="font-weight:500;border-radius:50px 50px 50px 50px;">
Begin
</button>
</ion-content>

Welcome.ts

import { Component } from '@angular/core';
import { NavController, IonicPage, NavParams } from 'ionic-angular';
import {functions} from '../functions';
import {BarriersQ1Page} from '../barriers-q1/barriers-q1';

@Component({
selector: 'page-welcome',
templateUrl: 'welcome.html'
})

export class WelcomePage {
nextPage = BarriersQ1Page;

barrierClick(val){

functions.barrierClick(val);
}

constructor(public navCtrl: NavController) {

}

}

Functions.ts

 export class functions
 {
 public static barrierClick(val: string)
 {
 console.log(val);

 }

 }

Currently, the console logs undefined and I want it to log the button value currently "0".

Body:
There is no this reference in the html.
You can pass the entire click event to the function like,

(click) = barrierClick($event)

This will contain all the information including the value of the button.

And in your ts file,

barrierClick(event) {
   functions.barrierClick(event.target.value); // Should pass button's value to functions.barrierClick
}


问:
While loop isn't outputting the correct data
So I made corrections to my code as you all suggested. I'm able to get into the loop however once I input a correct name I'm still not able to get out of it. Any suggestions?
Here's what I got:

```<code>import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

```<code>Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system
</code>```

Here's what the output should look like when the code runs.

```<code>Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours
</code>```

and the csv looks like this:

```<code>   First Name   Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4
</code>```

答:
You're missing a line in your while loop that connects name to full_name:

```<code>full_name = name.lower()
</code>```

Add this in your while loop, just below the input() call, like you have towards the top of your file.

Inside your while loop, it should say:

```<code>name = input('Enter your full name: ')
full_name = name.lower()
</code>```

That will get your program to run, further, at least!

Also, please note that the logic of your program is probably flawed... You step through each line of the CSV, checking for a person's name. That means that if you have more than one entry in the CSV file, (i.e. - the CSV file holds more than just one person's info), you're only really able to access the first in the list.  You should probably prompt for a username, THEN run through each row of the CSV to check for a match.  Only if there is no match in the entire CSV should you ask for another name... Just give it a look...

Body:
So I made corrections to my code as you all suggested. I'm able to get into the loop however once I input a correct name I'm still not able to get out of it. Any suggestions?
Here's what I got:

import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system

Here's what the output should look like when the code runs.

Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours

and the csv looks like this:

   First Name   Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4

Body:
You're missing a line in your while loop that connects name to full_name:

full_name = name.lower()

Add this in your while loop, just below the input() call, like you have towards the top of your file.

Inside your while loop, it should say:

name = input('Enter your full name: ')
full_name = name.lower()

That will get your program to run, further, at least!

Also, please note that the logic of your program is probably flawed... You step through each line of the CSV, checking for a person's name. That means that if you have more than one entry in the CSV file, (i.e. - the CSV file holds more than just one person's info), you're only really able to access the first in the list.  You should probably prompt for a username, THEN run through each row of the CSV to check for a match.  Only if there is no match in the entire CSV should you ask for another name... Just give it a look...


问:
How to get value of node in firebase database in Cloud Function
```<code>exports.respublished =
functions.database.ref('/Posts/{postid}').onWrite(event => {
  const snapshot = event.data;
  const postid = event.params.examid;
  const uid = snapshot.child('uid').val();
  const ispublic = snapshot.child('Public').val();
  firebase.database.ref('Users/' + uid).once(event => {
    const snapshot = event.data;
    const name = snapshot.child('name').val();
  });
});
</code>```

The event is triggered by another node and i want to retrive data from another node of firebase database. I have tried the above code but it produces an error saying TypeError: firebase.database.ref(...).once is not a function.

答:
yes i got the answer we can use this code</p>

```<code>exports.respublished = functions.database.ref('/Posts/{postid}').onWrite(event => {
  const snapshot = event.data;
  const postid = event.params.examid;
  const uid = snapshot.child('uid').val();
  const ispublic = snapshot.child('Public').val();
  return admin.database().ref('Users/' + uid).once(event => {
    const snapshot = event.data;
    const name = snapshot.child('name').val();
  });
});
</code>```

Body:
exports.respublished =
functions.database.ref('/Posts/{postid}').onWrite(event => {
  const snapshot = event.data;
  const postid = event.params.examid;
  const uid = snapshot.child('uid').val();
  const ispublic = snapshot.child('Public').val();
  firebase.database.ref('Users/' + uid).once(event => {
    const snapshot = event.data;
    const name = snapshot.child('name').val();
  });
});

The event is triggered by another node and i want to retrive data from another node of firebase database. I have tried the above code but it produces an error saying TypeError: firebase.database.ref(...).once is not a function.

Body:
yes i got the answer we can use this code

exports.respublished = functions.database.ref('/Posts/{postid}').onWrite(event => {
  const snapshot = event.data;
  const postid = event.params.examid;
  const uid = snapshot.child('uid').val();
  const ispublic = snapshot.child('Public').val();
  return admin.database().ref('Users/' + uid).once(event => {
    const snapshot = event.data;
    const name = snapshot.child('name').val();
  });
});


问:
Macro to export Excel Doc as PDF for all Users
I need to create a macro that will save an excel document as a PDF file to any user's desktop (i.e. multiple people will be using this document/macro).

Here is VBA code I have so far:

```<code>Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub
</code>```

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?

答:
You can use environment variables.  %USERPROFILE%\Desktop should work in this instance.

Here's a list of environment variables. https://en.wikipedia.org/wiki/Environment_variable#Default_Values

Accessing environment variables with VBA: Environ Function code samples for VBA

In VBA you could translate it to Environ("USERPROFILE") & "\Desktop" This is untested as I'm not using Windows.

Body:
I need to create a macro that will save an excel document as a PDF file to any user's desktop (i.e. multiple people will be using this document/macro).

Here is VBA code I have so far:

Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?


问:
Read txt file into array and assign to variables
So essentially what I need to do is make this while loop run through the txt file and store it in an array to be stored inside the instance variables

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * <insert class description here>
 *
 * @author Chris Crosby
 *
 */
public class TrackInput
{
    private Scanner keyboard = new Scanner(System.in);

    public int readTrackData(Railroad[] Reservations) {
        final String FILE_NAME = "TrackData.txt";
        int size =0;
        Scanner input = null;
        try {
            input= new Scanner(new File(FILE_NAME));
        }
        catch(FileNotFoundException e) {
            System.out.println("Unable to open file " + FILE_NAME + ".");
        }
        String passengerName="";
        String routeNumber="";
        String departureDate="";
        String departureTrack="";
        String arrivalTrack="";
        String departureTime="";
        String arrivalTime="";
        String seat="";
        String returnRouteNumber="";
        String ReturnDate="";

        while (input.hasNext()&& size<Reservations.length) {

        }
        return size;
    }
}
</code>```

here's the txt file that the loop is reading through

```<code>Carl Foreman
1234
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23A
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8A
Jennifer Foreman
1235
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23B
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8B
Jane Anderson
4577
UA317
08/04/2014
ORD
SFO
8:10 AM
10:45 AM
11C
UA728
08/14/2014
SFO
ORD
12:52 PM
7:03 PM
10D
Jason Anderson
4578
</code>```

TrackData.txt format

passenger name – include first and last name in one variable

reservation number

departure route number

departure date

departure track

arrival track

departure time

arrival time

seat

return route number

return date

departure track

arrival track

departure time

arrival time

seat

here's a similar method I had to write for a previous assignment

```<code>public int readInventory(Automobile[] inventory)
    {
        final String FILENAME = "inventory.csv";
        int size = 0;

        Scanner input = null;
        try
        {
            input = new Scanner(new File(FILENAME));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Unable to open file " + FILENAME + ".");
        }

        // read header line and discard first line
        String line = input.nextLine();

        // create vars
        int year = 0;
        String make = "";
        String model = "";
        double price = 0.0;
        String condition = "";
        int rating = 0;
        String status = "";
        String vin = "";

        // Customer vars
        String firstName = "";
        String lastName = "";
        String streetAddress = "";
        String city = "";
        String state = "";
        String zip = "";
        String email = "";
        String phone = "";

        while (input.hasNext() && size < inventory.length)
        {
            line = input.nextLine();
            String[] record = line.split(",");

            year = Integer.parseInt(record[0]);
            make = record[1];
            model = record[2];

            // If use this version, comment out the following if statements

            if (!(record[3].equals("")))
            {
                price = Double.parseDouble(record[3]);
            }
            else
            {
                price = 0;
            }

            condition = record[4];

            if (!(record[5].equals("")))
            {
                rating = Integer.parseInt(record[5]);
            }
            else
            {
                rating = 0;
            }

            status = record[6];
            vin = record[7];

            // this is where the records differ
            // they either don't have buyer information or some do

            if (record.length > 8)
            {
                if (!(record[8].equals("")))
                    firstName = record[8];
                else
                    firstName = "";

                if (!(record[9].equals("")))
                    lastName = record[9];
                else
                    lastName = "";

                if (!(record[10].equals("")))
                    streetAddress = record[10];
                else
                    streetAddress = "";

                if (!(record[11].equals("")))
                    city = record[11];
                else
                    city = "";

                if (!(record[12].equals("")))
                    state = record[12];
                else
                    state = "";

                if (!(record[13].equals("")))
                    zip = record[13];
                else
                    zip = "";

                if (!(record[14].equals("")))
                    email = record[14];
                else
                    email = "";

                if (!(record[15].equals("")))
                    phone = record[15];
                else
                    phone = "";

            }

            // changes to integrate Customer class go below

            Customer tempCustomer = new Customer(firstName,lastName, city, state, email, phone,zip,streetAddress);
            Automobile tempAutomobile = new Automobile( year, make, model, price,
                    condition, rating, status, vin, tempCustomer);

            inventory[size] = tempAutomobile;
            size++;

        } // end of while loop

        input.close();

        return size;
    }
</code>```

not sure how to make it work for this program since this is multilined and the previous was a single line separated by commas hence the line.split

答:
Hmmm... I am not sure i should answer this since it is not that hard and i am sure you can solve it yourself. Sadly i dont have enough reputation to just comment (that is why i am here in the first place).

I will just drop some hints to help you:

1) You know how to read line by line. You can choose when to start, stop and even skip lines. Sadly you can only move forward but that is enough for this problem.

2) The data file follows a constant pattern. This means this is the easy to handle data.

3) You know the pattern beforehand. Pst, it is the OP!

I think that is it. Now you should just pay attention and wait for the AHA! moment.

Body:
So essentially what I need to do is make this while loop run through the txt file and store it in an array to be stored inside the instance variables

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * <insert class description here>
 *
 * @author Chris Crosby
 *
 */
public class TrackInput
{
    private Scanner keyboard = new Scanner(System.in);

    public int readTrackData(Railroad[] Reservations) {
        final String FILE_NAME = "TrackData.txt";
        int size =0;
        Scanner input = null;
        try {
            input= new Scanner(new File(FILE_NAME));
        }
        catch(FileNotFoundException e) {
            System.out.println("Unable to open file " + FILE_NAME + ".");
        }
        String passengerName="";
        String routeNumber="";
        String departureDate="";
        String departureTrack="";
        String arrivalTrack="";
        String departureTime="";
        String arrivalTime="";
        String seat="";
        String returnRouteNumber="";
        String ReturnDate="";

        while (input.hasNext()&& size<Reservations.length) {

        }
        return size;
    }
}

here's the txt file that the loop is reading through

Carl Foreman
1234
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23A
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8A
Jennifer Foreman
1235
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23B
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8B
Jane Anderson
4577
UA317
08/04/2014
ORD
SFO
8:10 AM
10:45 AM
11C
UA728
08/14/2014
SFO
ORD
12:52 PM
7:03 PM
10D
Jason Anderson
4578

TrackData.txt format

passenger name – include first and last name in one variable

reservation number

departure route number

departure date

departure track

arrival track

departure time

arrival time

seat

return route number

return date

departure track

arrival track

departure time

arrival time

seat

here's a similar method I had to write for a previous assignment

public int readInventory(Automobile[] inventory)
    {
        final String FILENAME = "inventory.csv";
        int size = 0;

        Scanner input = null;
        try
        {
            input = new Scanner(new File(FILENAME));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Unable to open file " + FILENAME + ".");
        }

        // read header line and discard first line
        String line = input.nextLine();

        // create vars
        int year = 0;
        String make = "";
        String model = "";
        double price = 0.0;
        String condition = "";
        int rating = 0;
        String status = "";
        String vin = "";

        // Customer vars
        String firstName = "";
        String lastName = "";
        String streetAddress = "";
        String city = "";
        String state = "";
        String zip = "";
        String email = "";
        String phone = "";

        while (input.hasNext() && size < inventory.length)
        {
            line = input.nextLine();
            String[] record = line.split(",");

            year = Integer.parseInt(record[0]);
            make = record[1];
            model = record[2];

            // If use this version, comment out the following if statements

            if (!(record[3].equals("")))
            {
                price = Double.parseDouble(record[3]);
            }
            else
            {
                price = 0;
            }

            condition = record[4];

            if (!(record[5].equals("")))
            {
                rating = Integer.parseInt(record[5]);
            }
            else
            {
                rating = 0;
            }

            status = record[6];
            vin = record[7];

            // this is where the records differ
            // they either don't have buyer information or some do

            if (record.length > 8)
            {
                if (!(record[8].equals("")))
                    firstName = record[8];
                else
                    firstName = "";

                if (!(record[9].equals("")))
                    lastName = record[9];
                else
                    lastName = "";

                if (!(record[10].equals("")))
                    streetAddress = record[10];
                else
                    streetAddress = "";

                if (!(record[11].equals("")))
                    city = record[11];
                else
                    city = "";

                if (!(record[12].equals("")))
                    state = record[12];
                else
                    state = "";

                if (!(record[13].equals("")))
                    zip = record[13];
                else
                    zip = "";

                if (!(record[14].equals("")))
                    email = record[14];
                else
                    email = "";

                if (!(record[15].equals("")))
                    phone = record[15];
                else
                    phone = "";

            }

            // changes to integrate Customer class go below

            Customer tempCustomer = new Customer(firstName,lastName, city, state, email, phone,zip,streetAddress);
            Automobile tempAutomobile = new Automobile( year, make, model, price,
                    condition, rating, status, vin, tempCustomer);

            inventory[size] = tempAutomobile;
            size++;

        } // end of while loop

        input.close();

        return size;
    }

not sure how to make it work for this program since this is multilined and the previous was a single line separated by commas hence the line.split


问:
Replace multiple %in% statements with a single line of dplyr code

I would like to create a flag that is 1 if any one of 13 columns contains any one of a large number of codes and is 0 otherwise. I need to use dplyr because my data is in database. I can accomplish what I'm after using many %in% statements. I am wondering if there is a more concise way to write this code. Is there a version of %in% that allows multiple variables on the left hand side?

The following code gives the correct result. I've included only 5 columns and 2 rows for brevity.

```<code>library(dplyr)

match_dx <- c(paste0("C0", 0:9), paste0("C", 10:20))

df <- tibble(dx1 = c("C00", "G01"),
   dx2 = c("C50", "Z11"),
   dx3 = c("D20", "D22"),
   dx4 = c("A40", "C21"),
   dx13 = c("G20", "C30"))

df %>%
 mutate(flag = case_when(
      dx1 %in% match_dx ~ 1,
      dx2 %in% match_dx ~ 1,
      dx3 %in% match_dx ~ 1,
      dx4 %in% match_dx ~ 1,
      dx13 %in% match_dx ~ 1,
      T ~ 0
 ))
</code>```

I would like to know if there is something like

```<code>df %>%
 mutate(flag = case_when(
      any(vars(dx1:dx13) %in% match_dx) ~ 1,
      T ~ 0
 ))
</code>```

This does work but perhaps there is something similar or another way to accomplish this without needing one line per variable.

Thanks!

答:
We can use apply with mutate to compare all columns at once.

```<code>library(dplyr)

df %>%
  mutate(flag = apply(., 1, function(x) any(x %in% match_dx) * 1))
# # A tibble: 2 x 6
#     dx1   dx2   dx3   dx4  dx13  flag
#   <chr> <chr> <chr> <chr> <chr> <dbl>
# 1   C00   C50   D20   A40   G20     1
# 2   G01   Z11   D22   C21   C30     0
</code>```

Body:
I would like to create a flag that is 1 if any one of 13 columns contains any one of a large number of codes and is 0 otherwise. I need to use dplyr because my data is in database. I can accomplish what I'm after using many %in% statements. I am wondering if there is a more concise way to write this code. Is there a version of %in% that allows multiple variables on the left hand side?

The following code gives the correct result. I've included only 5 columns and 2 rows for brevity.

library(dplyr)

match_dx <- c(paste0("C0", 0:9), paste0("C", 10:20))

df <- tibble(dx1 = c("C00", "G01"),
   dx2 = c("C50", "Z11"),
   dx3 = c("D20", "D22"),
   dx4 = c("A40", "C21"),
   dx13 = c("G20", "C30"))

df %>%
 mutate(flag = case_when(
      dx1 %in% match_dx ~ 1,
      dx2 %in% match_dx ~ 1,
      dx3 %in% match_dx ~ 1,
      dx4 %in% match_dx ~ 1,
      dx13 %in% match_dx ~ 1,
      T ~ 0
 ))

I would like to know if there is something like

df %>%
 mutate(flag = case_when(
      any(vars(dx1:dx13) %in% match_dx) ~ 1,
      T ~ 0
 ))

This does work but perhaps there is something similar or another way to accomplish this without needing one line per variable.

Thanks!

Body:
We can use apply with mutate to compare all columns at once.

library(dplyr)

df %>%
  mutate(flag = apply(., 1, function(x) any(x %in% match_dx) * 1))
# # A tibble: 2 x 6
#     dx1   dx2   dx3   dx4  dx13  flag
#   <chr> <chr> <chr> <chr> <chr> <dbl>
# 1   C00   C50   D20   A40   G20     1
# 2   G01   Z11   D22   C21   C30     0


问:
a simple regexp validator
How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter

it must end with a letter

it can contain a dash (minus sign), but not at start or end of the expression

答: What I meant, to be able to create tags. For example: "Wild-things" or "something-wild" or "into-the-wild" or "in-wilderness" "my-wild-world" etc...</p>

OwnerDisplayName: new-to-rails

ContentLicense: CC BY-SA 2.5

Title: a simple regexp validator


问:
Repeat Python function call on exception?
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

```<code>try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2
</code>```

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

答:
```<code>success = False
attempts = 0
while not success and attempts < 10: # or however many times you want to attempt
    try:
        functionCall()
        success = True
    except:
        i += 1
if not success:
    raise functionCallFailedError
</code>```

Hope this helps

Body:
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

Body:
success = False
attempts = 0
while not success and attempts < 10: # or however many times you want to attempt
    try:
        functionCall()
        success = True
    except:
        i += 1
if not success:
    raise functionCallFailedError

Hope this helps


问:
what is the "editId" in Coq's XML Protocol document?
In Coq's XML Protocol document (for the Add operation), a line reads <int>${editId}</int>. What is the editID here?

I asked this because I failed to interact with coqtop in the ideslave mode. Using coq-8.6.1/theories/FSets/FSetCompat.v as an example, I inputted

```<code><call val="Init"><option val="none"/></call>
</code>```

,

```<code><call val="Add"><pair><pair><string>Require Import FSetInterface FSetFacts MSetInterface MSetFacts.</string><int>1</int></pair><pair><state_id val="1"/><bool val="true"/></pair></pair></call>
</code>```

,

```<code><call val="Add"><pair><pair><string>Set Implicit Arguments.</string><int>1</int></pair><pair><state_id val="2"/><bool val="true"/></pair></pair></call>
</code>```

, and then

```<code><call val="Add"><pair><pair><string>Unset Strict Implicit.</string><int>1</int></pair><pair><state_id val="3"/><bool val="true"/></pair></pair></call>
</code>```

They all generated correct outputs. However, at this time when I typed

```<code><call val="Add"><pair><pair><string>Module Backport_WSets
    (E:DecidableType.DecidableType)
    (M:MSetInterface.WSets with Definition E.t := E.t
                           with Definition E.eq := E.eq)
<: FSetInterface.WSfun E.</string><int>1</int></pair><pair><state_id val="4"/><bool val="true"/></pair></pair></call>
</code>```

I got the following error:

```<code>[pid 48519] XML syntax error: Attribute value expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <int>1</int>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <pair>
  <state_id val="4"/>
  <bool val="true"/>
</pair>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected
</code>```

I suspect that this error is because of the multi-line string, and maybe if I change editId, I should get the correct answer. Am I right? If no, what does editID do, and how should I deal with this error? Thanks for helping!

答:
EditId was removed in Coq 8.7; its original purpose and history is a bit complex due to intricacies of the protocol and historical issues.

Namely, the Add operation is synchronous in the sense that the user interface has to wait for a reply with the newly assigned identifier (Stateid.t) for the added span.

However, if a parser error occurred, the asynchronous feedback system needed a temporal identifier, edit_id served that purpose.

We removed edit_id as Add is synchronous anyway, so it makes sense for the caller of Add to use the synchronous error handler instead of the edit_id-based feedback.

Note that I strongly recommend against using the current synchronous version of Add. It forces the client to implement a complex blocking system, and it will be replaced soon by an asynchronous-friendly version [where the UI chooses the span_id upfront] . Such a version is already available in the ML API and exposed by SerAPI (*) and likely by the XML protocol itself starting in 8.8.

(*) The usual disclaimers apply: I am the author of SerAPI, also note that I was  the person behind the removal of edit_id from Coq 8.7.

Body:
In Coq's XML Protocol document (for the Add operation), a line reads <int>${editId}</int>. What is the editID here?

I asked this because I failed to interact with coqtop in the ideslave mode. Using coq-8.6.1/theories/FSets/FSetCompat.v as an example, I inputted

<call val="Init"><option val="none"/></call>

,

<call val="Add"><pair><pair><string>Require Import FSetInterface FSetFacts MSetInterface MSetFacts.</string><int>1</int></pair><pair><state_id val="1"/><bool val="true"/></pair></pair></call>

,

<call val="Add"><pair><pair><string>Set Implicit Arguments.</string><int>1</int></pair><pair><state_id val="2"/><bool val="true"/></pair></pair></call>

, and then

<call val="Add"><pair><pair><string>Unset Strict Implicit.</string><int>1</int></pair><pair><state_id val="3"/><bool val="true"/></pair></pair></call>

They all generated correct outputs. However, at this time when I typed

<call val="Add"><pair><pair><string>Module Backport_WSets
    (E:DecidableType.DecidableType)
    (M:MSetInterface.WSets with Definition E.t := E.t
                           with Definition E.eq := E.eq)
<: FSetInterface.WSfun E.</string><int>1</int></pair><pair><state_id val="4"/><bool val="true"/></pair></pair></call>

I got the following error:

[pid 48519] XML syntax error: Attribute value expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <int>1</int>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <pair>
  <state_id val="4"/>
  <bool val="true"/>
</pair>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected

I suspect that this error is because of the multi-line string, and maybe if I change editId, I should get the correct answer. Am I right? If no, what does editID do, and how should I deal with this error? Thanks for helping!


问:
Handling dynamically populated CMenu messages
I'm implementing a right click menu in an MFC app whose contents are not known until runtime.

While it's simple enough to add menu items to a CMenu object, I haven't figured out a way to handle the messages sent by each menu item.

One technique I was investigating was assigning the same resource ID to each dynamically created menu item and handling all the messages by one callback which would contain the logic to handle each message appropriately. The problem with this approach is that, apart from being kludgey, CMenu menuitem messages are caught using the ON_COMMAND macro which requires a parameterless callback, so no information is passed to it other than than the implicit information that it was called by a resource with a certain resource ID.

I tried to trap the messages using the ON_MESSAGE macro instead as the callbacks it uses receive WPARAM and LPARAM arguments, but the callback is never invoked, so that option seems to be out.

It seems to me that there has to be a way to implement what I'm trying to do but I can't figure out it thus far. Any help is much appreciated.

答:
Look at this answer:

https://stackoverflow.com/a/3673672/2287576

As for the message map, assuming all your menu item IDs are within a certain range, you can use ON_COMMAND_RANGE to map the entire range to a single function. This function will receive the ID as a parameter, and within the function, you can perform different operations based on the ID.

Assuming you can set aside a range of ID values this method will work.


问:
Is it possible to know if a std::thread finished given its std::thread::id?
I have a collection of std::thread::id, and I would like to know if the related std::thread has finished, for any of the std::thread::id in the collection.

Is it possible?

答:
I think I found out how:

```<code>struct logger {
enum level : int16_t { debug = 0, info = 1, warn = 2, error = 3, fatal = 4 };

~logger() {
    write_all();
}

logger & operator()(level p_level) {
    add(true)
            << "[" << get_level(p_level) << "]"
            << "[" << std::time(NULL) << "]"
            << "[" << std::this_thread::get_id() << "] ";
    return *this;
}

template <typename T>
logger & operator << (const T & p_val) {
    add() << p_val;
    return *this;
}
private:

struct at_thread_end {
  at_thread_end (std::function<void (std::thread::id)> p_callback
                 , std::thread::id p_id)
      : m_callback(p_callback)
      , m_id(p_id){}

  at_thread_end(at_thread_end && p_at_thread_end)
      : m_callback(std::move(p_at_thread_end.m_callback))
      , m_id(std::move(p_at_thread_end.m_id)) {}

  at_thread_end & operator=(at_thread_end && p_at_thread_end) {
      m_callback = std::move(p_at_thread_end.m_callback);
      m_id = std::move(p_at_thread_end.m_id);
      return *this;
  }

  ~at_thread_end() {
      m_callback(m_id);
  }

private:
  std::function<void (std::thread::id)> m_callback;
  std::thread::id m_id;
};

typedef std::map<std::thread::id, std::stringstream> streams;

void on_thread_end(std::thread::id p_id) {
    std::cout << "thread " << p_id << " ended" << std::endl;
    streams::iterator _ite = m_streams.find(p_id);
    if (_ite != m_streams.end()) {
        write(_ite->second.str());
        std::lock_guard<std::mutex> _lock(m_mutex_streams);
        m_streams.erase(_ite);
    }
}

std::stringstream & add(bool p_clean = false) {
    std::thread::id _id  = std::this_thread::get_id();
    streams::iterator _ite = m_streams.find(_id);
    if (_ite != m_streams.end()) {
        if (p_clean) {
            write(_ite->second.str());
            _ite->second.str("");
        }
        return _ite->second;
    }

    using std::placeholders::_1;
    thread_local at_thread_end
            _at_thread_end(std::bind(&logger::on_thread_end, this, _1)
                           ,_id);

    std::lock_guard<std::mutex> _lock(m_mutex_streams);
    m_streams[_id] = std::stringstream();
    return m_streams[_id];
}

std::string get_level(level p_level) {
    switch (p_level) {
    case level::debug:
        return "DEB";
    case level::info:
        return "INF";
    case level::warn:
        return "WAR";
    case level::error:
        return "ERR";
    case level::fatal:
        return "FAT";
    }
    return "LEVEL UNKNOW";
}

void write(const std::string & p_str) {
    std::lock_guard<std::mutex> _lock(m_mutex_write);
    if (p_str.size()) {
        std::cout << p_str << std::endl;
    }
}

void write_all() {
    std::lock_guard<std::mutex> _lock(m_mutex_streams);
    streams::iterator _end = m_streams.end();
    for (streams::iterator _ite = m_streams.begin(); _ite != _end; ++_ite) {
        write(_ite->second.str());
    }
}

streams m_streams;
std::mutex m_mutex_streams;
std::mutex m_mutex_write;

};
</code>```

You can look at a full example at https://pastebin.com/z2HrF70U

Body:
I think I found out how:

struct logger {
enum level : int16_t { debug = 0, info = 1, warn = 2, error = 3, fatal = 4 };

~logger() {
    write_all();
}

logger & operator()(level p_level) {
    add(true)
            << "[" << get_level(p_level) << "]"
            << "[" << std::time(NULL) << "]"
            << "[" << std::this_thread::get_id() << "] ";
    return *this;
}

template <typename T>
logger & operator << (const T & p_val) {
    add() << p_val;
    return *this;
}
private:

struct at_thread_end {
  at_thread_end (std::function<void (std::thread::id)> p_callback
                 , std::thread::id p_id)
      : m_callback(p_callback)
      , m_id(p_id){}

  at_thread_end(at_thread_end && p_at_thread_end)
      : m_callback(std::move(p_at_thread_end.m_callback))
      , m_id(std::move(p_at_thread_end.m_id)) {}

  at_thread_end & operator=(at_thread_end && p_at_thread_end) {
      m_callback = std::move(p_at_thread_end.m_callback);
      m_id = std::move(p_at_thread_end.m_id);
      return *this;
  }

  ~at_thread_end() {
      m_callback(m_id);
  }

private:
  std::function<void (std::thread::id)> m_callback;
  std::thread::id m_id;
};

typedef std::map<std::thread::id, std::stringstream> streams;

void on_thread_end(std::thread::id p_id) {
    std::cout << "thread " << p_id << " ended" << std::endl;
    streams::iterator _ite = m_streams.find(p_id);
    if (_ite != m_streams.end()) {
        write(_ite->second.str());
        std::lock_guard<std::mutex> _lock(m_mutex_streams);
        m_streams.erase(_ite);
    }
}

std::stringstream & add(bool p_clean = false) {
    std::thread::id _id  = std::this_thread::get_id();
    streams::iterator _ite = m_streams.find(_id);
    if (_ite != m_streams.end()) {
        if (p_clean) {
            write(_ite->second.str());
            _ite->second.str("");
        }
        return _ite->second;
    }

    using std::placeholders::_1;
    thread_local at_thread_end
            _at_thread_end(std::bind(&logger::on_thread_end, this, _1)
                           ,_id);

    std::lock_guard<std::mutex> _lock(m_mutex_streams);
    m_streams[_id] = std::stringstream();
    return m_streams[_id];
}

std::string get_level(level p_level) {
    switch (p_level) {
    case level::debug:
        return "DEB";
    case level::info:
        return "INF";
    case level::warn:
        return "WAR";
    case level::error:
        return "ERR";
    case level::fatal:
        return "FAT";
    }
    return "LEVEL UNKNOW";
}

void write(const std::string & p_str) {
    std::lock_guard<std::mutex> _lock(m_mutex_write);
    if (p_str.size()) {
        std::cout << p_str << std::endl;
    }
}

void write_all() {
    std::lock_guard<std::mutex> _lock(m_mutex_streams);
    streams::iterator _end = m_streams.end();
    for (streams::iterator _ite = m_streams.begin(); _ite != _end; ++_ite) {
        write(_ite->second.str());
    }
}

streams m_streams;
std::mutex m_mutex_streams;
std::mutex m_mutex_write;

};

You can look at a full example at https://pastebin.com/z2HrF70U


问:
Wordpress: Filter/Sort posts within a page?
If I have a parent category, say, "Travel" with subcategories "belgium", "netherlands", "japan", etc., how can I create a page with all of the posts from the categories above?
Then, I need users to be able to filter which posts they see, depending on which subcategory they choose.

If they want to see "travel" posts from the subcategory "japan", I need it to hide the other posts from "netherlands" and "belgium".

All this is done preferably without needing to refresh.

Please Help!

答: A detailed article is given here & it works I have tested it too.</p>


答:
If you are actually interested in other solutions go for my answer else just skip it. With pandas it is more easier to solve your need.

So I have a CSV file("names.csv") with this values in it,

```<code>Name    Hours
Sri Mati    1
Some Name   2
</code>```

Here is the code:

```<code>import pandas

if __name__ == "__main__":
    csv = pandas.read_csv("names.csv")
    name = input("Enter your name: ")
    if (csv["Name"]==name).any():
        print("Name Present")
        correct_name = csv.loc[csv["Name"] == name]
        # print everything
        print(csv)
        print()
        #print correct name
        print(correct_name)
        print() # for clear display
        # get individual things
        print("Correct Inidividual Values")
        print(correct_name.values)
    else:
        print("Name not there")
</code>```

Sample Input and Output:

```<code>Enter your name: Steve Miller
Name not there
</code>```

Next run,

```<code>Enter your name: Sri Mati
Name Present
        Name  Hours
0   Sri Mati      1
1  Some Name      2

       Name  Hours
0  Sri Mati      1

Correct Inidividual Values
[['Sri Mati' 1]]
</code>```

Title: While loop isn't outputting the correct data

Body:
If you are actually interested in other solutions go for my answer else just skip it. With pandas it is more easier to solve your need.

So I have a CSV file("names.csv") with this values in it,

Name    Hours
Sri Mati    1
Some Name   2

Here is the code:

import pandas

if __name__ == "__main__":
    csv = pandas.read_csv("names.csv")
    name = input("Enter your name: ")
    if (csv["Name"]==name).any():
        print("Name Present")
        correct_name = csv.loc[csv["Name"] == name]
        # print everything
        print(csv)
        print()
        #print correct name
        print(correct_name)
        print() # for clear display
        # get individual things
        print("Correct Inidividual Values")
        print(correct_name.values)
    else:
        print("Name not there")

Sample Input and Output:

Enter your name: Steve Miller
Name not there

Next run,

Enter your name: Sri Mati
Name Present
        Name  Hours
0   Sri Mati      1
1  Some Name      2

       Name  Hours
0  Sri Mati      1

Correct Inidividual Values
[['Sri Mati' 1]]


问:
Deploying cloud functions on cli, "Firebase config variables are not available."
Trying to configure environment variables with firebase sdk. It contains a token which will be used in a google cloud function.

I've followed the docs to a tee and I get this error when I try to redeploy the cloud function.

I've got these at the top of my index.js file

```<code>const functions = require("firebase-functions");
const token = functions.config().slack.token;
</code>```

This is my package.json file

```<code>{
  "name": "quincygeorge",
  "version": "1.0.0",
  "description": "smart-office-assistant",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jonathan Puc",
  "license": "ISC",
  "dependencies": {
    "firebase-admin": "^5.5.1",
    "firebase-functions": "^0.7.3",
    "slack": "^9.1.0"
  }
}
</code>```

As stated in the docs, I ran "firebase deploy --only functions" first before trying to run...

"gcloud beta functions deploy myfunction --stage-bucket mybucket  --trigger-http"

again. But I still get this error.

My firebase tools and all the modules are up to date as I only installed them today.

答:
The error message is complaining about your version of the Firebase CLI.

Update to the latest version.  3.16.0 at the time of this writing.

```<code>npm update -g firebase-tools
</code>```

Body:
Trying to configure environment variables with firebase sdk. It contains a token which will be used in a google cloud function.

I've followed the docs to a tee and I get this error when I try to redeploy the cloud function.

I've got these at the top of my index.js file

const functions = require("firebase-functions");
const token = functions.config().slack.token;

This is my package.json file

{
  "name": "quincygeorge",
  "version": "1.0.0",
  "description": "smart-office-assistant",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jonathan Puc",
  "license": "ISC",
  "dependencies": {
    "firebase-admin": "^5.5.1",
    "firebase-functions": "^0.7.3",
    "slack": "^9.1.0"
  }
}

As stated in the docs, I ran "firebase deploy --only functions" first before trying to run...

"gcloud beta functions deploy myfunction --stage-bucket mybucket  --trigger-http"

again. But I still get this error.

My firebase tools and all the modules are up to date as I only installed them today.

Body:
The error message is complaining about your version of the Firebase CLI.

Update to the latest version.  3.16.0 at the time of this writing.

npm update -g firebase-tools


问:
Is it possible to connect Dialogflow (Api.ai) with Slack so that humans can monitor and possibly even intervene or add to the conversation via Slack?
I know Dialogflow (Api.ai) can be a bot in Slack.  But what about monitoring the conversation and possibly manually intervene in the conversation?  If possible, what would be the general direction to implement this?</p>

答:
Dialogflow has an sample on how to do this: https://github.com/dialogflow/agent-human-handoff-nodejs

You'll have to build you own front end for the human to override the response and call the Dialogflow query API to integrate:

Slack <--> Front end w/human override <--> Dialogflow's query API <--> Dialogflow Agent


问:
Checking a password
I think I have the right idea of solving this function, but I'm not sure why
I don't get the desired results shown in the docstring. Can anyone please help me fix this?</p>

```<code>def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False
</code>```

答:
See this answer:
https://stackoverflow.com/a/2990682/7579116
the best way to check if a password match all the requirements is by using a regex.</p>

Title: Checking a password

Body:
I think I have the right idea of solving this function, but I'm not sure why
I don't get the desired results shown in the docstring. Can anyone please help me fix this?

def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False


问:
Not sure how to implement bullets into Pong Game
I want to implement bullets into my pong game in which my paddles can shoot out bullets. Right now, I just want to focus on the PlayerPaddle shooting out bullets that travel towards the right. These bullets would originate from the position of the paddle. However, I'm not sure how to approach this. I believe that making a sprite group would overcomplicate my project and I just want my bullets to be able to collide into the pong ball I have eventually. This is what I have so far.

```<code>class PlayerPaddle(Image):

    def __init__(self, screen_size, width, height, filename, color=(255,0,0)):

        # speed and direction have to be before super()
        self.speed = 3
        self.direction = 0

        super().__init__(screen_size, width, height, filename, color=(255, 0, 0))

        self.rect.centerx = 40
        self.rect.centery = screen_size[1] // 2

        self.rect.height = 100

    def update(self):

        self.rect.centery += self.direction*self.speed   # <--- use directly rect.centery

        super().update()

        #self.rect.center = (self.centerx, self.centery) # <-- don't need it

        if self.rect.top < 0:
            self.rect.top = 0

        if self.rect.bottom > self.screen_size[1]-1:
            self.rect.bottom = self.screen_size[1]-1

    def handle_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.direction = -1
            elif event.key == pygame.K_DOWN:
                self.direction = 1
            elif event.key == pygame.K_LEFT:
                self.turnLeft()
            elif event.key == pygame.K_RIGHT:
                self.turnRight()
            elif event.key == pygame.K_u:
                bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
                bullet.rect.centerx = self.rect.centerx
                bullet.rect.centery = self.rect.centery
                bullet.draw()
                bullet.update()

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP and self.direction == -1:
                self.direction = 0
            elif event.key == pygame.K_DOWN and self.direction == 1:
                self.direction = 0
</code>```

and Here is my bullet class

```<code>class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

    def update(self):

        self.rect.centery -= 3
</code>```

答:
I would create Group() outside PlayerPaddle()

```<code>self.bullets_group = pygame.sprite.Group()
</code>```

and use it as argument in PlayerPaddle()

```<code>self.player_paddle = PlayerPaddle(..., self.bullets_group)
</code>```

This way player can easly add bullets to group

```<code>   elif event.key == pygame.K_u:
       bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
       bullet.rect.centerx = self.rect.centerx
       bullet.rect.centery = self.rect.centery

       self.bullets_group.add(bullet)
</code>```

and mainloop can draw and update it

```<code>def Update():
    self.bullets_group.update()
    self.player_paddle.update()
    self.ai_paddle.update(..., self.bullets_group)

def Render():
    self.bullets_group.draw()
    self.player_paddle.draw()
</code>```

Body:
I want to implement bullets into my pong game in which my paddles can shoot out bullets. Right now, I just want to focus on the PlayerPaddle shooting out bullets that travel towards the right. These bullets would originate from the position of the paddle. However, I'm not sure how to approach this. I believe that making a sprite group would overcomplicate my project and I just want my bullets to be able to collide into the pong ball I have eventually. This is what I have so far.

class PlayerPaddle(Image):

    def __init__(self, screen_size, width, height, filename, color=(255,0,0)):

        # speed and direction have to be before super()
        self.speed = 3
        self.direction = 0

        super().__init__(screen_size, width, height, filename, color=(255, 0, 0))

        self.rect.centerx = 40
        self.rect.centery = screen_size[1] // 2

        self.rect.height = 100

    def update(self):

        self.rect.centery += self.direction*self.speed   # <--- use directly rect.centery

        super().update()

        #self.rect.center = (self.centerx, self.centery) # <-- don't need it

        if self.rect.top < 0:
            self.rect.top = 0

        if self.rect.bottom > self.screen_size[1]-1:
            self.rect.bottom = self.screen_size[1]-1

    def handle_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.direction = -1
            elif event.key == pygame.K_DOWN:
                self.direction = 1
            elif event.key == pygame.K_LEFT:
                self.turnLeft()
            elif event.key == pygame.K_RIGHT:
                self.turnRight()
            elif event.key == pygame.K_u:
                bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
                bullet.rect.centerx = self.rect.centerx
                bullet.rect.centery = self.rect.centery
                bullet.draw()
                bullet.update()

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP and self.direction == -1:
                self.direction = 0
            elif event.key == pygame.K_DOWN and self.direction == 1:
                self.direction = 0

and Here is my bullet class

class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

    def update(self):

        self.rect.centery -= 3

Body:
I would create Group() outside PlayerPaddle()

self.bullets_group = pygame.sprite.Group()

and use it as argument in PlayerPaddle()

self.player_paddle = PlayerPaddle(..., self.bullets_group)

This way player can easly add bullets to group

   elif event.key == pygame.K_u:
       bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
       bullet.rect.centerx = self.rect.centerx
       bullet.rect.centery = self.rect.centery

       self.bullets_group.add(bullet)

and mainloop can draw and update it

def Update():
    self.bullets_group.update()
    self.player_paddle.update()
    self.ai_paddle.update(..., self.bullets_group)

def Render():
    self.bullets_group.draw()
    self.player_paddle.draw()


问:
How to handle renewal of autorenewable subscriptions (ios/android)?
Perhaps I am simply not looking in the correct places, but I am surprised at the lack of documentation around cross-platform apps incorporating renewing subscriptions.

I have a cross-platform (iOS and Android) Ionic app with a Rails API for the back-end. I am using https://github.com/AlexDisler/cordova-plugin-inapppurchase as a wrapper around the iOS/Google store SDKs.

My question revolves around subscription renewal:

From what I gather, it is recommended that I have a daily job checking each of my subscriptions for their expiration date. If a subscription is about to expire, I can send the receipt stored in my database to either Google/Apple and check if the subscription has been renewed. If it has, I update the expiration date and keep the subscription active. If the subscription has not been renewed, I mark the subscription as inactive.

Now, what happens if a user renews a subscription? How will I know that a subscription has been renewed? And when do I check for subscription renewal? Seems like my options are:

Every day, check every expired subscription for renewal. Problems with this: 1) as the number of users grows, so will the number of users with expired subscriptions. Eventually, this will result in checking many, many expired subscriptions every night. 2) A user will be unable to access subscription-only content between the time they renew their subscription through the app/play store and the nightly subscription-checking job is run.

Every time a user with an expired subscription logs into the app, check to see if they have renewed their subscription. Problems with this: 1) My app uses token authentication. Therefore, users are not required to login with each use. So, if a user renews their subscription, but their token is still valid, the app will have no way of knowing that their subscription is up-to-date.

Is there another option? What am I missing here?

答:
I would suggest using a combination of both options.

When a user opens your app you should send a separate request to your backend that will fetch the receipt a check if its renewed and cache the expiration date and the time it was checked. Then I would have another job run nightly that doesn't check all the expired receipts, but clears the expiration date cache if it hasn't been checked within a certain period. Then, the next time a user opens the app, the cache will be empty and and will be fetched.

I'm working on adding Android subscriptions to RevenueCat but it won't be ready for a couple months.


问:
Hadoop Data Blocks and Data Content
Hadoop breaks up the content of the input data into blocks without regard to the content.

As a post described:

HDFS has no idea (and doesn’t care) what’s stored inside the file, so raw files are not split in accordance with rules that we humans would understand. Humans, for example, would want record boundaries — the lines showing where a record begins and ends — to be respected.

The part I am unclear is that if the data is split based only on the data size without regards to the content, then would there not be implication on the accuracy of queries performed later? For instance, an often sited example of list of cities and daily temperatures. could a city be in one block and its temperature somewhere else, how then a map operation correctly queries the info. There seems to be something fundamental about blocks and MR queries that I am missing.

Any help would be greatly appreciated.

答:
could a city be in one block and its temperature somewhere else

That is entirely possible, yes. In this instance, the record boundary crosses two blocks, and both are gathered.

Accuracy is not lost, but performance is, sure, in terms of Disk and network IO. When the end of a block is detected without reaching an InputSplit, then the next block is read. Even if this split  is within the first few bytes of that following block, it's byte stream is still processed.

Title: Hadoop Data Blocks and Data Content


答:
Here is one option by gathering to 'long' format and then spread it to 'wide'

```<code>library(tidyverse)
df %>%
    rownames_to_column('rn') %>%
    gather(key, val, -rn) %>% group_by(rn) %>%
    mutate(flag = as.integer(any(val %in% match_dx))) %>%
    spread(key, val)
# A tibble: 2 x 7
# Groups:   rn [2]
#     rn  flag   dx1  dx13   dx2   dx3   dx4
#* <chr> <int> <chr> <chr> <chr> <chr> <chr>
#1     1     1   C00   G20   C50   D20   A40
#2     2     0   G01   C30   Z11   D22   C21
</code>```

Or by using mutate_all to create logical columns, then reduce it to single logical vector and mutate to create the 'flag'

```<code>df %>%
  mutate_all(funs(. %in% match_dx)) %>%
  reduce(`|`) %>%
  as.integer %>%
  mutate(df, flag = .)
# A tibble: 2 x 6
#     dx1   dx2   dx3   dx4  dx13  flag
#    <chr> <chr> <chr> <chr> <chr> <int>
#1   C00   C50   D20   A40   G20     1
#2   G01   Z11   D22   C21   C30     0
</code>```

Or use the Reduce/lapply base R option suggested by @thelatemail

```<code>df$flag <- as.integer(Reduce(`|`, lapply(df, is.element, set=match_dx)))
</code>```

Or using %in%

```<code>as.integer(Reduce(`|`, lapply(df, `%in%`, match_dx)))
</code>```

Title: Replace multiple %in% statements with a single line of dplyr code

Body:
Here is one option by gathering to 'long' format and then spread it to 'wide'

library(tidyverse)
df %>%
    rownames_to_column('rn') %>%
    gather(key, val, -rn) %>% group_by(rn) %>%
    mutate(flag = as.integer(any(val %in% match_dx))) %>%
    spread(key, val)
# A tibble: 2 x 7
# Groups:   rn [2]
#     rn  flag   dx1  dx13   dx2   dx3   dx4
#* <chr> <int> <chr> <chr> <chr> <chr> <chr>
#1     1     1   C00   G20   C50   D20   A40
#2     2     0   G01   C30   Z11   D22   C21

Or by using mutate_all to create logical columns, then reduce it to single logical vector and mutate to create the 'flag'

df %>%
  mutate_all(funs(. %in% match_dx)) %>%
  reduce(`|`) %>%
  as.integer %>%
  mutate(df, flag = .)
# A tibble: 2 x 6
#     dx1   dx2   dx3   dx4  dx13  flag
#    <chr> <chr> <chr> <chr> <chr> <int>
#1   C00   C50   D20   A40   G20     1
#2   G01   Z11   D22   C21   C30     0

Or use the Reduce/lapply base R option suggested by @thelatemail

df$flag <- as.integer(Reduce(`|`, lapply(df, is.element, set=match_dx)))

Or using %in%

as.integer(Reduce(`|`, lapply(df, `%in%`, match_dx)))


问:
How to use SELECT COUNT sql to generate an int
I have this code in python querying an existing database:

```<code>count = db.execute("SELECT COUNT (player_id) FROM players WHERE user_id
= :id", id = session["user_id"])

for player in range(count):
    db.execute("INSERT INTO live_players (player_id) VALUES (:filler)",
filler = 0)
</code>```

However, it doesn't run because 'count' isn't an int. I want SELECT COUNT to return 2, but instead it returns '[{'COUNT (player_id)': 2}]'. How could I remedy this?

答:
You're getting back a result dictionary. Simply access it. To make this access easier, give it an alias:

```<code>SELECT COUNT(player_id) AS player_count ...
</code>```

Then:

```<code>for player in range(count["player_count"]):
   ...
</code>```

Body:
I have this code in python querying an existing database:

count = db.execute("SELECT COUNT (player_id) FROM players WHERE user_id
= :id", id = session["user_id"])

for player in range(count):
    db.execute("INSERT INTO live_players (player_id) VALUES (:filler)",
filler = 0)

However, it doesn't run because 'count' isn't an int. I want SELECT COUNT to return 2, but instead it returns '[{'COUNT (player_id)': 2}]'. How could I remedy this?

Body:
You're getting back a result dictionary. Simply access it. To make this access easier, give it an alias:

SELECT COUNT(player_id) AS player_count ...

Then:

for player in range(count["player_count"]):
   ...


问:
What's the problem in my code? c# winforms
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

```<code>namespace Login
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}
</code>```

Login form

```<code>namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}
</code>```

Where do you think I'm doing it wrong?
Thanks....

答:
You should just call Form.Close() in your button event handler, when you want to close the form (after setting desired DialogResult).

As far as I know, it is not going to happen automagically.

I have never done it any other way, and this approach has always worked for me.

Body:
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

namespace Login
{
    static class Program
    {
        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}

Login form

namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}

Where do you think I'm doing it wrong?
Thanks....


问:
Cannot get my loop to keep prompting user for a score
My code is nearly complete, and is functioning just fine, except I want my if statement to keep asking the user for a score. As it is right now, it asks the user for a score, and if you enter an invalid entry, it gives the line saying please try again, but then the code stops. I want it to keep prompting the user until they enter an invalid number.</p>

```<code>//Variables
            double grade;
            string studentName;
            //Prompt the user for the student's name
            Console.WriteLine("Please enter the student's name:");
            studentName = Console.ReadLine();
            //Prompt the user for the student's score
            Console.WriteLine("Please enter the student's score between 0 and 100:");
            if (!(double.TryParse(Console.ReadLine(), out grade)))
            {
               Console.WriteLine("Invalid entry, scores entered must be numeric. Please try again");
            }
            else if (grade >=90)
            {
                Console.WriteLine("{0} has a score of {1} which is an A.", studentName, grade);
            }
            else if (grade < 90 && grade >= 80)
            {
                Console.WriteLine("{0} has a score of {1} which is a B.", studentName, grade);
            }
            else if (grade < 80 && grade >=70)
            {
                Console.WriteLine("{0} has a score of {1} which is a C.", studentName, grade);
            }
            else if (grade < 70 && grade >= 60)
            {
                Console.WriteLine("{0} has a score of {1} which is a D.", studentName, grade);
            }
            else
            {
                Console.WriteLine("{0} has a score of {1} which is an F.", studentName, grade);
            }
            Console.ReadLine();
</code>```

答:
You can use an infinite while loop-

```<code>while (true)
{
    Console.WriteLine("Please enter the student's name:");
    studentName = Console.ReadLine();
    //Prompt the user for the student's score
    Console.WriteLine("Please enter the student's score between 0 and 100:");
    if (!(double.TryParse(Console.ReadLine(), out grade)))
    {
        Console.WriteLine("Invalid entry, scores entered must be numeric. Please try again");
        break;
    }
    else if (grade >= 90)
    {
        Console.WriteLine("{0} has a score of {1} which is an A.", studentName, grade);
    }
    else if (grade < 90 && grade >= 80)
    {
        Console.WriteLine("{0} has a score of {1} which is a B.", studentName, grade);
    }
    else if (grade < 80 && grade >= 70)
    {
        Console.WriteLine("{0} has a score of {1} which is a C.", studentName, grade);
    }
    else if (grade < 70 && grade >= 60)
    {
        Console.WriteLine("{0} has a score of {1} which is a D.", studentName, grade);
    }
    else
    {
        Console.WriteLine("{0} has a score of {1} which is an F.", studentName, grade);
    }
}
</code>```

I included a break statement to break the while-loop if a value is entered that is not numeric (as per your if condition).

Body:
My code is nearly complete, and is functioning just fine, except I want my if statement to keep asking the user for a score. As it is right now, it asks the user for a score, and if you enter an invalid entry, it gives the line saying please try again, but then the code stops. I want it to keep prompting the user until they enter an invalid number.

//Variables
            double grade;
            string studentName;
            //Prompt the user for the student's name
            Console.WriteLine("Please enter the student's name:");
            studentName = Console.ReadLine();
            //Prompt the user for the student's score
            Console.WriteLine("Please enter the student's score between 0 and 100:");
            if (!(double.TryParse(Console.ReadLine(), out grade)))
            {
               Console.WriteLine("Invalid entry, scores entered must be numeric. Please try again");
            }
            else if (grade >=90)
            {
                Console.WriteLine("{0} has a score of {1} which is an A.", studentName, grade);
            }
            else if (grade < 90 && grade >= 80)
            {
                Console.WriteLine("{0} has a score of {1} which is a B.", studentName, grade);
            }
            else if (grade < 80 && grade >=70)
            {
                Console.WriteLine("{0} has a score of {1} which is a C.", studentName, grade);
            }
            else if (grade < 70 && grade >= 60)
            {
                Console.WriteLine("{0} has a score of {1} which is a D.", studentName, grade);
            }
            else
            {
                Console.WriteLine("{0} has a score of {1} which is an F.", studentName, grade);
            }
            Console.ReadLine();

Body:
You can use an infinite while loop-

while (true)
{
    Console.WriteLine("Please enter the student's name:");
    studentName = Console.ReadLine();
    //Prompt the user for the student's score
    Console.WriteLine("Please enter the student's score between 0 and 100:");
    if (!(double.TryParse(Console.ReadLine(), out grade)))
    {
        Console.WriteLine("Invalid entry, scores entered must be numeric. Please try again");
        break;
    }
    else if (grade >= 90)
    {
        Console.WriteLine("{0} has a score of {1} which is an A.", studentName, grade);
    }
    else if (grade < 90 && grade >= 80)
    {
        Console.WriteLine("{0} has a score of {1} which is a B.", studentName, grade);
    }
    else if (grade < 80 && grade >= 70)
    {
        Console.WriteLine("{0} has a score of {1} which is a C.", studentName, grade);
    }
    else if (grade < 70 && grade >= 60)
    {
        Console.WriteLine("{0} has a score of {1} which is a D.", studentName, grade);
    }
    else
    {
        Console.WriteLine("{0} has a score of {1} which is an F.", studentName, grade);
    }
}

I included a break statement to break the while-loop if a value is entered that is not numeric (as per your if condition).


问:
Using KVC with Singleton pattern
My questionwas about if it was possible to use KVC on a Singleton property on Swift.  I was testing KVC on a class was able to get it working but decided to see if it work on a Singleton class.

I'm running into an error stating that the "shared" property of my Singleton isn't KVC-compliant.

```<code> class KVOObject: NSObject {
    @objc static let shared = KVOObject()
    private override init(){}

    @objc dynamic var fontSize = 18
 }

 override func viewDidLoad() {
    super.viewDidLoad()

    addObserver(self, forKeyPath: #keyPath(KVOObject.shared.fontSize), options: [.old, .new], context: nil)
 }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
   if keyPath == #keyPath(KVOObject.shared.fontSize) {
      // do something
   }
 }
</code>```

I am currently getting the error below:

NetworkCollectionTest[9714:452848] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ addObserver: forKeyPath:@"shared.fontSize" options:3 context:0x0] was sent to an object that is not KVC-compliant for the "shared" property.'

答:
The key path is not correct. It’s KVOObject.fontSize. And you need to add the observer to that singleton:

```<code> KVOObject.shared.addObserver(self, forKeyPath: #keyPath(KVOObject.fontSize), options: [.old, .new], context: nil)
</code>```

As an aside, (a) you should probably use a context to identify whether you're handling this or whether it might be used by the superclass; (b) you should call the super implementation if it's not yours; and (c) make sure to remove the observer on deinit:

```<code>class ViewController: UICollectionViewController {

    private var observerContext = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        KVOObject.shared.addObserver(self, forKeyPath: #keyPath(KVOObject.fontSize), options: [.new, .old], context: &observerContext)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &observerContext {
            // do something
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }

    deinit {
        KVOObject.shared.removeObserver(self, forKeyPath: #keyPath(KVOObject.fontSize))
    }

    ...
}
</code>```

Or, if in Swift 4, it's now much easier as it's closure-based (avoiding need for context) and is automatically removed when the NSKeyValueObservation falls out of scope:

```<code>class ViewController: UICollectionViewController {

    private var token: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()

        token = KVOObject.shared.observe(\.fontSize, options: [.new, .old]) { [weak self] object, change in
            // do something
        }
    }

    ...
}
</code>```

By the way, a few observations on the singleton:

The shared property does not require @objc qualifier; only the property being observed needs that; and

The init method really should be calling super; and

I'd probably also declare it to be final to avoid confusion that can result in subclassing singletons.

Thus:

```<code>final class KVOObject: NSObject {
    static let shared = KVOObject()

    override private init() { super.init() }

    @objc dynamic var fontSize: Int = 18
}
</code>```

Title: Using KVC with Singleton pattern

Body:
My questionwas about if it was possible to use KVC on a Singleton property on Swift.  I was testing KVC on a class was able to get it working but decided to see if it work on a Singleton class.

I'm running into an error stating that the "shared" property of my Singleton isn't KVC-compliant.

 class KVOObject: NSObject {
    @objc static let shared = KVOObject()
    private override init(){}

    @objc dynamic var fontSize = 18
 }

 override func viewDidLoad() {
    super.viewDidLoad()

    addObserver(self, forKeyPath: #keyPath(KVOObject.shared.fontSize), options: [.old, .new], context: nil)
 }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
   if keyPath == #keyPath(KVOObject.shared.fontSize) {
      // do something
   }
 }

I am currently getting the error below:

NetworkCollectionTest[9714:452848] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ addObserver: forKeyPath:@"shared.fontSize" options:3 context:0x0] was sent to an object that is not KVC-compliant for the "shared" property.'

Body:
The key path is not correct. It’s KVOObject.fontSize. And you need to add the observer to that singleton:

 KVOObject.shared.addObserver(self, forKeyPath: #keyPath(KVOObject.fontSize), options: [.old, .new], context: nil)

As an aside, (a) you should probably use a context to identify whether you're handling this or whether it might be used by the superclass; (b) you should call the super implementation if it's not yours; and (c) make sure to remove the observer on deinit:

class ViewController: UICollectionViewController {

    private var observerContext = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        KVOObject.shared.addObserver(self, forKeyPath: #keyPath(KVOObject.fontSize), options: [.new, .old], context: &observerContext)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &observerContext {
            // do something
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }

    deinit {
        KVOObject.shared.removeObserver(self, forKeyPath: #keyPath(KVOObject.fontSize))
    }

    ...
}

Or, if in Swift 4, it's now much easier as it's closure-based (avoiding need for context) and is automatically removed when the NSKeyValueObservation falls out of scope:

class ViewController: UICollectionViewController {

    private var token: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()

        token = KVOObject.shared.observe(\.fontSize, options: [.new, .old]) { [weak self] object, change in
            // do something
        }
    }

    ...
}

By the way, a few observations on the singleton:

The shared property does not require @objc qualifier; only the property being observed needs that; and

The init method really should be calling super; and

I'd probably also declare it to be final to avoid confusion that can result in subclassing singletons.

Thus:

final class KVOObject: NSObject {
    static let shared = KVOObject()

    override private init() { super.init() }

    @objc dynamic var fontSize: Int = 18
}


问:
How can css pixels stretch out when zooming in?
Acoording to this article here https://www.quirksmode.org/mobile/viewports.html the CSS pixels start to grow, and now one CSS pixels overlaps several device pixels. According to me if the CSS pixels grow, then I will be able to see more content of the page not less. But when zooming I am able to do the opposite: to see less content. Can someone clarify this?</p>

答:
The article is question is correct; as you zoom in, the CSS pixels increase in size. However, because the CSS pixels increase in size while the viewport remains the same size, fewer CSS pixels can be displayed (meaning you see fewer CSS pixels).

Consider this in math:

```<code>              CSS pixels * viewport size = visible pixels

ZOOMED OUT:         1280 * 1024          = 1,310,720
DEFAULT:            1024 * 1024          = 1,048,576
ZOOMED IN:           768 * 1024          =   768,432
</code>```

Hopefully this helps clarify this a little :)

Body:
The article is question is correct; as you zoom in, the CSS pixels increase in size. However, because the CSS pixels increase in size while the viewport remains the same size, fewer CSS pixels can be displayed (meaning you see fewer CSS pixels).

Consider this in math:

              CSS pixels * viewport size = visible pixels

ZOOMED OUT:         1280 * 1024          = 1,310,720
DEFAULT:            1024 * 1024          = 1,048,576
ZOOMED IN:           768 * 1024          =   768,432

Hopefully this helps clarify this a little :)


问:
How to get a specific value from JSON site and put on Label?
I'm trying to put the "last" value of the "USDT_BTC" of a JSON inside a label...

CODE

```<code>    Dim BitcoinPrice As String = ""

    Dim json = New IO.StreamReader(DirectCast(DirectCast(Net.WebRequest.Create("https://poloniex.com/public?command=returnTicker"), Net.HttpWebRequest).GetResponse, Net.HttpWebResponse).GetResponseStream)
    Dim rq As Newtonsoft.Json.Linq.JToken = Newtonsoft.Json.Linq.JObject.Parse(json.ReadToEnd)

    BitCoinPrice = $"{rq.SelectToken("USDT_BTC")}" 'and value of "last"

    Label1.Text = BitCoinPrice
</code>```

SITE

```<code>https://poloniex.com/public?command=returnTicker
</code>```

JSON Example

```<code>"BTC_XRP":{"id":117,"last":"0.00001990"},
"USDT_BTC":{"id":121,"last":"11714.68222119"}, ' "last" Value
"USDT_DASH":{"id":122,"last":"736.33990743"},
</code>```

答:
A guy on Facebook Group really interested in helping told me that the solution is to just put the value of the "last" after the "USDT_BTC".

Something like this:

```<code>BitCoinPrice = $"{rq.SelectToken("USDT_BTC")("last")}"
</code>```

Body:
I'm trying to put the "last" value of the "USDT_BTC" of a JSON inside a label...

CODE

    Dim BitcoinPrice As String = ""

    Dim json = New IO.StreamReader(DirectCast(DirectCast(Net.WebRequest.Create("https://poloniex.com/public?command=returnTicker"), Net.HttpWebRequest).GetResponse, Net.HttpWebResponse).GetResponseStream)
    Dim rq As Newtonsoft.Json.Linq.JToken = Newtonsoft.Json.Linq.JObject.Parse(json.ReadToEnd)

    BitCoinPrice = $"{rq.SelectToken("USDT_BTC")}" 'and value of "last"

    Label1.Text = BitCoinPrice

SITE

https://poloniex.com/public?command=returnTicker

JSON Example

"BTC_XRP":{"id":117,"last":"0.00001990"},
"USDT_BTC":{"id":121,"last":"11714.68222119"}, ' "last" Value
"USDT_DASH":{"id":122,"last":"736.33990743"},

Body:
A guy on Facebook Group really interested in helping told me that the solution is to just put the value of the "last" after the "USDT_BTC".

Something like this:

BitCoinPrice = $"{rq.SelectToken("USDT_BTC")("last")}"