问:
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.

答:
You're not stuck in a loop, you stuck in recursion

```<code>def change_password():
    my_password = input("Enter your CURRENT password > ")
    change_password()
</code>```

notice that you just keep calling change password over and over... also you have double methods for some reason, use the ones in you User class.

when 'c' is chosen you have no context, you don't know WHO is trying to change their password, so first you must ask who the user is, try the following changes:
before your while true loop put current_user = None
change the entry for 'f' to be current_user = find_user()
and the entry for 'c' to be

```<code>if current_user is None:
    print("No user selected!")
    continue
else:
    current_user.change_password()
</code>```

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.

Body:
You're not stuck in a loop, you stuck in recursion

def change_password():
    my_password = input("Enter your CURRENT password > ")
    change_password()

notice that you just keep calling change password over and over... also you have double methods for some reason, use the ones in you User class.

when 'c' is chosen you have no context, you don't know WHO is trying to change their password, so first you must ask who the user is, try the following changes:
before your while true loop put current_user = None
change the entry for 'f' to be current_user = find_user()
and the entry for 'c' to be

if current_user is None:
    print("No user selected!")
    continue
else:
    current_user.change_password()


来源: stackexchange

问:
Desired Compute-To-Memory-Ratio (OP/B) on GPU
I am trying to undertand the architecture of the GPUs and how we assess the performance of our programs on the GPU. I know that the application can be:

Compute-bound: performance limited by the FLOPS rate. The processor’s cores are fully utilized (always have work to do)

Memory-bound: performance limited by the memory
bandwidth. The processor’s cores are frequently idle because memory cannot supply data fast enough

The image below shows the FLOPS rate, peak memory bandwidth, and the Desired Compute to memory ratio, labeled by (OP/B), for each microarchitecture.

I also have an example of how to compute this OP/B metric. Example: Below is part of a CUDA code for applying matrix-matrix multiplication

```<code>for(unsigned int i = 0; i < N; ++i) {
  sum += A[row*N + i]*B[i*N + col];
}
</code>```

and the way to calculate OP/B for this matrix-matrix multiplication is as follows:

Matrix multiplication performs 0.25 OP/B

1 FP add and 1 FP mul for every 2 FP values (8B) loaded

Ignoring stores

and if we want to utilize this:

But matrix multiplication has high potential for reuse. For NxN matrices:

Data loaded: (2 input matrices)×(N^2 values)×(4 B) = 8N^2 B

Operations: (N^2 dot products)(N adds + N muls each) = 2N^3 OP

Potential compute-to-memory ratio: 0.25N OP/B

So if I understand this clearly well, I have the following questions:

It is always the case that the greater OP/B, the better ?

how do we know how much FP operations we have ? Is it the adds and the multiplications

how do we know how many bytes are loaded per FP operation ?

答:
It is always the case that the greater OP/B, the better ?

Not always.  The target value balances the load on compute pipe throughput and memory pipe throughput (i.e. that level of op/byte means that both pipes will be fully loaded).  As you increase op/byte beyond that or some level, your code will switch from balanced to compute-bound.  Once your code is compute bound, the performance will be dictated by the compute pipe that is the limiting factor.  Additional op/byte increase beyond this point may have no effect on code performance.

how do we know how much FP operations we have ? Is it the adds and the multiplications

Yes, for the simple code you have shown, it is the adds and multiplies.  Other more complicated codes may have other factors (e.g. sin, cos, etc.) which may also contribute.

As an alternative to "manually counting" the FP operations, the GPU profilers can indicate the number of FP ops that a code has executed.

how do we know how many bytes are loaded per FP operation ?

Similar to the previous question, for simple codes you can "manually count".  For complex codes you may wish to try to use profiler capabilities to estimate.  For the code you have shown:

```<code>sum += A[row*N + i]*B[i*N + col];
</code>```

The values from A and B have to be loaded.  If they are float quantities then they are 4 bytes each.  That is a total of 8 bytes.  That line of code will require 1 floating point multiplication (A * B) and one floating point add operation (sum +=).  The compiler will fuse these into a single instruction (fused multiply-add) but the net effect is you are performing two floating point operations per 8 bytes.  op/byte is 2/8 = 1/4.  The loop does not change the ratio in this case.  To increase this number, you would want to explore various optimization methods, such as a tiled shared-memory matrix multiply, or just use CUBLAS.

(Operations like row*N + i are integer arithmetic and don't contribute to the floating-point load, although its possible they may be significant, performance-wise.)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to undertand the architecture of the GPUs and how we assess the performance of our programs on the GPU. I know that the application can be:

Compute-bound: performance limited by the FLOPS rate. The processor’s cores are fully utilized (always have work to do)

Memory-bound: performance limited by the memory
bandwidth. The processor’s cores are frequently idle because memory cannot supply data fast enough

The image below shows the FLOPS rate, peak memory bandwidth, and the Desired Compute to memory ratio, labeled by (OP/B), for each microarchitecture.

I also have an example of how to compute this OP/B metric. Example: Below is part of a CUDA code for applying matrix-matrix multiplication

for(unsigned int i = 0; i < N; ++i) {
  sum += A[row*N + i]*B[i*N + col];
}

and the way to calculate OP/B for this matrix-matrix multiplication is as follows:

Matrix multiplication performs 0.25 OP/B

1 FP add and 1 FP mul for every 2 FP values (8B) loaded

Ignoring stores

and if we want to utilize this:

But matrix multiplication has high potential for reuse. For NxN matrices:

Data loaded: (2 input matrices)×(N^2 values)×(4 B) = 8N^2 B

Operations: (N^2 dot products)(N adds + N muls each) = 2N^3 OP

Potential compute-to-memory ratio: 0.25N OP/B

So if I understand this clearly well, I have the following questions:

It is always the case that the greater OP/B, the better ?

how do we know how much FP operations we have ? Is it the adds and the multiplications

how do we know how many bytes are loaded per FP operation ?

Body:
It is always the case that the greater OP/B, the better ?

Not always.  The target value balances the load on compute pipe throughput and memory pipe throughput (i.e. that level of op/byte means that both pipes will be fully loaded).  As you increase op/byte beyond that or some level, your code will switch from balanced to compute-bound.  Once your code is compute bound, the performance will be dictated by the compute pipe that is the limiting factor.  Additional op/byte increase beyond this point may have no effect on code performance.

how do we know how much FP operations we have ? Is it the adds and the multiplications

Yes, for the simple code you have shown, it is the adds and multiplies.  Other more complicated codes may have other factors (e.g. sin, cos, etc.) which may also contribute.

As an alternative to "manually counting" the FP operations, the GPU profilers can indicate the number of FP ops that a code has executed.

how do we know how many bytes are loaded per FP operation ?

Similar to the previous question, for simple codes you can "manually count".  For complex codes you may wish to try to use profiler capabilities to estimate.  For the code you have shown:

sum += A[row*N + i]*B[i*N + col];

The values from A and B have to be loaded.  If they are float quantities then they are 4 bytes each.  That is a total of 8 bytes.  That line of code will require 1 floating point multiplication (A * B) and one floating point add operation (sum +=).  The compiler will fuse these into a single instruction (fused multiply-add) but the net effect is you are performing two floating point operations per 8 bytes.  op/byte is 2/8 = 1/4.  The loop does not change the ratio in this case.  To increase this number, you would want to explore various optimization methods, such as a tiled shared-memory matrix multiply, or just use CUBLAS.

(Operations like row*N + i are integer arithmetic and don't contribute to the floating-point load, although its possible they may be significant, performance-wise.)


问:
Get today's date print to the console in Protractor
I'm new to Protractor. I need to  select today's date from the date picker.

Is there a specific anyway to select the today's date from the date picker?

Thanks. :)

答:
This method will give you current date time with seconds:</p>

```<code>getCurrentDatemmddyyyy: function () {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1; //January is 0!
  var yyyy = today.getFullYear();
  var hh = today.getHours();
  var mins = today.getMinutes();
  var ss = today.getSeconds();
  if (dd < 10) {
    dd = "0" + dd;
  }
  if (mm < 10) {
    mm = "0" + mm;
  }
  if (hh < 10) {
    hh = "0" + hh;
  }
  if (mins < 10) {
    mins = "0" + mins;
  }

  if (ss < 10) {
    ss = "0" + ss;
  }

  var today = mm + dd + yyyy + hh + mins + ss;
  return today;

},
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This method will give you current date time with seconds:

getCurrentDatemmddyyyy: function () {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1; //January is 0!
  var yyyy = today.getFullYear();
  var hh = today.getHours();
  var mins = today.getMinutes();
  var ss = today.getSeconds();
  if (dd < 10) {
    dd = "0" + dd;
  }
  if (mm < 10) {
    mm = "0" + mm;
  }
  if (hh < 10) {
    hh = "0" + hh;
  }
  if (mins < 10) {
    mins = "0" + mins;
  }

  if (ss < 10) {
    ss = "0" + ss;
  }

  var today = mm + dd + yyyy + hh + mins + ss;
  return today;

},


问:
Strange behavior of Get-NetFirewallRule
I came across the fact that Get-NetFirewallRule cmdlet displays the parameters differently. For demonstration, I added "123.exe" to the firewall (Block Action). The cmdlet gives such a mapping of parameter values (for compactness of space, I have reduced some parameters):

```<code>$Rules = [HashTable]::Synchronized(@{})
$Rules.Get = (Get-NetFirewallRule).Where({ $_.Action -in 'Block', 4 })
$Rules.Get

------------
DisplayName           : 123
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Domain, Private, Public
Platform              : {}
Direction             : Outbound
Action                : Block
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False
</code>```

Then, for the experiment, I placed the cmdlet in a different space and got a completely different display of parameters, which now has no Profile (I see the Profiles instead and the number 7 as the value):

```<code>$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule).Where({ $_.Action -in 'Block', 4 })
})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get

------------
Action                  : 4
Direction               : 2
DisplayGroup            :
DisplayName             : 123
EdgeTraversalPolicy     : 0
EnforcementStatus       : {0}
LocalOnlyMapping        : False
LooseSourceMapping      : False
Platforms               : {}
PolicyStoreSource       : PersistentStore
PolicyStoreSourceType   : 1
PrimaryStatus           : 1
Profiles                : 7
</code>```

Well, I added -All. I got again a convenient display of information:

```<code>$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule -All).Where({ $_.Action -in 'Block', 4 })
})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get

------------
DisplayName           : 123
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Domain, Private, Public
Platform              : {}
Direction             : Outbound
Action                : Block
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False
</code>```

I closed PowerShell ISE and reopened. I entered the same script and got what I expected. I got the numbers again as values:

```<code>$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule -All).Where({ $_.Action -in 'Block', 4 })
})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get

------------
Action                  : 4
Direction               : 2
DisplayGroup            :
DisplayName             : 123
EdgeTraversalPolicy     : 0
EnforcementStatus       : {0}
LocalOnlyMapping        : False
LooseSourceMapping      : False
Platforms               : {}
PolicyStoreSource       : PersistentStore
PolicyStoreSourceType   : 1
PrimaryStatus           : 1
Profiles                : 7
</code>```

Question: how to always get such a display of parameters?

```<code>------------
DisplayName           : 123
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Domain, Private, Public
Platform              : {}
Direction             : Outbound
Action                : Block
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False
</code>```

Thanks

答:
if you modify your call to Get-NetFirewallRule to include Select the properties you are looking for, it will get you the data you need.

```<code>Get-NetFirewallRule -All | select DisplayName, DisplayGroup, Group, Enabled, Profile, platform, direction, action, edgetraversalpolicy, looseSourceMapping, localonlymapping
</code>```

You can pipe it to format-table if you are looking to generate a table like view, or Out-GridView for form like display.

```<code>$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule -All | select DisplayName, DisplayGroup, Group, Enabled, Profile, platform, direction, action, edgetraversalpolicy, looseSourceMapping, localonlymapping) | ? { $_.Action -in 'Block', 4 }

})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get
</code>```

Title: Strange behavior of Get-NetFirewallRule

Body:
I came across the fact that Get-NetFirewallRule cmdlet displays the parameters differently. For demonstration, I added "123.exe" to the firewall (Block Action). The cmdlet gives such a mapping of parameter values (for compactness of space, I have reduced some parameters):

$Rules = [HashTable]::Synchronized(@{})
$Rules.Get = (Get-NetFirewallRule).Where({ $_.Action -in 'Block', 4 })
$Rules.Get

------------
DisplayName           : 123
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Domain, Private, Public
Platform              : {}
Direction             : Outbound
Action                : Block
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False

Then, for the experiment, I placed the cmdlet in a different space and got a completely different display of parameters, which now has no Profile (I see the Profiles instead and the number 7 as the value):

$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule).Where({ $_.Action -in 'Block', 4 })
})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get

------------
Action                  : 4
Direction               : 2
DisplayGroup            :
DisplayName             : 123
EdgeTraversalPolicy     : 0
EnforcementStatus       : {0}
LocalOnlyMapping        : False
LooseSourceMapping      : False
Platforms               : {}
PolicyStoreSource       : PersistentStore
PolicyStoreSourceType   : 1
PrimaryStatus           : 1
Profiles                : 7

Well, I added -All. I got again a convenient display of information:

$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule -All).Where({ $_.Action -in 'Block', 4 })
})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get

------------
DisplayName           : 123
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Domain, Private, Public
Platform              : {}
Direction             : Outbound
Action                : Block
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False

I closed PowerShell ISE and reopened. I entered the same script and got what I expected. I got the numbers again as values:

$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule -All).Where({ $_.Action -in 'Block', 4 })
})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get

------------
Action                  : 4
Direction               : 2
DisplayGroup            :
DisplayName             : 123
EdgeTraversalPolicy     : 0
EnforcementStatus       : {0}
LocalOnlyMapping        : False
LooseSourceMapping      : False
Platforms               : {}
PolicyStoreSource       : PersistentStore
PolicyStoreSourceType   : 1
PrimaryStatus           : 1
Profiles                : 7

Question: how to always get such a display of parameters?

------------
DisplayName           : 123
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Domain, Private, Public
Platform              : {}
Direction             : Outbound
Action                : Block
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False

Thanks

Body:
if you modify your call to Get-NetFirewallRule to include Select the properties you are looking for, it will get you the data you need.

Get-NetFirewallRule -All | select DisplayName, DisplayGroup, Group, Enabled, Profile, platform, direction, action, edgetraversalpolicy, looseSourceMapping, localonlymapping

You can pipe it to format-table if you are looking to generate a table like view, or Out-GridView for form like display.

$Rules = [HashTable]::Synchronized(@{})
$RS = [Runspacefactory]::CreateRunspace(); $RS.Open()
$RS.SessionStateProxy.SetVariable('Rules', $Rules)
$PS = [PowerShell]::Create().AddScript({

    $Rules.Get = (Get-NetFirewallRule -All | select DisplayName, DisplayGroup, Group, Enabled, Profile, platform, direction, action, edgetraversalpolicy, looseSourceMapping, localonlymapping) | ? { $_.Action -in 'Block', 4 }

})
$PS.Runspace = $RS
$Null = $PS.Invoke()
$Rules.Get


问:
Set sender name in JavaMailSender
I'm using JavaMailSender to send an email to my client by my gmail account.
In my gmail account settings, I can set value to "Send mail as" in order to display my customize name in my client email.
For example, if I send email in gmail, my client email will show this:

From: This is my customize name (not my email address)

To: client-email@mail.com

Subject ...

Body ...

How can I set up the configuration of JavaMailSender in Spring ?

This is my configuration file:

```<code><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="myemailaddress@gmail.com" />
    <property name="password" value="mypassword@gmail.com" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
           </props>
    </property>
 </bean>
</code>```

Thank in advance

答: To show email with a customized name showing in the inbox. I use MimeMessageHelper class from method. The one requiring two String parameters. It takes the email address and the customized name in this order</p>

Title: Set sender name in JavaMailSender

Body:
I'm using JavaMailSender to send an email to my client by my gmail account.
In my gmail account settings, I can set value to "Send mail as" in order to display my customize name in my client email.
For example, if I send email in gmail, my client email will show this:

From: This is my customize name (not my email address)

To: client-email@mail.com

Subject ...

Body ...

How can I set up the configuration of JavaMailSender in Spring ?

This is my configuration file:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="myemailaddress@gmail.com" />
    <property name="password" value="mypassword@gmail.com" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
           </props>
    </property>
 </bean>

Thank in advance


问:
How to extract elements from JSON File with python?
I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

```<code>import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])
</code>```

Error:

```<code>File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax
</code>```

this is my file.

```<code>[
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }
    ]
</code>```

答:
You need to iterate over the list in the JSON file</p>

```<code>data = json.load(json_file)
for item in data:
    if item['name'] == 'jim':
        print(item['dob_year'])
</code>```

Body:
I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])

Error:

File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax

this is my file.

[
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }
    ]

Body:
You need to iterate over the list in the JSON file

data = json.load(json_file)
for item in data:
    if item['name'] == 'jim':
        print(item['dob_year'])


答:
data is a list of dictionaries! you cannot directly access the key value pairs.
Try encapsulating it in a loop to check every dict in the list:

import json

with open('j.json') as json_file:
    data = json.load(json_file)
    for set in data:
        if set['name'] == 'jim':
            print(set['dob_year'])
```

Title: How to extract elements from JSON File with python?


问:
How to write SQL query to find the total bonus amount they should receive given that the bonus gets calculated only for referrals_valid=1
```<code>SELECT P.profile_id
       , (P.first_name+' '+P.last_name) AS [Full Name]
       , P.email
       , P.phone
       , P.referral_code
       , R.[Total referrals]
       , R.[Total Bonus Amount]
FROM Profiles P
JOIN (SELECT referrer_id
             , SUM(referrer_bonus_amount) AS [Total Bonus Amount]
             , COUNT(referrer_id) AS [Total referrals]
      FROM Referrals
      GROUP BY referrer_id) R
ON P.profile_id=R.referrer_id
WHERE R.[Total referrals] > 1
</code>```

Above is the code for which I am getting the results as below
Query results image but now I need to calculate the Total Bonus Amount only for valid_referrals column equal to 1
(Note: valid_referrals column comes from Referrals table.)

Can someone help me out with the code....??

答:
it seems that by adding the where clause in your subquery, it should do the job.</p>

```<code>SELECT P.profile_id,
  (P.first_name+' '+P.last_name) AS [Full Name],
  P.email,
  P.phone,
  P.referral_code,
  R.[Total referrals],
  R.[Total Bonus Amount]
FROM Profiles P
JOIN (
  SELECT
   referrer_id,SUM(referrer_bonus_amount) AS [Total Bonus Amount],
   COUNT(referrer_id) AS [Total referrals]
  FROM Referrals
  WHERE Referrals.referral_valid = 1
  GROUP BY referrer_id
) R
ON P.profile_id=R.referrer_id
WHERE R.[Total referrals]>1

</code>```

Body:
SELECT P.profile_id
       , (P.first_name+' '+P.last_name) AS [Full Name]
       , P.email
       , P.phone
       , P.referral_code
       , R.[Total referrals]
       , R.[Total Bonus Amount]
FROM Profiles P
JOIN (SELECT referrer_id
             , SUM(referrer_bonus_amount) AS [Total Bonus Amount]
             , COUNT(referrer_id) AS [Total referrals]
      FROM Referrals
      GROUP BY referrer_id) R
ON P.profile_id=R.referrer_id
WHERE R.[Total referrals] > 1

Above is the code for which I am getting the results as below
Query results image but now I need to calculate the Total Bonus Amount only for valid_referrals column equal to 1
(Note: valid_referrals column comes from Referrals table.)

Can someone help me out with the code....??

Body:
it seems that by adding the where clause in your subquery, it should do the job.

SELECT P.profile_id,
  (P.first_name+' '+P.last_name) AS [Full Name],
  P.email,
  P.phone,
  P.referral_code,
  R.[Total referrals],
  R.[Total Bonus Amount]
FROM Profiles P
JOIN (
  SELECT
   referrer_id,SUM(referrer_bonus_amount) AS [Total Bonus Amount],
   COUNT(referrer_id) AS [Total referrals]
  FROM Referrals
  WHERE Referrals.referral_valid = 1
  GROUP BY referrer_id
) R
ON P.profile_id=R.referrer_id
WHERE R.[Total referrals]>1


问:
Asp.net MVC 5 dynamically created button and calls to a javascript function with argument
From my razor view i have a loop for creating some datas inside a table.

```<code>@foreach (var item in Model.ItemModel) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ItemCode)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ItemName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Brand)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PurchaseQty)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SalesQty)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Stock)
        </td>
        <td>
            <button onclick="showModal(item.ItemCode);">Show Details/button>
        </td>
    </tr>
}
</code>```

My javascript function is to accept one parameter (when button clicks) and print it inside a modal.

```<code><script type="text/javascript">
    function showModal(itemCode)
    {
        var mod = $('#myModal');
        mod.modal();
        $('#recordId').html(itemCode);
    }
</script>
</code>```

I got exception when i run above code, and it works fine when i use some manual input parameters like 123.

```<code><button onclick="showModal(123);">Show Details/button>
</code>```

i want to call this method by using dynamic parameter ( value from loop ), whats wrong here? help me!

答:
The answer is "showModal(@item.ItemCode);" ,
i missed @ at the beginning.

Body:
From my razor view i have a loop for creating some datas inside a table.

@foreach (var item in Model.ItemModel) {

            @Html.DisplayFor(modelItem => item.ItemCode)

            @Html.DisplayFor(modelItem => item.ItemName)

            @Html.DisplayFor(modelItem => item.Brand)

            @Html.DisplayFor(modelItem => item.PurchaseQty)

            @Html.DisplayFor(modelItem => item.SalesQty)

            @Html.DisplayFor(modelItem => item.Stock)

            <button onclick="showModal(item.ItemCode);">Show Details/button>

}

My javascript function is to accept one parameter (when button clicks) and print it inside a modal.

I got exception when i run above code, and it works fine when i use some manual input parameters like 123.

<button onclick="showModal(123);">Show Details/button>

i want to call this method by using dynamic parameter ( value from loop ), whats wrong here? help me!


问:
Preventing relayout due to scrollbar
How can I prevent the body of the page being "pushed" to the left when a scrollbar appears due to ajax content?
I can of course set overflow:scroll to the body, but it wouldn't look nice.

I am using bootstrap, but I guess it is a general question.

答: In my case, I was getting an annoying pop event on my navbar whenever the scrollbar appears, but applying position fixed on my nav solved it for me.</p>

Title: Preventing relayout due to scrollbar


问:
MVVM Silverlight and page navigation
I'm just starting out with Silverlight and also with the MVVM model.
When performing page navigation and sending arguments from one page to another, .. is the use of querystring the most accepted method?

It seems to be a big confusion on how passing arguments while performing page navigation should be performed. At least I find several topics about this on various web resources, but no one seems to agree upon a "best practice" method.

答:
NOTE: The below solution of using query strings in the NavigationContext works for both in and out of browser.

You normally set your UriMapper something like this:

```<code>           <navigation:Frame Source="/Home" >
                <navigation:Frame.UriMapper>
                    <uriMapper:UriMapper>
                        <uriMapper:UriMapping Uri=""
                                   MappedUri="/Views/Home.xaml"/>
                        <uriMapper:UriMapping Uri="/{pageName}/{key}"
                                   MappedUri="/Views/{pageName}.xaml?entityGuid={key}"/>
                        <uriMapper:UriMapping Uri="/{pageName}"
                                   MappedUri="/Views/{pageName}.xaml"/>
                    </uriMapper:UriMapper>
                </navigation:Frame.UriMapper>
            </navigation:Frame>
</code>```

And then to get the NavigationContext into the view model, you add a helper to your View like so:

```<code><navigation:Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:helpers="clr-namespace:MyApp.Helpers"
                 xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
                 DataContext="{Binding Path=Entity, Source={StaticResource Locator}}"
                 helpers:Navigator.Source="{Binding}">
</code>```

And then you have an attached property helper like so (I modified this from someone else, though I forgot who):

```<code>using System.Windows;
using System.Windows.Controls;

namespace MyApp.Helpers
{

    public interface INavigable
    {
        System.Windows.Navigation.NavigationService NavigationService { get; set; }
        System.Windows.Navigation.NavigationContext NavigationContext { get; set; }
    }

    public static class Navigator
    {
        public static INavigable GetSource(DependencyObject obj)
        {
            return (INavigable)obj.GetValue(SourceProperty);
        }

        public static void SetSource(DependencyObject obj, INavigable value)
        {
            obj.SetValue(SourceProperty, value);
        }

        public static readonly DependencyProperty SourceProperty =
             DependencyProperty.RegisterAttached("Source", typeof(INavigable), typeof(Navigator), new PropertyMetadata(OnSourceChanged));

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Page page = (Page)d;

            page.Loaded += PageLoaded;
        }

        private static void PageLoaded(object sender, RoutedEventArgs e)
        {
            Page page = (Page)sender;

            INavigable navSource = GetSource(page);

            if (navSource != null)
            {
                navSource.NavigationService = page.NavigationService;
                navSource.NavigationContext = page.NavigationContext;
            }
        }
    }
}
</code>```

And then add the following to your ViewModel:

```<code>    private NavigationContext _NavigationContext;
    public NavigationContext NavigationContext {
        get { return _NavigationContext; }
        set {
            if (_NavigationContext == value)
                return;
            _NavigationContext = value;
            RaisePropertyChanged("NavigationContext");
        }
    }
    protected override void RaisePropertyChanged(string propertyName) {
        base.RaisePropertyChanged(propertyName);

        switch (propertyName) {
            case "NavigationContext":
                if (NavigationContext.QueryString.ContainsKey("entityGuid")) {
                    if (NavigationContext.QueryString["entityGuid"].Equals("new", StringComparison.InvariantCultureIgnoreCase)) {
                        LoadNewEntity();  // your 'new' logic
                    } else {
                        this.EntityGuid = new Guid(NavigationContext.QueryString["entityGuid"]);
                        LoadExistingEntity(EntityGuid);  // your 'existing' logic
                    }
                }
                break;
        }
    }
</code>```

Title: MVVM Silverlight and page navigation

Body:
NOTE: The below solution of using query strings in the NavigationContext works for both in and out of browser.

You normally set your UriMapper something like this:

           <navigation:Frame Source="/Home" >
                <navigation:Frame.UriMapper>
                    <uriMapper:UriMapper>
                        <uriMapper:UriMapping Uri=""
                                   MappedUri="/Views/Home.xaml"/>
                        <uriMapper:UriMapping Uri="/{pageName}/{key}"
                                   MappedUri="/Views/{pageName}.xaml?entityGuid={key}"/>
                        <uriMapper:UriMapping Uri="/{pageName}"
                                   MappedUri="/Views/{pageName}.xaml"/>
                    </uriMapper:UriMapper>
                </navigation:Frame.UriMapper>
            </navigation:Frame>

And then to get the NavigationContext into the view model, you add a helper to your View like so:

<navigation:Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:helpers="clr-namespace:MyApp.Helpers"
                 xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
                 DataContext="{Binding Path=Entity, Source={StaticResource Locator}}"
                 helpers:Navigator.Source="{Binding}">

And then you have an attached property helper like so (I modified this from someone else, though I forgot who):

using System.Windows;
using System.Windows.Controls;

namespace MyApp.Helpers
{

    public interface INavigable
    {
        System.Windows.Navigation.NavigationService NavigationService { get; set; }
        System.Windows.Navigation.NavigationContext NavigationContext { get; set; }
    }

    public static class Navigator
    {
        public static INavigable GetSource(DependencyObject obj)
        {
            return (INavigable)obj.GetValue(SourceProperty);
        }

        public static void SetSource(DependencyObject obj, INavigable value)
        {
            obj.SetValue(SourceProperty, value);
        }

        public static readonly DependencyProperty SourceProperty =
             DependencyProperty.RegisterAttached("Source", typeof(INavigable), typeof(Navigator), new PropertyMetadata(OnSourceChanged));

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Page page = (Page)d;

            page.Loaded += PageLoaded;
        }

        private static void PageLoaded(object sender, RoutedEventArgs e)
        {
            Page page = (Page)sender;

            INavigable navSource = GetSource(page);

            if (navSource != null)
            {
                navSource.NavigationService = page.NavigationService;
                navSource.NavigationContext = page.NavigationContext;
            }
        }
    }
}

And then add the following to your ViewModel:

    private NavigationContext _NavigationContext;
    public NavigationContext NavigationContext {
        get { return _NavigationContext; }
        set {
            if (_NavigationContext == value)
                return;
            _NavigationContext = value;
            RaisePropertyChanged("NavigationContext");
        }
    }
    protected override void RaisePropertyChanged(string propertyName) {
        base.RaisePropertyChanged(propertyName);

        switch (propertyName) {
            case "NavigationContext":
                if (NavigationContext.QueryString.ContainsKey("entityGuid")) {
                    if (NavigationContext.QueryString["entityGuid"].Equals("new", StringComparison.InvariantCultureIgnoreCase)) {
                        LoadNewEntity();  // your 'new' logic
                    } else {
                        this.EntityGuid = new Guid(NavigationContext.QueryString["entityGuid"]);
                        LoadExistingEntity(EntityGuid);  // your 'existing' logic
                    }
                }
                break;
        }
    }


问:
Executing Symfony 4 Custom Command in fixtures
I have a custom command in my symfony project to populate the database with the default data that the application need to work in both dev and prod environments.

For the dev environment I have a fixture script that depends on these default common data.
I'm trying to call my custom Symfony command in the fixture script so that I'm sure to have the required data to properly load my fixtures.

This is my custom command app:db:populate in "pseudo script", just creating a bunch of entities, persit & flush. My custom command works fine when I call it through php bin/console app:db:populate

```<code>protected function execute(InputInterface $input, OutputInterface $output)
{
    // Creating a bunch of default entities, persist them and flush

    $data = new MyDefaultEntity();
    // ...
    $this->manager->persist($data);
    // ...
    $this->manager->flush();
}
</code>```

Then, in my fixture script, I want to call app:db:populate first, because fixtures depends on these data. So I tried to use the Process class to execute my script this way :

```<code>public function load(ObjectManager $manager)
{
    // Execute the custom command
    $cmd = 'php bin/console app:db:populate';
    $process = new Process($cmd);
    $process->run(function ($type, $buffer) {
        if (Process::ERR === $type) {
            echo 'ERR > '.$buffer;
        } else {
            echo 'OUT > '.$buffer;
        }
    });

    // Then load the fixtures !
    // ...
}
</code>```

The custom command seems to execute well until the $this->manager->flush();

I have the following error in my console (Data is obfuscated for the post):

```<code>In AbstractMySQLDriver.php line 36:

  An exception occurred while executing 'INSERT INTO ....(..., ..., ...) VALUES (?, ?, ?)' with params ["...", "...", "..."]:

  SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction
</code>```

I don't know what to do regarding this error ... Why the command is working normally when used through a classic console call and why it is not working in a Process?

答:
So, the short answer is

Quoting Symfony documentation :

You may have the need to execute some function that is only available in a console command. Usually, you should refactor the command and move some logic into a service that can be reused in the controller.

I ended up making a service class that handles all the app:db:populate logic (read a json file and insert basic app entities in the database). Then I call this service in both app:db:populate execute methods and AppFixtures load methods.

Hope this will help someone.

Body:
I have a custom command in my symfony project to populate the database with the default data that the application need to work in both dev and prod environments.

For the dev environment I have a fixture script that depends on these default common data.
I'm trying to call my custom Symfony command in the fixture script so that I'm sure to have the required data to properly load my fixtures.

This is my custom command app:db:populate in "pseudo script", just creating a bunch of entities, persit & flush. My custom command works fine when I call it through php bin/console app:db:populate

protected function execute(InputInterface $input, OutputInterface $output)
{
    // Creating a bunch of default entities, persist them and flush

    $data = new MyDefaultEntity();
    // ...
    $this->manager->persist($data);
    // ...
    $this->manager->flush();
}

Then, in my fixture script, I want to call app:db:populate first, because fixtures depends on these data. So I tried to use the Process class to execute my script this way :

public function load(ObjectManager $manager)
{
    // Execute the custom command
    $cmd = 'php bin/console app:db:populate';
    $process = new Process($cmd);
    $process->run(function ($type, $buffer) {
        if (Process::ERR === $type) {
            echo 'ERR > '.$buffer;
        } else {
            echo 'OUT > '.$buffer;
        }
    });

    // Then load the fixtures !
    // ...
}

The custom command seems to execute well until the $this->manager->flush();

I have the following error in my console (Data is obfuscated for the post):

In AbstractMySQLDriver.php line 36:

  An exception occurred while executing 'INSERT INTO ....(..., ..., ...) VALUES (?, ?, ?)' with params ["...", "...", "..."]:

  SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction

I don't know what to do regarding this error ... Why the command is working normally when used through a classic console call and why it is not working in a Process?


问:
Jenkins - Storing curl output into file for future use
I'm currently trying to make Jenkins job that runs if there's difference between the version number between 2 runs.

What I'm currently thinking on doing is by running curl on my webapp endpoint to get the webapp version. I'm looking to store this webapp version information onto jenkinsfile or any file.

The next time the jenkins job runs, it will do curl again to my webapp endpoint and compare the version between the current curl output and the saved version information from last run.

However, as I'm still kind of new to Jenkins, i have no idea on where to start to create the file to store the information i want, anyone have some recommendation or advice for me on how to solve this problem ?

Thanks

答:
you can write a file to represent the state in a shared location and check it next run (no need any plugins):

```<code># this will create initial file in jenkins home folder
curl http://version-check > ~/version
</code>```

when u run the job u can use a simple sh script:

```<code>stage {
  sh """
    LAST_VER=$(cat ~/version)
    CURRENT_VER=$(curl http://version-check)
    if [ "$LAST_VER" = "$CURRENT_VER" ]; then
      echo "versions are equal"
    else
      echo "version are not equal"
      echo $CURRENT_VER > ~/version # update new state
    fi
  """
}
</code>```

Body:
you can write a file to represent the state in a shared location and check it next run (no need any plugins):

# this will create initial file in jenkins home folder
curl http://version-check > ~/version

when u run the job u can use a simple sh script:

stage {
  sh """
    LAST_VER=$(cat ~/version)
    CURRENT_VER=$(curl http://version-check)
    if [ "$LAST_VER" = "$CURRENT_VER" ]; then
      echo "versions are equal"
    else
      echo "version are not equal"
      echo $CURRENT_VER > ~/version # update new state
    fi
  """
}


问:
Can I create a pointer of a type that is determined at run time in C++?
Is there a way (or function) in C++ to create pointers of type that is determined at run time.
Example:
There is a pointer *ptr of type Base.
Base *ptr=new Base();
Suppose we have a function getType capable of returning type of the pointer passed as its argument.
getType(ptr) which returns the type of the pointer so that I can use it to create pointers of similar type like

```<code>getType(ptr) *newPtr=new getType(ptr)();.
</code>```

Is there anyway in C++ to do this?

答:
Yes, there is an easy solution that matches your requirement.

Simply replace in your example

```<code>getType(ptr) *newPtr=new getType(ptr)();
</code>```

getType by decltype. That is all. Or, I do misunderstand your question.

Example code:

```<code>#include <iostream>
#include <string>

int main() {

    std::string answer{};
    int i{};

    // Equivalent to your pseudo code:
    // getType(ptr)  *newPtr           = new getType(ptr)();

    decltype(answer) *newAnswerPointer = new decltype(answer)();
    decltype(i)      *newIPointer      = new decltype(i)();

    // Assign values to the new types
    *newAnswerPointer = "The answer is: ";
    *newIPointer = 42;

    // Show result
    std::cout << *newAnswerPointer << *newIPointer << "\n";

    return 0;
}
</code>```

Edit:

I just saw that user "super" also mentioned decltype. Becuase he was first. All credits go to him . . .

Body:
Is there a way (or function) in C++ to create pointers of type that is determined at run time.
Example:
There is a pointer *ptr of type Base.
Base *ptr=new Base();
Suppose we have a function getType capable of returning type of the pointer passed as its argument.
getType(ptr) which returns the type of the pointer so that I can use it to create pointers of similar type like

getType(ptr) *newPtr=new getType(ptr)();.

Is there anyway in C++ to do this?

Body:
Yes, there is an easy solution that matches your requirement.

Simply replace in your example

getType(ptr) *newPtr=new getType(ptr)();

getType by decltype. That is all. Or, I do misunderstand your question.

Example code:

#include <iostream>
#include <string>

int main() {

    std::string answer{};
    int i{};

    // Equivalent to your pseudo code:
    // getType(ptr)  *newPtr           = new getType(ptr)();

    decltype(answer) *newAnswerPointer = new decltype(answer)();
    decltype(i)      *newIPointer      = new decltype(i)();

    // Assign values to the new types
    *newAnswerPointer = "The answer is: ";
    *newIPointer = 42;

    // Show result
    std::cout << *newAnswerPointer << *newIPointer << "\n";

    return 0;
}

Edit:

I just saw that user "super" also mentioned decltype. Becuase he was first. All credits go to him . . .


问:
how to get the full tweet of the user timeline with twitter4j?
I want to get tweets from certain user timelines using java library twitter4j, currently I have source code which can get ~ 3200 tweets from user time line but I can't get full tweet. I have searched in various sources on the internet but I can't find a solution to my problem. anyone can help me or can anyone provide an alternative to get a full tweet from the user timeline with java programming?

my source code :

```<code>public static void main(String[] args) throws SQLException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey("aaa")
      .setOAuthConsumerSecret("aaa")
      .setOAuthAccessToken("aaa")
      .setOAuthAccessTokenSecret("aaa");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    int pageno = 1;
    String user = "indtravel";
    List statuses = new ArrayList();
    while (true) {
        try {
            int size = statuses.size();
            Paging page = new Paging(pageno++, 100);
            statuses.addAll(twitter.getUserTimeline(user, page));
            System.out.println("***********************************************");
            System.out.println("Gathered " + twitter.getUserTimeline(user, page).size() + " tweets");

            //get status dan user
            for (Status status: twitter.getUserTimeline(user, page)) {
                //System.out.println("*********Place Tweets :**************\npalce country :"+status.getPlace().getCountry()+"\nplace full name :"+status.getPlace().getFullName()+"\nplace name :"+status.getPlace().getName()+"\nplace id :"+status.getPlace().getId()+"\nplace tipe :"+status.getPlace().getPlaceType()+"\nplace addres :"+status.getPlace().getStreetAddress());
                System.out.println("["+(no++)+".] "+"Status id : "+status.getId());
                System.out.println("id user : "+status.getUser().getId());
                System.out.println("Length status :  "+status.getText().length());
                System.out.println("@" + status.getUser().getScreenName() +" . "+status.getCreatedAt()+ " : "+status.getUser().getName()+"--------"+status.getText());
                System.out.println("url :"+status.getUser().getURL());
                System.out.println("Lang :"+status.getLang());
            }
            if (statuses.size() == size)
                break;
        }catch(TwitterException e) {
            e.printStackTrace();
        }
    }
    System.out.println("Total: "+statuses.size());
}
</code>```

Update :
After the answer given by @AndyPiper

the my problem is every tweet that I get will be truncated or not complete. a tweets that I get will be truncated if the length of tweet more than 140 characters. I found the reference tweet_mode=extended, but I do not know how to use it. if you know something please tell me.

答:
If you are implementing twitter api using twitter4j.properties file and getting truncated timeline text value,simply add the below property in it at the end.
tweetModeExtended=TRUE</p>

Body:
I want to get tweets from certain user timelines using java library twitter4j, currently I have source code which can get ~ 3200 tweets from user time line but I can't get full tweet. I have searched in various sources on the internet but I can't find a solution to my problem. anyone can help me or can anyone provide an alternative to get a full tweet from the user timeline with java programming?

my source code :

public static void main(String[] args) throws SQLException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey("aaa")
      .setOAuthConsumerSecret("aaa")
      .setOAuthAccessToken("aaa")
      .setOAuthAccessTokenSecret("aaa");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    int pageno = 1;
    String user = "indtravel";
    List statuses = new ArrayList();
    while (true) {
        try {
            int size = statuses.size();
            Paging page = new Paging(pageno++, 100);
            statuses.addAll(twitter.getUserTimeline(user, page));
            System.out.println("***********************************************");
            System.out.println("Gathered " + twitter.getUserTimeline(user, page).size() + " tweets");

            //get status dan user
            for (Status status: twitter.getUserTimeline(user, page)) {
                //System.out.println("*********Place Tweets :**************\npalce country :"+status.getPlace().getCountry()+"\nplace full name :"+status.getPlace().getFullName()+"\nplace name :"+status.getPlace().getName()+"\nplace id :"+status.getPlace().getId()+"\nplace tipe :"+status.getPlace().getPlaceType()+"\nplace addres :"+status.getPlace().getStreetAddress());
                System.out.println("["+(no++)+".] "+"Status id : "+status.getId());
                System.out.println("id user : "+status.getUser().getId());
                System.out.println("Length status :  "+status.getText().length());
                System.out.println("@" + status.getUser().getScreenName() +" . "+status.getCreatedAt()+ " : "+status.getUser().getName()+"--------"+status.getText());
                System.out.println("url :"+status.getUser().getURL());
                System.out.println("Lang :"+status.getLang());
            }
            if (statuses.size() == size)
                break;
        }catch(TwitterException e) {
            e.printStackTrace();
        }
    }
    System.out.println("Total: "+statuses.size());
}

Update :
After the answer given by @AndyPiper

the my problem is every tweet that I get will be truncated or not complete. a tweets that I get will be truncated if the length of tweet more than 140 characters. I found the reference tweet_mode=extended, but I do not know how to use it. if you know something please tell me.


问:
How to make a condition for onclick loader when user don't completed all fields in form
I have a problem with the form, there is some information in the form and a photo to upload. The time to send the form is different depending on the weight of the file, if it is ~ 3MB it's ok, however if someone uses the mobile version they use the camera in the phone and then the photo can weigh up to 7MB - then the loading time is too long and the user is confused. Therefore I used a simple loader on onclick and the same with onload on the next page, works great, unless someone don't fill the field in the form, then the loader covers the whole page and turns forever. How can I make the condition that the loader appears on oncick only if all fields are completed correctly?

There's form:

```<code><div id="preloader" aria-busy="true" aria-label="Loading, please wait." role="progressbar"><img class="icon" src="https://raziraz.github.io/codepen/img/bolt.svg">
</div>

    <main id="site" role="main">
    <script  src="./preloaderr.js"></script>

        <h2>Dodaj nową licencję</h2>
        <form method="POST" action="Licencja_Użytkownik_Dodawanie_Skrypt.php" enctype="multipart/form-data">
        <input type="hidden" name="login" value="$login">

        <div id="inputtitle">Prześlij zdjęcie</div>
        <input type="file" name="licencja_plik" required>
        </br>

        <div id="inputtitle">Numer licencji</div>
        <input type="text" name="Numer_Licencji"  placeholder="Numer licencji" required></br>

        <div id="inputtitle">Numer wypisu</div>
        <input type="text" name="Numer_Wypisu"  placeholder="Numer wypisu" required></br>

        <div id="inputtitle">Miasto</div>
        <input type="text" name="Miasto_Licencji"  placeholder="Miasto" required></br>

        <div id="inputtitle">Numer rejestracyjny</div>
        <input type="text" name="Numer_Rejestracyjny"  placeholder="Numer rejestracyjny" required></br>

        <div id="inputtitle">Licencja ważna do:</div>
        <input type="date" name="Licencja_Do"  placeholder="05-02-2020" required></br>

        <div id="containera">
        <div id="right">

        <button type="submit" class="buttondodaj" onclick="teest(); window.parent.parent.scrollTo(0,0)">
        Dodaj   <i class="fas fa-arrow-right"></i>
        </button>

        </form></div>

        <form method="GET" action="Licencja_Użytkownik.php" >
        <input type="hidden" name="login" value="$login">

        <div id="left">

        <button type="submit" class="buttonanuluj">
        <i class="fas fa-arrow-left"></i>   Anuluj
        </button>

        </form>
        </div>
        </div>
    </main>

</code>```

There's js preloader and loader:

```<code>
function preloader() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "0";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "1";
}
window.onload = preloader;

function teest() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "1";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "0";

}
</code>```

I will be grateful for the hints :).

答:
Just update your submit button to

<button type="submit"
        class="buttondodaj"
        id="submitBtn" window.parent.parent.scrollTo(0,0)"
>
   Dodaj
</button>
```

<pre class="lang-js prettyprint-override"><code>//Return true if the form is not empty, false if it is
const isNotEmpty = () => {
  //supose the form is not empty
  let flag = true;
  //For all input, check if the value is different of empty
  document
    .querySelectorAll("input")
    .forEach(input => flag =  input.value !== "" && flag);
  return flag;
};

//Listen when user click on the submit button
document.getElementById('submitBtn').addEventListener('click',e => {
  let flag = isNotEmpty();
  if(!flag) {
    //don't submit form because it's empty
    e.preventDefault();
    //don't display the placeholer loader
    return;
  }
  //Now we can display the placeholder
  //So put the placeholder loader logic here
})
</code>```

Body:
I have a problem with the form, there is some information in the form and a photo to upload. The time to send the form is different depending on the weight of the file, if it is ~ 3MB it's ok, however if someone uses the mobile version they use the camera in the phone and then the photo can weigh up to 7MB - then the loading time is too long and the user is confused. Therefore I used a simple loader on onclick and the same with onload on the next page, works great, unless someone don't fill the field in the form, then the loader covers the whole page and turns forever. How can I make the condition that the loader appears on oncick only if all fields are completed correctly?

There's form:

Dodaj nową licencję

        <form method="POST" action="Licencja_Użytkownik_Dodawanie_Skrypt.php" enctype="multipart/form-data">
        <input type="hidden" name="login" value="$login">

Prześlij zdjęcie

        <input type="file" name="licencja_plik" required>

Numer licencji

        <input type="text" name="Numer_Licencji"  placeholder="Numer licencji" required>

Numer wypisu

        <input type="text" name="Numer_Wypisu"  placeholder="Numer wypisu" required>

Miasto

        <input type="text" name="Miasto_Licencji"  placeholder="Miasto" required>

Numer rejestracyjny

        <input type="text" name="Numer_Rejestracyjny"  placeholder="Numer rejestracyjny" required>

Licencja ważna do:

        <input type="date" name="Licencja_Do"  placeholder="05-02-2020" required>

        <button type="submit" class="buttondodaj" onclick="teest(); window.parent.parent.scrollTo(0,0)">
        Dodaj
        </button>

        </form>

        <form method="GET" action="Licencja_Użytkownik.php" >
        <input type="hidden" name="login" value="$login">

        <button type="submit" class="buttonanuluj">
           Anuluj
        </button>

        </form>

There's js preloader and loader:

function preloader() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "0";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "1";
}
window.onload = preloader;

function teest() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "1";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "0";

}

I will be grateful for the hints :).

Body:
Just update your submit button to

<button type="submit"
        class="buttondodaj"
        id="submitBtn" window.parent.parent.scrollTo(0,0)"
>
   Dodaj&nbsp;&nbsp;&nbsp;<i class="fas fa-arrow-right"></i>
</button>

//Return true if the form is not empty, false if it is
const isNotEmpty = () => {
  //supose the form is not empty
  let flag = true;
  //For all input, check if the value is different of empty
  document
    .querySelectorAll("input")
    .forEach(input => flag =  input.value !== "" && flag);
  return flag;
};

//Listen when user click on the submit button
document.getElementById('submitBtn').addEventListener('click',e => {
  let flag = isNotEmpty();
  if(!flag) {
    //don't submit form because it's empty
    e.preventDefault();
    //don't display the placeholer loader
    return;
  }
  //Now we can display the placeholder
  //So put the placeholder loader logic here
})


问:
FileNotFoundException when using BufferedReader on a file
I'm very confused on getting basic file reading to work with Java.  Lots of mixed signals.

I've tried it a couple different ways and I consistently get a not found exception each time.  I've checked with a file object set to the current path to print the current directory and I am indeed in the directory the file I'm trying to open is in.  The permissions are set so everyone can read.  I'm not sure what is going on:

```<code>BufferedReader infixLines = new BufferedReader ( new FileReader ( "input.infix" ));
</code>```

This is the line that throws the error, consequently each consecutive line using infixLines also throws an error.

I've tried it using FileInputStream as well and get the same kind of error.

That being said simply doing

```<code>File file = new File("input.infix");
if ( file.exists() )
    System.out.println( "Exists" );
</code>```

DOES work.

Very confused.

EDIT: (Stacktrace?)

```<code>ParseInfix.java:13: unreported exception java.io.FileNotFoundException; must be
            BufferedReader infixLines = new BufferedReader(new FileReader (n
                                                           ^
ParseInfix.java:15: unreported exception java.io.IOException; must be caught or
            while ( ( line = infixLines.readLine()) != null )
</code>```

答:
try this</p>

```<code>String fileName = "input.infix";
File fil = new File(fileName);
String filePath = fil.getAbsolutePath();
BufferedReader infixLines = new BufferedReader(new FileReader(filePath));
</code>```

Body:
I'm very confused on getting basic file reading to work with Java.  Lots of mixed signals.

I've tried it a couple different ways and I consistently get a not found exception each time.  I've checked with a file object set to the current path to print the current directory and I am indeed in the directory the file I'm trying to open is in.  The permissions are set so everyone can read.  I'm not sure what is going on:

BufferedReader infixLines = new BufferedReader ( new FileReader ( "input.infix" ));

This is the line that throws the error, consequently each consecutive line using infixLines also throws an error.

I've tried it using FileInputStream as well and get the same kind of error.

That being said simply doing

File file = new File("input.infix");
if ( file.exists() )
    System.out.println( "Exists" );

DOES work.

Very confused.

EDIT: (Stacktrace?)

ParseInfix.java:13: unreported exception java.io.FileNotFoundException; must be
            BufferedReader infixLines = new BufferedReader(new FileReader (n
                                                           ^
ParseInfix.java:15: unreported exception java.io.IOException; must be caught or
            while ( ( line = infixLines.readLine()) != null )

Body:
try this

String fileName = "input.infix";
File fil = new File(fileName);
String filePath = fil.getAbsolutePath();
BufferedReader infixLines = new BufferedReader(new FileReader(filePath));


问:
In NetLogo, how to access the coordinates and value of variables of neighbouring patches for a turtle?
For example, I would like to get the coordinates of the first patch above, below, to the left and right of the patch the turtle is currently on, as well as the value of a variable for each of those patches, such as plabel or pcolor. Essentially I would like to use this information so that then the agent can make a decision as to which patch to move to.

I think neighbors4 might be how to do this but I'm not quite sure of the code needed. For accessing variable values, I have been trying

```<code>let LabelsOfPatches neighbors4 [plabel]
</code>```

or

```<code>let ColorOfPatches neighbors4 [pcolor]
</code>```

But I get an error saying a command was expected in between the square brackets.

答:
I have seemingly done what I wanted by using

```<code>let NeighbourList []
</code>```

ask neighbors4 [set ValuesOfInterest (list (pxcor) (pycor) (pcolor) (plabel))
set NeighbourList lput ValuesOfInterest NeighbourList
]

Body:
For example, I would like to get the coordinates of the first patch above, below, to the left and right of the patch the turtle is currently on, as well as the value of a variable for each of those patches, such as plabel or pcolor. Essentially I would like to use this information so that then the agent can make a decision as to which patch to move to.

I think neighbors4 might be how to do this but I'm not quite sure of the code needed. For accessing variable values, I have been trying

let LabelsOfPatches neighbors4 [plabel]

or

let ColorOfPatches neighbors4 [pcolor]

But I get an error saying a command was expected in between the square brackets.

Body:
I have seemingly done what I wanted by using

let NeighbourList []

ask neighbors4 [set ValuesOfInterest (list (pxcor) (pycor) (pcolor) (plabel))
set NeighbourList lput ValuesOfInterest NeighbourList
]


问:
jQuery selector chaining
We're having an issue trying to chain selectors together. We are trying to get all checkboxes that are checked and have the data-action attribute with hideplan as the value. I've got a page that has two checkboxes, one button and this javascript on it:

```<code><script type="text/javascript">
    var hiddenplans = $('input:checkbox[data-action="hideplan":checked');
    $("#hide_btn").click(function() {
        hiddenplans.each(

        function(index) {
            alert('checked' + index);
        });
    });
</script>
</code>```

This doesn't display any alerts when one or more checkboxes are selected - hiddenplans is empty. However, if we copy $('input:checkbox[data-action="hideplan":checked'); and put it into the firebug console and run it we will get results if one or more checkboxes are selected. If I remove :checked it will alert for checkboxes with data-action=hideplan.

We've tried several different ways of writing the selector (i.e. $("input[type=checkbox][data-action=hideplan]:checked") and $("input[type=checkbox][data-action=hideplan]").filter(":checked"); and more) and they work in the console but will not return alerts.

I've created a Fiddle with the full code in case we missed something obvious http://jsfiddle.net/xCnSs/5/

答:
You forgot the closing bracket:

```<code>$('input:checkbox[data-action="hideplan"]:checked');
</code>```

But remember you can also filter results:

```<code>$('input:checkbox[data-action="hideplan"]').filter(':checked');
</code>```

Title: jQuery selector chaining

Body:
We're having an issue trying to chain selectors together. We are trying to get all checkboxes that are checked and have the data-action attribute with hideplan as the value. I've got a page that has two checkboxes, one button and this javascript on it:

This doesn't display any alerts when one or more checkboxes are selected - hiddenplans is empty. However, if we copy $('input:checkbox[data-action="hideplan":checked'); and put it into the firebug console and run it we will get results if one or more checkboxes are selected. If I remove :checked it will alert for checkboxes with data-action=hideplan.

We've tried several different ways of writing the selector (i.e. $("input[type=checkbox][data-action=hideplan]:checked") and $("input[type=checkbox][data-action=hideplan]").filter(":checked"); and more) and they work in the console but will not return alerts.

I've created a Fiddle with the full code in case we missed something obvious http://jsfiddle.net/xCnSs/5/

Body:
You forgot the closing bracket:

$('input:checkbox[data-action="hideplan"]:checked');

But remember you can also filter results:

$('input:checkbox[data-action="hideplan"]').filter(':checked');


问:
Circular buffer in JavaScript
Has anyone already implemented a circular buffer in JavaScript? How would you do that without having pointers?</p>

答:
I wasn't doing any perf checks, but as per my understanding sequential array access should be faster than linked list. Also I've noticed that multiple implementations suffer from obsolete prototype based ES3 (at least) style which makes my eyeballs pop. Also none of them support dynamic size increase i.e. "growing". So here's how I see this implementation. Feel free to expand as per your needs:

```<code>export class Dequeue<T> {
    private buffer: T[];
    private head: number;
    private tail: number;
    private size: number;

    constructor(initialCapacity: number) {
        this.buffer = [];
        this.buffer.length = initialCapacity;
        this.head = this.tail = this.size = 0;
    }

    public enqueue(value: T): T {
        let next = this.head + 1;
        let buffer = this.buffer;
        let length = buffer.length;

        if (length <= next) {
            next -= length;
        }

        if (buffer.length <= this.size) {
            buffer.length += length;

            for (let index = next; index < length; index++) {
                buffer[index + length] = buffer[index];
            }
        }

        this.size++;
        buffer[this.head] = value;
        this.head = next;

        return value;
    }

    public dequeue(): T | undefined {
        if (this.size > 0) {
            this.size--;

            let buffer = this.buffer;
            let length = buffer.length;
            let value = buffer[this.tail];

            let next = this.tail + 1;

            if (length <= next) {
                next -= length;
            }

            this.tail = next;

            return value;
        } else {
            return undefined;
        }
    }

    public get length() {
        return this.size;
    }
}
</code>```

To prevent propagation of undefined in the interface I can suggest the following version:

```<code>export function Throw(message: string): never {
    throw new Error(message);
}

export class Dequeue<T> {
    private buffer: T[];
    private head: number;
    private tail: number;
    private size: number;

    constructor(initialCapacity: number) {
        this.buffer = [];
        this.buffer.length = initialCapacity;
        this.head = this.tail = this.size = 0;
    }

    public enqueue(value: T): T {
        let next = this.head + 1;
        let buffer = this.buffer;
        let length = buffer.length;

        if (length <= next) {
            next -= length;
        }

        if (buffer.length <= this.size) {
            buffer.length += length;

            for (let index = next; index < length; index++) {
                buffer[index + length] = buffer[index];
            }
        }

        this.size++;
        buffer[this.head] = value;
        this.head = next;

        return value;
    }

    public dequeue(defaultValueFactory: () => T = () => Throw('No elements to dequeue')): T {
        if (this.size > 0) {
            this.size--;

            let buffer = this.buffer;
            let length = buffer.length;
            let value = buffer[this.tail];

            let next = this.tail + 1;

            if (length <= next) {
                next -= length;
            }

            this.tail = next;

            return value;
        } else {
            return defaultValueFactory();
        }
    }

    public get length() {
        return this.size;
    }
}
</code>```

Title: Circular buffer in JavaScript

Body:
I wasn't doing any perf checks, but as per my understanding sequential array access should be faster than linked list. Also I've noticed that multiple implementations suffer from obsolete prototype based ES3 (at least) style which makes my eyeballs pop. Also none of them support dynamic size increase i.e. "growing". So here's how I see this implementation. Feel free to expand as per your needs:

export class Dequeue<T> {
    private buffer: T[];
    private head: number;
    private tail: number;
    private size: number;

    constructor(initialCapacity: number) {
        this.buffer = [];
        this.buffer.length = initialCapacity;
        this.head = this.tail = this.size = 0;
    }

    public enqueue(value: T): T {
        let next = this.head + 1;
        let buffer = this.buffer;
        let length = buffer.length;

        if (length <= next) {
            next -= length;
        }

        if (buffer.length <= this.size) {
            buffer.length += length;

            for (let index = next; index < length; index++) {
                buffer[index + length] = buffer[index];
            }
        }

        this.size++;
        buffer[this.head] = value;
        this.head = next;

        return value;
    }

    public dequeue(): T | undefined {
        if (this.size > 0) {
            this.size--;

            let buffer = this.buffer;
            let length = buffer.length;
            let value = buffer[this.tail];

            let next = this.tail + 1;

            if (length <= next) {
                next -= length;
            }

            this.tail = next;

            return value;
        } else {
            return undefined;
        }
    }

    public get length() {
        return this.size;
    }
}

To prevent propagation of undefined in the interface I can suggest the following version:

export function Throw(message: string): never {
    throw new Error(message);
}

export class Dequeue<T> {
    private buffer: T[];
    private head: number;
    private tail: number;
    private size: number;

    constructor(initialCapacity: number) {
        this.buffer = [];
        this.buffer.length = initialCapacity;
        this.head = this.tail = this.size = 0;
    }

    public enqueue(value: T): T {
        let next = this.head + 1;
        let buffer = this.buffer;
        let length = buffer.length;

        if (length <= next) {
            next -= length;
        }

        if (buffer.length <= this.size) {
            buffer.length += length;

            for (let index = next; index < length; index++) {
                buffer[index + length] = buffer[index];
            }
        }

        this.size++;
        buffer[this.head] = value;
        this.head = next;

        return value;
    }

    public dequeue(defaultValueFactory: () => T = () => Throw('No elements to dequeue')): T {
        if (this.size > 0) {
            this.size--;

            let buffer = this.buffer;
            let length = buffer.length;
            let value = buffer[this.tail];

            let next = this.tail + 1;

            if (length <= next) {
                next -= length;
            }

            this.tail = next;

            return value;
        } else {
            return defaultValueFactory();
        }
    }

    public get length() {
        return this.size;
    }
}


问:
SwiftUI Navigation on iPad - How to show master list
My app has simple navigation needs

List View (parent objects)

List View (child objects)

Detail View (child object)

I have this setup and working on iPhone, but when I run the app on iPad in portrait mode the master list is always hidden.

I'm using .isDetailLink(false) on the navigation link from the first list to the second, so both lists always stay in the master column. In iPad landscape everything works as expected but in portrait the detail view fills the screen. I can swipe in from the left side of the screen to show the list but I'd like to provide more clarity to the user.

I'd like to show or add the back button to show the master/list side (sort of like the Apple Notes app). On the iPhone I get the back button by default but on iPad in portrait mode there is nothing in its place.

This is what I see on iPhone

But this is what I see on iPad

Parent list

```<code>struct ParentList: View {

    let firstList = ["Sample data 01", "Sample data 02", "Sample data 03", "Sample data 04", "Sample data 05"]

    var body: some View {
        NavigationView {
            List{
                ForEach(firstList, id: \.self) { item in
                    NavigationLink(destination: ChildList()){

                        Text(item)
                    }
                    .isDetailLink(false)

                }
            }
        }
    }
}
</code>```

Child list

```<code>struct ChildList: View {

    let secondList = ["More Sample data 01", "More Sample data 02", "More Sample data 03", "More Sample data 04", "More Sample data 05"]

    var body: some View {
        List{
            ForEach(secondList, id: \.self) { item in
                NavigationLink(destination: ChildDetail()){

                    Text(item)

                }
            }
        }
    }
}
</code>```

Child detail

```<code>struct ChildDetail: View {

    var body: some View {
        Text("Child detail view")
    }

}
</code>```

Update: As of Oct 17, 2019 I have not found a way to get this to work. I decided to use .navigationViewStyle(StackNavigationViewStyle()) for the time being. Interestingly, this needs to go outside of the navigation view like a normal modifier, not inside it with the navigation title.

答:
in iOS 13.4, a "back to master view" button has been added to the iPad layout. From the release notes:

When using a NavigationView with multiple columns, the navigation bar now shows a control to toggle the columns. (49074511)

For example:

```<code>struct MyNavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: Text("navigated"),
                label: {Text("Go somwhere")}
            )
            .navigationBarTitle("Pick Item")
        }
    }
}
</code>```

Has the following result:

Body:
My app has simple navigation needs

List View (parent objects)

List View (child objects)

Detail View (child object)

I have this setup and working on iPhone, but when I run the app on iPad in portrait mode the master list is always hidden.

I'm using .isDetailLink(false) on the navigation link from the first list to the second, so both lists always stay in the master column. In iPad landscape everything works as expected but in portrait the detail view fills the screen. I can swipe in from the left side of the screen to show the list but I'd like to provide more clarity to the user.

I'd like to show or add the back button to show the master/list side (sort of like the Apple Notes app). On the iPhone I get the back button by default but on iPad in portrait mode there is nothing in its place.

This is what I see on iPhone

But this is what I see on iPad

Parent list

struct ParentList: View {

    let firstList = ["Sample data 01", "Sample data 02", "Sample data 03", "Sample data 04", "Sample data 05"]

    var body: some View {
        NavigationView {
            List{
                ForEach(firstList, id: \.self) { item in
                    NavigationLink(destination: ChildList()){

                        Text(item)
                    }
                    .isDetailLink(false)

                }
            }
        }
    }
}

Child list

struct ChildList: View {

    let secondList = ["More Sample data 01", "More Sample data 02", "More Sample data 03", "More Sample data 04", "More Sample data 05"]

    var body: some View {
        List{
            ForEach(secondList, id: \.self) { item in
                NavigationLink(destination: ChildDetail()){

                    Text(item)

                }
            }
        }
    }
}

Child detail

struct ChildDetail: View {

    var body: some View {
        Text("Child detail view")
    }

}

Update: As of Oct 17, 2019 I have not found a way to get this to work. I decided to use .navigationViewStyle(StackNavigationViewStyle()) for the time being. Interestingly, this needs to go outside of the navigation view like a normal modifier, not inside it with the navigation title.

Body:
in iOS 13.4, a "back to master view" button has been added to the iPad layout. From the release notes:

When using a NavigationView with multiple columns, the navigation bar now shows a control to toggle the columns. (49074511)

For example:

struct MyNavView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: Text("navigated"),
                label: {Text("Go somwhere")}
            )
            .navigationBarTitle("Pick Item")
        }
    }
}

Has the following result:


问:
Check the render method of BottomNavigation - React Native
I am creating bottom navigation in react native project. It is working fine for the following coding.

App.js

import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { MaterialCommunityIcons } from 'react-native-vector-icons';
import { NavigationContainer } from '@react-navigation/native';

import Accounts from './src/components/Accounts';
// ...importing other screens here...

const Tab = createMaterialBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator
      initialRouteName="Feed"
      activeColor="#e91e63"
      labelStyle={{ fontSize: 12 }}
      style={{ backgroundColor: 'tomato' }}>
      <Tab.Screen name="Accounts" component={Accounts} />
      ...Other screens comes here...
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <MyTabs />
    </NavigationContainer>
  );
}
```
<p>But I need to add icons to the tabs. So I added the following props to the<code>Screen</code></p>
<pre class="lang-js prettyprint-override"><code><Tab.Screen
  name="Accounts"
  component={Accounts}
  options={{
    tabBarLabel: 'Home',
    tabBarIcon: ({ color, size }) => (
      <MaterialCommunityIcons name="home" color={color} size={size} />
    ),
  }}
/>
</code>```

After adding these props I am getting the following error

Invariant violation: Element type is invalid: expected string (for
built-in components) or a class/function (for a composite components)
but got undefined. You likely forgot to export your component from the
file it's defined in, or you might have mixed up default and named
imports

as per the documentation, I am doing everything correctly. The props is suggested from the React Navigation documentation. What is the wrong in my coding? I need icons in my tabs

答:
I believe you must create the icons on the Tab.Navigator prop.

Here is an example utilizing a different icon package but should work the same: https://reactnavigation.org/docs/en/tab-based-navigation.html

// You can import Ionicons from @expo/vector-icons if you use Expo or
// react-native-vector-icons/Ionicons otherwise.
import { Ionicons } from '@expo/vector-icons';

// (...)

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;

            if (route.name === 'Home') {
              iconName = focused
                ? 'ios-information-circle'
                : 'ios-information-circle-outline';
            } else if (route.name === 'Settings') {
              iconName = focused ? 'ios-list-box' : 'ios-list';
            }

            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: 'tomato',
          inactiveTintColor: 'gray',
        }}>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}
```

Body:
I am creating bottom navigation in react native project. It is working fine for the following coding.

App.js

import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { MaterialCommunityIcons } from 'react-native-vector-icons';
import { NavigationContainer } from '@react-navigation/native';

import Accounts from './src/components/Accounts';
// ...importing other screens here...

const Tab = createMaterialBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator
      initialRouteName="Feed"
      activeColor="#e91e63"
      labelStyle={{ fontSize: 12 }}
      style={{ backgroundColor: 'tomato' }}>
      <Tab.Screen name="Accounts" component={Accounts} />
      ...Other screens comes here...
    </Tab.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <MyTabs />
    </NavigationContainer>
  );
}

But I need to add icons to the tabs. So I added the following props to theScreen

<Tab.Screen
  name="Accounts"
  component={Accounts}
  options={{
    tabBarLabel: 'Home',
    tabBarIcon: ({ color, size }) => (
      <MaterialCommunityIcons name="home" color={color} size={size} />
    ),
  }}
/>

After adding these props I am getting the following error

Invariant violation: Element type is invalid: expected string (for
built-in components) or a class/function (for a composite components)
but got undefined. You likely forgot to export your component from the
file it's defined in, or you might have mixed up default and named
imports

as per the documentation, I am doing everything correctly. The props is suggested from the React Navigation documentation. What is the wrong in my coding? I need icons in my tabs


问:
Java GWT Application - Compile Works Sometimes and Sometimes Not
Hopefully I provide everything needed for this:

Java 8
GWT 2.5.1
Eclipse 2018-09 (4.9.0)
Git

I have a project that I cannot get to consistently compile.  In Eclipse, I compile using the GWT -> Compile option, while on our web servers we use Ant.

I can get successful compiles on one or more of these machines (we have a Dev and a QA server).  I can get them to compile once, twice, maybe three times.  Then, on any machine, it will fail and fail and fail.

The error is this:

[ERROR] Errors in 'jar:file:/C:/Users/htaylor/git/codemanagerclient/CodeManagerClient/war/WEB-INF/lib/guava-gwt-12.0.jar!/com/google/common/base/Strings.java'
      [ERROR] Line 1: The type java.util.regex.Pattern cannot be resolved. It is indirectly referenced from required .class files

I've only been coding with Java for a bit over a year and I'm just frankly stumped. I don't understand why it would compile one time and then not the next, even when done immediately after the successful one.  To me, it suggests that something is not getting done in the same, proper, order each time.

I'm just wondering if anyone can help shed some light on this.

答:
You need to use regex from GWT libraries:

```<code>import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
</code>```

Here's a complete working Regex utility with GWT:

```<code>public class RegexHelper {

    public static ArrayList<String> getMatches(String input, String pattern) {
        ArrayList<String> matches = new ArrayList<String>();
        RegExp regExp = RegExp.compile(pattern, "g");
        for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) {
            for(int i=0;i<matcher.getGroupCount();i++) {
                if(i != 0) {
                    matches.add(matcher.getGroup(i));
                }
            }
        }
        return matches;
    }
}
</code>```

You can use it like this:

```<code>RegexHelper.getMatches(INPUT_STRING, REGEX_PATTERN);
</code>```

Hope this helps.

Body:
You need to use regex from GWT libraries:

import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;

Here's a complete working Regex utility with GWT:

public class RegexHelper {

    public static ArrayList<String> getMatches(String input, String pattern) {
        ArrayList<String> matches = new ArrayList<String>();
        RegExp regExp = RegExp.compile(pattern, "g");
        for (MatchResult matcher = regExp.exec(input); matcher != null; matcher = regExp.exec(input)) {
            for(int i=0;i<matcher.getGroupCount();i++) {
                if(i != 0) {
                    matches.add(matcher.getGroup(i));
                }
            }
        }
        return matches;
    }
}

You can use it like this:

RegexHelper.getMatches(INPUT_STRING, REGEX_PATTERN);

Hope this helps.


问:
Trouble setting up git with my GitHub Account error: could not lock config file
I'm getting this error when trying to set the global config:

```<code>$ git config --global user.name "Your Name Here"
error: could not lock config file /pathto/file/.gitconfig: No such file or directory
</code>```

and the file .gitconfig is already exists, anyone have any ideas??

答:
So I know this thread is Old, but I had the same issue and fixed it. Hopefully this works for someone else.

When i tried using "sudo" or anything in powershell/cmd it was an unrecognized command.
So i reinstalled git for windows, during the install it failed and pointed me to C:/ProgramFiles/git/etc/gitconfig
I deleted that file, and reinstalled. Same Error when saving credentials, So i moved the newly created gitconfig from programfiles, to my HomePath location C:/Users/Name

Now I can save credentials under file-->Options-->git
Finally, I can commit/push on githubdesktop

Body:
I'm getting this error when trying to set the global config:

$ git config --global user.name "Your Name Here"
error: could not lock config file /pathto/file/.gitconfig: No such file or directory

and the file .gitconfig is already exists, anyone have any ideas??