问:
How can I identify the column, where two (or more) rows are different (same ID)?
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

```<code>ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)
</code>```
```<code>   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805
</code>```

My goal would be an additional column, which contains the changed column, i.e. desired output:

```<code>   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>
</code>```

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

答:
Since you mentioned you're open to other solutions that may be more 'elegant' - here's a way to report the columns which are heterogeneous within one ID in a more 'tidy' fashion.

library(tidyverse)

# data
df <- structure(list(ID = c(1, 2, 2, 4, 5, 5, 5, 6, 6, 7), Info1 = c(10, 20, 20, 40, 50, 50, 50, 65, 60, 70), Info2 = c("A", "B", "A", "D", "E", "E", "F", "Z", "A", "B"), Info3 = c(999, 998, 997, 995, 995, 995, 995, 946, 800, 805)), class = "data.frame", row.names = c(NA, -10L))

# enumerate columns that are heterogeneous within one ID in tidy format
changes <- df %>%
  group_by(ID) %>%
  mutate(across(everything(), ~n_distinct(.x) > 1)) %>%
  pivot_longer(-ID, names_to = "col", values_to = "changed") %>%
  filter(changed) %>%
  select(-changed) %>%
  distinct()

# inspect result
changes
#> # A tibble: 6 x 2
#> # Groups:   ID [3]
#>      ID col
#>   <dbl> <chr>
#> 1     2 Info2
#> 2     2 Info3
#> 3     5 Info2
#> 4     6 Info1
#> 5     6 Info2
#> 6     6 Info3
```
<p>This makes it easy to then report which <code>ID</code>s have changes in the 'important' columns.</p>
<pre class="lang-r prettyprint-override"><code># indicate important columns
important_cols <- c("Info2", "Info3")

# report IDs with changes in important columns
changes %>%
  filter(col %in% important_cols)
#> # A tibble: 5 x 2
#> # Groups:   ID [3]
#>      ID col
#>   <dbl> <chr>
#> 1     2 Info2
#> 2     2 Info3
#> 3     5 Info2
#> 4     6 Info2
#> 5     6 Info3
</code>```

Or even subset the original data to just the 'important' changes so you can manually inspect or further analyze if needed.

# or subset original data for 'important' changes
df %>%
  select(ID,
         any_of(intersect(unique(changes$col),
                          important_cols))) %>%
  filter(ID %in% changes$ID)
#>   ID Info2 Info3
#> 1  2     B   998
#> 2  2     A   997
#> 3  5     E   995
#> 4  5     E   995
#> 5  5     F   995
#> 6  6     Z   946
#> 7  6     A   800
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)

   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805

My goal would be an additional column, which contains the changed column, i.e. desired output:

   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

Body:
Since you mentioned you're open to other solutions that may be more 'elegant' - here's a way to report the columns which are heterogeneous within one ID in a more 'tidy' fashion.

library(tidyverse)

# data
df <- structure(list(ID = c(1, 2, 2, 4, 5, 5, 5, 6, 6, 7), Info1 = c(10, 20, 20, 40, 50, 50, 50, 65, 60, 70), Info2 = c("A", "B", "A", "D", "E", "E", "F", "Z", "A", "B"), Info3 = c(999, 998, 997, 995, 995, 995, 995, 946, 800, 805)), class = "data.frame", row.names = c(NA, -10L))

# enumerate columns that are heterogeneous within one ID in tidy format
changes <- df %>%
  group_by(ID) %>%
  mutate(across(everything(), ~n_distinct(.x) > 1)) %>%
  pivot_longer(-ID, names_to = "col", values_to = "changed") %>%
  filter(changed) %>%
  select(-changed) %>%
  distinct()

# inspect result
changes
#> # A tibble: 6 x 2
#> # Groups:   ID [3]
#>      ID col
#>   <dbl> <chr>
#> 1     2 Info2
#> 2     2 Info3
#> 3     5 Info2
#> 4     6 Info1
#> 5     6 Info2
#> 6     6 Info3

This makes it easy to then report which IDs have changes in the 'important' columns.

# indicate important columns
important_cols <- c("Info2", "Info3")

# report IDs with changes in important columns
changes %>%
  filter(col %in% important_cols)
#> # A tibble: 5 x 2
#> # Groups:   ID [3]
#>      ID col
#>   <dbl> <chr>
#> 1     2 Info2
#> 2     2 Info3
#> 3     5 Info2
#> 4     6 Info2
#> 5     6 Info3

Or even subset the original data to just the 'important' changes so you can manually inspect or further analyze if needed.

# or subset original data for 'important' changes
df %>%
  select(ID,
         any_of(intersect(unique(changes$col),
                          important_cols))) %>%
  filter(ID %in% changes$ID)
#>   ID Info2 Info3
#> 1  2     B   998
#> 2  2     A   997
#> 3  5     E   995
#> 4  5     E   995
#> 5  5     F   995
#> 6  6     Z   946
#> 7  6     A   800

Created on 2022-02-09 by the reprex package (v2.0.1)


来源: stackexchange

问:
Why doesn't my function for finding card combinations work for more than 2 cards?
I'm trying to make a cribbage game in python, and I have a pretty good things going except for when I'm trying to find combinations of cards that add up to 15 after the player discards 2 cards to the crib, it doesn't work for combinations of 3 or greater. My code is below.

```<code>import math
import random
from itertools import *

deck = ['dA','d2','d3','d4','d5','d6','d7','d8','d9','dT','dJ','dQ','dK',

'hA','h2','h3','h4','h5','h6','h7','h8','h9','hT','hJ','hQ','hK',

'sA','s2','s3','s4','s5','s6','s7','s8','s9','sT','sJ','sQ','sK',

'cA','c2','c3','c4','c5','c6','c7','c8','c9','cT','cJ','cQ','cK']

newHand = []

CARD_SYMBOLS = {"d": "♦", "h": "♥", "s": "♠", "c": "♣"}

def show_hand(cards):
    print("┌─────┐\t"*len(cards))
    print( "\t".join([f"|  {card[1]}  |" for card in cards]))
    print( "\t".join([f"|  {CARD_SYMBOLS[card[0]]}  |" for card in cards]))
    print("└─────┘\t"*len(cards))

hand = []
handPoints = []
computerHand = []
crib = []
separator = ''

def cutCard():
  CD = random.choice(deck)
  newHand.append(CD)
  deck.remove(CD)

def dealCards():
  for x in range(6):
    card_dealt = random.choice(deck)
    hand.append(card_dealt)
    deck.remove(card_dealt)

    compCard_dealt = random.choice(deck)
    computerHand.append(compCard_dealt)
    deck.remove(compCard_dealt)

AtoK = {'2','3','4','5','6','7','8','9'}
tens = {'T','J','Q','K'}

twoCard15s = {'T5','J5','Q5','K5','78','96'}
threeCard15s = {'K4A','K32','Q4A','Q32','T4A','T32','95A','942','933','86A','852','843','77A','762','753','744','662','654','555'}
fourCard15s = {'K3AA','K22A','Q3AA','Q22A','J3AA','J22A','T3AA','T22A','94AA','932A','9222','85AA','842A','833A','8322','76AA','752A','7244','743A','7332','662A','6522','653A','6432','6441','6333','5433','5442','554A','555A','5532','4443'}

def countPoints():

  def count15s():
    #------2 card----this all works
    for num1 in range(0,4):
      for num2 in range(0,4):
        if(num1 != num2):
          combo = ''.join(newHand[num1][1]+newHand[num2][1])
          if(combo in twoCard15s):
            handPoints.append(combo)

   #-------3 card---works for about 3 combinations and I can't figure out why
    for numX in range(0,4):
      for numY in range(0,4):
        for numZ in range(0,4):
          if(numX != numY and numY != numZ and numX != numZ):
            combThree = ''.join(newHand[numX-1][1] + newHand[numY-1][1] + newHand[numZ-1][1])
            if(combThree in threeCard15s):
              if(combThree not in handPoints):
                handPoints.append(combThree)

    #---------4 card---also doesn't work
        for numX in range(0,4):
          for numY in range(0,4):
            for numZ in range(0,4):
              for numA in range(0,4):
                if(numX != numY != numZ != numA):
                  combFour = ''.join(newHand[numX][1] + newHand[numY][1] + newHand[numZ][1] + newHand[numA][1])
                  if(combFour in fourCard15s ):
                    if(combFour not in handPoints):
                      handPoints.append(combFour)

  count15s() #actually makes the function run
  print(handPoints) #prints the array of card combinations--I'm going to change this later so it actually counts points instead

def makeCrib():
  whichCards = input("Which cards do you want to put in the crib? (1-6) : ")
  if(whichCards[0] != whichCards[1]):
    if(len(whichCards) == 2):
      value1 = hand[int(whichCards[0]) - 1]
      value2 = hand[int(whichCards[1]) - 1]

      #chooses the inputed cards from the player's hand, subtracts 1 so it's more appealing to the eye, then adds the new cards to a separate array.
      both = []
      both.append(value1)
      both.append(value2)
# for each card in the hand, if the card selected isn't in the array of selected cards, push the card to the newHand (scored)
      for x in range(0,6):
        if(hand[x] not in both):
          newHand.append(hand[x])

#makes it appealing to the eye
print('Your Hand: \n   1       2       3       4       5       6')

dealCards() #randomizes the cards and deals them
show_hand(hand) #prints the card art for the hand
makeCrib()
cutCard()
show_hand(newHand)

countPoints()

</code>```

I guess my main question is why does this work for 2 card combinations, and how can I make it so it works for 3-5?

What it ends up printing is something like this:

The combination of 8 6 and A should be printed in the array at the very bottom but it doesn't.

Also is there an easier/more efficient way to check every combination other than a quad nested for loop? Thank you in advance to anyone who can help!

答:
You should use a dictionary to map cards to their numeric value and compute the sum of values for combinations (rather than searching for pre-defined combinations).

Also, you should use the combinations function from itertools instead of nested loops.  (your loops are combining the some cards with themselves and also repeating permutations of the same combinations which requires extra work to compensate)

```<code>from itertools import combinations

kinds      = "dhsc"
faces      = "A23456789TJQK"
cardValues = {kind+face:min(10,value) for kind in kinds
              for value,face in enumerate(faces,1)}

def count15s(cards):
    points = 0
    combos = []
    for size in (2,3,4,5):
        for combo in combinations(cards,size):
            if sum(map(cardValues.get,combo)) == 15:
                points += 2
                combos.append(combo)
    return points,combos

print(*count15s(['s7','dA','h6','h8','d5']))
# 4 [('s7', 'h8'), ('dA', 'h6', 'h8')]

print(*count15s(['s2','d7','h3','h5','dK']))
# 6 [('h5', 'dK'), ('s2', 'h3', 'dK'), ('d7', 'h3', 'h5')]

print(*count15s(['s2','d5','h3','h5','dK']))
# 8 [('d5', 'dK'), ('h5', 'dK'), ('s2', 'h3', 'dK'), ('s2', 'd5', 'h3', 'h5')]

print(*count15s(['s5','d5','h5','c5','dK']))
# 16 [('s5', 'dK'), ('d5', 'dK'), ('h5', 'dK'), ('c5', 'dK'),
      ('s5', 'd5', 'h5'), ('s5', 'd5', 'c5'), ('s5', 'h5', 'c5'),
      ('d5', 'h5', 'c5')]
</code>```

The same approach can be used to count sequences:

```<code>cardOrder = {kind+face:order for kind in kinds
              for order,face in enumerate(faces)}

def countSeq(cards):
    cards  = sorted(cards,key=cardOrder.get)
    points = 0
    combos = []
    for size in (5,4,3):
        for combo in combinations(cards,size):
            sequence = "".join(card[1] for card in combo)
            if sequence in faces:
                points += size
                combos.append(combo)
        if points: break
    return points,combos

print(*countSeq(['s7','d8','h8','h9','d9']))
# 12 [('s7', 'd8', 'h9'), ('s7', 'd8', 'd9'),
      ('s7', 'h8', 'h9'), ('s7', 'h8', 'd9')]

print(*countSeq(['sA','d2','h2','c2','d3']))
# 9 [('sA', 'd2', 'd3'), ('sA', 'h2', 'd3'), ('sA', 'c2', 'd3')]

print(*countSeq(['sT','dJ','hQ','cK','dK']))
# 8 [('sT', 'dJ', 'hQ', 'cK'), ('sT', 'dJ', 'hQ', 'dK')]

print(*countSeq(['sT','d9','hQ','cJ','dK']))
# 5 [('d9', 'sT', 'cJ', 'hQ', 'dK')]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a cribbage game in python, and I have a pretty good things going except for when I'm trying to find combinations of cards that add up to 15 after the player discards 2 cards to the crib, it doesn't work for combinations of 3 or greater. My code is below.

import math
import random
from itertools import *

deck = ['dA','d2','d3','d4','d5','d6','d7','d8','d9','dT','dJ','dQ','dK',

'hA','h2','h3','h4','h5','h6','h7','h8','h9','hT','hJ','hQ','hK',

'sA','s2','s3','s4','s5','s6','s7','s8','s9','sT','sJ','sQ','sK',

'cA','c2','c3','c4','c5','c6','c7','c8','c9','cT','cJ','cQ','cK']

newHand = []

CARD_SYMBOLS = {"d": "♦", "h": "♥", "s": "♠", "c": "♣"}

def show_hand(cards):
    print("┌─────┐\t"*len(cards))
    print( "\t".join([f"|  {card[1]}  |" for card in cards]))
    print( "\t".join([f"|  {CARD_SYMBOLS[card[0]]}  |" for card in cards]))
    print("└─────┘\t"*len(cards))

hand = []
handPoints = []
computerHand = []
crib = []
separator = ''

def cutCard():
  CD = random.choice(deck)
  newHand.append(CD)
  deck.remove(CD)

def dealCards():
  for x in range(6):
    card_dealt = random.choice(deck)
    hand.append(card_dealt)
    deck.remove(card_dealt)

    compCard_dealt = random.choice(deck)
    computerHand.append(compCard_dealt)
    deck.remove(compCard_dealt)

AtoK = {'2','3','4','5','6','7','8','9'}
tens = {'T','J','Q','K'}

twoCard15s = {'T5','J5','Q5','K5','78','96'}
threeCard15s = {'K4A','K32','Q4A','Q32','T4A','T32','95A','942','933','86A','852','843','77A','762','753','744','662','654','555'}
fourCard15s = {'K3AA','K22A','Q3AA','Q22A','J3AA','J22A','T3AA','T22A','94AA','932A','9222','85AA','842A','833A','8322','76AA','752A','7244','743A','7332','662A','6522','653A','6432','6441','6333','5433','5442','554A','555A','5532','4443'}

def countPoints():

  def count15s():
    #------2 card----this all works
    for num1 in range(0,4):
      for num2 in range(0,4):
        if(num1 != num2):
          combo = ''.join(newHand[num1][1]+newHand[num2][1])
          if(combo in twoCard15s):
            handPoints.append(combo)

   #-------3 card---works for about 3 combinations and I can't figure out why
    for numX in range(0,4):
      for numY in range(0,4):
        for numZ in range(0,4):
          if(numX != numY and numY != numZ and numX != numZ):
            combThree = ''.join(newHand[numX-1][1] + newHand[numY-1][1] + newHand[numZ-1][1])
            if(combThree in threeCard15s):
              if(combThree not in handPoints):
                handPoints.append(combThree)

    #---------4 card---also doesn't work
        for numX in range(0,4):
          for numY in range(0,4):
            for numZ in range(0,4):
              for numA in range(0,4):
                if(numX != numY != numZ != numA):
                  combFour = ''.join(newHand[numX][1] + newHand[numY][1] + newHand[numZ][1] + newHand[numA][1])
                  if(combFour in fourCard15s ):
                    if(combFour not in handPoints):
                      handPoints.append(combFour)

  count15s() #actually makes the function run
  print(handPoints) #prints the array of card combinations--I'm going to change this later so it actually counts points instead

def makeCrib():
  whichCards = input("Which cards do you want to put in the crib? (1-6) : ")
  if(whichCards[0] != whichCards[1]):
    if(len(whichCards) == 2):
      value1 = hand[int(whichCards[0]) - 1]
      value2 = hand[int(whichCards[1]) - 1]

      #chooses the inputed cards from the player's hand, subtracts 1 so it's more appealing to the eye, then adds the new cards to a separate array.
      both = []
      both.append(value1)
      both.append(value2)
# for each card in the hand, if the card selected isn't in the array of selected cards, push the card to the newHand (scored)
      for x in range(0,6):
        if(hand[x] not in both):
          newHand.append(hand[x])

#makes it appealing to the eye
print('Your Hand: \n   1       2       3       4       5       6')

dealCards() #randomizes the cards and deals them
show_hand(hand) #prints the card art for the hand
makeCrib()
cutCard()
show_hand(newHand)

countPoints()

I guess my main question is why does this work for 2 card combinations, and how can I make it so it works for 3-5?

What it ends up printing is something like this:

The combination of 8 6 and A should be printed in the array at the very bottom but it doesn't.

Also is there an easier/more efficient way to check every combination other than a quad nested for loop? Thank you in advance to anyone who can help!

Body:
You should use a dictionary to map cards to their numeric value and compute the sum of values for combinations (rather than searching for pre-defined combinations).

Also, you should use the combinations function from itertools instead of nested loops.  (your loops are combining the some cards with themselves and also repeating permutations of the same combinations which requires extra work to compensate)

from itertools import combinations

kinds      = "dhsc"
faces      = "A23456789TJQK"
cardValues = {kind+face:min(10,value) for kind in kinds
              for value,face in enumerate(faces,1)}

def count15s(cards):
    points = 0
    combos = []
    for size in (2,3,4,5):
        for combo in combinations(cards,size):
            if sum(map(cardValues.get,combo)) == 15:
                points += 2
                combos.append(combo)
    return points,combos

print(*count15s(['s7','dA','h6','h8','d5']))
# 4 [('s7', 'h8'), ('dA', 'h6', 'h8')]

print(*count15s(['s2','d7','h3','h5','dK']))
# 6 [('h5', 'dK'), ('s2', 'h3', 'dK'), ('d7', 'h3', 'h5')]

print(*count15s(['s2','d5','h3','h5','dK']))
# 8 [('d5', 'dK'), ('h5', 'dK'), ('s2', 'h3', 'dK'), ('s2', 'd5', 'h3', 'h5')]

print(*count15s(['s5','d5','h5','c5','dK']))
# 16 [('s5', 'dK'), ('d5', 'dK'), ('h5', 'dK'), ('c5', 'dK'),
      ('s5', 'd5', 'h5'), ('s5', 'd5', 'c5'), ('s5', 'h5', 'c5'),
      ('d5', 'h5', 'c5')]

The same approach can be used to count sequences:

cardOrder = {kind+face:order for kind in kinds
              for order,face in enumerate(faces)}

def countSeq(cards):
    cards  = sorted(cards,key=cardOrder.get)
    points = 0
    combos = []
    for size in (5,4,3):
        for combo in combinations(cards,size):
            sequence = "".join(card[1] for card in combo)
            if sequence in faces:
                points += size
                combos.append(combo)
        if points: break
    return points,combos

print(*countSeq(['s7','d8','h8','h9','d9']))
# 12 [('s7', 'd8', 'h9'), ('s7', 'd8', 'd9'),
      ('s7', 'h8', 'h9'), ('s7', 'h8', 'd9')]

print(*countSeq(['sA','d2','h2','c2','d3']))
# 9 [('sA', 'd2', 'd3'), ('sA', 'h2', 'd3'), ('sA', 'c2', 'd3')]

print(*countSeq(['sT','dJ','hQ','cK','dK']))
# 8 [('sT', 'dJ', 'hQ', 'cK'), ('sT', 'dJ', 'hQ', 'dK')]

print(*countSeq(['sT','d9','hQ','cJ','dK']))
# 5 [('d9', 'sT', 'cJ', 'hQ', 'dK')]


问:
Kotlin ActivityMainBinding build id in for loop
I have a problem. In my xml file, I have multiple textViews with the following id's:

```<code>txtRow1Column1
txtRow1Column2
txtRow2Column1
txtRow2Column2
txtRow3Column1
txtRow3Column2
txtRow4Column1
txtRow4Column2
</code>```

Now I filled an array with random numbers between 1..2 and using the 1 or 2 I want to add a text in the textview from the resources. For that I already have the following function:

```<code>private fun startNewRound() {

    // Define the array for (row, column, value)
    val rows = arrayOf<Array<Int>>();

    // Fill the array for each row and for each column
    for (row in 1..4) {
        rows.set(row, emptyArray())
        for (column in 1..2) {
            rows[row].plus((1..2).random())
        }
    }

    // Show the correct text using the filled array
    for (columns in rows) {
        for (value in columns) {
            val id = "txtRow" + rows.indexOf(columns) + "Column" + (columns.indexOf(value) + 1)
            when (value) {
                1 -> binding."ID HERE".text = getString(R.string.strTrue)
                2 -> binding."ID HERE".text = getString(R.string.strFalse)
            }
        }
    }
}
</code>```

Currently I have added "ID HERE" instead of the id of the view, because I need to use a string as id to bind to the view. My question is: How can I use that string to find the correct id and be able to bind to that specific view?

答:
Side note, the way you're building that 2D array looks like O(n^2), even if it wasn't going to throw IndexOutOfBoundsExceptions.

The way you're getting the column index won't work. Suppose you have the value 1 twice in a column. indexOf is going to return 0 both times because it returns the first valid match. Also, using indexOf inside your 2D loop results in O(n^3) complexity when it could just be O(n).

As to your problem, you can use Resources.getIdentifier() to find the Int ID of a view so you can find the view using findViewById. The alternative would be to use reflection on the binding class to find a field with that name, but that's uglier.

```<code>fun <T> View.getChildWithName(name: String): T {
    val id = context.resources.getIdentifier("id", name, context.packageName)
    return findViewById(id)
}

private fun startNewRound() {

    val rows = Array(4) { Array(2) { (1..2).random() } }

    rows.forEachIndexed { rowIndex, row ->
        row.forEachIndexed { colIndex, value ->
            val id = "txtRow${rowIndex + 1}Column${colIndex  + 1}"
            val view = binding.root.getChildWithName<TextView>(id)
            view.text = when (value) {
                1 -> getString(R.string.strTrue)
                2 -> getString(R.string.strFalse)
            }
        }
    }
}
</code>```

Body:
I have a problem. In my xml file, I have multiple textViews with the following id's:

txtRow1Column1
txtRow1Column2
txtRow2Column1
txtRow2Column2
txtRow3Column1
txtRow3Column2
txtRow4Column1
txtRow4Column2

Now I filled an array with random numbers between 1..2 and using the 1 or 2 I want to add a text in the textview from the resources. For that I already have the following function:

private fun startNewRound() {

    // Define the array for (row, column, value)
    val rows = arrayOf<Array<Int>>();

    // Fill the array for each row and for each column
    for (row in 1..4) {
        rows.set(row, emptyArray())
        for (column in 1..2) {
            rows[row].plus((1..2).random())
        }
    }

    // Show the correct text using the filled array
    for (columns in rows) {
        for (value in columns) {
            val id = "txtRow" + rows.indexOf(columns) + "Column" + (columns.indexOf(value) + 1)
            when (value) {
                1 -> binding."ID HERE".text = getString(R.string.strTrue)
                2 -> binding."ID HERE".text = getString(R.string.strFalse)
            }
        }
    }
}

Currently I have added "ID HERE" instead of the id of the view, because I need to use a string as id to bind to the view. My question is: How can I use that string to find the correct id and be able to bind to that specific view?

Body:
Side note, the way you're building that 2D array looks like O(n^2), even if it wasn't going to throw IndexOutOfBoundsExceptions.

The way you're getting the column index won't work. Suppose you have the value 1 twice in a column. indexOf is going to return 0 both times because it returns the first valid match. Also, using indexOf inside your 2D loop results in O(n^3) complexity when it could just be O(n).

As to your problem, you can use Resources.getIdentifier() to find the Int ID of a view so you can find the view using findViewById. The alternative would be to use reflection on the binding class to find a field with that name, but that's uglier.

fun <T> View.getChildWithName(name: String): T {
    val id = context.resources.getIdentifier("id", name, context.packageName)
    return findViewById(id)
}

private fun startNewRound() {

    val rows = Array(4) { Array(2) { (1..2).random() } }

    rows.forEachIndexed { rowIndex, row ->
        row.forEachIndexed { colIndex, value ->
            val id = "txtRow${rowIndex + 1}Column${colIndex  + 1}"
            val view = binding.root.getChildWithName<TextView>(id)
            view.text = when (value) {
                1 -> getString(R.string.strTrue)
                2 -> getString(R.string.strFalse)
            }
        }
    }
}


问:
Python - How can I line up the equals sign of all my equations?
Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.

Here is the code I already wrote :

```<code>def div(n):
  return [x for x in range(1,n+1) if n%x==0]

def pgcd(x,y):
  a = x
  b = y

  while b > 0:
    reste = a % b
    print(a, "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
</code>```

And it ouputs this :

```<code>pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
</code>```

I want it to output that :

```<code>178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0
</code>```

I've read many articles online but I have no idea how to put that into my code.

Thanks in advance.

答:
Ok I asked it on a Discord server and they found out so if anyone is having the same problem as me here is the solution (did not put all code for space) :

```<code>def pgcd(x,y):
  a = x
  b = y

  maxi = len(str(a))
  while b > 0:
    reste = a % b
    print(" "*(maxi-len(str(a))),a, "=", a//b, "*", b, "+", a%b)
</code>```

Basically compare to original code we added a maxi variable that has the maximum lenght of my integers, and then if the int is smaller like 8 compare to 178 we add to spaces because the difference of their length is 2.
This explanation is probably not 100% correct but it helps getting an idea.

Body:
Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.

Here is the code I already wrote :

def div(n):
  return [x for x in range(1,n+1) if n%x==0]

def pgcd(x,y):
  a = x
  b = y

  while b > 0:
    reste = a % b
    print(a, "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)

And it ouputs this :

pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0

I want it to output that :

178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0

I've read many articles online but I have no idea how to put that into my code.

Thanks in advance.

Body:
Ok I asked it on a Discord server and they found out so if anyone is having the same problem as me here is the solution (did not put all code for space) :

def pgcd(x,y):
  a = x
  b = y

  maxi = len(str(a))
  while b > 0:
    reste = a % b
    print(" "*(maxi-len(str(a))),a, "=", a//b, "*", b, "+", a%b)

Basically compare to original code we added a maxi variable that has the maximum lenght of my integers, and then if the int is smaller like 8 compare to 178 we add to spaces because the difference of their length is 2.
This explanation is probably not 100% correct but it helps getting an idea.


问:
Active link with React-Router?
I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

```<code>const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)
</code>```

答:
```<code>import { NavLink, useMatch, useResolvedPath } from 'react-router-dom';

const CustomNavLink = ({ to, title }) => {
   let resolved = useResolvedPath(to);
   let match = useMatch({ path: resolved.pathname, end: true });

   return (
      <NavLink to={to} className={`d-flex align-items-center py-2 px-4 ${match ? 'cta-btn' : 'c-n-b-link'}`} >
        <span className='ms-1 f-w-600'>{title}</span>
      </NavLink>
)
}
</code>```

For React router V6The above custom component will return a navlink that an active class can be activated whenever the path matches the given to path.

ContentLicense: CC BY-SA 3.0

Title: Active link with React-Router?

Body:
I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

const Router = () => (
  <BrowserRouter>

        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />

  </BrowserRouter>
)

Body:
import { NavLink, useMatch, useResolvedPath } from 'react-router-dom';

const CustomNavLink = ({ to, title }) => {
   let resolved = useResolvedPath(to);
   let match = useMatch({ path: resolved.pathname, end: true });

   return (
      <NavLink to={to} className={`d-flex align-items-center py-2 px-4 ${match ? 'cta-btn' : 'c-n-b-link'}`} >
        <span className='ms-1 f-w-600'>{title}</span>
      </NavLink>
)
}

For React router V6The above custom component will return a navlink that an active class can be activated whenever the path matches the given to path.


问:
R: Delete ID if any of the rows within ID contain specific strings (or multiple partial strings) in longitudinal format?
I would like to delete ID in any row that contains certain strings (A or D) within ID.
Here is my data frame:

```<code>id   time   dx
1     1     C
1     2     B
2     1     A
2     2     C
2     3     B
3     1     D
</code>```

I would like the following:

```<code>id    time  dx
 1     1     C
 1     2     B
</code>```

Based on the earlier post regarding this (Delete rows containing specific strings in R), I tried d %>% filter(!grepl('A|D', dx)). However, it only deletes the rows that contain A or D, not the whole IDs. I'd appreciate any help!

##Update: All the below answers worked well for the above post. Thank you all! Note that for this post, I simplified my data frame, and later on, I realized that I actually needed R codes to delete the IDs with certain partial strings (e.g., A or B0) from the following data frame. I was able to achieve this by modifying the first r2evans' answer: d %>% group_by(id) %>% filter(!any(str_detect(dx, "A|B0"))) %>% ungroup(). I have included the note here in case someone needs it. I would appreciate any additional suggestions.

Data frame:

```<code>id time dx
1   1   C01
1   2   B1
2   1   A34
2   2   C01
2   3   B1
3   1   B01X
</code>```

The results I wanted:

```<code>id time dx
1   1   C01
1   2   B1
</code>```

答:
grep is the wrong tool for this based on your question and sample data, I think %in% is the better way to go. Combine that with natural dplyr:group_by and an any(.) conditional, and we get our results

dplyr

dat %>%
  group_by(id) %>%
  filter(!any(dx %in% c("A", "D"))) %>%
  ungroup()
# # A tibble: 2 x 3
#      id  time dx
#   <int> <int> <chr>
# 1     1     1 C
# 2     1     2 B
```
<h2>base R</h2>
<pre class="lang-r prettyprint-override"><code>dat[ave(dat$dx, dat$id, FUN = function(z) !any(z %in% c("A", "D"))) == "TRUE",]
#   id time dx
# 1  1    1  C
# 2  1    2  B
</code>```

(ave requires that its output be the same class as its input which, in this case, is character. That's why I'm comparing against the string "TRUE" instead of using it as a literal TRUE.)

Data

dat <- structure(list(id = c(1L, 1L, 2L, 2L, 2L, 3L), time = c(1L, 2L, 1L, 2L, 3L, 1L), dx = c("C", "B", "A", "C", "B", "D")), class = "data.frame", row.names = c(NA, -6L))
```

Body:
I would like to delete ID in any row that contains certain strings (A or D) within ID.
Here is my data frame:

id   time   dx
1     1     C
1     2     B
2     1     A
2     2     C
2     3     B
3     1     D

I would like the following:

id    time  dx
 1     1     C
 1     2     B

Based on the earlier post regarding this (Delete rows containing specific strings in R), I tried d %>% filter(!grepl('A|D', dx)). However, it only deletes the rows that contain A or D, not the whole IDs. I'd appreciate any help!

##Update: All the below answers worked well for the above post. Thank you all! Note that for this post, I simplified my data frame, and later on, I realized that I actually needed R codes to delete the IDs with certain partial strings (e.g., A or B0) from the following data frame. I was able to achieve this by modifying the first r2evans' answer: d %>% group_by(id) %>% filter(!any(str_detect(dx, "A|B0"))) %>% ungroup(). I have included the note here in case someone needs it. I would appreciate any additional suggestions.

Data frame:

id time dx
1   1   C01
1   2   B1
2   1   A34
2   2   C01
2   3   B1
3   1   B01X

The results I wanted:

id time dx
1   1   C01
1   2   B1

Body:
grep is the wrong tool for this based on your question and sample data, I think %in% is the better way to go. Combine that with natural dplyr:group_by and an any(.) conditional, and we get our results

dplyr

dat %>%
  group_by(id) %>%
  filter(!any(dx %in% c("A", "D"))) %>%
  ungroup()
# # A tibble: 2 x 3
#      id  time dx
#   <int> <int> <chr>
# 1     1     1 C
# 2     1     2 B

base R

dat[ave(dat$dx, dat$id, FUN = function(z) !any(z %in% c("A", "D"))) == "TRUE",]
#   id time dx
# 1  1    1  C
# 2  1    2  B

(ave requires that its output be the same class as its input which, in this case, is character. That's why I'm comparing against the string "TRUE" instead of using it as a literal TRUE.)

Data

dat <- structure(list(id = c(1L, 1L, 2L, 2L, 2L, 3L), time = c(1L, 2L, 1L, 2L, 3L, 1L), dx = c("C", "B", "A", "C", "B", "D")), class = "data.frame", row.names = c(NA, -6L))


问:
Chrome devtools: Drop into debugger without switching to Sources tab
If I put the debugger statement in my JavaScript source with the Chrome devtools open, it'll stop execution so I can interactively explore the current context from the console. It's really awesome.

But unfortunately it will also switch to the Sources tab and display the line where the debugger statement happened. Most of the time, I want to type JavaScript commands, so I have to manually switch back to the Console tab.

Can I avoid the tab-switching and stay in the Console tab?

Or am I using it wrong?

答:
Looks like Chrome added a preference for this in the intervening 9 years: https://stackoverflow.com/a/69216922/66673

Quoting that answer:

I had the same issue and it was driving me nuts! The way I managed it to stop switching was to go to into the DevTools settings -> Preferences.

Under Sources options, uncheck Focus Sources panel when triggering a breakpoint.


问:
phpmyadmin in XAMPP is not working mac OS BigSur
I am new to php. I was already running mysql ver 8.0.27 on my mac 11.5 (BigSur)
Now i have installed XAMPP (8.0.15), Apache is running perfectly but MySQL Database is stopped and also localhost/phpmyadmin is not working. But my previously installed mysql is running, i am using it through workbench. Can i use my running mysql with it or need to change the port to run from XAMPP?</p>

答:
You should use modern dev stacks like Docker or Vagrant (I prefer docker) ... XAMPP is outdated. But it looks like a port problem. If you really want to use XAMPP, try changing the port numbers.

Also take a look at this video https://www.youtube.com/watch?v=YXWQTpSHIMc&ab_channel=BINARYHACK


问:
Why does the following code cause a "parse error (possibly incorrent indentation or mismatched brackets) at the next line of code
I'm attempting to create a replace function and the code below creates the error described in the post title in the first line of non-commented code following it. I have no idea as to why this is happening, so any help would be greatly appreciated.</p>
```<code> replace [] t r n = []
    replace [] _ _ _ = []
    replace xs _ _ 0 = xs
    replace (x:xs) t r n
         | x == t = r:(replace [xs] t r (n-1))
         | otherwise x (replace [xs] t r n)
</code>```

答:
There are some problems here: all the parts of the definition should start at the same column, so you should unindent the lines after the first one. Furthermore you need to write a = after the otherwise. xs is a list, so you call replace with replace xs, not replace <s>[xs]</s>. For the last guard you are constructing a list, so x : (…), not x (…). The second clause also does not make much sense, since that is equivalent to the first one.

You thus can implement this as:

```<code>replace :: (Integral n, Eq a) => [a] -> a -> a -> n -> [a]
replace [] _ _ _ = []
replace xs _ _ 0 = xs
replace (x:xs) t r n
  | x == t = r : replace <strong>xs</strong> t r (n-1)
  | otherwise <strong>=</strong> x <strong>:</strong> replace xs t r n</code>```

Body:
I'm attempting to create a replace function and the code below creates the error described in the post title in the first line of non-commented code following it. I have no idea as to why this is happening, so any help would be greatly appreciated.

 replace [] t r n = []
    replace [] _ _ _ = []
    replace xs _ _ 0 = xs
    replace (x:xs) t r n
         | x == t = r:(replace [xs] t r (n-1))
         | otherwise x (replace [xs] t r n)

Body:
There are some problems here: all the parts of the definition should start at the same column, so you should unindent the lines after the first one. Furthermore you need to write a = after the otherwise. xs is a list, so you call replace with replace xs, not replace <s>[xs]</s>. For the last guard you are constructing a list, so x : (…), not x (…). The second clause also does not make much sense, since that is equivalent to the first one.

You thus can implement this as:

replace :: (Integral n, Eq a) => [a] -> a -> a -> n -> [a]
replace [] _ _ _ = []
replace xs _ _ 0 = xs
replace (x:xs) t r n
  | x == t = r : replace xs t r (n-1)
  | otherwise = x : replace xs t r n


问:
how to make application with android
I am trying to create a new android apps but it says me like this

[2011-08-18 15:27:39 - jeetu] Conversion to Dalvik format failed:
  Unable to execute dex: wrapper was not properly loaded first

What does it mean?

答:
Notepad

Thats pretty good place to start

Title: how to make application with android


问:
How to sum two double linked lists in one list efficiently?
For example listA = [3,6,7,4] and listB = [2,3,1] and the output has to be listC=[5,9,8,6]. This is what I have so far but it is not very efficient.</p>
```<code>`public void sum(doublelist aList) {`
for (int i = 0; i < size(); i++) {
     set(i, this.get(i) + other.get(i % other.size()));
}
}
</code>```

答:
As you said you are using linked lists, you could navigate from element to element:

public void sum(DoubleList aList){
    DoubleNode cur=this.head;
    DoubleNode other=aList.head;
    while(cur!=null){
        cur.setValue(cur.getValue()+other.getValue());
        other=other.getNext();
        if(other==null){
            other=aList.head;
        }
        cur=cur.getNext();
    }
}
```

This code assumes that your DoubleList contains a head node attribute named head from the type DoubleNode and DoubleNode has the methods double getValue()/void setValue(double value) for accessing the value and DoubleNode getNext() for retrieving the next element.

This should be more efficient as you don't have to query the list every time (O(n) instead of O(n^2)).

Body:
For example listA = [3,6,7,4] and listB = [2,3,1] and the output has to be listC=[5,9,8,6]. This is what I have so far but it is not very efficient.

`public void sum(doublelist aList) {`
for (int i = 0; i < size(); i++) {
     set(i, this.get(i) + other.get(i % other.size()));
}
}

Body:
As you said you are using linked lists, you could navigate from element to element:

public void sum(DoubleList aList){
    DoubleNode cur=this.head;
    DoubleNode other=aList.head;
    while(cur!=null){
        cur.setValue(cur.getValue()+other.getValue());
        other=other.getNext();
        if(other==null){
            other=aList.head;
        }
        cur=cur.getNext();
    }
}

This code assumes that your DoubleList contains a head node attribute named head from the type DoubleNode and DoubleNode has the methods double getValue()/void setValue(double value) for accessing the value and DoubleNode getNext() for retrieving the next element.

This should be more efficient as you don't have to query the list every time (O(n) instead of O(n^2)).


问:
convert txt file to different sheet in excel
I wrote a code that passed information from a text file to excel.I sorted according to specific parameters I want to take from the file ("X,Y,O,P,E"). I neet to pass this information to sheet number 2. How can i do that ?</p>
```<code>import xlsxwriter

def readFile(_path):
    f = open(_path, "r")
    return f.readlines()

def test():
    file = open("Test.txt", 'r')

    data = []
    line_data = ""

    for line in file:
        if "_____ X" in line:
            line_data = line[24:].replace("\t", "").replace("\n", "").split(":")[0]
        elif "Y:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "O:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "P:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "E=" in line:
            line_data = line[21:].replace("\t", "").replace("\n", "").split[0]

        if len(line_data) > 0:
            data.append(line_data)
        line_data = ""

    writeToxlsx(data)

def writeToxlsx(data):
    _output_path = "Book1.xlsx"
    workbook = xlsxwriter.Workbook(_output_path)
    worksheet = workbook.add_worksheet()
    row = 0
    for item in data:
        worksheet.write(row, 1, item)
        row += 1
    workbook.close()

test()
</code>```

答:
Are you trying to write to an existing sheet? If so, you need to use openpyxl, not xlsxwriter. How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

If you are writing to a new sheet, then where you have the line:

worksheet = workbook.add_worksheet()

instead write:

worksheet = workbook.add_worksheet('The Sheetname You Want')

or if you really need it to be the second sheet, you will have to create a dummy sheet for the front page. You can use the example provided here: Python XlsxWriter - Write to many sheets

Body:
I wrote a code that passed information from a text file to excel.I sorted according to specific parameters I want to take from the file ("X,Y,O,P,E"). I neet to pass this information to sheet number 2. How can i do that ?

import xlsxwriter

def readFile(_path):
    f = open(_path, "r")
    return f.readlines()

def test():
    file = open("Test.txt", 'r')

    data = []
    line_data = ""

    for line in file:
        if "_____ X" in line:
            line_data = line[24:].replace("\t", "").replace("\n", "").split(":")[0]
        elif "Y:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "O:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "P:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "E=" in line:
            line_data = line[21:].replace("\t", "").replace("\n", "").split[0]

        if len(line_data) > 0:
            data.append(line_data)
        line_data = ""

    writeToxlsx(data)

def writeToxlsx(data):
    _output_path = "Book1.xlsx"
    workbook = xlsxwriter.Workbook(_output_path)
    worksheet = workbook.add_worksheet()
    row = 0
    for item in data:
        worksheet.write(row, 1, item)
        row += 1
    workbook.close()

test()


问:
DacFx and Custom DeploymentContributor (AgileSqlClub.DeploymentFilterContributor)
I've tried at least a dozen or so ways to get the module to load and work but still get the same error:

Error SQL0: Required contributor with id 'AgileSqlClub.DeploymentFilterContributor' could not be loaded.

I've tried to run it with DacFax/SqlPackage 150 (x64) and 140 (Both x86 and x64).
All iterations of SqlPackage command attempted:

Full Path to DLL 150 DacFx

"C:\Program Files\Microsoft SQL Server\150\DAC\bin\sqlpackage.exe" /a:Publish /SourceFile:C:\work\somedb.dacpac /TargetConnectionString:"Server=tcp:somedb.database.windows.net,1433;" /p:ExcludeObjectTypes="Users;Permissions;Logins;RoleMembership" /p:VerifyDeployment=False /p:AllowIncompatiblePlatform=True /p:TreatVerificationErrorsAsWarnings=True /p:AdditionalDeploymentContributorPaths="C:\Program Files\Microsoft SQL Server\150\DAC\bin\Extensions\AgileSqlClub.SqlPackageFilter.dll" /p:AdditionalDeploymentContributors=AgileSqlClub.DeploymentFilterContributor /p:AdditionalDeploymentContributorArguments="SqlPackageFilter0=IgnoreName(.PainInTheRearFunction.)"

Full Path to Dir w DLL 150 DacFx

"C:\Program Files\Microsoft SQL Server\150\DAC\bin\sqlpackage.exe" /a:Publish /SourceFile:C:\work\somedb.dacpac /TargetConnectionString:"Server=tcp:somedb.database.windows.net,1433;" /p:ExcludeObjectTypes="Users;Permissions;Logins;RoleMembership" /p:VerifyDeployment=False /p:AllowIncompatiblePlatform=True /p:TreatVerificationErrorsAsWarnings=True /p:AdditionalDeploymentContributorPaths="C:\Program Files\Microsoft SQL Server\150\DAC\bin\Extensions" /p:AdditionalDeploymentContributors=AgileSqlClub.DeploymentFilterContributor /p:AdditionalDeploymentContributorArguments="SqlPackageFilter0=IgnoreName(.PainInTheRearFunction.)"

No Path 150 DacFx

"C:\Program Files\Microsoft SQL Server\150\DAC\bin\sqlpackage.exe" /a:Publish /SourceFile::C:\work\somedb.dacpac /TargetConnectionString:"Server=tcp:somedb.database.windows.net,1433;" /p:ExcludeObjectTypes="Users;Permissions;Logins;RoleMembership" /p:VerifyDeployment=False /p:AllowIncompatiblePlatform=True /p:TreatVerificationErrorsAsWarnings=True /p:AdditionalDeploymentContributors=AgileSqlClub.DeploymentFilterContributor /p:AdditionalDeploymentContributorArguments="SqlPackageFilter0=IgnoreName(.PainInTheRearFunction.)"

140 DacFx x86 (Doesn't support Additional Path Argument)

"C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\sqlpackage.exe" /a:Publish /SourceFile:C:\work\somedb.dacpac /TargetConnectionString:"tcp:somedb.database.windows.net,1433;" /p:ExcludeObjectTypes="Users;Permissions;Logins;RoleMembership" /p:VerifyDeployment=False /p:AllowIncompatiblePlatform=True /p:TreatVerificationErrorsAsWarnings=True  /p:AdditionalDeploymentContributors=AgileSqlClub.DeploymentFilterContributor /p:AdditionalDeploymentContributorArguments="SqlPackageFilter0=IgnoreName(.PainInTheRearFunction.)"

140 DacFx x64 (Doesn't support Additional Path Argument)

"C:\Program Files\Microsoft SQL Server\140\DAC\bin\sqlpackage.exe" /a:Publish /SourceFile:C:\work\somedb.dacpac /TargetConnectionString:" tcp:somedb.database.windows.net,1433;" /p:ExcludeObjectTypes="Users;Permissions;Logins;RoleMembership" /p:VerifyDeployment=False /p:AllowIncompatiblePlatform=True /p:TreatVerificationErrorsAsWarnings=True  /p:AdditionalDeploymentContributors=AgileSqlClub.DeploymentFilterContributor /p:AdditionalDeploymentContributorArguments="SqlPackageFilter0=IgnoreName(. PainInTheRearFunction.)"

Where I've tried to put the dll and pdb file:

C:\Program Files\Microsoft SQL Server\150\DAC\bin

C:\Program Files\Microsoft SQL Server\150\DAC\bin\Extensions

C:\Program Files\Microsoft SQL Server\150\DAC\bin\Extensions\AgileSqlClub.DeploymentFilterContributor

C:\Program Files\Microsoft SQL Server\140\DAC\bin\

C:\Program Files\Microsoft SQL Server\140\DAC\bin\Extensions

C:\Program Files\Microsoft SQL Server\140\DAC\bin\Extension\AgileSqlClub.DeploymentFilterContributor

C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\

C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\Extensions

C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\Extension\AgileSqlClub.DeploymentFilterContributor

Same folder as dacpac (C:\work)

I am using the release version of the AgileSqlClub Deployment Contributor downloaded in zip format from here:

https://github.com/GoEddie/DeploymentContributorFilterer/releases/tag/1.4.4.1

Zip contains 2 files:

AgileSqlClub.SqlPackageFilter.dll

AgileSqlClub.SqlPackageFilter.pdb

I've read a dozen or so articles including:

SQL Server Data Tools: Error loading custom DeploymentPlanModifier: Required contributor with id could not be loaded

https://dba.stackexchange.com/questions/268707/exclude-certain-schema-along-with-unnamed-constraints-in-ssdt

https://the.agilesql.club/2015/01/howto-filter-dacpac-deployments/

I am not using SSDT just downloaded versions of DacFramework.msi (140/150)

If I remove the DeploymentFilter arguments then SqlPackage loads everything but fails at the PainInTheRearFunction I am trying to filter and Ignore on.

Any help would be greatly appreciated.

答:
I had the same issue.
Lots of those links referred to "unblocking" the dll which I originally dismissed, thinking things had moved on since versions of windows that were referenced.

I still needed to do this. Screenshot below to illustrate.
Having the AgileSqlClub.SqlPackageFilter.dll in the same folder as SqlPackage.exe was where it worked


答:
You can use the rjust string method.

The thing is you need to figure out what is the widest string on the left hand side you will print. Luckily here, it would be the first value.

So I would go with this.

def pgcd(x,y):
  a = x
  b = y

  len_a = len(f"{a}")

  while b > 0:
    reste = a % b
    print(f"{a}".rjust(len_a), "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
```
<p>Should print this.</p>
```>>> pgcd(178,52)
178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0
'PGCD(178;52) = 2'
```

Title: Python - How can I line up the equals sign of all my equations?

Body:
You can use the rjust string method.

The thing is you need to figure out what is the widest string on the left hand side you will print. Luckily here, it would be the first value.

So I would go with this.

def pgcd(x,y):
  a = x
  b = y

  len_a = len(f"{a}")

  while b > 0:
    reste = a % b
    print(f"{a}".rjust(len_a), "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)

Should print this.

>>> pgcd(178,52)
178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0
'PGCD(178;52) = 2'


问:
centering a div in a grid item
I've been trying to horizontally center a div on the screen of an Iphone.  The div is a bit narrower than the phone screen.  I have been googling and searching this site and trying every combination of display, flex, margin, width, justify*, align*, placeself, etc. etc. in the container as well as item style and nothing has worked.  Here is the code, with all my attempts removed from the style since none of it worked and I assume may interfere with correct solution.  No matter what I try, the div just stays on the left side of the screen.

{left} and {right} are divs, with width: 400px

```<code>    <Mobile>
        <Grid container style={{  }} >
            <Grid item xs={12} style={{  }}>{left}{right}</Grid>
        </Grid>
    </Mobile>

const Mobile = ({ children }) => useMediaQuery({ maxWidth: 799 }) && children
</code>```

答:
Here is what finally worked for me after lots of trial and error.

```<code>    <Mobile>
        <Grid container style={{ justifyItems: 'center', alignItems: 'center', display: 'inline-grid', width: '100%' }} >
            <Grid item xs={12} style={{ width: '400px' }}>{left}{right}</Grid>
        </Grid>
    </Mobile>
</code>```

To clarify, my question was probably inaccurate.  What I needed to do was center the grid item in the grid container.

Title: centering a div in a grid item

Body:
I've been trying to horizontally center a div on the screen of an Iphone.  The div is a bit narrower than the phone screen.  I have been googling and searching this site and trying every combination of display, flex, margin, width, justify*, align*, placeself, etc. etc. in the container as well as item style and nothing has worked.  Here is the code, with all my attempts removed from the style since none of it worked and I assume may interfere with correct solution.  No matter what I try, the div just stays on the left side of the screen.

{left} and {right} are divs, with width: 400px

    <Mobile>
        <Grid container style={{  }} >
            <Grid item xs={12} style={{  }}>{left}{right}</Grid>
        </Grid>
    </Mobile>

const Mobile = ({ children }) => useMediaQuery({ maxWidth: 799 }) && children

Body:
Here is what finally worked for me after lots of trial and error.

    <Mobile>
        <Grid container style={{ justifyItems: 'center', alignItems: 'center', display: 'inline-grid', width: '100%' }} >
            <Grid item xs={12} style={{ width: '400px' }}>{left}{right}</Grid>
        </Grid>
    </Mobile>

To clarify, my question was probably inaccurate.  What I needed to do was center the grid item in the grid container.


答:
IntelliJ displays this:

And when I run:

VyxalLexer lexer = new VyxalLexer(CharStreams.fromString("⟨1|2⟩⟨1|2⟩"));
VyxalParser parser = new VyxalParser(new CommonTokenStream(lexer));
System.out.println(parser.file().toStringTree(parser));
```
<p>the following is printed:</p>
```(file (program (literal (list ⟨ (program (literal (number (integer 1)))) | (program (literal (number (integer 2)))) ⟩)) (literal (list ⟨ (program (literal (number (integer 1)))) | (program (literal (number (integer 2)))) ⟩))) <EOF>)
```

Which is in sync with what IntelliJ displays.

I'm guessing you haven't recently generated new parser classes. Causing your own Java code to use older parser classes than the IntelliJ plugin is using.

Title: ANTLR4 parser errors in code when Intellij plugin constructs it correctly

Body:
I am attempting to construct a compiler for the golfing language Vyxal and am using ANTLR for parsing. I have managed to write down almost the entire language, and it works perfectly in the Intellij plugin for ANTLR, but when I try running the code using the input ⟨1|2⟩⟨1|2⟩, it says line 1:10 mismatched input '<EOF>' expecting . I found this question, but my lexer and parser rules are in the same file, and I have already confirmed that the tokens are correct.

My grammar:

grammar Vyxal;

@header {
package io.github.seggan.jyxal.antlr;
}

file
    : program EOF
    ;

program
    : (literal | structure | element)+
    ;

element
    : PREFIX? element_type
    ;

element_type
    : ALPHA | '<' | ':' | '\u00d7' | '\u1e40' | '\u1e6b' | '\u2087' | '\u00be' | '\u2084' | '\u21b5'
    | '\u00b9' | '\u03a0' | '\u00e6' | '\u1e61' | '\u2211' | '\u1e8e'    | '\u221a' | '\u1e0b' | '\u00a7'
    | '\u00b2' | '\u2026' | '\u1e45' | '\u017b' | '\u01cd' | '-' | '\u2235' | '\u2194' | '\u2260' | '\u027e'
    | '\u00a4' | '\u20b4' | '\u01cf'    | '\u21e7' | '\u0121' | '\u1e8f' | '\u207c' | '\u204b' | '\u2229'
    | '\u2248' | '\u2237' | '\u2088' | '\u00f7' | '\u0227' | '\u0280' | '\u2080' | '\u1e02' | '\u228d'
    | '\u2234'    | '\u2228' | '\u022f' | '\u2070' | '\u1e8a' | '\u21e9' | '\u1e87' | '\u2039' | '\u1e2d'
    | '\u2020' | '\u201f' | '\u2308' | '\u2081' | '!' | '\u20ac' | '\u0188' | '\u01d2'    | '\u027d' | '\u0281'
    | ',' | '\u022e' | '\u22ce' | '\u03c4' | '\u01ce' | '\u1e59' | '%' | '\u1e86' | '\u2227' | '\u21b2'
    | '\u01d0' | '\u00a2' | '\u201e' | '\u0116'    | '\u2082' | '\u1e1e' | '\ua60d' | '}' | '*' | '\u1e8b'
    | '?' | '\u2085' | '\u0140' | '\u00df' | '\u27c7' | '\u2105' | '\u00a5'| '\u2086' | '\u0120' | '\u1e57'
    | '\u221e' | '\u1e56' | '\ua71d' | '\u01d3' | '\u203a' | '\u03b5' | '\u25a1' | '\u1e6a' | '\u00a6'
    | '\u0117' | '$' | '\u1e58' | '\u0130' | '=' | '\u2193' | '\u010b'    | '\u2083' | '\u1e22' | '_' | '\u27d1'
    | '\u010a' | '\u013f' | '\u00ac' | '\u00b6' | '\u00f0' | '\u1e1f' | '\u00a1' | '\u00af' | '\u2265'
    | '\u01d4' | '\u017c' | '\u2191'    | '\u1e0a' | '\u00bc' | '\u22cf' | '\u01d1' | '>' | '\u1e41' | '\u00a3'
    | '\u215b' | '\u1e23' | '+' | '\u00b1' | '/' | '\u21b3' | '\u222a' | '\u2207' | '\u2264'    | '\u1e03'
    | '\u2310' | '^' | '\u1e60' | '\u0226' | '\u03b2' | '\u2022' | '\u00bd' | '\u1e44'
    ;

// structures
structure
    : if_statement
    | for_loop
    | while_loop
    | lambda
    | function
    | variable_assn
    ;

if_statement
    : '[' program ('|' program)? ']'?
    ;

for_loop
    : '(' (variable '|')? program ')'?
    ;

while_loop
    : '{' (program '|')? program '}'?
    ;

lambda
    : LAMBDA_TYPE (integer '|')? program ';'?
    ;

function
    : '@' variable ((':' parameter (':' parameter)*)? '|' program)? ';'?
    ;

variable_assn
    : ASSN_SIGN variable
    ;

variable
    : (ALPHA | DIGIT)+
    ;

parameter
    : '*' | variable | integer
    ;

// types
literal
    : number
    | string
    | list
    ;

string
    : normal_string
    | compressed_string
    | single_char_string
    | double_char_string
    ;

number
    : integer
    | complex
    | compressed_number
    ;

integer
    : DIGIT+ ('.' DIGIT+)?
    ;

complex
    : integer '°' integer
    ;

list
    : '\u27e8' program ('|' program)* '\u27e9'?
    ;

any_text
    : .+?
    ;

compressed_string
    : '\u00ab' any_text '\u00ab'?
    ;

normal_string
    : '`' any_text '`'?
    ;

single_char_string
    : '\\' .
    ;

double_char_string
    : '‛' . .
    ;

compressed_number
    : '\u00bb' any_text '\u00bb'?
    ;

DIGIT
    : [0-9]
    ;

// code
PREFIX
    : [¨Þkø∆]
    ;

ALPHA
    : [a-zA-Z]
    ;

ASSN_SIGN
    : '→' | '←'
    ;

// strucutres
LAMBDA_TYPE
    : [λƛ'µ]
    ;

WHT
    : [ \t\n\r] -> skip
    ;

The code I use is simple:

String s = Files.readString(Path.of(args[0]));
VyxalLexer lexer = new VyxalLexer(CharStreams.fromString(s));
VyxalParser parser = new VyxalParser(new CommonTokenStream(lexer));

The Intellij plugin constructs it properly:

And the tokens are of the correct values:

[@-1,0:0='⟨',<163>,1:0]
[@-1,1:1='1',<170>,1:1]
[@-1,2:2='|',<154>,1:2]
[@-1,3:3='2',<170>,1:3]
[@-1,4:4='⟩',<164>,1:4]
[@-1,5:5='⟨',<163>,1:5]
[@-1,6:6='1',<170>,1:6]
[@-1,7:7='|',<154>,1:7]
[@-1,8:8='2',<170>,1:8]
[@-1,9:9='⟩',<164>,1:9]

Body:
IntelliJ displays this:

And when I run:

VyxalLexer lexer = new VyxalLexer(CharStreams.fromString("⟨1|2⟩⟨1|2⟩"));
VyxalParser parser = new VyxalParser(new CommonTokenStream(lexer));
System.out.println(parser.file().toStringTree(parser));

the following is printed:

(file (program (literal (list ⟨ (program (literal (number (integer 1)))) | (program (literal (number (integer 2)))) ⟩)) (literal (list ⟨ (program (literal (number (integer 1)))) | (program (literal (number (integer 2)))) ⟩))) <EOF>)

Which is in sync with what IntelliJ displays.

I'm guessing you haven't recently generated new parser classes. Causing your own Java code to use older parser classes than the IntelliJ plugin is using.


问:
What must I know to use GNU Screen properly?
I've just introduced a friend to GNU Screen and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent Screen utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?

It would be awesome.

答: ^A A switches back to the screen you just came from.</p>

OwnerDisplayName: PintSizedCat

LastEditorDisplayName: EnderMB

OwnerDisplayName: dummy

ContentLicense: CC BY-SA 2.5


问:
What's an example of Ruby code that's "too clever"?
I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?</p>

答: I'm not sure if this qualifies as "too clever," but I have seen code that made me wonder if the author was either a genius or an idiot.  One developer seemed to have a rule that no method should have more than two lines of code.  That pushed the call stack very deep and made debugging rather difficult.  The upside is that his overall design was very abstract and even elegant from a distance.</p>

OwnerDisplayName: amsterdam

LastEditorDisplayName: amsterdam

OwnerDisplayName: chris


问:
Issue with tabbing between form fields when using jQuery custom scrollbars
I'm working on project to provide a bolt-on tool for websites, which makes heavy use of jQuery.  Presentation / design is crucial, and I want to replace the standard (ugly) scrollbar applied by the browser to html elements with overflowing content, with something better looking.

There are numerous jQuery plug-ins around that apply custom scrollbars and allow styling via CSS which is great, but all the ones I've tried seem to suffer from the same problem which is this:  if the scrollable content contains a form with text fields etc, tabbing between fields does not activate the scrollbar, and in some cases can screw up the custom scrollbar layout altogether.

Two examples of plug-ins I've tried:

http://manos.malihu.gr/jquery-custom-content-scroller
http://baijs.nl/tinyscrollbar/

I've tried others also, but in all demos / examples the content is plain text.  I've done a lot of searching on this already, but it seems no-one has tried using these plug-ins with form-based content.

All these plug-ins seem to work in more or less the same way, and I can see exactly what happens and why, but just wondered if anyone else has had this problem and / or found a solution?

This issue can be easily replicated as follows (using the tinyscrollbar plug-in):

Add this to a standard html test page -

CSS:

```<code><style>
    #tinyscrollbartest { width: 520px; height: 250px;  padding-right: 20px; background-color: #eee; }
    #tinyscrollbartest .viewport { width: 500px; height: 200px; overflow: hidden; position: relative; }
    #tinyscrollbartest .overview { list-style: none; position: absolute; left: 0; top: 0; }
    #tinyscrollbartest .scrollbar { position: relative; float: right; width: 15px; }
    #tinyscrollbartest .track { background: #d8eefd; height: 100%; width: 13px; position: relative; padding: 0 1px; }
    #tinyscrollbartest .thumb { height: 20px; width: 13px; cursor: pointer; overflow: hidden; position: absolute; top: 0; }
    #tinyscrollbartest .thumb .end { overflow: hidden; height: 5px; width: 13px; }
    #tinyscrollbartest .thumb, #tinyscrollbartest .thumb .end { background-color: #003d5d; }
    #tinyscrollbartest .disable { display: none; }
</style>
</code>```

Html:

```<code><div id="tinyscrollbartest">
    <div class="scrollbar">
        <div class="track">
            <div class="thumb">
                <div class="end"></div>
            </div>
        </div>
    </div>
    <div class="viewport">
        <div class="overview">
            </p>Here's a text field: <input type="text"/><p>
            ...
            // lots of content to force scrollbar to appear,
            // and to push the next field out of sight ..
            ...
            <p>Here's another field: <input type="text"/></p>
        </div>
    </div>
</div>
</code>```

Plug-in reference (assuming jquery libraries etc are referenced also):

```<code><script type="text/javascript" src="scripts/jquery.tinyscrollbar.min.js"></script>
</code>```

Jquery code:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $('#tinyscrollbartest').tinyscrollbar();
    });
</script>
</code>```

Now click in the first text field so it has focus, hit the tab key to move to the next one and see what happens.

答:
I understand your problem.. But is hard to find a good solution to this. You could try to set a focus event on your form elements. And let this event trigger the scrollbar_update function of tinyscrollbar. You can set the offsetTop of the form element that currently has focus as the methods parameter. I think that would work.

$('formelements').focus(function(){
    YourScrollbar.tinyscrollbar_update(this.offsetTop);
});

Body:
I'm working on project to provide a bolt-on tool for websites, which makes heavy use of jQuery.  Presentation / design is crucial, and I want to replace the standard (ugly) scrollbar applied by the browser to html elements with overflowing content, with something better looking.

There are numerous jQuery plug-ins around that apply custom scrollbars and allow styling via CSS which is great, but all the ones I've tried seem to suffer from the same problem which is this:  if the scrollable content contains a form with text fields etc, tabbing between fields does not activate the scrollbar, and in some cases can screw up the custom scrollbar layout altogether.

Two examples of plug-ins I've tried:

http://manos.malihu.gr/jquery-custom-content-scroller
http://baijs.nl/tinyscrollbar/

I've tried others also, but in all demos / examples the content is plain text.  I've done a lot of searching on this already, but it seems no-one has tried using these plug-ins with form-based content.

All these plug-ins seem to work in more or less the same way, and I can see exactly what happens and why, but just wondered if anyone else has had this problem and / or found a solution?

This issue can be easily replicated as follows (using the tinyscrollbar plug-in):

Add this to a standard html test page -

CSS:

Html:

Here's a text field: <input type="text"/>

            ...
            // lots of content to force scrollbar to appear,
            // and to push the next field out of sight ..
            ...

Here's another field: <input type="text"/>

Plug-in reference (assuming jquery libraries etc are referenced also):

Jquery code:

Now click in the first text field so it has focus, hit the tab key to move to the next one and see what happens.


问:
R: Create a linear mixed-effect model loop that removes one fixed independent variable, then adds it back in and removes another
I'm looking for a way to create a linear mixed-effect model loop that removes one fixed effect independent variable, runs the model, adds it back in, and removes another fixed independent variable from the model.

For example:

library(lme4)

L1 <- lmer(cyl ~ disp + hp + mpg (carb|gear), mtcars)

How can I create a loop of this model so that each new regression loop iteration removes a single fixed effect independent variable, adds it back in on the next iteration, and removes a different fixed independent variable?

Doing this would produce these models:

Original full model: lmer(cyl ~ disp + mpg +  (carb|gear), mtcars)

Partial model with mpg removed: lmer(cyl ~ disp + hp + (carb|gear), mtcars)

Partial model with mpg re-added and disp removed: lmer(cyl ~ hp + mpg  (carb|gear), mtcars)

Partial model with disp re-added and hp removed:  lmer(cyl ~ disp + mpg  (carb|gear), mtcars)

I am also curious how I can add each model to a list after each loop iteration.

Thanks a lot!

答:
Map over the fixed variables constructing the formula, fo, using reformulate and run lmer.  This will produce a named list of "lmerMod" objects, one for each component of fixed such that that model omits that component.  The full model will have an empty name.

```<code>library(lme4)

fixed <- c("", "disp", "hp", "mpg")

f <- function(v, data) {
  fo <- reformulate(c(setdiff(fixed, v), "(carb | gear)"), "cyl")
  cat("Running", format(fo), "\n")
  lmer(fo, data = data)
}
out <- Map(f, fixed, MoreArgs = list(data = mtcars))
## Running cyl ~ disp + hp + mpg + (carb | gear)
## boundary (singular) fit: see ?isSingular
## Running cyl ~ hp + mpg + (carb | gear)
## Running cyl ~ disp + mpg + (carb | gear)
## boundary (singular) fit: see ?isSingular
## Running cyl ~ disp + hp + (carb | gear)
</code>```

drop1

Also, lme4 has a "merMod" method for drop1 which will use extractAIC to calculate the AIC value for each single term deletion.

```<code>fm <- lmer(cyl ~ disp + hp + mpg + (carb | gear), data = mtcars)
## boundary (singular) fit: see ?isSingular

drop1(fm)
## boundary (singular) fit: see ?isSingular
## Single term deletions
##
## Model:
## cyl ~ disp + hp + mpg + (carb | gear)
##        npar    AIC
## <none>      79.239
## disp      1 86.511
## hp        1 81.417
## mpg       1 78.901
</code>```

This is similar to the following which shows the degrees of freedom and AIC for each single term deletion.

```<code>sapply(out, extractAIC)
##                  disp       hp      mpg
## [1,]  8.00000  7.00000  7.00000  7.00000
## [2,] 79.23877 86.51109 81.41726 78.90149
</code>```

Body:
Map over the fixed variables constructing the formula, fo, using reformulate and run lmer.  This will produce a named list of "lmerMod" objects, one for each component of fixed such that that model omits that component.  The full model will have an empty name.

library(lme4)

fixed <- c("", "disp", "hp", "mpg")

f <- function(v, data) {
  fo <- reformulate(c(setdiff(fixed, v), "(carb | gear)"), "cyl")
  cat("Running", format(fo), "\n")
  lmer(fo, data = data)
}
out <- Map(f, fixed, MoreArgs = list(data = mtcars))
## Running cyl ~ disp + hp + mpg + (carb | gear)
## boundary (singular) fit: see ?isSingular
## Running cyl ~ hp + mpg + (carb | gear)
## Running cyl ~ disp + mpg + (carb | gear)
## boundary (singular) fit: see ?isSingular
## Running cyl ~ disp + hp + (carb | gear)

drop1

Also, lme4 has a "merMod" method for drop1 which will use extractAIC to calculate the AIC value for each single term deletion.

fm <- lmer(cyl ~ disp + hp + mpg + (carb | gear), data = mtcars)
## boundary (singular) fit: see ?isSingular

drop1(fm)
## boundary (singular) fit: see ?isSingular
## Single term deletions
##
## Model:
## cyl ~ disp + hp + mpg + (carb | gear)
##        npar    AIC
## <none>      79.239
## disp      1 86.511
## hp        1 81.417
## mpg       1 78.901

This is similar to the following which shows the degrees of freedom and AIC for each single term deletion.

sapply(out, extractAIC)
##                  disp       hp      mpg
## [1,]  8.00000  7.00000  7.00000  7.00000
## [2,] 79.23877 86.51109 81.41726 78.90149


问:
Incomparable weight shape between caffe and tensorflow / keras
I am trying to convert a caffe model to keras, I have successfully been able to use both MMdnn and even caffe-tensorflow. The output I have are .npy files and .pb files. I have not had much luck with the .pb files, so I stuck to .npy files which contain the weights and biases. I have reconstructed an mAlexNet network as follows:

```<code>import tensorflow as tf
from tensorflow import keras
from keras.layers import Conv2D, MaxPool2D, Dropout, Dense, Flatten

def define_malexnet():
    input = keras.Input(shape=(224, 224, 3), name='data')
    x = Conv2D(16, kernel_size=(11,11), strides=(4,4), activation='relu', name='conv1')(input)
    x = MaxPool2D(pool_size=(3,3), strides=(2,2), padding='same', name='pool1')(x)
    x = Conv2D(20, kernel_size=(5,5), strides=(1,1), activation='relu', name='conv2')(x)
    x = MaxPool2D(pool_size=(3,3), strides=(2,2), name='pool2')(x)
    x = Conv2D(30, kernel_size=(3,3), strides=(1,1), activation='relu', name='conv3')(x)
    x = MaxPool2D(pool_size=(3,3), strides=(2,2), name='pool3')(x)
    x = Flatten()(x)
    x = Dense(48, activation='relu', name='fc4')(x)
    output = Dense(2, activation='softmax', name='fc5')(x)

    occupancy_model = keras.Model(input, output, name='occupancy_malexnet')
    occupancy_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return occupancy_model
</code>```

Then I try to load the weights using this code snippet:

```<code>import numpy as np

weights_data = np.load('weights.npy', allow_pickle=True).item()
model = define_malexnet()

for layer in model.layers:
  if layer.name in weights_data.keys():
    layer_weights = weights_data[layer.name]
    layer.set_weights((layer_weights['weights'], layer_weights['bias']))
</code>```

During this process I get an error:

ValueError: Layer conv1 weight shape (16,) is not compatible with
provided weight shape (1, 1, 1, 16).

Now as I understand this is because of the different backends and how they initialize weights, but I have not found a way to solve this problem. My question is, how do I tweak the weights loaded from the file to fit my keras model? Link to weights.npy file https://drive.google.com/file/d/1QKzY-WxiUnf9VnlhWQS38DE3uF5I_qTl/view?usp=sharing.

答:
The problem is the bias vector.  It is shaped as a 4D tensor but Keras assumes it is a 1D tensor.  Just flatten the bias vector:

```<code>import numpy as np

weights_data = np.load('weights.npy', allow_pickle=True).item()
model = define_malexnet()

for layer in model.layers:
  if layer.name in weights_data.keys():
    layer_weights = weights_data[layer.name]
    layer.set_weights((layer_weights['weights'], layer_weights['bias'].flatten()))
</code>```

As a sanity check, once I create your model I will access the conv1 weights and your corresponding weights you cached then compare them both:

```<code>In [22]: weights1 = model.layers[1].weights[0].numpy()

In [23]: weights2 = weights_data['conv1']['weights']

In [24]: np.allclose(weights1, weights2)
Out[24]: True

</code>```

The same for the biases:

```<code>In [25]: bias1 = model.layers[1].weights[1].numpy()

In [26]: bias2 = weights_data['conv1']['bias']

In [27]: np.allclose(bias1, bias2)
Out[27]: True
</code>```

Notice that I didn't have to flatten the biases from your cached results because np.allclose flattens singleton dimensions internally.

Body:
I am trying to convert a caffe model to keras, I have successfully been able to use both MMdnn and even caffe-tensorflow. The output I have are .npy files and .pb files. I have not had much luck with the .pb files, so I stuck to .npy files which contain the weights and biases. I have reconstructed an mAlexNet network as follows:

import tensorflow as tf
from tensorflow import keras
from keras.layers import Conv2D, MaxPool2D, Dropout, Dense, Flatten

def define_malexnet():
    input = keras.Input(shape=(224, 224, 3), name='data')
    x = Conv2D(16, kernel_size=(11,11), strides=(4,4), activation='relu', name='conv1')(input)
    x = MaxPool2D(pool_size=(3,3), strides=(2,2), padding='same', name='pool1')(x)
    x = Conv2D(20, kernel_size=(5,5), strides=(1,1), activation='relu', name='conv2')(x)
    x = MaxPool2D(pool_size=(3,3), strides=(2,2), name='pool2')(x)
    x = Conv2D(30, kernel_size=(3,3), strides=(1,1), activation='relu', name='conv3')(x)
    x = MaxPool2D(pool_size=(3,3), strides=(2,2), name='pool3')(x)
    x = Flatten()(x)
    x = Dense(48, activation='relu', name='fc4')(x)
    output = Dense(2, activation='softmax', name='fc5')(x)

    occupancy_model = keras.Model(input, output, name='occupancy_malexnet')
    occupancy_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return occupancy_model

Then I try to load the weights using this code snippet:

import numpy as np

weights_data = np.load('weights.npy', allow_pickle=True).item()
model = define_malexnet()

for layer in model.layers:
  if layer.name in weights_data.keys():
    layer_weights = weights_data[layer.name]
    layer.set_weights((layer_weights['weights'], layer_weights['bias']))

During this process I get an error:

ValueError: Layer conv1 weight shape (16,) is not compatible with
provided weight shape (1, 1, 1, 16).

Now as I understand this is because of the different backends and how they initialize weights, but I have not found a way to solve this problem. My question is, how do I tweak the weights loaded from the file to fit my keras model? Link to weights.npy file https://drive.google.com/file/d/1QKzY-WxiUnf9VnlhWQS38DE3uF5I_qTl/view?usp=sharing.

Body:
The problem is the bias vector.  It is shaped as a 4D tensor but Keras assumes it is a 1D tensor.  Just flatten the bias vector:

import numpy as np

weights_data = np.load('weights.npy', allow_pickle=True).item()
model = define_malexnet()

for layer in model.layers:
  if layer.name in weights_data.keys():
    layer_weights = weights_data[layer.name]
    layer.set_weights((layer_weights['weights'], layer_weights['bias'].flatten()))

As a sanity check, once I create your model I will access the conv1 weights and your corresponding weights you cached then compare them both:

In [22]: weights1 = model.layers[1].weights[0].numpy()

In [23]: weights2 = weights_data['conv1']['weights']

In [24]: np.allclose(weights1, weights2)
Out[24]: True

The same for the biases:

In [25]: bias1 = model.layers[1].weights[1].numpy()

In [26]: bias2 = weights_data['conv1']['bias']

In [27]: np.allclose(bias1, bias2)
Out[27]: True

Notice that I didn't have to flatten the biases from your cached results because np.allclose flattens singleton dimensions internally.


问:
Print a specific cell from a string array
I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).

I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.

I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".

(Yes, I tested this when I already inserted some data.)

Here's the full code:

```<code>
package appartamento;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Appartamento {
    public static void main(String[] args) throws IOException {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader keyb = new BufferedReader(input);
        boolean attiva = true;

        do {
            System.out.println("what do you want to do?");
            System.out.println("1 - check for a person");
            System.out.println("2 - Add person");
            int choice = Integer.parseInt(keyb.readLine());
            Datiutente du[] = new Datiutente[10];

            if (choice == 2){
                System.out.println("How many people?");
                int hm = Integer.parseInt(keyb.readLine());

                for (int i=0;i<hm;i++){
                    du[i] = new Datiutente();
                    System.out.println("insert name:");
                    du[i].setName(keyb.readLine());
                    System.out.println("insert surname");
                    du[i].setSurname(keyb.readLine());
                }
            }

            if (choice == 1){
                System.out.println("which person are you searching?");
                int vd = Integer.parseInt(keyb.readLine());
                System.out.println("position: " + i);
                System.out.println("Name: "+  du[i]);
                System.out.println("Surname: " + du[i]);
            }
        } while (attiva = true);
    }
}
</code>```

and the class "Datiutente":

```<code>package appartamento;

public class Datiutente {
    private String name;
    private String surname;
    private String codfis;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setSurname(String surname){
        this.surname = surname;
    }

    public String getSurname(){
        return surname;
    }
}
</code>```

答:
In every iteration you define the Datiutente du[] = new Datiutente[10];, so du is reset to {null,...,null} and the data saved in the previous iteration are replaced;

Try to define the array before the loop statement.

Body:
I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).

I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.

I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".

(Yes, I tested this when I already inserted some data.)

Here's the full code:

package appartamento;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Appartamento {
    public static void main(String[] args) throws IOException {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader keyb = new BufferedReader(input);
        boolean attiva = true;

        do {
            System.out.println("what do you want to do?");
            System.out.println("1 - check for a person");
            System.out.println("2 - Add person");
            int choice = Integer.parseInt(keyb.readLine());
            Datiutente du[] = new Datiutente[10];

            if (choice == 2){
                System.out.println("How many people?");
                int hm = Integer.parseInt(keyb.readLine());

                for (int i=0;i<hm;i++){
                    du[i] = new Datiutente();
                    System.out.println("insert name:");
                    du[i].setName(keyb.readLine());
                    System.out.println("insert surname");
                    du[i].setSurname(keyb.readLine());
                }
            }

            if (choice == 1){
                System.out.println("which person are you searching?");
                int vd = Integer.parseInt(keyb.readLine());
                System.out.println("position: " + i);
                System.out.println("Name: "+  du[i]);
                System.out.println("Surname: " + du[i]);
            }
        } while (attiva = true);
    }
}

and the class "Datiutente":

package appartamento;

public class Datiutente {
    private String name;
    private String surname;
    private String codfis;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setSurname(String surname){
        this.surname = surname;
    }

    public String getSurname(){
        return surname;
    }
}


问:
Getting first day of every week in 6 months
I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

```<code>2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc
</code>```

答:
If you're trying to make Saturday (or any other day for that matter)
  the first day of the week to select datasets,  here's a good
  workaround:

```<code><?php  $last_sat=date("z", strtotime("last Saturday"));
$second_last_sat=date("z", strtotime("last Saturday-1 week"));  ?>
</code>```

source: http://www.php.net/manual/en/function.strtotime.php

What you'd probably want is

```<code><?php  $last_mon=date("z", strtotime("last Monday "));
$second_last_mon=date("z", strtotime("last Monday-1 week"));  ?>
</code>```

etc..

Body:
I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc

Body:
If you're trying to make Saturday (or any other day for that matter)
  the first day of the week to select datasets,  here's a good
  workaround:

<?php  $last_sat=date("z", strtotime("last Saturday"));
$second_last_sat=date("z", strtotime("last Saturday-1 week"));  ?>

source: http://www.php.net/manual/en/function.strtotime.php

What you'd probably want is

<?php  $last_mon=date("z", strtotime("last Monday "));
$second_last_mon=date("z", strtotime("last Monday-1 week"));  ?>

etc..


问:
Property in Data is undefined inside methods() method
I'm brand new to Vue so trying to understand the basics so far. I'm using Vue 3.

My intention is to:

Create a select with the items in the array as options, this works.

Once the button is clicked, store the value of the select, this also works.

Push an object using the value of the select as an object's key's value

It's at this final stage that the error occurs, specifically the line getGeneMutationData: () => this.queryConstraints.push({

Error:

```<code>Uncaught TypeError: Cannot read properties of undefined (reading 'queryConstraints')
    at Proxy.getGeneMutationData (Query.vue?12c2:46:14)
    at eval (runtime-dom.esm-bundler.js?3191:380:1)
    at callWithErrorHandling (runtime-core.esm-bundler.js?a261:155:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:164:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:174:1)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?3191:366:39)
</code>```

I'm not sure why this isn't working, based on the documentation I'm not sure what's different in the approaches:

```<code>data() {
    return { count: 4 }
  },
  methods: {
    increment() {
      // `this` will refer to the component instance
      this.count++
    }
  }
</code>```

Here's a minimised of my code:

```<code><template>
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData">Get results</input>
</template>

<script>
  export default {
    name: 'Home',
    data: () => ({
      geneMutations: ['ACTC',
                      'MYBPC3'
      ],
      queryConstraints: [],
      selectedGeneMutation: ''
    }),
    setup() {},
    methods: {
      getGeneMutationData: () => this.queryConstraints.push({
        fieldPath: this.selectedGeneMutation,
        opStr: '==',
        value: true
      })
    }
  };
</script>
</code>```

Any help as to why I can't access the properties in 'data' would really be appreciated

答:
You are using an Arrow Function. It's limited and doesn't have its own binding to this, that's why your method fails. The documentation you're referring to is using a traditional function expression.

So in your case try this:

```<code>getGeneMutationData: function () {
  this.queryConstraints.push({
  fieldPath: this.selectedGeneMutation,
  opStr: "==",
  value: true,
});
</code>```

EDIT: Actually Nikola Pavicevic's answer is correct. Yes, using a traditional function expression solves your problem, however, it seems like mixing up composition and options API (or rather not understanding the difference between the two) is what caused the issue in the first place. In Vue 3, when you use composition API you're not using this. The setup() method returns an object, and all of its properties are exposed to the rest of the component.

Body:
I'm brand new to Vue so trying to understand the basics so far. I'm using Vue 3.

My intention is to:

Create a select with the items in the array as options, this works.

Once the button is clicked, store the value of the select, this also works.

Push an object using the value of the select as an object's key's value

It's at this final stage that the error occurs, specifically the line getGeneMutationData: () => this.queryConstraints.push({

Error:

Uncaught TypeError: Cannot read properties of undefined (reading 'queryConstraints')
    at Proxy.getGeneMutationData (Query.vue?12c2:46:14)
    at eval (runtime-dom.esm-bundler.js?3191:380:1)
    at callWithErrorHandling (runtime-core.esm-bundler.js?a261:155:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:164:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:174:1)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?3191:366:39)

I'm not sure why this isn't working, based on the documentation I'm not sure what's different in the approaches:

data() {
    return { count: 4 }
  },
  methods: {
    increment() {
      // `this` will refer to the component instance
      this.count++
    }
  }

Here's a minimised of my code:

<template>
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData">Get results</input>
</template>

Any help as to why I can't access the properties in 'data' would really be appreciated

Body:
You are using an Arrow Function. It's limited and doesn't have its own binding to this, that's why your method fails. The documentation you're referring to is using a traditional function expression.

So in your case try this:

getGeneMutationData: function () {
  this.queryConstraints.push({
  fieldPath: this.selectedGeneMutation,
  opStr: "==",
  value: true,
});

EDIT: Actually Nikola Pavicevic's answer is correct. Yes, using a traditional function expression solves your problem, however, it seems like mixing up composition and options API (or rather not understanding the difference between the two) is what caused the issue in the first place. In Vue 3, when you use composition API you're not using this. The setup() method returns an object, and all of its properties are exposed to the rest of the component.


问:
JavaScript Regex to capture repeating part of decimal
Looking for the best way to take an arbitrary number with potentially repeating decimal part, and discover the repeating part (if present).

Ultimately, I need to decorate the number with overline notation (either with css text-decoration or MathML mline), so I need to know the index of where the repetition begins also.

So I need regex that will get me (or can be used in an algorithm to get) the following results:

```<code>1.333 // result: {"pattern": 3, index: 0}
1.5444 // result: {"pattern": 4, index: 1}
1.123123 // result: {"pattern": 123, index: 0}
1.5432121212 // result: {"pattern": 12, index: 4}
1.321 // result: null
1.44212 // result: null
</code>```

Additional Example (from comments):

```<code>1.3333 // result: { "pattern": 3, index: 0}
</code>```

答:
The accepeted answer is OKish as per the given examples in the question are concerned. However if one day you find yourself here what you probably need is exactly what the topic says.

JavaScript Regex to capture repeating part of decimal

So you have the floating part of a string and you want to know if it is repeating or not. The accepted answer fails in practice. You can never guarantee that the string ends when the repeating part ends. Most of the time the string ends with a portion of the repeating part or sometimes *thanks* to the double precision errors jumps to irrelevant figures towards the end. So my suggestion is
```<code>/(\d+)\1+(?=\d*$)/g
</code>```

Now this is not a silver bullet. It's helpful but won't protect you from vampires like 3.1941070707811985 which happens to have no repetend at all. In order to feel it you have to develop deeper mechanisms. However in most cases it's just fine in percieving the repend like in

```<code>3.1941070707811985   // 07 which is wrong so prove it later
7.16666666810468     // 666 but reduce it to 6 later
3.00000000000001     // 000000 but reduce it to "" later
0.008928571428571428 // 285714 just fine, do nothing
</code>```

It is not an easy task to find if the floating part of a decimal has repetends or not in this environment. Most possibly you need to do further processing on the given string and the result of the regex for futher reduction / decision.

Body:
Looking for the best way to take an arbitrary number with potentially repeating decimal part, and discover the repeating part (if present).

Ultimately, I need to decorate the number with overline notation (either with css text-decoration or MathML mline), so I need to know the index of where the repetition begins also.

So I need regex that will get me (or can be used in an algorithm to get) the following results:

1.333 // result: {"pattern": 3, index: 0}
1.5444 // result: {"pattern": 4, index: 1}
1.123123 // result: {"pattern": 123, index: 0}
1.5432121212 // result: {"pattern": 12, index: 4}
1.321 // result: null
1.44212 // result: null

Additional Example (from comments):

1.3333 // result: { "pattern": 3, index: 0}

Body:
The accepeted answer is OKish as per the given examples in the question are concerned. However if one day you find yourself here what you probably need is exactly what the topic says.

JavaScript Regex to capture repeating part of decimal

So you have the floating part of a string and you want to know if it is repeating or not. The accepted answer fails in practice. You can never guarantee that the string ends when the repeating part ends. Most of the time the string ends with a portion of the repeating part or sometimes *thanks* to the double precision errors jumps to irrelevant figures towards the end. So my suggestion is

/(\d+)\1+(?=\d*$)/g

Now this is not a silver bullet. It's helpful but won't protect you from vampires like 3.1941070707811985 which happens to have no repetend at all. In order to feel it you have to develop deeper mechanisms. However in most cases it's just fine in percieving the repend like in

3.1941070707811985   // 07 which is wrong so prove it later
7.16666666810468     // 666 but reduce it to 6 later
3.00000000000001     // 000000 but reduce it to "" later
0.008928571428571428 // 285714 just fine, do nothing

It is not an easy task to find if the floating part of a decimal has repetends or not in this environment. Most possibly you need to do further processing on the given string and the result of the regex for futher reduction / decision.