问:
Table Populated by Core Data doesn't Display Properly
I'm populating a TableViewController given an array of NSManagedObjects of class "SampleClass".  Although the number of objects in the fetched array returns correctly (i.e. if the table is to display 59 objects, 59 rows are created), the other parameters for the cell are "glitchy" to display.

For example, where there should be a title set by object.name, "null" until you click on the the cell, select another cell, and then come back to the initial cell.

I've tried `[tableview reloadData]' in the view will appear, and it still takes too long to load the data.  Is there a better way to fill in the cell instead of:

```<code>    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

}

Class *classObject = [dataArray objectAtIndex:indexPath.row];

cell.textLabel.text = [classObject name].....
</code>```

where dataArray points to the NSMutableFetchedArray from a coreData call

Note: the simulator misses filling more of the cells than the actual iPad.  once another tab is selected however, all the cells display correctly when you return to the tab.`

答:
You may want to look into NSFetchedResultsController

http://developer.apple.com/library/iOS/ipad/#documentation/CoreData/Reference/NSFetchedResultsController_Class/Reference/Reference.html

It is a special class which is meant specifically for populating a table with results from a core data query.

In the past when using core data I have always used this class over other means.

Body:
I'm populating a TableViewController given an array of NSManagedObjects of class "SampleClass".  Although the number of objects in the fetched array returns correctly (i.e. if the table is to display 59 objects, 59 rows are created), the other parameters for the cell are "glitchy" to display.

For example, where there should be a title set by object.name, "null" until you click on the the cell, select another cell, and then come back to the initial cell.

I've tried `[tableview reloadData]' in the view will appear, and it still takes too long to load the data.  Is there a better way to fill in the cell instead of:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

}

Class *classObject = [dataArray objectAtIndex:indexPath.row];

cell.textLabel.text = [classObject name].....

where dataArray points to the NSMutableFetchedArray from a coreData call

Note: the simulator misses filling more of the cells than the actual iPad.  once another tab is selected however, all the cells display correctly when you return to the tab.`


来源: stackexchange

问:
Rename a column in MySQL
I am trying to rename a column in MySQL community server 5.5.27 using this SQL expression:

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;
```

<p>I also tried</p>

<pre class="lang-sql prettyprint-override"><code>ALTER TABLE table_name RENAME old_col_name TO new_col_name;
</code>```

But it says:

Error: check the Manual that corresponds to your MySQL server version

答:
```<code>ALTER TABLE table_name CHANGE old_column_name new_column_name columnDataType;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rename a column in MySQL

Body:
I am trying to rename a column in MySQL community server 5.5.27 using this SQL expression:

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

I also tried

ALTER TABLE table_name RENAME old_col_name TO new_col_name;

But it says:

Error: check the Manual that corresponds to your MySQL server version

ContentLicense: CC BY-SA 4.0


问:
TicTacToe Heavy Win Condition
I made a TicTacToe game in Ruby. I am pretty new to Ruby OOP. My win conditions for checking row, column and diagonals are really heavy and they take too much code line and look pretty horrible. My code also always repeating.

So my question is how to implement the below win conditions into my code?

 WIN_COMBINATIONS = [
[0,1,2], # top_row
[3,4,5], # middle_row
[6,7,8], # bottom_row
[0,3,6], # left_column
[1,4,7], # center_column
[2,5,8], # right_column
[0,4,8], # left_diagonal
[6,4,2] # right_diagonal
]
```
<p>Here is my win conditions:</p>
<pre class="lang-rb prettyprint-override"><code>module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end
</code>```

I invoke these conditions from this line of code:

def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

```
<p>Here is my full of project that it is correctly working.</p>
<pre class="lang-rb prettyprint-override"><code>module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

# TicTacToe Board
class Board
  include CheckWinner
  attr_accessor :board

  def initialize
    @board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  end

  def print_board
    puts '-------------'
    @board.each do |row|
      print '|'
      row.each do |col|
        print " #{col}"
        print ' | '
      end
      puts
    end
    puts '-------------'
  end

  def twodimentional_board
    @board = @board.each_slice(3).map { |el| el }
  end

  def occupied_error(value)
    puts 'There is a value or wrong place! Try Again!'
    twodimentional_board
    print_board
    value == @player1 ? player2(@player1) : player1(@player2) # Stay same player
  end

  def move_if_possible(place, value)
    @board.flatten!
    if @board[place - 1] == 'X' || @board[place - 1] == 'O' || !place.between?(1, 9)
      occupied_error(value)
    else
      @board[place - 1] = value
      twodimentional_board
      @board
    end
  end

  def full?
    if @board.flatten.all?(String)
      puts 'Draw!'
      true
    end
  end

  def choosing_player
    puts 'Choose for Player1(X or O)'
    loop do
      @player1 = gets.chomp!
      break if @player1 == 'X' || @player1 == 'O'

      puts 'Try Again!(X or O)'
    end
    puts "Player 1 is: #{@player1}"

    @player1 == 'X' ? @player2 = 'O' : @player2 = 'X'
    puts "Player 2 is: #{@player2}"
    print_board
  end

  def player1(player1)
    puts "Choice #{player1} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player1)
    print_board
  end

  def player2(player2)
    puts "Choice #{player2} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player2)
    print_board
  end

  def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

board = Board.new
board.game
</code>```

If you want to live preview here is repl link

答:
Why don't you track state helping you determine winning condition as you mark new moves? That way you don't have to recompute all what you already know.

For instance, if I tell you my board size is 3, that there's already 2 Xs in the first row and now X played a new move in that row leading to 3 Xs, you know X won immediately right? You don't even need to know anything else about the state of the board.

You can apply the same logic here and simply keep track of X & O counts per row, cols & diags as marks are recorded and you won't even have to loop to check who's won.

The above-described approach is easy to implement and takes O(1) time complexity to check the winning condition. You trade a bit of memory (O(n)) for computation speed.

Title: TicTacToe Heavy Win Condition

Body:
I made a TicTacToe game in Ruby. I am pretty new to Ruby OOP. My win conditions for checking row, column and diagonals are really heavy and they take too much code line and look pretty horrible. My code also always repeating.

So my question is how to implement the below win conditions into my code?

 WIN_COMBINATIONS = [
[0,1,2], # top_row
[3,4,5], # middle_row
[6,7,8], # bottom_row
[0,3,6], # left_column
[1,4,7], # center_column
[2,5,8], # right_column
[0,4,8], # left_diagonal
[6,4,2] # right_diagonal
]

Here is my win conditions:

module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

I invoke these conditions from this line of code:

def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

Here is my full of project that it is correctly working.

module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

# TicTacToe Board
class Board
  include CheckWinner
  attr_accessor :board

  def initialize
    @board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  end

  def print_board
    puts '-------------'
    @board.each do |row|
      print '|'
      row.each do |col|
        print " #{col}"
        print ' | '
      end
      puts
    end
    puts '-------------'
  end

  def twodimentional_board
    @board = @board.each_slice(3).map { |el| el }
  end

  def occupied_error(value)
    puts 'There is a value or wrong place! Try Again!'
    twodimentional_board
    print_board
    value == @player1 ? player2(@player1) : player1(@player2) # Stay same player
  end

  def move_if_possible(place, value)
    @board.flatten!
    if @board[place - 1] == 'X' || @board[place - 1] == 'O' || !place.between?(1, 9)
      occupied_error(value)
    else
      @board[place - 1] = value
      twodimentional_board
      @board
    end
  end

  def full?
    if @board.flatten.all?(String)
      puts 'Draw!'
      true
    end
  end

  def choosing_player
    puts 'Choose for Player1(X or O)'
    loop do
      @player1 = gets.chomp!
      break if @player1 == 'X' || @player1 == 'O'

      puts 'Try Again!(X or O)'
    end
    puts "Player 1 is: #{@player1}"

    @player1 == 'X' ? @player2 = 'O' : @player2 = 'X'
    puts "Player 2 is: #{@player2}"
    print_board
  end

  def player1(player1)
    puts "Choice #{player1} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player1)
    print_board
  end

  def player2(player2)
    puts "Choice #{player2} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player2)
    print_board
  end

  def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

board = Board.new
board.game

If you want to live preview here is repl link


答:
If you want box-and-whiskers plots by regions, then that should be the x variable's value. And add position = position_dodge to the points layer.

Also, you don't need to explicitly coerce to factor when the variable (region) is of class character.

```<code>ggplot(dt, aes(x=region, y=norm_diameter, group = region, colour = region))+
  geom_point(position = position_dodge(width = 0.75)) +
  geom_boxplot(aes(fill = after_scale(alpha(colour, 0.4))))
</code>```

Title: Box plot representing the wrong aesthetics

Body:
I have the following data

structure(list(imaging_date = structure(c(19010, 19010, 19024,
19024, 19010, 19024, 19010, 19024, 19010, 19024, 19010, 19024,
19010, 19010, 19024, 19010, 19010, 19010, 19024, 19024, 19024,
19010, 19010, 19010, 19024, 19024, 19010, 19010, 19010, 19010,
19010, 19010, 19010, 19010, 19024, 19024), class = "Date"), diameter_on_mask = c(960L,
960L, 960L, 960L, 480L, 480L, 480L, 480L, 480L, 480L, 480L, 480L,
480L, 480L, 480L, 960L, 960L, 960L, 960L, 960L, 960L, 960L, 960L,
960L, 960L, 960L, 480L, 480L, 480L, 480L, 480L, 480L, 480L, 480L,
480L, 480L), diameter_measured = c(1020L, 1040L, 1210L, 1120L,
532L, 626L, 541L, 595L, 519L, 602L, 515L, 638L, 519L, 518L, 593L,
1030L, 989L, 999L, 1120L, 1140L, 1220L, 1000L, 1010L, 1010L,
1370L, 1290L, 519L, 511L, 505L, 522L, 502L, 501L, 536L, 532L,
686L, 754L), slideno_cno_region_id = c("3_1_1", "3_1_2", "3_1_1",
"3_1_2", "3_1_3", "3_1_3", "3_1_4", "3_1_4", "3_1_5", "3_1_5",
"3_1_6", "3_1_6", "", "", "", "", "", "", "", "", "", "3_1_7",
"", "", "3_1_7", "", "", "", "", "", "", "", "", "", "", ""),
    region = c("inlet", "inlet", "inlet", "inlet", "inlet", "inlet",
    "inlet", "inlet", "inlet", "inlet", "inlet", "inlet", "inlet",
    "inlet", "inlet", "middle", "middle", "middle", "middle",
    "middle", "middle", "outlet", "outlet", "outlet", "outlet",
    "outlet", "outlet", "outlet", "outlet", "outlet", "outlet",
    "outlet", "outlet", "outlet", "outlet", "outlet"), norm_diameter = c(1.0625,
    1.08333333333333, 1.26041666666667, 1.16666666666667, 1.10833333333333,
    1.30416666666667, 1.12708333333333, 1.23958333333333, 1.08125,
    1.25416666666667, 1.07291666666667, 1.32916666666667, 1.08125,
    1.07916666666667, 1.23541666666667, 1.07291666666667, 1.03020833333333,
    1.040625, 1.16666666666667, 1.1875, 1.27083333333333, 1.04166666666667,
    1.05208333333333, 1.05208333333333, 1.42708333333333, 1.34375,
    1.08125, 1.06458333333333, 1.05208333333333, 1.0875, 1.04583333333333,
    1.04375, 1.11666666666667, 1.10833333333333, 1.42916666666667,
    1.57083333333333)), row.names = c(NA, -36L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x7fc0c100d2e0>, index = structure(integer(0), "`__imaging_date`" = c(1L,
2L, 5L, 7L, 9L, 11L, 13L, 14L, 16L, 17L, 18L, 22L, 23L, 24L,
27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 3L, 4L, 6L, 8L, 10L,
12L, 15L, 19L, 20L, 21L, 25L, 26L, 35L, 36L)))

I want to plot tranparent boxplots under the actual data points. I did

ggplot(dt, aes(x=imaging_date, y=norm_diameter, colour = factor(region)))+
  geom_point()+
  geom_boxplot(aes(fill = after_scale(alpha(colour, 0.4))))

and got

First of all, I have data belonging to only 2 different days. Second of all, the location of the boxplots belong to neither of those dates. If I group the data inside with imaging_date, these problems disappear, but then they lose their colors.

What is wrong with my data/code?

Body:
If you want box-and-whiskers plots by regions, then that should be the x variable's value. And add position = position_dodge to the points layer.

Also, you don't need to explicitly coerce to factor when the variable (region) is of class character.

ggplot(dt, aes(x=region, y=norm_diameter, group = region, colour = region))+
  geom_point(position = position_dodge(width = 0.75)) +
  geom_boxplot(aes(fill = after_scale(alpha(colour, 0.4))))


问:
Sql Server 2005 using count and distinct together
I'm trying to get the count of each distinct field in my database. For example, we are using something called sourceCodes - I want to be able to see how many of each different sourceCode there is in my database. So far, I have this

```<code>SELECT sourceCode, COUNT(DISTINCT sourceCode)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode
</code>```

(I'm trying to display the name of the sourceCode first, and then the count). So far though, the only thing I ever get in my second column is "1"...and I'm positive there are more than one. I know I worded this question really poorly, but I can't really figure out any other way to say it. Can anybody see why this is happening?

答:
The "distinct" in your sample is not being applied at the correct place. By grouping by SourceCode, you are already getting distinct values from that column.

So, you only need to count the rows in each group:

```<code>SELECT sourceCode, COUNT(*)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode
</code>```

Body:
I'm trying to get the count of each distinct field in my database. For example, we are using something called sourceCodes - I want to be able to see how many of each different sourceCode there is in my database. So far, I have this

SELECT sourceCode, COUNT(DISTINCT sourceCode)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode

(I'm trying to display the name of the sourceCode first, and then the count). So far though, the only thing I ever get in my second column is "1"...and I'm positive there are more than one. I know I worded this question really poorly, but I can't really figure out any other way to say it. Can anybody see why this is happening?

Body:
The "distinct" in your sample is not being applied at the correct place. By grouping by SourceCode, you are already getting distinct values from that column.

So, you only need to count the rows in each group:

SELECT sourceCode, COUNT(*)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode


问:
Power Q: how to add conditional col and split based on length if another col contains text of same col
In power Q: creating a custom col based on condition:
If col A contains text of col b then split col A starting at the position of the length of ColumB

example: col A is MyMothersBasement123 and col B is MyMothersBase
col c would =  ment123

Somthing along the lines of :
 if Text.Contains([ColumnA], [ColumnB]) then SplitTextByPositions({length of ColumB}) else [ColumnA]

答:
You could also try

```<code>Text.AfterDelimiter([Column1], [Column2])
</code>```

as long as [Column2] isn't blank.

You can use try ... otherwise to cover that situation.

```<code>try Text.AfterDelimiter([Column1], [Column2]) otherwise ""
</code>```

Body:
You could also try

Text.AfterDelimiter([Column1], [Column2])

as long as [Column2] isn't blank.

You can use try ... otherwise to cover that situation.

try Text.AfterDelimiter([Column1], [Column2]) otherwise ""


问:
How do i make my player follow my finger when i start to pull it
im trying to make a 2D maze game, its simple but i need to make the player follow my finger at screen, i just made the player go and follow my finger to where i put my finger on screen, but i just want it to start following only when i'm with my finger over the player but it just doesn't works.

I'm using this script atm but isn't working as i want :X

```<code>void Update() {
        if(Input.GetMouseButton(0)) {
            Vector3 pos = Input.mousePosition;
            pos.z = distanceFromCamera;
            pos= cam.ScreenToWorldPoint(pos);
            rb.velocity = (pos-square.position)*velocity;
        }
        if(Input.GetMouseButtonUp(0)) {
            rb.velocity = Vector3.zero;
        }
}
</code>```

Tried now this script:

```<code> using UnityEngine;
 using System.Collections;

[RequireComponent(typeof(MeshCollider))]

public class DraggingObject : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;

    void OnMouseDown() {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag() {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }

}
</code>```

It drags like i want, but when i need to make a collision it doesn't work, just pass like no collision has been added to the game.

答:
I'd just use IDragHandler to make this easy:

```<code>public class FollowFinger : MonoBehaviour, IDragHandler
{
    // ...

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos = eventData.position
        pos.z = distanceFromCamera;
        pos= cam.ScreenToWorldPoint(pos);
        rb.velocity = (pos-square.position)*velocity;
    }
}
</code>```

You might need to add a Physics2DRaycaster to your camera (or PhysicsRaycaster if you're using 3d).

You might also want to make the collider (whatever kind that is appropriate) for your player a bit larger than they appear so the player can drag their finger further away.

See here for more guidance.

Body:
im trying to make a 2D maze game, its simple but i need to make the player follow my finger at screen, i just made the player go and follow my finger to where i put my finger on screen, but i just want it to start following only when i'm with my finger over the player but it just doesn't works.

I'm using this script atm but isn't working as i want :X

void Update() {
        if(Input.GetMouseButton(0)) {
            Vector3 pos = Input.mousePosition;
            pos.z = distanceFromCamera;
            pos= cam.ScreenToWorldPoint(pos);
            rb.velocity = (pos-square.position)*velocity;
        }
        if(Input.GetMouseButtonUp(0)) {
            rb.velocity = Vector3.zero;
        }
}

Tried now this script:

 using UnityEngine;
 using System.Collections;

[RequireComponent(typeof(MeshCollider))]

public class DraggingObject : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;

    void OnMouseDown() {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag() {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }

}

It drags like i want, but when i need to make a collision it doesn't work, just pass like no collision has been added to the game.

Body:
I'd just use IDragHandler to make this easy:

public class FollowFinger : MonoBehaviour, IDragHandler
{
    // ...

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos = eventData.position
        pos.z = distanceFromCamera;
        pos= cam.ScreenToWorldPoint(pos);
        rb.velocity = (pos-square.position)*velocity;
    }
}

You might need to add a Physics2DRaycaster to your camera (or PhysicsRaycaster if you're using 3d).

You might also want to make the collider (whatever kind that is appropriate) for your player a bit larger than they appear so the player can drag their finger further away.

See here for more guidance.


问:
Setup NetSuite Non-Inventory Item with Avatax
The NetSuite Non-Inventory item form doesn't seem to have a tax code field for me to populate with the “AVATAX” tax code. Does anyone have experience setting this up and could provide guidance on how to properly do this? My desired outcome is that when entering a transaction (Sales Order or Invoice) the tax code would auto-populate with "AVATAX."</p>

答: The custom item field is "AvaTax Tax Code" (custitem_ava_taxcode); installed by the AvaTax bundle and should create an AvaTax subtab on the non-inventory item form.


问:
TypeError: Cannot convert undefined or null to object - Typescript & Next.js
photo of error

I'm trying to render a button that will allow me to have login functionality. I am using Typescript and NextAuth. I have added a file for auth typings to try and solve the problem but for some reason, I am not able to use Object here with these map parameters.

At this instance, I have places the provider type as any. There's no error in the code editor but on the DOM, the type error still persists.

```<code>import { getProviders, signIn } from 'next-auth/react'
function Login({ providers }) {
return (
<div>
    <img className='w-52 mb-5' src="https://links.papareact.com/9xl" alt="Spotify logo at sign-in" />

    {Object.values(providers).map((provider:any) => (
        <div key={provider.name}>
            <button>Login with {provider.name}</button>
        </div>
    ))}
</div>
);
}

export default Login;

export async function getServerSideProps() {
const providers = await getProviders();

return {
    props: {
        providers,
    },
};
}
</code>```

At this instance, I removed the type for provider and the code editor yields an error for provider.name that states "Property 'name' does not exist on type 'unknown'."

```<code>import { getProviders, signIn } from 'next-auth/react'
function Login({ providers }) {
return (
<div>
    <img className='w-52 mb-5' src="https://links.papareact.com/9xl" alt="Spotify logo at sign-in" />

    {Object.values(providers).map((provider) => (
        <div key={provider.name}>
            <button>Login with {provider.name}</button>
        </div>
    ))}
</div>
);
}

export default Login;

export async function getServerSideProps() {
const providers = await getProviders();

return {
    props: {
        providers,
    },
};
}
</code>```

Here's my typings file:

```<code>export interface Providers {
provider: string;
name: string;
_id: string;
}
</code>```

I have tried a few things to try and solve the error. I am new to Typescript and this is my first time using NextAuth so any help would be greatly appreciated!

Thanks!

答:
looks like you can use next's built in InferGetServerSideProps to infer the types from next-auth and save yourself some work.

Check out this example:

import { getProviders, signIn } from 'next-auth/react'
import { InferGetServerSidePropsType } from 'next'

export default function SignIn({
  providers,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <>
      {Object.values(providers).map((provider) => (

          <button onClick={() => signIn(provider.id)}>
            Sign in with {provider.name}
          </button>

      ))}
    </>
  )
}

export const getServerSideProps = async () => {
  return {
    props: {
      providers: await getProviders(),
    },
  }
}
```

Since NextAuth.js is written in Typescript, it can automatically infer the types based off the return value of getProviders()

Body:
photo of error

I'm trying to render a button that will allow me to have login functionality. I am using Typescript and NextAuth. I have added a file for auth typings to try and solve the problem but for some reason, I am not able to use Object here with these map parameters.

At this instance, I have places the provider type as any. There's no error in the code editor but on the DOM, the type error still persists.

import { getProviders, signIn } from 'next-auth/react'
function Login({ providers }) {
return (

    {Object.values(providers).map((provider:any) => (

            <button>Login with {provider.name}</button>

    ))}

);
}

export default Login;

export async function getServerSideProps() {
const providers = await getProviders();

return {
    props: {
        providers,
    },
};
}

At this instance, I removed the type for provider and the code editor yields an error for provider.name that states "Property 'name' does not exist on type 'unknown'."

import { getProviders, signIn } from 'next-auth/react'
function Login({ providers }) {
return (

    {Object.values(providers).map((provider) => (

            <button>Login with {provider.name}</button>

    ))}

);
}

export default Login;

export async function getServerSideProps() {
const providers = await getProviders();

return {
    props: {
        providers,
    },
};
}

Here's my typings file:

export interface Providers {
provider: string;
name: string;
_id: string;
}

I have tried a few things to try and solve the error. I am new to Typescript and this is my first time using NextAuth so any help would be greatly appreciated!

Thanks!

Body:
looks like you can use next's built in InferGetServerSideProps to infer the types from next-auth and save yourself some work.

Check out this example:

import { getProviders, signIn } from 'next-auth/react'
import { InferGetServerSidePropsType } from 'next'

export default function SignIn({
  providers,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <>
      {Object.values(providers).map((provider) => (
        <div key={provider.name}>
          <button onClick={() => signIn(provider.id)}>
            Sign in with {provider.name}
          </button>
        </div>
      ))}
    </>
  )
}

export const getServerSideProps = async () => {
  return {
    props: {
      providers: await getProviders(),
    },
  }
}

Since NextAuth.js is written in Typescript, it can automatically infer the types based off the return value of getProviders()


问:
FAcebook like button -the meaning of the number near it

What makes up the number shown on my Like button? The number shown is
  the sum of:

•The number of likes of this URL

  •The number of shares of this URL
  (this includes copy/pasting a link back to Facebook)

  •The number of
  likes and comments on stories on Facebook about this URL

  •The number
  of inbox messages containing this URL as an attachment.

Ok, now if user A likes something, and then user A shares the URL, will I have 2 likes displayed near the button? Or each user can only be counted once

Thanks, I try to understand this because I need to write an app around it

答:
Facebook have a pretty good guide and API for this if you do want to make use of it.
http://developers.facebook.com/docs/reference/plugins/like/

As far as the process goes, this explanation is better than anything I could come up with. But the long and short of it is, the more people who click on it independently, the more it will increment (See below). Therefore in your example user A likes it (+1), he shares it but only when his friend clicks like when it increment again.

http://www.adsforfacebook.com/the-facebook-like-button.php


问:
p5.js draw a rectangle at cursor position on mouse click
I have a very simple 9x9 grid. I know how to handle the rectangles on this grid. What I want is when I click on one of the grid rectangles, this rectangle should now be marked with a fill or border around it.

I can draw a rectangle, with a blue fill at exact the correct rectangle on the grid.

But with the next click on the grid, the new rectangle is drawn but the old rectangle is still there and will stay there. And so on.

My question is now, how can I paint always exact on rectangle at the click position?

Is maybe a class the right way?

Creating every time a new rectangle and destroy the old one?

var nullx = 140;
var nully = 50;

var breite = 65;
var hoehe = 65;

var pressed = false;

function setup() {
  createCanvas(800, 1200);
}

function draw() {
  //background(220);
  noFill();
  //strokeWeight(2);

  sudokulines();
  numberstorect();
  if(pressed == true){
    sqMark();
  }

  if (mousePressed == true){
    console.log("click...")
    sqMark();
  }
}

function mousePressed(){
  pressed = true;
}

function sqMark(){
  var tempX;
  var tempY;
  //console.log(tempX,tempY);
  tempX = (floor((mouseX - nullx) / breite) * breite) + nullx;
  tempY = (floor((mouseY - nully) / hoehe) * hoehe) + nully;
  console.log(tempX,tempY);
  if (tempX > 139 && tempY > 49 ){
    if (tempX < 661 && tempY < 571){
      strokeWeight(0.7);
      fill(0,0,255);
      rect(tempX+2,tempY+2,breite-4,hoehe-4);
      pressed = false;
    }
  }
}

function sudokulines(){
  //The vertical lines
  for (var i = 1; i <= 8; i++){
    if (i == 3 || i == 6){
      strokeWeight(3);
    }else{
      strokeWeight(1);
    }
    line(nullx + breite * i, nully, nullx + breite * i, nully+ 9*hoehe);
  }
  //The horizontal lines
  for (var i = 1; i <= 8; i++){
    if (i == 3 || i == 6){
        strokeWeight(3);
      }else{
        strokeWeight(1);
      }
    //The big rectangle around
    line(nullx , nully + hoehe * i, nullx + 9*breite, nully + hoehe * i);
  }

  strokeWeight(3);
  rect(nullx,nully,9*breite,9*hoehe);
}

function numberstorect(){
  textAlign(CENTER,CENTER);
  fill(0);
  textSize(breite/1.3);
  text(2,nullx + breite/2, nully + hoehe/2);
}
```

答:
It's important to understand that p5.js draws in immediate mode, so each element, once drawn, is not removable unless intentionally drawn over or cleared. This simplest solution to your specific problem is to simply save to location to be highlighted when the user presses the mouse, and then always clear the canvas and redraw everything (including the selected square) in the draw function. Because there's no animation, you can optimize this by disabling looping in your setup function, and then explicitly calling redraw when something happens that effects the display (i.e. the mouse is pressed).

var nullx = 140;
var nully = 50;

var breite = 65;
var hoehe = 65;

let selectedX = -1;
let selectedY = -1;

function setup() {
  createCanvas(800, 1200);
  // By default don't re draw every frame
  noLoop();
}

function draw() {
  background(255);
  noFill();
  //strokeWeight(2);

  sudokulines();
  numberstorect();
  sqMark();
}

function mousePressed() {
  // Set the selection
  selectedX = (floor((mouseX - nullx) / breite) * breite) + nullx;
  selectedY = (floor((mouseY - nully) / hoehe) * hoehe) + nully;
  // Only redraw when something changes.
  redraw();
}

function sqMark() {
  if (selectedX > 139 && selectedY > 49) {
    if (selectedX < 661 && selectedY < 571) {
      strokeWeight(0.7);
      fill(0, 0, 255);
      rect(selectedX + 2, selectedY + 2, breite - 4, hoehe - 4);
      pressed = false;
    }
  }
}

function sudokulines() {
  //The vertical lines
  for (var i = 1; i <= 8; i++) {
    if (i == 3 || i == 6) {
      strokeWeight(3);
    } else {
      strokeWeight(1);
    }
    line(nullx + breite * i, nully, nullx + breite * i, nully + 9 * hoehe);
  }
  //The horizontal lines
  for (var i = 1; i <= 8; i++) {
    if (i == 3 || i == 6) {
      strokeWeight(3);
    } else {
      strokeWeight(1);
    }
    //The big rectangle around
    line(nullx, nully + hoehe * i, nullx + 9 * breite, nully + hoehe * i);
  }

  strokeWeight(3);
  rect(nullx, nully, 9 * breite, 9 * hoehe);
}

function numberstorect() {
  textAlign(CENTER, CENTER);
  fill(0);
  textSize(breite / 1.3);
  text(2, nullx + breite / 2, nully + hoehe / 2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script></code>```

Body:
It's important to understand that p5.js draws in immediate mode, so each element, once drawn, is not removable unless intentionally drawn over or cleared. This simplest solution to your specific problem is to simply save to location to be highlighted when the user presses the mouse, and then always clear the canvas and redraw everything (including the selected square) in the draw function. Because there's no animation, you can optimize this by disabling looping in your setup function, and then explicitly calling redraw when something happens that effects the display (i.e. the mouse is pressed).

var nullx = 140;
var nully = 50;

var breite = 65;
var hoehe = 65;

let selectedX = -1;
let selectedY = -1;

function setup() {
  createCanvas(800, 1200);
  // By default don't re draw every frame
  noLoop();
}

function draw() {
  background(255);
  noFill();
  //strokeWeight(2);

  sudokulines();
  numberstorect();
  sqMark();
}

function mousePressed() {
  // Set the selection
  selectedX = (floor((mouseX - nullx) / breite) * breite) + nullx;
  selectedY = (floor((mouseY - nully) / hoehe) * hoehe) + nully;
  // Only redraw when something changes.
  redraw();
}

function sqMark() {
  if (selectedX > 139 && selectedY > 49) {
    if (selectedX < 661 && selectedY < 571) {
      strokeWeight(0.7);
      fill(0, 0, 255);
      rect(selectedX + 2, selectedY + 2, breite - 4, hoehe - 4);
      pressed = false;
    }
  }
}

function sudokulines() {
  //The vertical lines
  for (var i = 1; i <= 8; i++) {
    if (i == 3 || i == 6) {
      strokeWeight(3);
    } else {
      strokeWeight(1);
    }
    line(nullx + breite * i, nully, nullx + breite * i, nully + 9 * hoehe);
  }
  //The horizontal lines
  for (var i = 1; i <= 8; i++) {
    if (i == 3 || i == 6) {
      strokeWeight(3);
    } else {
      strokeWeight(1);
    }
    //The big rectangle around
    line(nullx, nully + hoehe * i, nullx + 9 * breite, nully + hoehe * i);
  }

  strokeWeight(3);
  rect(nullx, nully, 9 * breite, 9 * hoehe);
}

function numberstorect() {
  textAlign(CENTER, CENTER);
  fill(0);
  textSize(breite / 1.3);
  text(2, nullx + breite / 2, nully + hoehe / 2);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>


问:
How to implement Javascript async/await/promise in both of AsyncStorage and Json.parse?
Everyone, Here is my dirty code.

```<code>const parseJson = async value => {
  try{
    const parsedData = await JSON.parse(value);
    console.log('2', parsedData);
    return parsedData;
  }catch(e){}
}

const getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){}
}

useEffect(() => {
  const authStateData = getAuthStateData();
  console.log('3', authStateData);
}, [])
</code>```

Expected console state order is

```<code>1, 2, 3
</code>```

Real console state order is

```<code>3, 1, 2
</code>```

The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms.
so I need to wait all of them. This is basic of javascript concept: async, sync, promise.
Please help me, seniors!

答:
The main issue is the missing await before getAuthStateData(), but you're missing some dependencies and cleanup as well. See inline comments:

```<code>const parseJson = (value) => { //not async -- see next comment
  try{
    const parsedData = JSON.parse(value); //JSON.parse is not an async method, so there's no reason to await here
    console.log('2', parsedData);
    return parsedData;
  }catch(e){
    console.error(e);
  }
}

const _getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){
    console.error(e);
  }
}

//get a memoized version of the callback
const getAuthStateData = React.useCallback(_getAuthStateData,[])

useEffect(() => {
  async function asyncFunc() {
    const authStateData = await getAuthStateData();
    console.log('3', authStateData);
  }
  asyncFunc(); //prevent a linter error about using an `async` function directly inside `useEffect` by wrapping an async function and calling it
},[getAuthStateData]) //because we use getAuthStateData, it should be a dependency -- that's why we memoized it above
</code>```

Body:
Everyone, Here is my dirty code.

const parseJson = async value => {
  try{
    const parsedData = await JSON.parse(value);
    console.log('2', parsedData);
    return parsedData;
  }catch(e){}
}

const getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){}
}

useEffect(() => {
  const authStateData = getAuthStateData();
  console.log('3', authStateData);
}, [])

Expected console state order is

1, 2, 3

Real console state order is

3, 1, 2

The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms.
so I need to wait all of them. This is basic of javascript concept: async, sync, promise.
Please help me, seniors!

Body:
The main issue is the missing await before getAuthStateData(), but you're missing some dependencies and cleanup as well. See inline comments:

const parseJson = (value) => { //not async -- see next comment
  try{
    const parsedData = JSON.parse(value); //JSON.parse is not an async method, so there's no reason to await here
    console.log('2', parsedData);
    return parsedData;
  }catch(e){
    console.error(e);
  }
}

const _getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){
    console.error(e);
  }
}

//get a memoized version of the callback
const getAuthStateData = React.useCallback(_getAuthStateData,[])

useEffect(() => {
  async function asyncFunc() {
    const authStateData = await getAuthStateData();
    console.log('3', authStateData);
  }
  asyncFunc(); //prevent a linter error about using an `async` function directly inside `useEffect` by wrapping an async function and calling it
},[getAuthStateData]) //because we use getAuthStateData, it should be a dependency -- that's why we memoized it above


问:
SwiftUI clean up ContentView
I'm trying to simplify the ContentView within a project and I'm struggling to understand how to move @State based logic into its own file and have ContentView adapt to any changes. Currently I have dynamic views that display themselves based on @Binding actions which I'm passing the $binding down the view hierarchy to have buttons toggle the bool values.

Here's my current attempt. I'm not sure how in SwiftUI to change the view state of SheetPresenter from a nested view without passing the $binding all the way down the view stack. Ideally I'd like it to look like ContentView.overlay(sheetPresenter($isOpen, $present).

Also, I'm learning SwiftUI so if this isn't the best approach please provide guidance.

```<code>class SheetPresenter: ObservableObject {

@Published var present: Present = .none
@State var isOpen: Bool = false

enum Present {
    case none, login, register
}

@ViewBuilder
func makeView(with presenter: Present) -> some View {
    switch presenter {
    case .none:
        EmptyView()
    case .login:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            LoginScreen()
        }
    case .register:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            RegisterScreen()
        }
    }
}
</code>```

}

答:
You are correct this is not the best approach, however it is a common mistake. In SwiftUI we actually use @State for transient data owned by the view. This means using a value type like a struct, not classes. This is explained at 4:18 in Data Essentials in SwiftUI from WWDC 2020.

EditorConfig can maintain invariants on its properties and be tested
independently. And because EditorConfig is a value type, any change to
a property of EditorConfig, like its progress, is visible as a change
to EditorConfig itself.

```<code>struct EditorConfig {
    var isEditorPresented = false
    var note = ""
    var progress: Double = 0
    mutating func present(initialProgress: Double) {
        progress = initialProgress
        note = ""
        isEditorPresented = true
    }
}
struct BookView: View {
    @State private var editorConfig = EditorConfig()
    func presentEditor() { editorConfig.present(…) }
    var body: some View {
        …
        Button(action: presentEditor) { … }
        …
    }
}
</code>```

Then you just use $editorConfig.isEditorPresented as the boolean binding in .sheet or .overlay.

Worth also taking a look at sheet(item:onDismiss:content:) which makes it much simpler to show an item because no boolean is required it uses an optional @State which you can set to nil to dismiss.

Title: SwiftUI clean up ContentView

Body:
I'm trying to simplify the ContentView within a project and I'm struggling to understand how to move @State based logic into its own file and have ContentView adapt to any changes. Currently I have dynamic views that display themselves based on @Binding actions which I'm passing the $binding down the view hierarchy to have buttons toggle the bool values.

Here's my current attempt. I'm not sure how in SwiftUI to change the view state of SheetPresenter from a nested view without passing the $binding all the way down the view stack. Ideally I'd like it to look like ContentView.overlay(sheetPresenter($isOpen, $present).

Also, I'm learning SwiftUI so if this isn't the best approach please provide guidance.

class SheetPresenter: ObservableObject {

@Published var present: Present = .none
@State var isOpen: Bool = false

enum Present {
    case none, login, register
}

@ViewBuilder
func makeView(with presenter: Present) -> some View {
    switch presenter {
    case .none:
        EmptyView()
    case .login:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            LoginScreen()
        }
    case .register:
        BottomSheetView(isOpen: $isOpen, maxHeight: UIConfig.Utils.screenHeight * 0.75) {
            RegisterScreen()
        }
    }
}

}

Body:
You are correct this is not the best approach, however it is a common mistake. In SwiftUI we actually use @State for transient data owned by the view. This means using a value type like a struct, not classes. This is explained at 4:18 in Data Essentials in SwiftUI from WWDC 2020.

EditorConfig can maintain invariants on its properties and be tested
independently. And because EditorConfig is a value type, any change to
a property of EditorConfig, like its progress, is visible as a change
to EditorConfig itself.

struct EditorConfig {
    var isEditorPresented = false
    var note = ""
    var progress: Double = 0
    mutating func present(initialProgress: Double) {
        progress = initialProgress
        note = ""
        isEditorPresented = true
    }
}
struct BookView: View {
    @State private var editorConfig = EditorConfig()
    func presentEditor() { editorConfig.present(…) }
    var body: some View {
        …
        Button(action: presentEditor) { … }
        …
    }
}

Then you just use $editorConfig.isEditorPresented as the boolean binding in .sheet or .overlay.

Worth also taking a look at sheet(item:onDismiss:content:) which makes it much simpler to show an item because no boolean is required it uses an optional @State which you can set to nil to dismiss.


问:
Alternating lines with Nested Loops
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

```<code>##########
**********
##########
**********
##########
</code>```

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

```<code>for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")
</code>```

答:
Since no input is specified, only a fixed output:

```<code>for _ in '_':
    for _ in '_':
        print('''##########
**********
##########
**********
##########''')
</code>```

And yes, if that was my homework exercise, I'd absolutely submit this.

Title: Alternating lines with Nested Loops

Body:
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

##########
**********
##########
**********
##########

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")

Body:
Since no input is specified, only a fixed output:

for _ in '_':
    for _ in '_':
        print('''##########
**********
##########
**********
##########''')

And yes, if that was my homework exercise, I'd absolutely submit this.


问:
How can I split a String and keep the delimiters in Swift?
I am new to Swift, I come from Java background. I want to make a struct for parsing input for a calculator. Here is my code

```<code>struct Parse {
    var runningCalc: String

    init(runningCalc: String) {
        self.runningCalc = runningCalc
    }

    mutating func toArray(String: runningCalc){
        runningCalc = runningCalc.split()
    }
}
</code>```

I want to have input of a string, and have it return a string Array with delimiters of
{ +-/*()%}.

In java you could do a string tokenizer to keep the delimiters in the returned string array.

How can I use the split or components method to separate my string input to a string array?

答:
I personally wouldn't use a struct. It's more common to extend an existing type with additional functionality. So, you want the components of a String that includes delimiters? Sounds like you want to extend String. Since String conforms to StringProtocol I'd extend StringProtocol so that any other types that conform to StringProtocol get this new functionality for free:

StringProtocol already has a method called components(separatedBy:) which takes a CharacterSet (a set of characters) to delimit the receiver.

Let's implement a method similar to the existing StringProtocol method.

```<code>extension StringProtocol {
    func components(separatedByIncluding delims: CharacterSet) -> [String] {
        var components: [String] = []
        var component = ""

        for character in self {
            if String(character).rangeOfCharacter(from: delims) != nil {
                if !component.isEmpty {
                    components.append(component)
                }
                components.append(String(character))
                component = ""
            } else {
                component += [character]
            }
        }
        if !component.isEmpty {
            components.append(component)
        }

        return components
    }
}
</code>```

The method loops over each Character and checks if it's a delimiter. If so, it adds a new String to the array consisting of the delimiter Character. If not, it constructs a substring consisting of non-delimiter Character values. The resulting array of delimiters and substrings are then returned.

Usage would be:

```<code>func testExample() throws {
    let delims = CharacterSet(charactersIn: "{ +-/*()%}")
    let text = "{abc def+ghi-jkl/mno"

    let components = text.components(separatedByIncluding: delims)

    print("================")
    print(components)
    print("================")
}
</code>```

The result is:

```<code>================
["{", "abc", " ", "def", "+", "ghi", "-", "jkl", "/", "mno"]
================
</code>```

Body:
I am new to Swift, I come from Java background. I want to make a struct for parsing input for a calculator. Here is my code

struct Parse {
    var runningCalc: String

    init(runningCalc: String) {
        self.runningCalc = runningCalc
    }

    mutating func toArray(String: runningCalc){
        runningCalc = runningCalc.split()
    }
}

I want to have input of a string, and have it return a string Array with delimiters of
{ +-/*()%}.

In java you could do a string tokenizer to keep the delimiters in the returned string array.

How can I use the split or components method to separate my string input to a string array?

Body:
I personally wouldn't use a struct. It's more common to extend an existing type with additional functionality. So, you want the components of a String that includes delimiters? Sounds like you want to extend String. Since String conforms to StringProtocol I'd extend StringProtocol so that any other types that conform to StringProtocol get this new functionality for free:

StringProtocol already has a method called components(separatedBy:) which takes a CharacterSet (a set of characters) to delimit the receiver.

Let's implement a method similar to the existing StringProtocol method.

extension StringProtocol {
    func components(separatedByIncluding delims: CharacterSet) -> [String] {
        var components: [String] = []
        var component = ""

        for character in self {
            if String(character).rangeOfCharacter(from: delims) != nil {
                if !component.isEmpty {
                    components.append(component)
                }
                components.append(String(character))
                component = ""
            } else {
                component += [character]
            }
        }
        if !component.isEmpty {
            components.append(component)
        }

        return components
    }
}

The method loops over each Character and checks if it's a delimiter. If so, it adds a new String to the array consisting of the delimiter Character. If not, it constructs a substring consisting of non-delimiter Character values. The resulting array of delimiters and substrings are then returned.

Usage would be:

func testExample() throws {
    let delims = CharacterSet(charactersIn: "{ +-/*()%}")
    let text = "{abc def+ghi-jkl/mno"

    let components = text.components(separatedByIncluding: delims)

    print("================")
    print(components)
    print("================")
}

The result is:

================
["{", "abc", " ", "def", "+", "ghi", "-", "jkl", "/", "mno"]
================


问:
Numba apply mapping to ndarray
Very simple question, which I have looked for but haven't found a clear answer. I would like to efficiently apply a mapping to an input ndarray, remapping each element in the array and returning the modified array.

A simple version using numpy would be something like:

def remap(a, mapping):
    return np.vectorize(mapping.__getitem__)(a)
```

I am pretty sure I can't use Numba vectorize but was hoping to be able to use guvectorize. But it looks like I can't pass a Numba TypedDict into a guvectorize function either. Any suggestions welcome

答:
If you know the number of dimentions of the target array, then you just need a simple loop. AFAIK, guvectorize does not support this use-case yet. However, you can solve this using a simple reshape.

import numba as nb

@nb.njit
def remap(a, mapping):
    # Linearize the array (can cause a copy of `a`)
    b = a.reshape(-1)

    for i in range(b.size):
        b[i] = mapping[b[i]]

    return b.reshape(a.shape)
```

Note that the first reshape can cause a copy of a if a is not contiguously store in memory and Numpy cannot find a unified stride in 1D. Thus, the returned array may be a copy of a. The second reshape is guaranteed not to copy the array. If you want to always return a copy of the input array (no mutation) like most Numpy function, then you can use flatten instead of the first reshape call.

Title: Numba apply mapping to ndarray

Body:
Very simple question, which I have looked for but haven't found a clear answer. I would like to efficiently apply a mapping to an input ndarray, remapping each element in the array and returning the modified array.

A simple version using numpy would be something like:

def remap(a, mapping):
    return np.vectorize(mapping.__getitem__)(a)

I am pretty sure I can't use Numba vectorize but was hoping to be able to use guvectorize. But it looks like I can't pass a Numba TypedDict into a guvectorize function either. Any suggestions welcome

Body:
If you know the number of dimentions of the target array, then you just need a simple loop. AFAIK, guvectorize does not support this use-case yet. However, you can solve this using a simple reshape.

import numba as nb

@nb.njit
def remap(a, mapping):
    # Linearize the array (can cause a copy of `a`)
    b = a.reshape(-1)

    for i in range(b.size):
        b[i] = mapping[b[i]]

    return b.reshape(a.shape)

Note that the first reshape can cause a copy of a if a is not contiguously store in memory and Numpy cannot find a unified stride in 1D. Thus, the returned array may be a copy of a. The second reshape is guaranteed not to copy the array. If you want to always return a copy of the input array (no mutation) like most Numpy function, then you can use flatten instead of the first reshape call.


问:
.Net5 Azure Function | Azure.Messaging.ServiceBus
I am implementing a scenario where I have created Azure ServiceBus singleton client in Azure Function (v3, .net v5). Within my Azure function code, I am creating ServiceBusMessageBatch and then I'm trying to add some messages in the batch and finally a Task into List<Task> but as soon as I start my azure function (or after 1-2 runs) I'm starting to get Error: System.InvalidOperationException: The message batch is currently being used in communication with the Service Bus service; messages may not be added until the active operation is complete. Error.

Below is my code

```<code>int batchSize = int.Parse(configuration["batchSize"]) > 0 ? int.Parse(configuration["batchSize"]) : 1;
var SBSender = serviceBusClient.CreateSender(configuration["QueueName"]);
using ServiceBusMessageBatch messageBatch = await SBSender.CreateMessageBatchAsync();
List<Task> addQueues = new();
try
{
    if (MyMessages.Count > 0)
    {
        int messageIndex = 0;
        for (int count = 0; count < MyMessages.Count; count += batchSize)
        {;
            BatchMessage bMessage = new();

            for (; messageIndex < count + batchSize && messageIndex < MyMessagesCount; messageIndex += 1)
                bMessage.Add(MyMessages[messageIndex]);

            if (!messageBatch.TryAddMessage(new ServiceBusMessage(JsonConvert.SerializeObject(bMessage))))
                throw new Exception($"Message is too large");
        }
        addQueues.Add(SBSender.SendMessagesAsync(messageBatch));
    }
}
</code>```

I am using Azure.Messaging.ServiceBus (v7.6) instead of bindings is because Microsoft.Azure.Functions.Worker.Extensions.ServiceBus doesn't support native ServiceBus types.

答:
The error is the result of attempting to use the same ServiceBusMessageBatch instance for multiple calls to SendMessagesAsync.

The part of your code where you are doing so doesn't appear to be included, but you'll want to ensure that you're using only one sender instance and creating a new batch for each call to SendMessagesAsync.

Body:
I am implementing a scenario where I have created Azure ServiceBus singleton client in Azure Function (v3, .net v5). Within my Azure function code, I am creating ServiceBusMessageBatch and then I'm trying to add some messages in the batch and finally a Task into List<Task> but as soon as I start my azure function (or after 1-2 runs) I'm starting to get Error: System.InvalidOperationException: The message batch is currently being used in communication with the Service Bus service; messages may not be added until the active operation is complete. Error.

Below is my code

int batchSize = int.Parse(configuration["batchSize"]) > 0 ? int.Parse(configuration["batchSize"]) : 1;
var SBSender = serviceBusClient.CreateSender(configuration["QueueName"]);
using ServiceBusMessageBatch messageBatch = await SBSender.CreateMessageBatchAsync();
List<Task> addQueues = new();
try
{
    if (MyMessages.Count > 0)
    {
        int messageIndex = 0;
        for (int count = 0; count < MyMessages.Count; count += batchSize)
        {;
            BatchMessage bMessage = new();

            for (; messageIndex < count + batchSize && messageIndex < MyMessagesCount; messageIndex += 1)
                bMessage.Add(MyMessages[messageIndex]);

            if (!messageBatch.TryAddMessage(new ServiceBusMessage(JsonConvert.SerializeObject(bMessage))))
                throw new Exception($"Message is too large");
        }
        addQueues.Add(SBSender.SendMessagesAsync(messageBatch));
    }
}

I am using Azure.Messaging.ServiceBus (v7.6) instead of bindings is because Microsoft.Azure.Functions.Worker.Extensions.ServiceBus doesn't support native ServiceBus types.


问:
TMUX using HJKL to navigate panes
Standard TMUX is set to use ctrl-b + [up, down, left, right] when navigating between panes.

I would like to make it so that I can use ctrl-b (or the prefix of my choice) + [h,j,k,l].

I thought I had done this with the following vi key in my ~/.tmux.conf settings:

```<code>set -g status-keys vi
setw -g mode-keys vi
</code>```

Yet this didn't seem to change anything (at least not what I was looking for). How can I get this to work. And yes my .tmux.conf is working properly. I can provide more info if needed.

Update:

Here is my full .tmux.conf after trying to get it to work:

```<code>set -g status-keys vi
setw -g mode-keys vi

set -g prefix C-a
unbind C-b
bind C-a send-prefix

# smart pane switching with awareness of vim splits
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
</code>```

Alternatively, I have tried using this w/ vim-tmux-navigator Vim plugin:

```<code># smart pane switching with awareness of vim splits
bind -n C-h run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-h) || tmux select-pane -L"
bind -n C-j run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-j) || tmux select-pane -D"
bind -n C-k run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-k) || tmux select-pane -U"
bind -n C-l run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-l) || tmux select-pane -R"
bind -n C-\ run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys 'C-\\') || tmux select-pane -l"
</code>```

source

Which also doesn't work either. I am a bit stumped.

答:
If you are looking for a modal mode for tmux (e.g. like in Vim text editor), there is a plugin tmux-modal that can be used to execute complex commands with just a few keystrokes. For example:

w h to select the left pane

w j to select the pane below

w k to select the pane above

w l to select the right pane

There is also a sticky mode (w w) that enables h, j, k, l to select the panes as you want to, without a prefix key. Please see the repository for more information.

Title: TMUX using HJKL to navigate panes

Body:
Standard TMUX is set to use ctrl-b + [up, down, left, right] when navigating between panes.

I would like to make it so that I can use ctrl-b (or the prefix of my choice) + [h,j,k,l].

I thought I had done this with the following vi key in my ~/.tmux.conf settings:

set -g status-keys vi
setw -g mode-keys vi

Yet this didn't seem to change anything (at least not what I was looking for). How can I get this to work. And yes my .tmux.conf is working properly. I can provide more info if needed.

Update:

Here is my full .tmux.conf after trying to get it to work:

set -g status-keys vi
setw -g mode-keys vi

set -g prefix C-a
unbind C-b
bind C-a send-prefix

# smart pane switching with awareness of vim splits
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

Alternatively, I have tried using this w/ vim-tmux-navigator Vim plugin:

# smart pane switching with awareness of vim splits
bind -n C-h run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-h) || tmux select-pane -L"
bind -n C-j run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-j) || tmux select-pane -D"
bind -n C-k run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-k) || tmux select-pane -U"
bind -n C-l run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-l) || tmux select-pane -R"
bind -n C-\ run "(tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys 'C-\\') || tmux select-pane -l"

source

Which also doesn't work either. I am a bit stumped.


问:
extracting from specific class in beautiful soup
Im looking to extract the weight of the products alone from the following site, i almost made it but the extracted output is the collection of some more things so how can i filter out only the weight of the product.

source : https://www.tendercuts.in/chicken

here is the code i used :

```<code>   import requests
   from bs4 import BeautifulSoup

   baseurl = 'https://www.tendercuts.in/'

   r = requests.get('https://www.tendercuts.in/chicken')
   soup = BeautifulSoup(r.content, 'lxml')

   producweight = soup.find_all('span', class_='callout')

   print(productweight)
</code>```

OUTPUT I DESIRE :

```<code>  480 - 500 Gms
     ''''''''
        ''''''
      ''''''
     so on ...
</code>```

答:
To only get the weight, you can use the following CSS selector:

```<code>import requests
from bs4 import BeautifulSoup

baseurl = 'https://www.tendercuts.in/'

r = requests.get('https://www.tendercuts.in/chicken')
soup = BeautifulSoup(r.content, 'lxml')

for tag in soup.select(".weight > span span:nth-of-type(2), .col-8 span:nth-of-type(2)"):
    print(tag.next_sibling)
</code>```

Output:

```<code>Customizable
Customizable
Customizable
 480 - 500 Gms
 190 - 210 Gms
 480 - 500 Gms
 280 - 360 Gms
 ...
 ...
</code>```

Or to only get the fixed prices:

```<code>for tag in soup.select(".weight > span span:nth-of-type(2), .col-8 span:nth-of-type(2)"):
    if tag.next_sibling != "Customizable":
        print(tag.next_sibling)
</code>```

Body:
Im looking to extract the weight of the products alone from the following site, i almost made it but the extracted output is the collection of some more things so how can i filter out only the weight of the product.

source : https://www.tendercuts.in/chicken

here is the code i used :

   import requests
   from bs4 import BeautifulSoup

   baseurl = 'https://www.tendercuts.in/'

   r = requests.get('https://www.tendercuts.in/chicken')
   soup = BeautifulSoup(r.content, 'lxml')

   producweight = soup.find_all('span', class_='callout')

   print(productweight)

OUTPUT I DESIRE :

  480 - 500 Gms
     ''''''''
        ''''''
      ''''''
     so on ...

Body:
To only get the weight, you can use the following CSS selector:

import requests
from bs4 import BeautifulSoup

baseurl = 'https://www.tendercuts.in/'

r = requests.get('https://www.tendercuts.in/chicken')
soup = BeautifulSoup(r.content, 'lxml')

for tag in soup.select(".weight > span span:nth-of-type(2), .col-8 span:nth-of-type(2)"):
    print(tag.next_sibling)

Output:

Customizable
Customizable
Customizable
 480 - 500 Gms
 190 - 210 Gms
 480 - 500 Gms
 280 - 360 Gms
 ...
 ...

Or to only get the fixed prices:

for tag in soup.select(".weight > span span:nth-of-type(2), .col-8 span:nth-of-type(2)"):
    if tag.next_sibling != "Customizable":
        print(tag.next_sibling)


问:
Keeping forward slashes in cookie PHP
I am building a log in page.  Right now, there is an expiration on the page that I use a cookie for.  I want the site to redirect back to the page they were on after they log in again.

For this, I use a cookie that has the name of the page stored in it (example, queue.php) and it will take them back.

This method works great if I'm going to a page that is in the same directory, but if I want to go back to a sub-directory, (for example, Deployment/deployment.php) it does not work.

I have tried urlencode(), backslashes, addslashes(), %2F in place of the forward slash, and nothing seems to be working.

This is how I am setting the cookie:

```<code>$url_name = "Deployment/deployment.php";
setcookie("url",$url_name);
</code>```

Any help would be appreciated, I am completely lost.

答: Perhaps you could base64_encode() the value and then base64_decode it upon retrieval?  Just a though.  I don't know why the forward slash wouldn't be allowed, though.  Perhaps someone else will be able to enlighten me!

Title: Keeping forward slashes in cookie PHP

Body:
I am building a log in page.  Right now, there is an expiration on the page that I use a cookie for.  I want the site to redirect back to the page they were on after they log in again.

For this, I use a cookie that has the name of the page stored in it (example, queue.php) and it will take them back.

This method works great if I'm going to a page that is in the same directory, but if I want to go back to a sub-directory, (for example, Deployment/deployment.php) it does not work.

I have tried urlencode(), backslashes, addslashes(), %2F in place of the forward slash, and nothing seems to be working.

This is how I am setting the cookie:

$url_name = "Deployment/deployment.php";
setcookie("url",$url_name);

Any help would be appreciated, I am completely lost.


问:
Next auth refresh token strategy
Using next.js auth (next auth) I'm creating CredentialsProvider, trying to connect it to django backend. All is working good except refresh token strategy: after obtaining new access token, access token and expire date not saving. So next auth is sending refresh token every request.
I don't know why, but I can't update token data after "first time token created".

Here is the code:

async function refreshAccessToken(token) {
  console.log('UPDATE')
  const refresh = await axios
    .post('/token/refresh/', {
      refresh: token.refreshToken
    })
    .catch((error) => {
      console.log(error)
    })
  if (refresh && refresh.status === 200 && refresh.data.access) {
    return {
      ...token,
      accessToken: refresh.data.access,
      expiresAt: Date.now() + 10 * 1000
    }
  }
  return {
    ...token,
    error: 'RefreshAccessTokenError'
  }
}

export default NextAuth({
  providers: [
    CredentialsProvider({
      id: 'credentials',
      name: 'my-project',
      async authorize(credentials) {
        const auth = await axios
          .post('/token/', {
            username: credentials.username,
            password: credentials.password
          })
          .catch((error) => {
            console.log(error)
          })

        if (auth.status === 200 && auth.data.access) {
          const profile = await axios
            .get('/v1/profile/', {
              headers: {
                Authorization: `Bearer ${auth.data.access}`
              }
            })
            .catch((error) => {
              console.log(error)
            })
          if (profile.status === 200 && profile.data) {
            return {
              ...profile.data,
              tokens: auth.data
            }
          }
        }
        return null
      }
    })
  ],
  pages: {
    signIn: '/login'
  },
  callbacks: {
    jwt: async ({ token, user, account }) => {
      if (account && user) {
        return {
          // works normally
          accessToken: user.tokens.access,
          refreshToken: user.tokens.refresh,
          expiresAt: Date.now() + 10 * 1000,
          user
        }
      }

      if (Date.now() < token.expiresAt) {
        return token
      }

      // token is obtaining in refreshAccessToken but not saved...
      // next request refreshAccessToken will be called again...
      return refreshAccessToken(token)
    },
    session: async ({ session, token }) => {
      session.user = token.user
      session.token = token.accessToken
      return session
    }
  },
  debug: true
})

```
<p>Any help please.
Here is simplified example:</p>
<pre class="lang-js prettyprint-override"><code>    jwt: async ({ token, user, account }) => {
      console.log(token.expiresAt)
      // here token.expiresAt will NEVER be equals 'hey'
      if (account && user) {
        return {
          accessToken: user.tokens.access,
          refreshToken: user.tokens.refresh,
          expiresAt: Date.now() + 10 * 1000,
          user
        }
      }

      if (Date.now() < token.expiresAt) {
        return token
      }

      token.expiresAt = 'hey'

      return token
    }
</code>```

答:
I don't know if this will cover exactly your use-case, as I think its more geared towards the built-in OAuth providers, but theres a tutorial on their docs site for how to handle refresh tokens.

See: https://next-auth.js.org/tutorials/refresh-token-rotation

I've also implemented something similar in a simple project using NextAuth of mine, check it out here: https://github.com/ndom91/newtelco-tab/blob/3f4153c7aa94c7f6cfeeb3778be3cdb1ec6ee243/src/pages/api/auth/%5B...nextauth%5D.ts#L32

Title: Next auth refresh token strategy

Body:
Using next.js auth (next auth) I'm creating CredentialsProvider, trying to connect it to django backend. All is working good except refresh token strategy: after obtaining new access token, access token and expire date not saving. So next auth is sending refresh token every request.
I don't know why, but I can't update token data after "first time token created".

Here is the code:

async function refreshAccessToken(token) {
  console.log('UPDATE')
  const refresh = await axios
    .post('/token/refresh/', {
      refresh: token.refreshToken
    })
    .catch((error) => {
      console.log(error)
    })
  if (refresh && refresh.status === 200 && refresh.data.access) {
    return {
      ...token,
      accessToken: refresh.data.access,
      expiresAt: Date.now() + 10 * 1000
    }
  }
  return {
    ...token,
    error: 'RefreshAccessTokenError'
  }
}

export default NextAuth({
  providers: [
    CredentialsProvider({
      id: 'credentials',
      name: 'my-project',
      async authorize(credentials) {
        const auth = await axios
          .post('/token/', {
            username: credentials.username,
            password: credentials.password
          })
          .catch((error) => {
            console.log(error)
          })

        if (auth.status === 200 && auth.data.access) {
          const profile = await axios
            .get('/v1/profile/', {
              headers: {
                Authorization: `Bearer ${auth.data.access}`
              }
            })
            .catch((error) => {
              console.log(error)
            })
          if (profile.status === 200 && profile.data) {
            return {
              ...profile.data,
              tokens: auth.data
            }
          }
        }
        return null
      }
    })
  ],
  pages: {
    signIn: '/login'
  },
  callbacks: {
    jwt: async ({ token, user, account }) => {
      if (account && user) {
        return {
          // works normally
          accessToken: user.tokens.access,
          refreshToken: user.tokens.refresh,
          expiresAt: Date.now() + 10 * 1000,
          user
        }
      }

      if (Date.now() < token.expiresAt) {
        return token
      }

      // token is obtaining in refreshAccessToken but not saved...
      // next request refreshAccessToken will be called again...
      return refreshAccessToken(token)
    },
    session: async ({ session, token }) => {
      session.user = token.user
      session.token = token.accessToken
      return session
    }
  },
  debug: true
})

Any help please.
Here is simplified example:

    jwt: async ({ token, user, account }) => {
      console.log(token.expiresAt)
      // here token.expiresAt will NEVER be equals 'hey'
      if (account && user) {
        return {
          accessToken: user.tokens.access,
          refreshToken: user.tokens.refresh,
          expiresAt: Date.now() + 10 * 1000,
          user
        }
      }

      if (Date.now() < token.expiresAt) {
        return token
      }

      token.expiresAt = 'hey'

      return token
    }


问:
Serverless Flask API crashes when trying to consume multipart/form-data
I have a serverless api through sam that consists of aws::serverless:function's and using flask-lambda to consume requests. I have been able to consume normal rest requests but I have a use-case to take in 3 property values and multiple files so naturally I considered using form-data to do this.

Sample lambda below:

```<code>from flask import request, jsonify
from flask_lambda import FlaskLambda

app = FlaskLambda(__name__)

@app.route('/kits', methods=['POST'])
def lambda_handler():
    print(request.form['title'])
    print(request.form['description'])
    print(request.form['kitType'])
    return jsonify("success"), 201

</code>```

After standing up the serverless api through sam local, I hit this endpoint through postman and the below error occurs as Flask tries to parse the form-data:

```<code>Traceback (most recent call last):
  File "/var/task/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/var/task/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/var/task/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/var/task/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/var/task/app.py", line 15, in kits_post
    print(request.form['title'])
  File "/var/task/werkzeug/utils.py", line 97, in __get__
    value = self.fget(obj)  # type: ignore
  File "/var/task/werkzeug/wrappers/request.py", line 447, in form
    self._load_form_data()
  File "/var/task/flask/wrappers.py", line 113, in _load_form_data
    RequestBase._load_form_data(self)
  File "/var/task/werkzeug/wrappers/request.py", line 285, in _load_form_data
    data = parser.parse(
  File "/var/task/werkzeug/formparser.py", line 265, in parse
    return parse_func(self, stream, mimetype, content_length, options)
  File "/var/task/werkzeug/formparser.py", line 142, in wrapper
    return f(self, stream, *args, **kwargs)
  File "/var/task/werkzeug/formparser.py", line 292, in _parse_multipart
    form, files = parser.parse(stream, boundary, content_length)
  File "/var/task/werkzeug/formparser.py", line 459, in parse
    parser.receive_data(data)
  File "/var/task/werkzeug/sansio/multipart.py", line 138, in receive_data
    self.buffer.extend(data)
TypeError: 'str' object cannot be interpreted as an integer
</code>```

I can't tell if there is misconfiguration in my sam template.yaml or if flask-lambda is just so out of date that this occurs for everyone.

Does anyone know why this is happening and how I can fix this?

NOTE: I do have the below set for BinaryMediaTypes on the API gateway configuration.

```<code>      BinaryMediaTypes:
        - '*~1*'  # converts to */* for any binary type
        - 'multipart/form-data'
</code>```

答:
Werkzeug/Flask expect a different type of object for environ['wsgi.input'] than what flask-lambda is providing.

I resolved this by copying the flask-lambda module into my project and changing:

[...] import StringIO

#  ...

environ['wsgi.input'] = StringIO(event['body'] or '')
```
<p>to</p>
<pre class="lang-py prettyprint-override"><code>import io

#  ...

environ['wsgi.input'] = io.BytesIO((event['body'] or '').encode())
</code>```

If you're using the original repo this is the relevant line.

I recommend this fork of a fork of flask-lambda but it has the same flaw.

(I'm using Python3.8, Flask==2.0.2, Werkzeug==2.0.3)

Body:
I have a serverless api through sam that consists of aws::serverless:function's and using flask-lambda to consume requests. I have been able to consume normal rest requests but I have a use-case to take in 3 property values and multiple files so naturally I considered using form-data to do this.

Sample lambda below:

from flask import request, jsonify
from flask_lambda import FlaskLambda

app = FlaskLambda(__name__)

@app.route('/kits', methods=['POST'])
def lambda_handler():
    print(request.form['title'])
    print(request.form['description'])
    print(request.form['kitType'])
    return jsonify("success"), 201

After standing up the serverless api through sam local, I hit this endpoint through postman and the below error occurs as Flask tries to parse the form-data:

Traceback (most recent call last):
  File "/var/task/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/var/task/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/var/task/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/var/task/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/var/task/app.py", line 15, in kits_post
    print(request.form['title'])
  File "/var/task/werkzeug/utils.py", line 97, in __get__
    value = self.fget(obj)  # type: ignore
  File "/var/task/werkzeug/wrappers/request.py", line 447, in form
    self._load_form_data()
  File "/var/task/flask/wrappers.py", line 113, in _load_form_data
    RequestBase._load_form_data(self)
  File "/var/task/werkzeug/wrappers/request.py", line 285, in _load_form_data
    data = parser.parse(
  File "/var/task/werkzeug/formparser.py", line 265, in parse
    return parse_func(self, stream, mimetype, content_length, options)
  File "/var/task/werkzeug/formparser.py", line 142, in wrapper
    return f(self, stream, *args, **kwargs)
  File "/var/task/werkzeug/formparser.py", line 292, in _parse_multipart
    form, files = parser.parse(stream, boundary, content_length)
  File "/var/task/werkzeug/formparser.py", line 459, in parse
    parser.receive_data(data)
  File "/var/task/werkzeug/sansio/multipart.py", line 138, in receive_data
    self.buffer.extend(data)
TypeError: 'str' object cannot be interpreted as an integer

I can't tell if there is misconfiguration in my sam template.yaml or if flask-lambda is just so out of date that this occurs for everyone.

Does anyone know why this is happening and how I can fix this?

NOTE: I do have the below set for BinaryMediaTypes on the API gateway configuration.

      BinaryMediaTypes:
        - '*~1*'  # converts to */* for any binary type
        - 'multipart/form-data'

Body:
Werkzeug/Flask expect a different type of object for environ['wsgi.input'] than what flask-lambda is providing.

I resolved this by copying the flask-lambda module into my project and changing:

[...] import StringIO

#  ...

environ['wsgi.input'] = StringIO(event['body'] or '')

to

import io

#  ...

environ['wsgi.input'] = io.BytesIO((event['body'] or '').encode())

If you're using the original repo this is the relevant line.

I recommend this fork of a fork of flask-lambda but it has the same flaw.

(I'm using Python3.8, Flask==2.0.2, Werkzeug==2.0.3)


问:
Rootless Docker - non-root container user cannot write to shared volume
On Ubuntu 21.10 I have installed rootless Docker following the instructions at https://docs.docker.com/engine/security/rootless/

My /etc/subuid and /etc/subgid appear to be configured correctly:

```<code>$ grep ^$(whoami): /etc/subuid
jtreminio:100000:65536

$ grep ^$(whoami): /etc/subgid
jtreminio:100000:65536
</code>```

From my (admittedly shallow) understanding of namespace mapping, I would expect rootless containers to map their internal root user 0:0 to my host's user 1000:1000. This seems to be the case:

```<code>$ docker container run --rm -it -v $PWD:/app -w /app bash touch foobar
$ ls -lah foobar
-rw-r--r-- 1 jtreminio jtreminio 0 Feb 11 16:50 foobar

</code>```

However, when I try to use any other user ID within the container, I lose all write permissions:

```<code>$ docker container run --rm -it -v $PWD:/app -w /app -u 1000:1000 bash touch barfoo
touch: barfoo: Permission denied
</code>```

If I create a directory with permissions set to 777 it seems this works:

```<code>$ mkdir barfoo && chmod 777 barfoo
$ docker container run --rm -it -v $PWD:/app -w /app -u 1000:1000 bash touch barfoo/foobar

$ ls -lah barfoo/
total 8.0K
drwxrwxrwx 2 jtreminio jtreminio 4.0K Feb 11 16:51 .
drwxr-xr-x 5 jtreminio jtreminio 4.0K Feb 11 16:51 ..
-rw-r--r-- 1    100999    100999    0 Feb 11 16:51 foobar
</code>```

My confusion here is that the contents of my /etc/subuid and /etc/subgid should be catching this? Am I completely misunderstanding how user namespaces work?

答:
There's no filesystem mapping of uid/gid on files across bind mounts. So the uid in the container will be the same as in the host side of the mount. User namespaces shift those uids in the container, so:

```<code>$ grep ^$(whoami): /etc/subuid
jtreminio:100000:65536

$ grep ^$(whoami): /etc/subgid
jtreminio:100000:65536
</code>```

Means to map the container uids 0-65536 to host uids 100000-165536 (and the same for gids), so those are the uids in the host you'll see from files created in the container.

Body:
On Ubuntu 21.10 I have installed rootless Docker following the instructions at https://docs.docker.com/engine/security/rootless/

My /etc/subuid and /etc/subgid appear to be configured correctly:

$ grep ^$(whoami): /etc/subuid
jtreminio:100000:65536

$ grep ^$(whoami): /etc/subgid
jtreminio:100000:65536

From my (admittedly shallow) understanding of namespace mapping, I would expect rootless containers to map their internal root user 0:0 to my host's user 1000:1000. This seems to be the case:

$ docker container run --rm -it -v $PWD:/app -w /app bash touch foobar
$ ls -lah foobar
-rw-r--r-- 1 jtreminio jtreminio 0 Feb 11 16:50 foobar

However, when I try to use any other user ID within the container, I lose all write permissions:

$ docker container run --rm -it -v $PWD:/app -w /app -u 1000:1000 bash touch barfoo
touch: barfoo: Permission denied

If I create a directory with permissions set to 777 it seems this works:

$ mkdir barfoo && chmod 777 barfoo
$ docker container run --rm -it -v $PWD:/app -w /app -u 1000:1000 bash touch barfoo/foobar

$ ls -lah barfoo/
total 8.0K
drwxrwxrwx 2 jtreminio jtreminio 4.0K Feb 11 16:51 .
drwxr-xr-x 5 jtreminio jtreminio 4.0K Feb 11 16:51 ..
-rw-r--r-- 1    100999    100999    0 Feb 11 16:51 foobar

My confusion here is that the contents of my /etc/subuid and /etc/subgid should be catching this? Am I completely misunderstanding how user namespaces work?

Body:
There's no filesystem mapping of uid/gid on files across bind mounts. So the uid in the container will be the same as in the host side of the mount. User namespaces shift those uids in the container, so:

$ grep ^$(whoami): /etc/subuid
jtreminio:100000:65536

$ grep ^$(whoami): /etc/subgid
jtreminio:100000:65536

Means to map the container uids 0-65536 to host uids 100000-165536 (and the same for gids), so those are the uids in the host you'll see from files created in the container.


问:
Breaking google sheet table into separate tables based on a column (Google App Script)
Is there a way that we can break the table based on 'Bank with' column (already sorted)?

Client name
Age
Bank with

Client 1
19
Bank 1

Client 2
32
Bank 1

Client 3
22
Bank 1

Client 4
34
Bank 2

Client 5
22
Bank 2

Client 5
28
Bank 3

Basically breaking into:

Client name
Age
Bank with

Client 1
19
Bank 1

Client 2
32
Bank 1

Client 3
22
Bank 1

Client name
Age
Bank with

Client 4
34
Bank 2

Client 5
22
Bank 2

Client name
Age
Bank with

Client 5
28
Bank 3

Thank you!

答:
It can be done several ways. Here is one of them:

```<code>function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();

  // get data from the first sheet
  var sheet = sheets[0];
  var [header, ...data] = sheet.getDataRange().getValues();
  var banks = Array.from(new Set(data.map(x => x[2])));

  // make the copies of the first sheet and rename them
  banks.forEach(b => sheet.copyTo(ss).setName(b));

  // remove redundant rows from the copied sheets
  for (let bank of banks) {
    let sheet = ss.getSheetByName(bank);
    let range = sheet.getDataRange();
    let [header, ...data] = range.getValues();
    data = data.filter(x => x[2] == bank);
    range.offset(1,0).clear();
    sheet.getRange(2,1,data.length,data[0].length).setValues(data);
  }
}
</code>```

The script puts each new table on a new sheet.

Body:
It can be done several ways. Here is one of them:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();

  // get data from the first sheet
  var sheet = sheets[0];
  var [header, ...data] = sheet.getDataRange().getValues();
  var banks = Array.from(new Set(data.map(x => x[2])));

  // make the copies of the first sheet and rename them
  banks.forEach(b => sheet.copyTo(ss).setName(b));

  // remove redundant rows from the copied sheets
  for (let bank of banks) {
    let sheet = ss.getSheetByName(bank);
    let range = sheet.getDataRange();
    let [header, ...data] = range.getValues();
    data = data.filter(x => x[2] == bank);
    range.offset(1,0).clear();
    sheet.getRange(2,1,data.length,data[0].length).setValues(data);
  }
}

The script puts each new table on a new sheet.