问:
My 'change password' function isn't working, and getting stuck in a loop instead
Here is my code:

```<code>import pickle

current_user = None

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def set_password(self):
        self.password = input("Enter NEW password > ")

    def __get_password(self):
        return self.password

    def __get_username(self):
        return self.username

    def change_password(self):
        my_password = input("Enter your CURRENT password > ")
        if my_password == self.__get_password():
            self.set_password()
        else:
            print("Please try again")

    def display_details(self):
        print()
        print("Username and password")
        print("---------------------")
        print("username is: ", User.__get_username(self))
        print("password is: ", User.__get_password(self))
        print()

    def __repr__(self):
        return f'username: {self.username}'

try:
    users = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
    users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
    pickle.dump(foo, open("users.pickle", "wb"))

def find_user(name):
    for user in users:
        if user.username == name:
            return user

def add_user():
    user = input("Enter NEW user > ")
    password = input(f"Enter password for {user} > ")
    users.append(User(user, password))

def delete_user():
    delete_user = input("Enter the user you wish to remove > ")
    user = find_user(delete_user)
    if user:
        users.remove(user)
        print('done')
    else:
        print(f'user {delete_user} not found')

def display_users():
    for user in users:
        print(user)

def invalid_entry():  # Response for invalid entries to menu.
    print("Invalid entry, please try again")
    print()

def menu():  # Display menu, prompt for and accept keyboard choice
    print("Please select one of the following:")
    print()
    print("Enter a if you want to add a new user")
    print("Enter d if you want to delete a user")
    print("Enter f if you want to find a user")
    print("Enter c if you want to change your password")
    print("Enter u if you want to display a list of users")
    print("Enter q if you want to Quit")
    choice = input("")
    return choice

while True:
    menu_choice = menu()
    if menu_choice.lower() == "a":
        add_user()
    elif menu_choice.lower() == "d":
        delete_user()
    elif menu_choice.lower() == "f":
        current_user = find_user()
    elif menu_choice.lower() == "c":
        if current_user is None:
            print("No user selected!")
            continue
        else:
            current_user.change_password()
    elif menu_choice.lower() == 'u':
        display_users()
    elif menu_choice.lower() == "q":
        print("Goodbye")
        with open('users.pickle', 'wb') as f:
            pickle.dump(users, f)
            quit()
    else:
        invalid_entry()
</code>```

There's clearly something wrong as it's getting stuck in a loop:

Enter your CURRENT password > password

  Enter your CURRENT password > password

  Enter your CURRENT password >

I can see PyCharm is coming up 'local variable my_password is not used' too.

I tried removing my_password = input("Enter your CURRENT password > ") from the def change_password() block, but that just results in a fatal error.

I also tried renaming the first change_password function to update_password and updating the second one accordingly, so that it went...

```<code>def change_password():
    update_password()
</code>```

...but that didn't work either.

This is the logic that I want to use:

IF the user selects 'c' in the menu THEN do the following...

Prompt the user to enter their current password

IF the entered input matches their current password THEN prompt them to enter a new password and update their password accordingly

IF the entered input does not match their current password THEN prompt them to try again

Any help please? TIA

By the way, I'm puzzled that PyCharm is coming up 'unresolved reference 'foo''. That section seems to work OK, but any insights on why that is and if it's a problem or not would be appreciated.

Edit: I've updated the code in line with the suggestions, as much as I can, anyway.

Edit 2: PyCharm said that self in if my_password == self.__get_password(self) is an unexpected argument, so I removed it, and that didn't seem to do any harm.

答:
The other change_password function in the outer scope also requests command line input. try to eliminate all the unneeded
input("Enter your CURRENT password > ")
except for one and use parameters in your function calls instead.

On top of that, the outer scope change_password() function is calling itself over and over, because its shadowing the inner one. Try renaming one of the two.

Body:
Here is my code:

import pickle

current_user = None

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def set_password(self):
        self.password = input("Enter NEW password > ")

    def __get_password(self):
        return self.password

    def __get_username(self):
        return self.username

    def change_password(self):
        my_password = input("Enter your CURRENT password > ")
        if my_password == self.__get_password():
            self.set_password()
        else:
            print("Please try again")

    def display_details(self):
        print()
        print("Username and password")
        print("---------------------")
        print("username is: ", User.__get_username(self))
        print("password is: ", User.__get_password(self))
        print()

    def __repr__(self):
        return f'username: {self.username}'

try:
    users = pickle.load(open("users.pickle", "rb"))
except (OSError, IOError) as f:
    users = [User("MichaelPalin", "P4rr0t"), User("EricIdle", "M0nty"), User("TerryJones", "Pyth0n")]
    pickle.dump(foo, open("users.pickle", "wb"))

def find_user(name):
    for user in users:
        if user.username == name:
            return user

def add_user():
    user = input("Enter NEW user > ")
    password = input(f"Enter password for {user} > ")
    users.append(User(user, password))

def delete_user():
    delete_user = input("Enter the user you wish to remove > ")
    user = find_user(delete_user)
    if user:
        users.remove(user)
        print('done')
    else:
        print(f'user {delete_user} not found')

def display_users():
    for user in users:
        print(user)

def invalid_entry():  # Response for invalid entries to menu.
    print("Invalid entry, please try again")
    print()

def menu():  # Display menu, prompt for and accept keyboard choice
    print("Please select one of the following:")
    print()
    print("Enter a if you want to add a new user")
    print("Enter d if you want to delete a user")
    print("Enter f if you want to find a user")
    print("Enter c if you want to change your password")
    print("Enter u if you want to display a list of users")
    print("Enter q if you want to Quit")
    choice = input("")
    return choice

while True:
    menu_choice = menu()
    if menu_choice.lower() == "a":
        add_user()
    elif menu_choice.lower() == "d":
        delete_user()
    elif menu_choice.lower() == "f":
        current_user = find_user()
    elif menu_choice.lower() == "c":
        if current_user is None:
            print("No user selected!")
            continue
        else:
            current_user.change_password()
    elif menu_choice.lower() == 'u':
        display_users()
    elif menu_choice.lower() == "q":
        print("Goodbye")
        with open('users.pickle', 'wb') as f:
            pickle.dump(users, f)
            quit()
    else:
        invalid_entry()

There's clearly something wrong as it's getting stuck in a loop:

Enter your CURRENT password > password

  Enter your CURRENT password > password

  Enter your CURRENT password >

I can see PyCharm is coming up 'local variable my_password is not used' too.

I tried removing my_password = input("Enter your CURRENT password > ") from the def change_password() block, but that just results in a fatal error.

I also tried renaming the first change_password function to update_password and updating the second one accordingly, so that it went...

def change_password():
    update_password()

...but that didn't work either.

This is the logic that I want to use:

IF the user selects 'c' in the menu THEN do the following...

Prompt the user to enter their current password

IF the entered input matches their current password THEN prompt them to enter a new password and update their password accordingly

IF the entered input does not match their current password THEN prompt them to try again

Any help please? TIA

By the way, I'm puzzled that PyCharm is coming up 'unresolved reference 'foo''. That section seems to work OK, but any insights on why that is and if it's a problem or not would be appreciated.

Edit: I've updated the code in line with the suggestions, as much as I can, anyway.

Edit 2: PyCharm said that self in if my_password == self.__get_password(self) is an unexpected argument, so I removed it, and that didn't seem to do any harm.


来源: stackexchange

问:
pull a remote repo and pushing those files
We're working on a big project here at work with feature "bundles" (EDIT: "bundle" is just a term we use internally to refer to a specific functionality package, and isn't meant as a git term) spread out into several different git repositories. I'm getting ready to send a batch of changes upstream for review and testing, but I've run into a snag trying to get everything to play together nicely.

What I've done so far is clone from the repo containing the code bundle into my main project, which works insofar as it gets the files where they need to go. However, when I go to add/commit and push, the files from the "bundle" repo won't go with it, presumably because they are part of a different git repository than the one I'm pushing from.

It's not really a viable option to ask all the other developers on the team to pull in my "bundle" every time it changes (especially since it's still somewhat early in the dev cycle and sees a lot of revisions and refactoring), and I don't really want to copy the files by hand every time I need to send them up, either. Preferably, I'd be able to set things up so that I could pull from my "bundle" repo into my main repo, then push the changes as a whole.

Is there a way to do what I'm looking for with git?

答:
I'm not getting a clear picture of what you want (the usage of the word bundle seems non-standard here?); However,

man git-remote might be what you need

git push --mirror (perhaps starting with a git clone --mirror

If you want the inverse (track all remote branches in a local repo), see my recent additions here: "fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

ContentLicense: CC BY-SA 3.0


问:
Why is pressing "Enter" equivalent to the number 0?
I don't understand why pressing enter key is the same as pressing 0 on the keyboard.

```<code>[int] $Choice = -1
$Count = 2

while ($Choice -lt 0 -or $Choice -gt $Count)
{
    Write-Host "Input number"
    $Choice = Read-Host

    Write-Host "choice:"
    Write-Host $Choice

}
</code>```

The output will be 0 even if just press enter. I want the user to explicitly input 0.

答:
In the very first statement:

```<code>[int] $Choice = -1
</code>```

... you type-cast $choice to [int].

When you apply a cast to the left-hand side of an assignment (to the left of the variable name), PowerShell will "remember" it as a type-constraint and treat the variable as strongly typed - PowerShell will attempt to convert anything you assign to $choice from there on out to an [int].

Hitting enter in the prompt without any other input results in Read-Host returning an empty string (like "")

The conversion logic treats the empty string as $null, and casting $null to [int] results in the value 0. You can see this by casting an empty string to [int] directly:

```<code>PS C:\> [int]""
0
</code>```

You should probably validate the input from Read-Host before assigning to $Choice if you explicitly require a number:

```<code>$inputString = Read-Host
if($inputString -notmatch '^\d+$') {
    Write-Host "Digits only please!"
    continue
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I don't understand why pressing enter key is the same as pressing 0 on the keyboard.

[int] $Choice = -1
$Count = 2

while ($Choice -lt 0 -or $Choice -gt $Count)
{
    Write-Host "Input number"
    $Choice = Read-Host

    Write-Host "choice:"
    Write-Host $Choice

}

The output will be 0 even if just press enter. I want the user to explicitly input 0.

Body:
In the very first statement:

[int] $Choice = -1

... you type-cast $choice to [int].

When you apply a cast to the left-hand side of an assignment (to the left of the variable name), PowerShell will "remember" it as a type-constraint and treat the variable as strongly typed - PowerShell will attempt to convert anything you assign to $choice from there on out to an [int].

Hitting enter in the prompt without any other input results in Read-Host returning an empty string (like "")

The conversion logic treats the empty string as $null, and casting $null to [int] results in the value 0. You can see this by casting an empty string to [int] directly:

PS C:\> [int]""
0

You should probably validate the input from Read-Host before assigning to $Choice if you explicitly require a number:

$inputString = Read-Host
if($inputString -notmatch '^\d+$') {
    Write-Host "Digits only please!"
    continue
}


问:
Renaming Sub Column names and then creating a data frame using renamed column in R
I am having a tricky dataset3922327258060dat.txt for which I have to create a function to read three columns. This dataset is having multiple columns, out of those columns I need to change name of 3 columns (Date, HrMn, Slp) to (Date, Time, AtmosPressure) and then make a data frame of these 3 columns. BUT the tricky thing is the columns has sub heading as those names(Date, HrMn, Slp) as when I am trying to write
colnames(noaaFilename)
 it is giving me this result
"Identification" "SLP"            "X3"
I am trying to do this, but unable to get result with sub column names and values.

Please help me to create a data frame with three main columns with name "Date", "Time", "AtmosPressure"

```<code>noaaFilename <- read_table2("3922327258060dat.txt")

readNOAAData <- function(filename=noaaFilename) {

  colnames(noaaFilename)
  noaaFilename <- read_table2("3922327258060dat.txt")

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaFiledf <- data.frame(Date, Time, AtmosPressure)

  noaaData <- subset(noaaFilename, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))

  ## Stop editing here
  return(noaaData)
}
</code>```

Sorry as this comes too long

```<code>dput(head(noaaFilename, 20))
</code>```

```<code>structure(list(Identification = c("Name", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC"),
    SLP = c("USAF", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY"), X3 = c("NCDC", ",997270,99999,20121029,0000,4,FM-18,",
    ",997270,99999,20121029,0100,4,FM-18,", ",997270,99999,20121029,0200,4,FM-18,",
    ",997270,99999,20121029,0300,4,FM-18,", ",997270,99999,20121029,0400,4,FM-18,",
    ",997270,99999,20121029,0500,4,FM-18,", ",997270,99999,20121029,0600,4,FM-18,",
    ",997270,99999,20121029,0700,4,FM-18,", ",997270,99999,20121029,0800,4,FM-18,",
    ",997270,99999,20121029,0900,4,FM-18,", ",997270,99999,20121029,1000,4,FM-18,",
    ",997270,99999,20121029,1100,4,FM-18,", ",997270,99999,20121029,1200,4,FM-18,",
    ",997270,99999,20121029,1300,4,FM-18,", ",997270,99999,20121029,1400,4,FM-18,",
    ",997270,99999,20121029,1500,4,FM-18,", ",997270,99999,20121029,1600,4,FM-18,",
    ",997270,99999,20121029,1700,4,FM-18,", ",997270,99999,20121029,1800,4,FM-18,"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L), problems = structure(list(row = 1:94, col = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_), expected = c("3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns"), actual = c("11 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "4 columns",
"4 columns", "4 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns"), file = c("'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'"
)), row.names = c(NA, -94L), class = c("tbl_df", "tbl", "data.frame"
)))
</code>```

答:
The difficulty is in the column headers not having commas between them.

There may be a way to import that dataset without editing it manually. If you can easily edit it, then I would do that. Open the text file, delete the first row, put commas in-between the column names in the now first row (previously the second row), save the file, and then try again without the skip=1 argument.

If you can't edit the file, or need to do this many times, then there may be a solution to import the file without the need to edit it.

Alternatively, since it looks like a fixed width file, you can try using the read.fwf function.

Edit: Or skip the first two rows since the headers are separated by space while the data is separated by commas.

```<code>dat <- read.csv("3922327258060dat.txt", skip=2, header=FALSE) # Added header thanks to 42
dat3 <- dat[,c(4,5,9)]
names(dat3) <- c("Date","Time","AtmosPressure")
</code>```

Body:
I am having a tricky dataset3922327258060dat.txt for which I have to create a function to read three columns. This dataset is having multiple columns, out of those columns I need to change name of 3 columns (Date, HrMn, Slp) to (Date, Time, AtmosPressure) and then make a data frame of these 3 columns. BUT the tricky thing is the columns has sub heading as those names(Date, HrMn, Slp) as when I am trying to write
colnames(noaaFilename)
 it is giving me this result
"Identification" "SLP"            "X3"
I am trying to do this, but unable to get result with sub column names and values.

Please help me to create a data frame with three main columns with name "Date", "Time", "AtmosPressure"

noaaFilename <- read_table2("3922327258060dat.txt")

readNOAAData <- function(filename=noaaFilename) {

  colnames(noaaFilename)
  noaaFilename <- read_table2("3922327258060dat.txt")

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaFiledf <- data.frame(Date, Time, AtmosPressure)

  noaaData <- subset(noaaFilename, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))

  ## Stop editing here
  return(noaaData)
}

Sorry as this comes too long

dput(head(noaaFilename, 20))

structure(list(Identification = c("Name", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC"),
    SLP = c("USAF", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY"), X3 = c("NCDC", ",997270,99999,20121029,0000,4,FM-18,",
    ",997270,99999,20121029,0100,4,FM-18,", ",997270,99999,20121029,0200,4,FM-18,",
    ",997270,99999,20121029,0300,4,FM-18,", ",997270,99999,20121029,0400,4,FM-18,",
    ",997270,99999,20121029,0500,4,FM-18,", ",997270,99999,20121029,0600,4,FM-18,",
    ",997270,99999,20121029,0700,4,FM-18,", ",997270,99999,20121029,0800,4,FM-18,",
    ",997270,99999,20121029,0900,4,FM-18,", ",997270,99999,20121029,1000,4,FM-18,",
    ",997270,99999,20121029,1100,4,FM-18,", ",997270,99999,20121029,1200,4,FM-18,",
    ",997270,99999,20121029,1300,4,FM-18,", ",997270,99999,20121029,1400,4,FM-18,",
    ",997270,99999,20121029,1500,4,FM-18,", ",997270,99999,20121029,1600,4,FM-18,",
    ",997270,99999,20121029,1700,4,FM-18,", ",997270,99999,20121029,1800,4,FM-18,"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L), problems = structure(list(row = 1:94, col = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_), expected = c("3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns"), actual = c("11 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "4 columns",
"4 columns", "4 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns"), file = c("'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'"
)), row.names = c(NA, -94L), class = c("tbl_df", "tbl", "data.frame"
)))

Body:
The difficulty is in the column headers not having commas between them.

There may be a way to import that dataset without editing it manually. If you can easily edit it, then I would do that. Open the text file, delete the first row, put commas in-between the column names in the now first row (previously the second row), save the file, and then try again without the skip=1 argument.

If you can't edit the file, or need to do this many times, then there may be a solution to import the file without the need to edit it.

Alternatively, since it looks like a fixed width file, you can try using the read.fwf function.

Edit: Or skip the first two rows since the headers are separated by space while the data is separated by commas.

dat <- read.csv("3922327258060dat.txt", skip=2, header=FALSE) # Added header thanks to 42
dat3 <- dat[,c(4,5,9)]
names(dat3) <- c("Date","Time","AtmosPressure")


问:
How to get Pin<&mut T> out of Pin<Arc<Mutex<T>>>
I'm writing a stream adapter that requires a shared ownership of the stream.

Is it correct to store the stream (privately) in Pin<Arc<Mutex<impl Stream>>>?

How can I call poll_next(self: Pin<&mut Stream> on the stream?

答:
Mutex does not have what is called structural pinning, which is described in the std::pin module documentation:

It turns out that it is actually up to the author of the data structure to decide whether the pinned projection for a particular field turns Pin<&mut Struct> into Pin<&mut Field> or &mut Field. [...] As the author of a data structure you get to decide for each field whether pinning "propagates" to this field or not. Pinning that propagates is also called "structural", because it follows the structure of the type.

Mutex<T> does not have structural pinning because the pinned-ness of the struct (the Mutex) does not propagate to the field (the T) -- it is safe to get an unpinned &mut T from a Pin<&mut Mutex<T>> (i.e., by using Deref instead of DerefMut and locking the mutex), even if T and Mutex<T> are !Unpin.

In order to turn this &mut T into a Pin<&mut T>, you have to make another layer of unchecked guarantee, using unsafe and Pin::new_unchecked, to prove that the T itself is never moved. This seems to defeat the purpose of the "outer" Pin.

Depending on what your data structures allow, you might consider one of these options:

writing a wrapper for Arc<Mutex> that pins the contents of the Mutex when accessed through a Pin (you couldn't implement Deref, but you could write methods that returned MutexGuards and did the Pin-wrapping internally)

simply pushing the shared mutability inside the type that implements Stream, if your data structure allows it.


问:
Java Thread priority has no effect
This is a test about thread priority.
The code is from Thinking in Java p.809

```<code>import java.util.concurrent.*;

public class SimplePriorities implements Runnable {
    private int countDown = 5;
    private volatile double d; // No optimization
    private int priority;

    public SimplePriorities(int priority) {
        this.priority = priority;
    }

    public String toString() {
        return Thread.currentThread() + ": " + countDown;
    }

    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            // An expensive, interruptable operation:
            for (int i = 1; i < 10000000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0)
                    Thread.yield();
            }
            System.out.println(this);
            if (--countDown == 0)
                return;
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        exec.shutdown();
    }
}
</code>```

I wonder why I can't get a regular result like:

```<code>Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-6,10,main]: 4
Thread[pool-1-thread-6,10,main]: 3
Thread[pool-1-thread-6,10,main]: 2
Thread[pool-1-thread-6,10,main]: 1
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-5,1,main]: 5
Thread[pool-1-thread-4,1,main]: 5
...
</code>```

but a random result (every time I run it changes):

```<code>Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-4,1,main]: 5
Thread[pool-1-thread-2,1,main]: 4
Thread[pool-1-thread-3,1,main]: 4
Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-5,1,main]: 5
...
</code>```

I use i3-2350M 2C4T CPU with Win 7 64 bit JDK 7.
Does it matter ?

答:
High-priority thread doesn't stop low-priority thread until it's done. High-priority doesn't make something faster either, if it did, we'd always make everything high-priority. And low-priority doesn't make things slower or we'd never use it.

As I understand you are misunderstanding that rest of the system should be idle and just let the highest-priority thread work while the rest of the system's capacity is wasted.

Title: Java Thread priority has no effect

Body:
This is a test about thread priority.
The code is from Thinking in Java p.809

import java.util.concurrent.*;

public class SimplePriorities implements Runnable {
    private int countDown = 5;
    private volatile double d; // No optimization
    private int priority;

    public SimplePriorities(int priority) {
        this.priority = priority;
    }

    public String toString() {
        return Thread.currentThread() + ": " + countDown;
    }

    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            // An expensive, interruptable operation:
            for (int i = 1; i < 10000000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0)
                    Thread.yield();
            }
            System.out.println(this);
            if (--countDown == 0)
                return;
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        exec.shutdown();
    }
}

I wonder why I can't get a regular result like:

Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-6,10,main]: 4
Thread[pool-1-thread-6,10,main]: 3
Thread[pool-1-thread-6,10,main]: 2
Thread[pool-1-thread-6,10,main]: 1
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-5,1,main]: 5
Thread[pool-1-thread-4,1,main]: 5
...

but a random result (every time I run it changes):

Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-4,1,main]: 5
Thread[pool-1-thread-2,1,main]: 4
Thread[pool-1-thread-3,1,main]: 4
Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-5,1,main]: 5
...

I use i3-2350M 2C4T CPU with Win 7 64 bit JDK 7.
Does it matter ?


问:
Split bash command into several reusable pieces
How can I split a command that uses pipes into different pieces?

I have the following working bash command:

```<code>RESULT=$(find "/path/to/releases" -maxdepth 0 -type d -print0 | xargs -r -0 ls -1 -t | tail -n 1)
</code>```

I would rather have the pipes split up into multiple variables like so, so I can reuse RESULT1 or RESULT2 somewhere else:

```<code>RESULT1=$(find "/path/to/releases" -maxdepth 0 -type d -print0)

if [ -n ${RESULT1} ]; then
  RESULT2=${RESULT1} | xargs -r -0 ls -1 -t
  RESULT3=${RESULT2} | tail -n 1
]
</code>```

Is this possible?

Update: The reason I also want to split things up is because I want to check first if the first part actually finds something before proceeding to the next pipe.

Update #2: Solved it like this; Used some examples above to make it easier to explain my problem. Here's the actual code.

```<code>DEPLOY_PATH="/data/www"
KEEP_RELEASES=3
function cleanup() {
      RELEASES=()
      OLDEST_RELEASE=

      for item in "${DEPLOY_PATH}"/releases/* ; do
        [[ -L ${item} || ! -d ${item} ]] && continue
        [[ -z ${OLDEST_RELEASE} || ${item} -ot ${OLDEST_RELEASE} ]] && OLDEST_RELEASE=${item}
        RELEASES+=("${item}")
      done

      if [ "${#RELEASES[@]}" -gt 0 ] && [ "${#RELEASES[@]}" -gt "${KEEP_RELEASES}" ]; then
        rm -rf "${DEPLOY_PATH}"/releases/$(basename "${OLDEST_RELEASE}")
        cleanup
      fi
}
</code>```

To bad that chaining with "find" and pipes likes xargs is not always the best choice. Imo it makes my script bigger when using a regular bash array.

答:
In terms of reusability, we'd better take an approach similar to this :</p>

```<code>find_release(){
    find "/path/to/releases" -maxdepth 0 -type d -print0
}

list_by_time(){
    xargs -r -0 ls -1 -t
}

tail_1(){
    tail -n 1
}

# Then you can do :
find_release | list_by_time | tail_1
</code>```

Body:
How can I split a command that uses pipes into different pieces?

I have the following working bash command:

RESULT=$(find "/path/to/releases" -maxdepth 0 -type d -print0 | xargs -r -0 ls -1 -t | tail -n 1)

I would rather have the pipes split up into multiple variables like so, so I can reuse RESULT1 or RESULT2 somewhere else:

RESULT1=$(find "/path/to/releases" -maxdepth 0 -type d -print0)

if [ -n ${RESULT1} ]; then
  RESULT2=${RESULT1} | xargs -r -0 ls -1 -t
  RESULT3=${RESULT2} | tail -n 1
]

Is this possible?

Update: The reason I also want to split things up is because I want to check first if the first part actually finds something before proceeding to the next pipe.

Update #2: Solved it like this; Used some examples above to make it easier to explain my problem. Here's the actual code.

DEPLOY_PATH="/data/www"
KEEP_RELEASES=3
function cleanup() {
      RELEASES=()
      OLDEST_RELEASE=

      for item in "${DEPLOY_PATH}"/releases/* ; do
        [[ -L ${item} || ! -d ${item} ]] && continue
        [[ -z ${OLDEST_RELEASE} || ${item} -ot ${OLDEST_RELEASE} ]] && OLDEST_RELEASE=${item}
        RELEASES+=("${item}")
      done

      if [ "${#RELEASES[@]}" -gt 0 ] && [ "${#RELEASES[@]}" -gt "${KEEP_RELEASES}" ]; then
        rm -rf "${DEPLOY_PATH}"/releases/$(basename "${OLDEST_RELEASE}")
        cleanup
      fi
}

To bad that chaining with "find" and pipes likes xargs is not always the best choice. Imo it makes my script bigger when using a regular bash array.

Body:
In terms of reusability, we'd better take an approach similar to this :

find_release(){
    find "/path/to/releases" -maxdepth 0 -type d -print0
}

list_by_time(){
    xargs -r -0 ls -1 -t
}

tail_1(){
    tail -n 1
}

# Then you can do :
find_release | list_by_time | tail_1


问:
Java - using recursion to create all substrings from a string
The following code in Java uses recursion to create all possible substrings from a string.
I am wondering is there a better way of coding this?  I want to use recursion.

```<code>public class main {

    public static void main(String[] args) {
        generate("hello");
    }

    public static void generate(String word) {
        if (word.length() == 1) {
            System.out.println(word);
            return;
        }else{
            System.out.println(word);
            generate(word.substring(0, word.length()-1));
            generate(word.substring(1, word.length()));
        }

    }

}
</code>```

FAQ
Q - Why do I want to do this using recursion?
A - Because the CEO of StackOverflow says recursion is important
http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

答:
```<code>public class SubsequencesOfStr {

 public static void main(String[] args) {

  String str = "abcd";
  System.out.println("0000----" + str.length());
  linearCombination(str);
 }

 static void linearCombination(String str) {
  for (int i = 0; i < str.length(); i++) {
   int endIndex = i + 1;
   for (int j = 0; j < str.length() - i; j++) {
    System.out.println(str.substring(j, endIndex));
    endIndex++;
   }
  }
 }
}
</code>```

Body:
The following code in Java uses recursion to create all possible substrings from a string.
I am wondering is there a better way of coding this?  I want to use recursion.

public class main {

    public static void main(String[] args) {
        generate("hello");
    }

    public static void generate(String word) {
        if (word.length() == 1) {
            System.out.println(word);
            return;
        }else{
            System.out.println(word);
            generate(word.substring(0, word.length()-1));
            generate(word.substring(1, word.length()));
        }

    }

}

FAQ
Q - Why do I want to do this using recursion?
A - Because the CEO of StackOverflow says recursion is important
http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html


问:
Close Window popup using Protractor

this.switchWindowByTitle = async function (title) {
    await browser.getAllWindowHandles().then(function (handles) {
        handles.forEach(function (handle) {
            console.log(handle.toString());
            browser.switchTo.window(handle);
            if (browser.getTitle() == title) {
                return true;
            }
        });
    });```

I'm using Protractor to work with Chrome browser and try to close window popup by compare title. I get all window handles and for each of this but my code is just only checked with the first value of list handles.

Can anyone help me to fix it?
Here is my issue detail. It just checks first value and then compares the title

Failures:
  1) Compare products Compare product should display correctly
    Message:
      Expected 'MOBILE' to equal 'COMPARE PRODUCTS'.
    Stack:
      Error: Failed expectation
          at UserContext. (E:\Protractor workspace\POM_PROTRACTOR\Testcases\TC_04_CompareProducts.spec.js:17:47)
          at C:\Users\tailet\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:112:25

答:
Use this method this will close your pop up</p>

```<code>closeBrowserPopup: () => {
  return new Promise((resolve, reject) => {
    closePopup();
    resolve("done");
  });
};
</code>```

Title: Close Window popup using Protractor

Body:
this.switchWindowByTitle = async function (title) {
    await browser.getAllWindowHandles().then(function (handles) {
        handles.forEach(function (handle) {
            console.log(handle.toString());
            browser.switchTo.window(handle);
            if (browser.getTitle() == title) {
                return true;
            }
        });
    });

I'm using Protractor to work with Chrome browser and try to close window popup by compare title. I get all window handles and for each of this but my code is just only checked with the first value of list handles.

Can anyone help me to fix it?
Here is my issue detail. It just checks first value and then compares the title

Failures:
  1) Compare products Compare product should display correctly
    Message:
      Expected 'MOBILE' to equal 'COMPARE PRODUCTS'.
    Stack:
      Error: Failed expectation
          at UserContext. (E:\Protractor workspace\POM_PROTRACTOR\Testcases\TC_04_CompareProducts.spec.js:17:47)
          at C:\Users\tailet\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:112:25

Body:
Use this method this will close your pop up

closeBrowserPopup: () => {
  return new Promise((resolve, reject) => {
    closePopup();
    resolve("done");
  });
};


问:
PHP setting to enable <?=
I just upgraded my WAMP.

A lot of my code used to use <?=$variable?> for a quick echo statement. Does anyone know the php setting to turn this back on?

答: In PHP.ini, set short_open_tag = 1</p>

Title: PHP setting to enable <?=

Body: In PHP.ini, set short_open_tag = 1


问:
iOS slow initialisation times due to cocoapods
I have a fairly simple iOS app that depends only on two pods, Firebase and Alamofire, but I get awful startup time before any code of mine could run.

I see times like

Total pre-main time: 18.5 seconds (100.0%)
 dylib loading time: 11.1 seconds (59.7%)
rebase/binding time: 366.92 milliseconds (1.9%)
    ObjC setup time: 752.48 milliseconds (4.0%)
   initializer time: 6.3 seconds (34.2%)

       slowest intializers :
         libSystem.B.dylib : 936.19 milliseconds (5.0%)
libMainThreadChecker.dylib : 1.8 seconds (9.8%)
                  CoreDuet : 514.37 milliseconds (2.7%)
              ShimmyMobile : 2.9 seconds (15.7%)
```

<p>Although the pre-main time has ranged from 2 seconds to this extreme.
I am running in the simulator so that may make things a little worse?</p>

<p>Firebase has a lot of dependencies, i.e. when running pod install I see:</p>

<pre class="lang-none prettyprint-override"><code>Installing Alamofire (4.9.1)
Installing Firebase (6.17.0)
Installing FirebaseAnalyticsInterop (1.5.0)
Installing FirebaseCore (6.6.2)
Installing FirebaseCoreDiagnostics (1.2.0)
Installing FirebaseCoreDiagnosticsInterop (1.2.0)
Installing FirebaseInstallations (1.1.0)
Installing FirebaseInstanceID (4.3.1)
Installing FirebaseMessaging (4.2.1)
Installing GoogleDataTransport (4.0.0)
Installing GoogleDataTransportCCTSupport (1.4.0)
Installing GoogleUtilities (6.5.1)
Installing PromisesObjC (1.2.8)
Installing Protobuf (3.11.4)
Installing nanopb (0.3.9011)
</code>```

I am only using FirebaseMessaging so is there something I can do to improve my startup times? Either removing unused dependencies or using a static build (I am using Swift 5)?

答:
I had the same issue, I found out that the iPhone emulator is much slower than a real phone. It was also partially my computer lagging.

Have you tried running it on a physical device?

I don't think you can delete those other dependencies because firebase relies on them in order to function properly.

Body:
I have a fairly simple iOS app that depends only on two pods, Firebase and Alamofire, but I get awful startup time before any code of mine could run.

I see times like

Total pre-main time: 18.5 seconds (100.0%)
 dylib loading time: 11.1 seconds (59.7%)
rebase/binding time: 366.92 milliseconds (1.9%)
    ObjC setup time: 752.48 milliseconds (4.0%)
   initializer time: 6.3 seconds (34.2%)

       slowest intializers :
         libSystem.B.dylib : 936.19 milliseconds (5.0%)
libMainThreadChecker.dylib : 1.8 seconds (9.8%)
                  CoreDuet : 514.37 milliseconds (2.7%)
              ShimmyMobile : 2.9 seconds (15.7%)

Although the pre-main time has ranged from 2 seconds to this extreme.
I am running in the simulator so that may make things a little worse?

Firebase has a lot of dependencies, i.e. when running pod install I see:

Installing Alamofire (4.9.1)
Installing Firebase (6.17.0)
Installing FirebaseAnalyticsInterop (1.5.0)
Installing FirebaseCore (6.6.2)
Installing FirebaseCoreDiagnostics (1.2.0)
Installing FirebaseCoreDiagnosticsInterop (1.2.0)
Installing FirebaseInstallations (1.1.0)
Installing FirebaseInstanceID (4.3.1)
Installing FirebaseMessaging (4.2.1)
Installing GoogleDataTransport (4.0.0)
Installing GoogleDataTransportCCTSupport (1.4.0)
Installing GoogleUtilities (6.5.1)
Installing PromisesObjC (1.2.8)
Installing Protobuf (3.11.4)
Installing nanopb (0.3.9011)

I am only using FirebaseMessaging so is there something I can do to improve my startup times? Either removing unused dependencies or using a static build (I am using Swift 5)?


问:
Mysql: Selecting id, then * on id is much faster than selecting *. Why?
I have a MySQL database table (roughly 100K rows):

id BIGINT(indexed), external_barcode VARCHAR(indexed), other simple columns, and a LongText column.

The LongText column is a JSON data dump. I save the large JSON objects because I will need to extract more of the data in the future.

When I run this query it takes 29+ seconds:

```<code>SELECT * FROM scraper_data WHERE external_barcode = '032429257284'
</code>```

EXPLAIN

```<code>#id  select_type table          partitions type  possible_keys key  key_len ref  rows     filtered Extra
'1' 'SIMPLE'     'scraper_data' NULL       'ALL' NULL          NULL NULL    NULL '119902' '0.00'   'Using where'
</code>```

This more complex query takes 0.00 seconds:

```<code>SELECT * FROM scraper_data WHERE id = (
    SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
)
</code>```

EXPLAIN

```<code># id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'PRIMARY', 'scraper_data', NULL, 'const', 'PRIMARY,id_UNIQUE', 'PRIMARY', '8', 'const', '1', '100.00', NULL
'2', 'SUBQUERY', 'scraper_data', NULL, 'ALL', NULL, NULL, NULL, NULL, '119902', '0.00', 'Using where'
</code>```

Less than 6 rows are returned from these queries. Why is the LONGTEXT slowing down the first query given that its not being referenced in the where clause?

CREATE TABLE

```<code>CREATE TABLE `scraper_data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `bzic` varchar(10) NOT NULL,
  `pzic` varchar(10) DEFAULT NULL,
  `internal_barcode` varchar(20) DEFAULT NULL,
  `external_barcode_type` enum('upc','isbn','ean','gtin') DEFAULT NULL,
  `external_barcode` varchar(15) DEFAULT NULL,
  `url` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `category` varchar(3) DEFAULT NULL,
  `description` text,
  `logo_image_url` varchar(255) DEFAULT NULL,
  `variant_image_urls` text,
  `parent_brand` varchar(10) DEFAULT NULL,
  `parent_brand_name` varchar(255) DEFAULT NULL,
  `manufacturer` varchar(10) DEFAULT NULL,
  `manufacturer_name` varchar(255) DEFAULT NULL,
  `manufacturer_part_number` varchar(255) DEFAULT NULL,
  `manufacturer_model_number` varchar(255) DEFAULT NULL,
  `contributors` text,
  `content_info` text,
  `content_rating` text,
  `release_date` timestamp NULL DEFAULT NULL,
  `reviews` int(11) DEFAULT NULL,
  `ratings` int(11) DEFAULT NULL,
  `internal_path` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `adult_product` tinyint(4) DEFAULT NULL,
  `height` varchar(255) DEFAULT NULL,
  `length` varchar(255) DEFAULT NULL,
  `width` varchar(255) DEFAULT NULL,
  `weight` varchar(255) DEFAULT NULL,
  `scraped` tinyint(4) NOT NULL DEFAULT '0',
  `scraped_timestamp` timestamp NULL DEFAULT NULL,
  `scrape_attempt_timestamp` timestamp NULL DEFAULT NULL,
  `processed` tinyint(4) NOT NULL DEFAULT '0',
  `processed_timestamp` timestamp NULL DEFAULT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `scrape_dump` longtext,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  UNIQUE KEY `url_UNIQUE` (`url`),
  UNIQUE KEY `internal_barcode_UNIQUE` (`internal_barcode`),
  KEY `bzic` (`bzic`),
  KEY `pzic` (`pzic`),
  KEY `internal_barcode` (`internal_barcode`),
  KEY `external_barcode` (`external_barcode`,`external_barcode_type`) /*!80000 INVISIBLE */,
  KEY `scrape_attempt` (`bzic`,`scraped`,`scrape_attempt_timestamp`)
) ENGINE=InnoDB AUTO_INCREMENT=121674 DEFAULT CHARSET=latin1;

</code>```

答:
Your queries are not equivalent, and your second query will throw an error if you have more than one row with that barcode:

Error Code: 1242. Subquery returns more than 1 row

This is probably what happens here: you do not actually get a result, just an error. Since MySQL can stop the full table scan as soon as it finds a second row, you can get this error faster than a correct result, including "0.00s" if those rows are among the first rows that are scanned (for example in ids 1 and 2).

From the execution plan, you can see that both do a full table scan (which, up to current versions, includes reading the blob field), and thus should perform similarly fast (as the first entry in your 2nd explain plan is neglectable for only a few rows).

So with a barcode that doesn't throw an error, both of your queries, as well as the corrected 2nd query (where you use IN instead of =),

```<code>SELECT * FROM scraper_data WHERE id IN (   -- IN instead of = !!
    SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
)
</code>```

as well as running your subquery

```<code>SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
</code>```

separately (which, if your assumption is correct, have to be even faster than your 2nd query) will have a similar (long) execution time.

As scaisEdge mentioned in his answer, an index on external_barcode will improve the performance significantly, as you do not not need to do a full table scan, as well as you do not need to read the blob field. You actually have such an index, but you disabled it (invisible). You can simply reenable it by using

```<code>ALTER TABLE scraper_data ALTER INDEX `external_barcode` VISIBLE;
</code>```

Body:
I have a MySQL database table (roughly 100K rows):

id BIGINT(indexed), external_barcode VARCHAR(indexed), other simple columns, and a LongText column.

The LongText column is a JSON data dump. I save the large JSON objects because I will need to extract more of the data in the future.

When I run this query it takes 29+ seconds:

SELECT * FROM scraper_data WHERE external_barcode = '032429257284'

EXPLAIN

#id  select_type table          partitions type  possible_keys key  key_len ref  rows     filtered Extra
'1' 'SIMPLE'     'scraper_data' NULL       'ALL' NULL          NULL NULL    NULL '119902' '0.00'   'Using where'

This more complex query takes 0.00 seconds:

SELECT * FROM scraper_data WHERE id = (
    SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
)

EXPLAIN

# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'PRIMARY', 'scraper_data', NULL, 'const', 'PRIMARY,id_UNIQUE', 'PRIMARY', '8', 'const', '1', '100.00', NULL
'2', 'SUBQUERY', 'scraper_data', NULL, 'ALL', NULL, NULL, NULL, NULL, '119902', '0.00', 'Using where'

Less than 6 rows are returned from these queries. Why is the LONGTEXT slowing down the first query given that its not being referenced in the where clause?

CREATE TABLE

CREATE TABLE `scraper_data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `bzic` varchar(10) NOT NULL,
  `pzic` varchar(10) DEFAULT NULL,
  `internal_barcode` varchar(20) DEFAULT NULL,
  `external_barcode_type` enum('upc','isbn','ean','gtin') DEFAULT NULL,
  `external_barcode` varchar(15) DEFAULT NULL,
  `url` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `category` varchar(3) DEFAULT NULL,
  `description` text,
  `logo_image_url` varchar(255) DEFAULT NULL,
  `variant_image_urls` text,
  `parent_brand` varchar(10) DEFAULT NULL,
  `parent_brand_name` varchar(255) DEFAULT NULL,
  `manufacturer` varchar(10) DEFAULT NULL,
  `manufacturer_name` varchar(255) DEFAULT NULL,
  `manufacturer_part_number` varchar(255) DEFAULT NULL,
  `manufacturer_model_number` varchar(255) DEFAULT NULL,
  `contributors` text,
  `content_info` text,
  `content_rating` text,
  `release_date` timestamp NULL DEFAULT NULL,
  `reviews` int(11) DEFAULT NULL,
  `ratings` int(11) DEFAULT NULL,
  `internal_path` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `adult_product` tinyint(4) DEFAULT NULL,
  `height` varchar(255) DEFAULT NULL,
  `length` varchar(255) DEFAULT NULL,
  `width` varchar(255) DEFAULT NULL,
  `weight` varchar(255) DEFAULT NULL,
  `scraped` tinyint(4) NOT NULL DEFAULT '0',
  `scraped_timestamp` timestamp NULL DEFAULT NULL,
  `scrape_attempt_timestamp` timestamp NULL DEFAULT NULL,
  `processed` tinyint(4) NOT NULL DEFAULT '0',
  `processed_timestamp` timestamp NULL DEFAULT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `scrape_dump` longtext,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  UNIQUE KEY `url_UNIQUE` (`url`),
  UNIQUE KEY `internal_barcode_UNIQUE` (`internal_barcode`),
  KEY `bzic` (`bzic`),
  KEY `pzic` (`pzic`),
  KEY `internal_barcode` (`internal_barcode`),
  KEY `external_barcode` (`external_barcode`,`external_barcode_type`) /*!80000 INVISIBLE */,
  KEY `scrape_attempt` (`bzic`,`scraped`,`scrape_attempt_timestamp`)
) ENGINE=InnoDB AUTO_INCREMENT=121674 DEFAULT CHARSET=latin1;

Body:
Your queries are not equivalent, and your second query will throw an error if you have more than one row with that barcode:

Error Code: 1242. Subquery returns more than 1 row

This is probably what happens here: you do not actually get a result, just an error. Since MySQL can stop the full table scan as soon as it finds a second row, you can get this error faster than a correct result, including "0.00s" if those rows are among the first rows that are scanned (for example in ids 1 and 2).

From the execution plan, you can see that both do a full table scan (which, up to current versions, includes reading the blob field), and thus should perform similarly fast (as the first entry in your 2nd explain plan is neglectable for only a few rows).

So with a barcode that doesn't throw an error, both of your queries, as well as the corrected 2nd query (where you use IN instead of =),

SELECT * FROM scraper_data WHERE id IN (   -- IN instead of = !!
    SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
)

as well as running your subquery

SELECT id FROM scraper_data WHERE external_barcode = '032429257284'

separately (which, if your assumption is correct, have to be even faster than your 2nd query) will have a similar (long) execution time.

As scaisEdge mentioned in his answer, an index on external_barcode will improve the performance significantly, as you do not not need to do a full table scan, as well as you do not need to read the blob field. You actually have such an index, but you disabled it (invisible). You can simply reenable it by using

ALTER TABLE scraper_data ALTER INDEX `external_barcode` VISIBLE;


问:
Rewriting subdirectory to query string parameter
I have two requirements;

That, for example, /product/12345 is internally redirected to /product/product.php?product=12345.

That if the user tries to access /product/product.php in the URL bar, it is redirected to /product/ for tidiness.

Separate, they both work correctly, but together it results in an infinite loop - I know that I'm redirecting from /product/ to /product.php and back again, but the difference is internal vs external and I'm not sure how to distinguish between them.

```<code>RewriteEngine On

RewriteRule ^product/product.php /product/ [NC,R=307,END]

RewriteCond %{REQUEST_URI} !^/product/product.php [NC]
RewriteRule ^product/(.*) /product/product.php?product=$1 [NC]
</code>```

答:
There probably exist other solutions, but it works if you change two things:

Add a condition to the first RewriteRule that checks if the query string is empty, i.e. product/product.php without query string redirects to /product/.

Change (.*) in the second RewriteRule to (.+) or ([0-9]+) to only rewrite requests containing a product id (requests to /product/ are not rewritten).

```<code>RewriteEngine On

RewriteCond %{QUERY_STRING}        ="" [NC]
RewriteRule ^product/product\.php$ /product/ [NC,R=307,END]

RewriteCond %{REQUEST_URI}  !^/product/product\.php [NC]
RewriteRule ^product/(.+)   /product/product.php?product=$1 [NC]
</code>```

Body:
I have two requirements;

That, for example, /product/12345 is internally redirected to /product/product.php?product=12345.

That if the user tries to access /product/product.php in the URL bar, it is redirected to /product/ for tidiness.

Separate, they both work correctly, but together it results in an infinite loop - I know that I'm redirecting from /product/ to /product.php and back again, but the difference is internal vs external and I'm not sure how to distinguish between them.

RewriteEngine On

RewriteRule ^product/product.php /product/ [NC,R=307,END]

RewriteCond %{REQUEST_URI} !^/product/product.php [NC]
RewriteRule ^product/(.*) /product/product.php?product=$1 [NC]

Body:
There probably exist other solutions, but it works if you change two things:

Add a condition to the first RewriteRule that checks if the query string is empty, i.e. product/product.php without query string redirects to /product/.

Change (.*) in the second RewriteRule to (.+) or ([0-9]+) to only rewrite requests containing a product id (requests to /product/ are not rewritten).

RewriteEngine On

RewriteCond %{QUERY_STRING}        ="" [NC]
RewriteRule ^product/product\.php$ /product/ [NC,R=307,END]

RewriteCond %{REQUEST_URI}  !^/product/product\.php [NC]
RewriteRule ^product/(.+)   /product/product.php?product=$1 [NC]


问:
Convert Java String to PostreSQL character varying («mpaa_rating»)?
I'm writing a Java method that searches the Postres sample 'DVD Rental' database table for «films» based on their «mpaa_rating» datatype in the «rating» column.

```<code>public static void rechercheRating() {

        System.out.println("======= Ratings menu =========");
        System.out.println("\t 'G' ");
        System.out.println("\t 'PG' ");
        System.out.println("\t 'PG-13' ");
        System.out.println("\t 'R' ");
        System.out.println("\t 'NC-17' ");
        System.out.println("Entrez le rating désiré :");
        String userInput = sc.nextLine().toUpperCase();
        try {
            int foovalue = 10;

            PreparedStatement st = conn.prepareStatement("SELECT title, rating FROM film WHERE (rating = ?);");

            st.setString(1, userInput);

            ResultSet rs = st.executeQuery();
            System.out.printf("%-20s %-15s\n", "Film", "Rating");

            while (rs.next()) {

                System.out.printf("%-20s %-15s\n", rs.getString(1), rs.getString(2));

            }
            rs.close();
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(DVDrental.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//rechercheRating
</code>```

The problem is the «mpaa_rating» is not a String datatype. The error I'm getting in my IDE is

"org.postgresql.util.PSQLException: ERROR: operator does not exist:
  mpaa_rating = character varying"

and

"Hint: No operator matches the given name and argument type(s). You
  might need to add explicit type casts."

How to convert a Java String to an Postres character varying?

答:
The explicit cast of the datatype «mpaa_rating» I added to my SQL prepared statement:

```<code> public static void rechercheRating() {

        System.out.println("======= Ratings menu =========");
        System.out.println("\t 'G' ");
        System.out.println("\t 'PG' ");
        System.out.println("\t 'PG-13' ");
        System.out.println("\t 'R' ");
        System.out.println("\t 'NC-17' ");
        System.out.println("Entrez le rating désiré :");
        String userInput = sc.nextLine().toUpperCase();

        try {
            int foovalue = 10;

            PreparedStatement st = conn.prepareStatement("SELECT title,
            rating FROM film WHERE (rating = ?::mpaa_rating);"); //added cast

            st.setString(1, userInput);

            ResultSet rs = st.executeQuery();
            System.out.printf("%-20s %-15s\n", "Film", "Rating");

            while (rs.next()) {

                System.out.printf("%-20s %-15s\n", rs.getString(1), rs.getString(2));

            }
            rs.close();
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(DVDrental.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//rechercheRating
</code>```

This converts composite types to string types.
The documentation on casts.

Body:
I'm writing a Java method that searches the Postres sample 'DVD Rental' database table for «films» based on their «mpaa_rating» datatype in the «rating» column.

public static void rechercheRating() {

        System.out.println("======= Ratings menu =========");
        System.out.println("\t 'G' ");
        System.out.println("\t 'PG' ");
        System.out.println("\t 'PG-13' ");
        System.out.println("\t 'R' ");
        System.out.println("\t 'NC-17' ");
        System.out.println("Entrez le rating désiré :");
        String userInput = sc.nextLine().toUpperCase();
        try {
            int foovalue = 10;

            PreparedStatement st = conn.prepareStatement("SELECT title, rating FROM film WHERE (rating = ?);");

            st.setString(1, userInput);

            ResultSet rs = st.executeQuery();
            System.out.printf("%-20s %-15s\n", "Film", "Rating");

            while (rs.next()) {

                System.out.printf("%-20s %-15s\n", rs.getString(1), rs.getString(2));

            }
            rs.close();
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(DVDrental.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//rechercheRating

The problem is the «mpaa_rating» is not a String datatype. The error I'm getting in my IDE is

"org.postgresql.util.PSQLException: ERROR: operator does not exist:
  mpaa_rating = character varying"

and

"Hint: No operator matches the given name and argument type(s). You
  might need to add explicit type casts."

How to convert a Java String to an Postres character varying?

Body:
The explicit cast of the datatype «mpaa_rating» I added to my SQL prepared statement:

 public static void rechercheRating() {

        System.out.println("======= Ratings menu =========");
        System.out.println("\t 'G' ");
        System.out.println("\t 'PG' ");
        System.out.println("\t 'PG-13' ");
        System.out.println("\t 'R' ");
        System.out.println("\t 'NC-17' ");
        System.out.println("Entrez le rating désiré :");
        String userInput = sc.nextLine().toUpperCase();

        try {
            int foovalue = 10;

            PreparedStatement st = conn.prepareStatement("SELECT title,
            rating FROM film WHERE (rating = ?::mpaa_rating);"); //added cast

            st.setString(1, userInput);

            ResultSet rs = st.executeQuery();
            System.out.printf("%-20s %-15s\n", "Film", "Rating");

            while (rs.next()) {

                System.out.printf("%-20s %-15s\n", rs.getString(1), rs.getString(2));

            }
            rs.close();
            st.close();
        } catch (SQLException ex) {
            Logger.getLogger(DVDrental.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//rechercheRating

This converts composite types to string types.
The documentation on casts.


问:
JavaScript/jQuery equation solver
Is there a plugin that can solve a simple system of equations?

I basically need the ability to solve a 3X3 matrix.

答: Sylvester is a JavaScript library designed to let you do mathematics with vectors and matrices.</p>

Title: JavaScript/jQuery equation solver


问:
PowerShell gaps in output
When I run two commands one after the other in a script, I often end up with big gaps, as you can see with these two commands (I've concatenated them with ";" so can see the issue as a one-liner, it's just a Get-Netipaddress followed by a gwmi) they end up with a three line gaps between them. Sometimes I want more compact information in my output. Is there a way to tell PowerShell to stop introducing huge gaps between output?

```<code>Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex ; gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}}
</code>```

答:
There's always also the option of writing a format function yourself.
Something like the below perhaps:

```<code>function Format-TableCompact {
    [CmdletBinding()]
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [PsObject]$InputObject,

        [switch]$AppendNewline
    )
    # If the data is sent through the pipeline, use $input to collect is as array
    if ($PSCmdlet.MyInvocation.ExpectingInput) { $InputObject = @($Input) }
    # or use : $InputObject = $Input | ForEach-Object { $_ }

    $result = ($InputObject | Format-Table -AutoSize | Out-String).Trim()
    if($AppendNewline) { $result += [Environment]::NewLine }
    $result
}
</code>```

This will output the object as table without any leading or trailing newlines, so called using

```<code>Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex | Format-TableCompact
gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}} | Format-TableCompact
</code>```

it will slam both tables directly against eachother.

In this case however I would opt for having at least one newline gap between the tables so I would use the -AppendNewline switch on the first table to output:

```<code>Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex | Format-TableCompact -AppendNewline
gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}} | Format-TableCompact
</code>```

Title: PowerShell gaps in output

Body:
When I run two commands one after the other in a script, I often end up with big gaps, as you can see with these two commands (I've concatenated them with ";" so can see the issue as a one-liner, it's just a Get-Netipaddress followed by a gwmi) they end up with a three line gaps between them. Sometimes I want more compact information in my output. Is there a way to tell PowerShell to stop introducing huge gaps between output?

Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex ; gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}}

Body:
There's always also the option of writing a format function yourself.
Something like the below perhaps:

function Format-TableCompact {
    [CmdletBinding()]
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [PsObject]$InputObject,

        [switch]$AppendNewline
    )
    # If the data is sent through the pipeline, use $input to collect is as array
    if ($PSCmdlet.MyInvocation.ExpectingInput) { $InputObject = @($Input) }
    # or use : $InputObject = $Input | ForEach-Object { $_ }

    $result = ($InputObject | Format-Table -AutoSize | Out-String).Trim()
    if($AppendNewline) { $result += [Environment]::NewLine }
    $result
}

This will output the object as table without any leading or trailing newlines, so called using

Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex | Format-TableCompact
gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}} | Format-TableCompact

it will slam both tables directly against eachother.

In this case however I would opt for having at least one newline gap between the tables so I would use the -AppendNewline switch on the first table to output:

Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex | Format-TableCompact -AppendNewline
gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}} | Format-TableCompact


问:
How to add embedded resource JSON file to ConfigurationBuilder without creating a temporary file?
I have  appsettings.json  with build action set to Embedded Resource. I usually extract the file and make a new copy of it as follows.

```<code>string jsonFullPath = Path.Combine(FileSystem.AppDataDirectory, "namespace.directory.appsettings.json");
Assembly assembly = Assembly.GetExecutingAssembly();

using (Stream resourceFileStream = assembly.GetManifestResourceStream(resourceFilename))
{
    if (resourceFileStream != null)
    {
        using (FileStream fileStream = File.Create(jsonFullPath))
        {
            resourceFileStream.CopyTo(fileStream);
        }
    }
}
</code>```

And add the copy to an instance of ConfigurationBuilder as follows.

```<code>Configuration = new ConfigurationBuilder()
    .AddJsonFile(jsonFullPath, optional: true, reloadOnChange: true)
    .Build();
</code>```

Question

Is it possible to make ConfigurationBuilder use the embedded JSON file directly without creating a new temporary file as I did above? If yes, how to do so?

答:
I would suggest that use AddJsonStream instead of AddJsonfile.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.jsonconfigurationextensions.addjsonstream?view=dotnet-plat-ext-3.1#Microsoft_Extensions_Configuration_JsonConfigurationExtensions_AddJsonStream_Microsoft_Extensions_Configuration_IConfigurationBuilder_System_IO_Stream_

Body:
I have  appsettings.json  with build action set to Embedded Resource. I usually extract the file and make a new copy of it as follows.

string jsonFullPath = Path.Combine(FileSystem.AppDataDirectory, "namespace.directory.appsettings.json");
Assembly assembly = Assembly.GetExecutingAssembly();

using (Stream resourceFileStream = assembly.GetManifestResourceStream(resourceFilename))
{
    if (resourceFileStream != null)
    {
        using (FileStream fileStream = File.Create(jsonFullPath))
        {
            resourceFileStream.CopyTo(fileStream);
        }
    }
}

And add the copy to an instance of ConfigurationBuilder as follows.

Configuration = new ConfigurationBuilder()
    .AddJsonFile(jsonFullPath, optional: true, reloadOnChange: true)
    .Build();

Question

Is it possible to make ConfigurationBuilder use the embedded JSON file directly without creating a new temporary file as I did above? If yes, how to do so?