问:
Python - getting errors in a text-based fighting game
I'm very new to Python and programming in general. I'm trying to make a simple text-based fighting game for my kids to play. It's the first program I've written on my own. I keep getting errors, and I'm not sure what it is I'm doing wrong.

Here's the code:

```<code>import random
print("Welcome to Sword Fight!")

#Character Stat Section
#Strength
x_strength = 8
y_strength = 7
z_strength = 4
a_strength = 2
#Speed
x_spd = 4
y_spd = 6
z_spd = 4
a_spd = 3
#Agility
x_agl = 3
y_agl = 5
z_agl = 6
a_agl = 2

#Weapon Stat Section
#Strength
katana_strength = 5
broadsword_strength = 6
spear_strength = 7
dagger_strength = 3
#Speed
katana_spd = 5
broadsword_spd = 4
spear_spd = 3
dagger_spd = 7
#Reach
katana_rch = 5
broadsword_rch = 6
spear_rch = 7
dagger_rch = 3

#Enemy Character Section
enemy = ['a goblin', 'a ninja', 'a swordfighter', 'an orc']
#Strength
goblin_strength = 2
ninja_strength = 4
swordfighter_strength = 5
orc_strength = 7
#Speed
goblin_spd = 4
ninja_spd = 7
swordfighter_spd = 5
orc_spd = 3
#Agility
goblin_agl = 3
ninja_agl = 6
swordfighter_agl = 5
orc_agl = 2

#Enemy Weapon Stat Section
#Strength
shiv_strength = 2
ninjato_strength = 4
longsword_strength = 5
axe_strength = 7
#Speed
shiv_spd = 6
ninjato_spd = 6
longsword_spd = 5
axe_spd = 3
#Reach
shiv_rch = 2
ninjato_rch = 4
longsword_rch = 5
axe_rch = 4

player = str(input("Select your character - X, Y, Z or A: "))
if player == "X" or "x":
    print("You've selected X.")
    p_strength = x_strength
    p_spd = x_spd
    p_agl = x_agl
elif player == "Y" or "y":
    print("You've selected Y.")
    p_strength = y_strength
    p_spd = y_spd
    p_agl = y_agl
elif player == "Z" or "z":
    print("You've selected Z.")
    p_strength = z_strength
    p_spd = z_spd
    p_agl = z_agl
elif player == "A" or "a":
    print("You've selected A.")
    p_strength = a_strength
    p_spd = a_spd
    p_agl = a_agl

weapon = str(input("Select your weapon - katana, broadsword, spear, or dagger: "))
if weapon == "Katana" or "katana":
    p_weap = 'katana'
    print("You've selected a katana.")
    w_strength = katana_strength
    w_spd = katana_spd
    w_rch = katana_rch
elif weapon == "Broadsword" or "broadsword":
    p_weap = 'broadsword'
    print("You've selected a broadsword.")
    w_strength = broadsword_strength
    w_spd = broadsword_spd
    w_rch = broadsword_rch
elif weapon == "Spear" or "spear":
    p_weap = 'spear'
    print("You've selected a spear.")
    w_strength = spear_strength
    w_spd = spear_spd
    w_rch = spear_rch
elif weapon == "Dagger" or "dagger":
    p_weap = 'dagger'
    print("You've selected a dagger.")
    w_strength = dagger_strength
    w_spd = dagger_spd
    w_rch = dagger_rch

print("An enemy approaches! It's", random.choice(enemy), "!")

if random.choice(enemy) == 'a goblin':
    print("It's armed with a shiv.")
    e_strength = goblin_strength
    e_spd = goblin_spd
    e_agl = goblin_agl
    ew_strength = shiv_strength
    ew_spd = shiv_spd
    ew_rch = shiv_rch
elif random.choice(enemy) == 'a ninja':
    print("He's armed with a ninjato.")
    e_strength = ninja_strength
    e_spd = ninja_spd
    e_agl = ninja_agl
    ew_strength = ninjato_strength
    ew_spd = ninjato_spd
    ew_rch = ninjato_rch
elif random.choice(enemy) == 'a swordfighter':
    print("She's armed with a longsword.")
    e_strength = swordfighter_strength
    e_spd = swordfighter_spd
    e_agl = swordfighter_agl
    ew_strength = longsword_strength
    ew_spd = longsword_spd
    ew_rch = longsword_rch
elif random.choice(enemy) == 'an orc':
    print("It's armed with a battleaxe.")
    e_strength = orc_strength
    e_spd = orc_spd
    e_agl = orc_agl
    ew_strength = axe_strength
    ew_spd = axe_spd
    ew_rch = axe_rch

print("The battle begins!")

p_hp = 10
e_hp = 10

while p_hp > 0 or e_hp > 0:
    print = ("Which attack will you use?")
    if p_weap == 'katana':
        attack = str(input("Slice, Stab, or Spinning Slash?: "))
    if attack == 'Slice' or 'slice':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Spinning slash' or 'spinning slash' or 'Spinning Slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'broadsword':
        attack = str(input("Overhead chop, Stab, or Slash?: "))
    if attack == 'Overhead chop' or 'overhead chop' or 'Overhead Chop':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Slash' or 'slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'spear':
        attack = str(input("Slam, Swipe, or Thrust?: "))
    if attack == 'Slam' or 'slam':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Swipe' or 'swipe':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'dagger':
        attack = str(input("Slash, Stab, or Thrust?: "))
    if attack == 'Slash' or 'slash':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

if p_hp == 0:
    print("You have been defeated...")
if e_hp == 0:
    print("You are victorious!")
</code>```

I'm sure there are simpler ways I could be doing all of this, but I haven't yet learned more advanced commands or techniques.

The first error I'm running into is that no matter what the user enters for their character selection, the program only picks character X.

Second error - regardless of what weapon the user selects, the program picks the katana.

Third error - when the program selects an enemy, sometimes it selects the correct enemy weapon, sometimes the wrong enemy weapon, and sometimes it doesn't select an enemy weapon at all.

Fourth error - If the program selects an enemy and the correct enemy weapon, I get a traceback error when the user enters an attack:

```<code>line 171, in <module>
    print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $
</code>```

Fifth error - When the program fails to select an enemy weapon, and the user enters an attack, I get a different traceback error:

```<code>line 168, in <module>
    e_atk = (e_strength + ew_strength)
NameError: name 'e_strength' is not defined
1|:/ $
</code>```

Sixth error - when the program selects an enemy and the incorrect enemy weapon, and the user enters an attack, another traceback error:

```<code>line 174, in <module>
    print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $
</code>```

Any help would be appreciated. Thanks!

答:
the third issue is that every time you run random.choice(enemy), it randomly picks a new enemy every time. You should put random.choice(enemy) into a variable and then run through the if/else statements.

as for the fourth issue, I would suggest using .format instead.

before

```<code>print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
</code>```

after

```<code>print("You slice the enemy and do {} points of damage.".format(p_atk - e_atk))
</code>```

The fifth and sixth errors should be fixed when putting random.choice(enemy) into a variable.

Body:
I'm very new to Python and programming in general. I'm trying to make a simple text-based fighting game for my kids to play. It's the first program I've written on my own. I keep getting errors, and I'm not sure what it is I'm doing wrong.

Here's the code:

import random
print("Welcome to Sword Fight!")

#Character Stat Section
#Strength
x_strength = 8
y_strength = 7
z_strength = 4
a_strength = 2
#Speed
x_spd = 4
y_spd = 6
z_spd = 4
a_spd = 3
#Agility
x_agl = 3
y_agl = 5
z_agl = 6
a_agl = 2

#Weapon Stat Section
#Strength
katana_strength = 5
broadsword_strength = 6
spear_strength = 7
dagger_strength = 3
#Speed
katana_spd = 5
broadsword_spd = 4
spear_spd = 3
dagger_spd = 7
#Reach
katana_rch = 5
broadsword_rch = 6
spear_rch = 7
dagger_rch = 3

#Enemy Character Section
enemy = ['a goblin', 'a ninja', 'a swordfighter', 'an orc']
#Strength
goblin_strength = 2
ninja_strength = 4
swordfighter_strength = 5
orc_strength = 7
#Speed
goblin_spd = 4
ninja_spd = 7
swordfighter_spd = 5
orc_spd = 3
#Agility
goblin_agl = 3
ninja_agl = 6
swordfighter_agl = 5
orc_agl = 2

#Enemy Weapon Stat Section
#Strength
shiv_strength = 2
ninjato_strength = 4
longsword_strength = 5
axe_strength = 7
#Speed
shiv_spd = 6
ninjato_spd = 6
longsword_spd = 5
axe_spd = 3
#Reach
shiv_rch = 2
ninjato_rch = 4
longsword_rch = 5
axe_rch = 4

player = str(input("Select your character - X, Y, Z or A: "))
if player == "X" or "x":
    print("You've selected X.")
    p_strength = x_strength
    p_spd = x_spd
    p_agl = x_agl
elif player == "Y" or "y":
    print("You've selected Y.")
    p_strength = y_strength
    p_spd = y_spd
    p_agl = y_agl
elif player == "Z" or "z":
    print("You've selected Z.")
    p_strength = z_strength
    p_spd = z_spd
    p_agl = z_agl
elif player == "A" or "a":
    print("You've selected A.")
    p_strength = a_strength
    p_spd = a_spd
    p_agl = a_agl

weapon = str(input("Select your weapon - katana, broadsword, spear, or dagger: "))
if weapon == "Katana" or "katana":
    p_weap = 'katana'
    print("You've selected a katana.")
    w_strength = katana_strength
    w_spd = katana_spd
    w_rch = katana_rch
elif weapon == "Broadsword" or "broadsword":
    p_weap = 'broadsword'
    print("You've selected a broadsword.")
    w_strength = broadsword_strength
    w_spd = broadsword_spd
    w_rch = broadsword_rch
elif weapon == "Spear" or "spear":
    p_weap = 'spear'
    print("You've selected a spear.")
    w_strength = spear_strength
    w_spd = spear_spd
    w_rch = spear_rch
elif weapon == "Dagger" or "dagger":
    p_weap = 'dagger'
    print("You've selected a dagger.")
    w_strength = dagger_strength
    w_spd = dagger_spd
    w_rch = dagger_rch

print("An enemy approaches! It's", random.choice(enemy), "!")

if random.choice(enemy) == 'a goblin':
    print("It's armed with a shiv.")
    e_strength = goblin_strength
    e_spd = goblin_spd
    e_agl = goblin_agl
    ew_strength = shiv_strength
    ew_spd = shiv_spd
    ew_rch = shiv_rch
elif random.choice(enemy) == 'a ninja':
    print("He's armed with a ninjato.")
    e_strength = ninja_strength
    e_spd = ninja_spd
    e_agl = ninja_agl
    ew_strength = ninjato_strength
    ew_spd = ninjato_spd
    ew_rch = ninjato_rch
elif random.choice(enemy) == 'a swordfighter':
    print("She's armed with a longsword.")
    e_strength = swordfighter_strength
    e_spd = swordfighter_spd
    e_agl = swordfighter_agl
    ew_strength = longsword_strength
    ew_spd = longsword_spd
    ew_rch = longsword_rch
elif random.choice(enemy) == 'an orc':
    print("It's armed with a battleaxe.")
    e_strength = orc_strength
    e_spd = orc_spd
    e_agl = orc_agl
    ew_strength = axe_strength
    ew_spd = axe_spd
    ew_rch = axe_rch

print("The battle begins!")

p_hp = 10
e_hp = 10

while p_hp > 0 or e_hp > 0:
    print = ("Which attack will you use?")
    if p_weap == 'katana':
        attack = str(input("Slice, Stab, or Spinning Slash?: "))
    if attack == 'Slice' or 'slice':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Spinning slash' or 'spinning slash' or 'Spinning Slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'broadsword':
        attack = str(input("Overhead chop, Stab, or Slash?: "))
    if attack == 'Overhead chop' or 'overhead chop' or 'Overhead Chop':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Slash' or 'slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'spear':
        attack = str(input("Slam, Swipe, or Thrust?: "))
    if attack == 'Slam' or 'slam':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Swipe' or 'swipe':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'dagger':
        attack = str(input("Slash, Stab, or Thrust?: "))
    if attack == 'Slash' or 'slash':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

if p_hp == 0:
    print("You have been defeated...")
if e_hp == 0:
    print("You are victorious!")

I'm sure there are simpler ways I could be doing all of this, but I haven't yet learned more advanced commands or techniques.

The first error I'm running into is that no matter what the user enters for their character selection, the program only picks character X.

Second error - regardless of what weapon the user selects, the program picks the katana.

Third error - when the program selects an enemy, sometimes it selects the correct enemy weapon, sometimes the wrong enemy weapon, and sometimes it doesn't select an enemy weapon at all.

Fourth error - If the program selects an enemy and the correct enemy weapon, I get a traceback error when the user enters an attack:

line 171, in <module>
    print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $

Fifth error - When the program fails to select an enemy weapon, and the user enters an attack, I get a different traceback error:

line 168, in <module>
    e_atk = (e_strength + ew_strength)
NameError: name 'e_strength' is not defined
1|:/ $

Sixth error - when the program selects an enemy and the incorrect enemy weapon, and the user enters an attack, another traceback error:

line 174, in <module>
    print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $

Any help would be appreciated. Thanks!

Body:
the third issue is that every time you run random.choice(enemy), it randomly picks a new enemy every time. You should put random.choice(enemy) into a variable and then run through the if/else statements.

as for the fourth issue, I would suggest using .format instead.

before

print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")

after

print("You slice the enemy and do {} points of damage.".format(p_atk - e_atk))

The fifth and sixth errors should be fixed when putting random.choice(enemy) into a variable.


来源: stackexchange

问:
Python zip function with iterator vs iterable
I am having trouble understanding working of the zip() function in python when an iterator is passed in instead of iterable.

Have a look at these two print statements:

```<code>string = "ABCDEFGHI"

print(list(zip(*[iter(string)] * 3)))
# Output: [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

print(list(zip(*[string] * 3)))
# Output: [('A', 'A', 'A'), ('B', 'B', 'B'), ('C', 'C', 'C'), ('D', 'D', 'D'), ('E', 'E', 'E'), ('F', 'F', 'F'), ('G', 'G', 'G'), ('H', 'H', 'H'), ('I', 'I', 'I')]
</code>```

Can someone explain me the working of zip() in both the cases?

答:
Let's use a clearer example:

```<code>a = iter("123456")  # One iterator
list(zip(a, a, a))
# [('1', '2', '3'), ('4', '5', '6')]
</code>```

vs

```<code>a = iter("123456")
b = iter("123456")
c = iter("123456")
list(zip(a, b, c))
# [('1', '1', '1'), ('2', '2', '2'), ('3', '3', '3'), ('4', '4', '4'), ('5', '5', '5'), ('6', '6', '6')]
</code>```

Obviously in the first example a can only yield 6 elements, and has to yield 3 to zip whenever zip needs to create a value.  In contrast, the second example has 18 elements total, and yields them in 6 groups of 3.

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble understanding working of the zip() function in python when an iterator is passed in instead of iterable.

Have a look at these two print statements:

string = "ABCDEFGHI"

print(list(zip(*[iter(string)] * 3)))
# Output: [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

print(list(zip(*[string] * 3)))
# Output: [('A', 'A', 'A'), ('B', 'B', 'B'), ('C', 'C', 'C'), ('D', 'D', 'D'), ('E', 'E', 'E'), ('F', 'F', 'F'), ('G', 'G', 'G'), ('H', 'H', 'H'), ('I', 'I', 'I')]

Can someone explain me the working of zip() in both the cases?

Body:
Let's use a clearer example:

a = iter("123456")  # One iterator
list(zip(a, a, a))
# [('1', '2', '3'), ('4', '5', '6')]

vs

a = iter("123456")
b = iter("123456")
c = iter("123456")
list(zip(a, b, c))
# [('1', '1', '1'), ('2', '2', '2'), ('3', '3', '3'), ('4', '4', '4'), ('5', '5', '5'), ('6', '6', '6')]

Obviously in the first example a can only yield 6 elements, and has to yield 3 to zip whenever zip needs to create a value.  In contrast, the second example has 18 elements total, and yields them in 6 groups of 3.


问:
Wordpress category href issue
Hi I was just wondering if there was any way using wordpress to change the Href of the li items outputted from this;

```<code><?php
                    if (is_category()) {
                         $this_category = get_category($cat);
                    if (get_category_children($this_category->cat_ID) != "") {
                         echo "<ul>";
                         echo str_replace('','', wp_list_categories('orderby=id&show_count=0&title_li=
                         &use_desc_for_title=1&child_of='.$this_category->cat_ID));
                         echo "</ul>";
                         }
                    }
                ?>
</code>```

So that the Href is simply an anchor to the id of the category li that has been pressed ie, the anchor within li item cat-item-11 would have a href of "#cat-item11"

Hope that makes sense!

Cheers

答:
There is not a way to tell wp_list_categories to add that to the link. You would likely be on the hook for writing your own function to pull out categories and display them as a nested list. </p>

<p>If you are open to a javascript solution, you could easily loop through the li elements when the page loads and add the hash to the url then. If you were using the hash for some sort of ajax effects, then there would definitely be no reason not to go that route. </p>

ContentLicense: CC BY-SA 3.0

Title: Wordpress category href issue

Body:
Hi I was just wondering if there was any way using wordpress to change the Href of the li items outputted from this;

<?php
                    if (is_category()) {
                         $this_category = get_category($cat);
                    if (get_category_children($this_category->cat_ID) != "") {
                         echo "
";
                         echo str_replace('','', wp_list_categories('orderby=id&show_count=0&title_li=
                         &use_desc_for_title=1&child_of='.$this_category->cat_ID));
                         echo "
";
                         }
                    }
                ?>

So that the Href is simply an anchor to the id of the category li that has been pressed ie, the anchor within li item cat-item-11 would have a href of "#cat-item11"

Hope that makes sense!

Cheers

Body:
There is not a way to tell wp_list_categories to add that to the link. You would likely be on the hook for writing your own function to pull out categories and display them as a nested list.

If you are open to a javascript solution, you could easily loop through the li elements when the page loads and add the hash to the url then. If you were using the hash for some sort of ajax effects, then there would definitely be no reason not to go that route.


问:
Where are the logs for HRegionServer?
When running jps, I see that I have no HRegionServer running, as in this question.

But in that question, he's showing some HRegionServer logs that I can't find. All I have about HRegionServer is part of the general hbase log:

```<code>2014-06-16 16:42:58,845 FATAL [RS:0;test-254:35769] regionserver.HRegionServer: ABORTING region server test-254.office,35769,1402929575620: Initi
alization of RS failed.  Hence aborting RS.
java.io.IOException: Received the shutdown message while waiting.
        at org.apache.hadoop.hbase.regionserver.HRegionServer.blockAndCheckIfStopped(HRegionServer.java:736)
        at org.apache.hadoop.hbase.regionserver.HRegionServer.initializeZooKeeper(HRegionServer.java:691)
        at org.apache.hadoop.hbase.regionserver.HRegionServer.preRegistrationInitialization(HRegionServer.java:657)
        at org.apache.hadoop.hbase.regionserver.HRegionServer.run(HRegionServer.java:785)
        at java.lang.Thread.run(Thread.java:744)
2014-06-16 16:42:58,848 FATAL [RS:0;test-254:35769] regionserver.HRegionServer: RegionServer abort: loaded coprocessors are: []
2014-06-16 16:42:58,848 INFO  [RS:0;test-254:35769] regionserver.HRegionServer: STOPPED: Initialization of RS failed.  Hence aborting RS.
</code>```

I have nothing HMaster/HRegionServer specific as the guy in that question. Do I need to specify it in some property?

答: In Cloudera 6.3.1 it's in /var/log/hbase/hbase-cmf-hbase-REGIONSERVER-host.log.out</p>

Title: Where are the logs for HRegionServer?

Body:
When running jps, I see that I have no HRegionServer running, as in this question.

But in that question, he's showing some HRegionServer logs that I can't find. All I have about HRegionServer is part of the general hbase log:

2014-06-16 16:42:58,845 FATAL [RS:0;test-254:35769] regionserver.HRegionServer: ABORTING region server test-254.office,35769,1402929575620: Initi
alization of RS failed.  Hence aborting RS.
java.io.IOException: Received the shutdown message while waiting.
        at org.apache.hadoop.hbase.regionserver.HRegionServer.blockAndCheckIfStopped(HRegionServer.java:736)
        at org.apache.hadoop.hbase.regionserver.HRegionServer.initializeZooKeeper(HRegionServer.java:691)
        at org.apache.hadoop.hbase.regionserver.HRegionServer.preRegistrationInitialization(HRegionServer.java:657)
        at org.apache.hadoop.hbase.regionserver.HRegionServer.run(HRegionServer.java:785)
        at java.lang.Thread.run(Thread.java:744)
2014-06-16 16:42:58,848 FATAL [RS:0;test-254:35769] regionserver.HRegionServer: RegionServer abort: loaded coprocessors are: []
2014-06-16 16:42:58,848 INFO  [RS:0;test-254:35769] regionserver.HRegionServer: STOPPED: Initialization of RS failed.  Hence aborting RS.

I have nothing HMaster/HRegionServer specific as the guy in that question. Do I need to specify it in some property?


问:
How to get the 3 highest values in a HashMap?
I have a hashmap which is the following:

```<code>    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);
</code>```

How would I get the keys which have the 3 highest values? So it would return:

```<code>    "c", "e", "b"
</code>```

Thanks.

答:
My solution, sort by values and get top 3 and return key list.

List<String> keys = hm.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).limit(3).map(Map.Entry::getKey).collect(Collectors.toList());

```

Hope it helps

Body:
I have a hashmap which is the following:

    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);

How would I get the keys which have the 3 highest values? So it would return:

    "c", "e", "b"

Thanks.

Body:
My solution, sort by values and get top 3 and return key list.

List<String> keys = hm.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).limit(3).map(Map.Entry::getKey).collect(Collectors.toList());

Hope it helps


问:
How to solve missing 1 required positional argument in this python code?
I am testing these two string characters whether they are string permutation or not for the following python code but I am getting error which I have attached after the code.

```<code>from collections import Counter

    str_1 = "driving"
    str_2 = "drivign"

    def check_permutation(str_1,str_2):
        if len(str_1) != len(str_2):
            return False
        counter = Counter()
        for c in str_1:
            counter[c] += 1
        for c in str_2:
            if counter[c] == 0:
                return False
            counter[c] -= 1
        return True
    print(check_permutation((str_1, str_2)))
</code>```

Error:

```<code>Traceback (most recent call last):
TypeError: check_permutation() missing 1 required positional argument: 'str_2'
</code>```

How can I solve this error and print the output in console?

答:
I guess you just had extra parentheses in your code, with minor indentation issue in your inputs str_1 and str_2:

Also, it would be best to declare your variables close to where you would be calling or using them.

You can also improve a little bit on naming your variables.

Code

```<code>from collections import Counter

def check_permutation(str_1, str_2):
    if len(str_1) != len(str_2):
        return False
    count_map = Counter()
    for char in str_1:
        count_map[char] += 1
    for char in str_2:
        if count_map[char] == 0:
            return False
        count_map[char] -= 1
    return True

str_1 = "driving"
str_2 = "drivign"

print(check_permutation(str_1, str_2))

</code>```

Output

```<code>True
</code>```

I guess, the following code would probably be what you are trying to do:

```<code>from collections import Counter

def check_permutation(str_1, str_2):
    if len(str_1) != len(str_2):
        return False
    count_map_1 = Counter(str_1)
    count_map_2 = Counter(str_2)
    return count_map_2 == count_map_1

str_1 = "driving"
str_2 = "drivign"
</code>```

Body:
I am testing these two string characters whether they are string permutation or not for the following python code but I am getting error which I have attached after the code.

from collections import Counter

    str_1 = "driving"
    str_2 = "drivign"

    def check_permutation(str_1,str_2):
        if len(str_1) != len(str_2):
            return False
        counter = Counter()
        for c in str_1:
            counter[c] += 1
        for c in str_2:
            if counter[c] == 0:
                return False
            counter[c] -= 1
        return True
    print(check_permutation((str_1, str_2)))

Error:

Traceback (most recent call last):
TypeError: check_permutation() missing 1 required positional argument: 'str_2'

How can I solve this error and print the output in console?

Body:
I guess you just had extra parentheses in your code, with minor indentation issue in your inputs str_1 and str_2:

Also, it would be best to declare your variables close to where you would be calling or using them.

You can also improve a little bit on naming your variables.

Code

from collections import Counter

def check_permutation(str_1, str_2):
    if len(str_1) != len(str_2):
        return False
    count_map = Counter()
    for char in str_1:
        count_map[char] += 1
    for char in str_2:
        if count_map[char] == 0:
            return False
        count_map[char] -= 1
    return True

str_1 = "driving"
str_2 = "drivign"

print(check_permutation(str_1, str_2))

Output

True

I guess, the following code would probably be what you are trying to do:

from collections import Counter

def check_permutation(str_1, str_2):
    if len(str_1) != len(str_2):
        return False
    count_map_1 = Counter(str_1)
    count_map_2 = Counter(str_2)
    return count_map_2 == count_map_1

str_1 = "driving"
str_2 = "drivign"


问:
How to make this simple generic function type check without introducing an ugly cast?
Learning TypeScript and hitting my head on the wall with this for the last 3 days. Can be simplified as this:

```<code>type StrKeyStrVal = {
    [key: string]: string
};

function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: string) {
    obj[key] = value;
}
</code>```

Basically, I have objects with string keys and (only) string values. I want to have a generic function that can set any string key on this object to any string value. Sounds very simple but TypeScript (strict) complains about the above obj[key] = value; assignment. I figured this happened after the following changes: https://github.com/microsoft/TypeScript/pull/30769

The above works fine before TypeScript 3.5 but the behavior was deemed unsafe. I can't see how this can be unsafe under these conditions. My object can only have string keys, the values can only be strings, T extends this type, obj is T, key is a keyof T, value is string, how can this ever be unsafe? What can I do to show TypeScript to show this is fine without jumping out of the type safety?

答:
It's unsafe for the same reason that this is unsafe: the caller chooses the type parameter, which can be narrower than the generic constraint, and one way to make a type narrower is to narrow its property types.  So the type Shirt defined as

```<code>type Shirt = { size: "S" | "M" | "L", color: string }
const redShirt: Shirt = { size: "L", color: "red" };
</code>```

is a subtype of StrKeyStrVal:

```<code>const strKeyStrVal: StrKeyStrVal = redShirt; // okay
</code>```

and that's a problem for you, because the size property is strictly narrower than string, and if you're not careful you'll assign some unacceptable string to it:

```<code>setKeyVal(redShirt, "size", "XXXXXL"); // oops
</code>```

So, what can you do?  If you don't expect to run into the above situation you can just a type assertion and move on.  If you want to avoid type assertions, you need to refactor.

One way to refactor which is just as unsafe as an assertion is to remove the generics:

```<code>function setKeyVal(obj: StrKeyStrVal, key: string, value: string) {
  obj[key] = value; // okay
}
setKeyVal(redShirt, "size", "XXXXXL"); // oops!
</code>```

That's because TypeScript is unsafe in places, and non-generic supertype property writing is one such place.  See microsoft/TypeScript#14150 for discussion about this.  The conclusion of that issue is that it would be incredibly annoying for many people to use TypeScript if it didn't allow property writes to supertypes.  So productivity wins out over type safety here.  That might be what you want in this case.

One safer way to refactor is to make the function sufficiently generic that it will only accept the right strings for the right keys:

```<code>  function setKeyVal<T extends StrKeyStrVal, K extends keyof T>(obj: T, key: K, value: T[K]) {
    obj[key] = value; // okay now
  }
</code>```

The implementation is now seen as safe, and the bad call above with redShirt now throws an error at the call site:

```<code>  setKeyVal(redShirt, "size", "XXXXXL"); // error!
  // -----------------------> ~~~~~~~~
  // Argument of type '"XXXXXL"' is not assignable to parameter of type '"S" | "M" | "L"'
</code>```

Now we have a function which is harder to use incorrectly, but is also harder to use and harder to annotate.  You get more type safety, but at some cost.

I guess it depends on your use cases and your priorities which way you want to proceed.  In any case I hope this helps make sense of the situation.  Good luck!

Playground link to code

Body:
Learning TypeScript and hitting my head on the wall with this for the last 3 days. Can be simplified as this:

type StrKeyStrVal = {
    [key: string]: string
};

function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: string) {
    obj[key] = value;
}

Basically, I have objects with string keys and (only) string values. I want to have a generic function that can set any string key on this object to any string value. Sounds very simple but TypeScript (strict) complains about the above obj[key] = value; assignment. I figured this happened after the following changes: https://github.com/microsoft/TypeScript/pull/30769

The above works fine before TypeScript 3.5 but the behavior was deemed unsafe. I can't see how this can be unsafe under these conditions. My object can only have string keys, the values can only be strings, T extends this type, obj is T, key is a keyof T, value is string, how can this ever be unsafe? What can I do to show TypeScript to show this is fine without jumping out of the type safety?

Body:
It's unsafe for the same reason that this is unsafe: the caller chooses the type parameter, which can be narrower than the generic constraint, and one way to make a type narrower is to narrow its property types.  So the type Shirt defined as

type Shirt = { size: "S" | "M" | "L", color: string }
const redShirt: Shirt = { size: "L", color: "red" };

is a subtype of StrKeyStrVal:

const strKeyStrVal: StrKeyStrVal = redShirt; // okay

and that's a problem for you, because the size property is strictly narrower than string, and if you're not careful you'll assign some unacceptable string to it:

setKeyVal(redShirt, "size", "XXXXXL"); // oops

So, what can you do?  If you don't expect to run into the above situation you can just a type assertion and move on.  If you want to avoid type assertions, you need to refactor.

One way to refactor which is just as unsafe as an assertion is to remove the generics:

function setKeyVal(obj: StrKeyStrVal, key: string, value: string) {
  obj[key] = value; // okay
}
setKeyVal(redShirt, "size", "XXXXXL"); // oops!

That's because TypeScript is unsafe in places, and non-generic supertype property writing is one such place.  See microsoft/TypeScript#14150 for discussion about this.  The conclusion of that issue is that it would be incredibly annoying for many people to use TypeScript if it didn't allow property writes to supertypes.  So productivity wins out over type safety here.  That might be what you want in this case.

One safer way to refactor is to make the function sufficiently generic that it will only accept the right strings for the right keys:

  function setKeyVal<T extends StrKeyStrVal, K extends keyof T>(obj: T, key: K, value: T[K]) {
    obj[key] = value; // okay now
  }

The implementation is now seen as safe, and the bad call above with redShirt now throws an error at the call site:

  setKeyVal(redShirt, "size", "XXXXXL"); // error!
  // -----------------------> ~~~~~~~~
  // Argument of type '"XXXXXL"' is not assignable to parameter of type '"S" | "M" | "L"'

Now we have a function which is harder to use incorrectly, but is also harder to use and harder to annotate.  You get more type safety, but at some cost.

I guess it depends on your use cases and your priorities which way you want to proceed.  In any case I hope this helps make sense of the situation.  Good luck!

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAysBOBpCI7wGoEMA2UC8UA3gFBRQDaA1igFxQDOCAlgHYDmAunY-K28QF8A3MVLFQkWAAsm8YPiIMmALwh0ARDHVQAPlHUBZbXvUAZdQBooAYwD22W-G7N2UAcTstGUeBAAmMDJydIGy8gSESqoa5lZ2Dk76vn7awh62XvI8yKgIWNghCDlo+QrJoXJCUAD01VC2lJggxCyYALYQ9GCY1tAA8rZg9ESkUABmAK4s1sBMGQwQwDn5ADwAKlAQAB7AECx+w2jFeTgAfAAUtgBGAFZ0a1bUIHRPtmNQD1AAbjgTagwuNgAShGZDI1xuVBQHAUP2wfxEZHcZHoi2WOHO5SCwCs6noKggln0AA1SaTzECqrV6oN6KJ3K0Ol0etBTJ16ABxPYQXjWUHjKYzOYsBZLFD5S63QpIFAlHCPWgA3jsKxwv7OZXA-ng25QkAwghqiBUuoNJqjZGi9HYTH+Co4-T41RE9Rk8nqSk1U20gCE9NEjM63V6UAMjggXJYPKYfJIZEm01m81RYpAqw2212+0ORVlJ2wVkQmx2ewOUFe7zWFwh9wVzygiFVv3+a3IiA4ILjYIheoN32bJvqjWaSNGKettoC2NxTsJuLdxIpg558EcfrI1IAtNud7u9-vt6coAA-U9n0+jakAQXgbAmHRY8jeUAk0AA5K63eY31AmMMWLY8iYPQ+JsK0VzYNAwC2FA3TwO0iw8vU7yvlAH5aLo+hGJhZjqG+giiEAA" rel="nofollow noreferrer">Playground link to code


问:
unable to remove class added by addClass on hover
i have this simple jquery which adds hide_share class after 10 seconds and it works flawlessely but i want to remove that class when users hovers over that.

```<code>.hide_share {
    opacity :0.1;
}
</code>```

this function adds that hide_share class

```<code>    setTimeout(function() {$("#main_id").addClass("hide_share");}, 10000);
</code>```

but when users brings cursor i want to remove hide_share class so that it is again visible

seems very simple but wasted my several hours then i searched whole stackoverflow and tried all ideas given by experts but none worked

here is my remove function

```<code> $("#main_id").hover(function () {$(this).removeClass("hide_share");} );
</code>```

when i run same thing in console it works and i can see that class is removed but not directly.

i have tried doing everything even added script tag in head but that also did not work and removed that.
i tried child parameter and everythig,

here is html

```<code><div id="main_id" class="button-position-left hide_share"><div class="button-label"><span>Share</span></div><div class="button2">Img_here</div></div>
</code>```

can anyone tell where i am doing mistake. i have used similar code and it used to work flawlessely.

答:
Maybe you're looking for this:

$("#main_id").hover(function () {
  $(this).removeClass("hide_share");
}, function () {
  $(this).addClass("hide_share");
});

setTimeout(function() {$("#main_id").addClass("hide_share");}, 10000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide_share {
    opacity :0.1;
}

#main_id {
  width: 100px;
  height: 100px;
  background-color: cyan;
}</code>```

```

.hover() method supports 2 parameters: handlerIn and handlerOut. You can set event when user leaves the cusor as the second parameter.

Body:
i have this simple jquery which adds hide_share class after 10 seconds and it works flawlessely but i want to remove that class when users hovers over that.

.hide_share {
    opacity :0.1;
}

this function adds that hide_share class

    setTimeout(function() {$("#main_id").addClass("hide_share");}, 10000);

but when users brings cursor i want to remove hide_share class so that it is again visible

seems very simple but wasted my several hours then i searched whole stackoverflow and tried all ideas given by experts but none worked

here is my remove function

 $("#main_id").hover(function () {$(this).removeClass("hide_share");} );

when i run same thing in console it works and i can see that class is removed but not directly.

i have tried doing everything even added script tag in head but that also did not work and removed that.
i tried child parameter and everythig,

here is html

Share

Img_here

can anyone tell where i am doing mistake. i have used similar code and it used to work flawlessely.

Body:
Maybe you're looking for this:

$("#main_id").hover(function () {
  $(this).removeClass("hide_share");
}, function () {
  $(this).addClass("hide_share");
});

setTimeout(function() {$("#main_id").addClass("hide_share");}, 10000);

.hide_share {
    opacity :0.1;
}

#main_id {
  width: 100px;
  height: 100px;
  background-color: cyan;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="main_id" class="button-position-left"></div>

.hover() method supports 2 parameters: handlerIn and handlerOut. You can set event when user leaves the cusor as the second parameter.


问:
php.ini Error Reporting problem
I get this error: Warning: date() [function.date]: It is not safe to rely on the system's timezone settings.

In php.ini I have error reporting set as error_reporting = E_ALL & ~E_NOTICE.

Any idea how I can get rid of those warnings?

EDIT:

I want to fix the Error Reporting as there's other kinds of Warnings showing up.

EDIT 2:

All warnings were date.timezone related.

Thank you.

答: you could just catch that warning using the @ operator. Turning off warnings is ill advised in my view</p>

Title: php.ini Error Reporting problem


问:
how hide/show dynamically created nodes in javafx?
I have created multiple nodes dynamically. Now, I have to find specific node when it is clicked, it must hide all other node in the pane. Also, When I click it again it should display the hidden node.

For example,In the attached image, the down-arrow icon on root node is clicked, it must hide all other nodes and when it is clicked second time, it must show the hidden nodes again.
This how I am creating the buttons.

```<code>  Node_Basic_Event_Node anode = new Node_Basic_Event_Node(calcNode_Id("Basic_Event_Node"), "Basic_Event_Node", editorName, editorType); anode.relocate(50, 50); elementsContent.getChildren().add(anode);
</code>```

Now, How I can hide nodes when clicking on root node's down-arrow icon in the image? I tried this sample of code but it is hiding all nodes including "root node"

```<code>    Pane elementsContent = (Pane) getParent();
    for (Node node : elementsContent.getChildren()) {
            node.managedProperty().set(true);
            node.setVisible(false);
    }
</code>```

答:
I am not absolutly sure where your problem exactly is, but I created a small example which will hopefully help you. The button which should not change visibility (here: certain text) is simply filtered out every time.</p>

```<code>package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.util.Optional;
import java.util.Random;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        VBox vBox = new VBox();

        Random random = new Random();
        int randomIndex = random.nextInt(10);

        String chosen = "The Chosen One", simple = "Simple Button";

        for (int i = 0; i < 10; i++) {

            Button button = new Button(simple);

            if (i == randomIndex)
                button.setText(chosen);

            vBox.getChildren().add(button);

            button.setOnAction(event -> {

                Button clickedButton = (Button) event.getSource();

                if (clickedButton.getText().equals(chosen)) {

                    // Save visibility status of the simple buttons:
                    Optional<Boolean> visible = vBox.getChildren().stream()
                            .filter(node -> node instanceof Button)
                            .map(node -> (Button) node)
                            .filter(btn -> !btn.getText().equals(chosen))
                            .findFirst().map(Button::isVisible);

                    // Change visibility of the buttons except the filtered chosen one:
                    vBox.getChildren().stream()
                            .filter(node -> node instanceof Button)
                            .map(node -> (Button) node)
                            .filter(btn -> !btn.getText().equals(chosen))
                            .forEach(btn -> btn.setVisible(!btn.isVisible()));

                    // Change the (not so) chosen one:
                    if (visible.isPresent() && !visible.get()) {
                        int nextIndex = random.nextInt(10);
                        for (int j = 0; j < vBox.getChildren().size(); j++) {
                            if (vBox.getChildren().get(j) instanceof Button) {
                                Button btn = (Button) vBox.getChildren().get(j);
                                if (j == nextIndex)
                                    btn.setText(chosen);
                                else
                                    btn.setText(simple);
                            }
                        }
                        vBox.requestFocus();
                    }
                }
            });
        }

        primaryStage.setScene(new Scene(vBox));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
I have created multiple nodes dynamically. Now, I have to find specific node when it is clicked, it must hide all other node in the pane. Also, When I click it again it should display the hidden node.

For example,In the attached image, the down-arrow icon on root node is clicked, it must hide all other nodes and when it is clicked second time, it must show the hidden nodes again.
This how I am creating the buttons.

  Node_Basic_Event_Node anode = new Node_Basic_Event_Node(calcNode_Id("Basic_Event_Node"), "Basic_Event_Node", editorName, editorType); anode.relocate(50, 50); elementsContent.getChildren().add(anode);

Now, How I can hide nodes when clicking on root node's down-arrow icon in the image? I tried this sample of code but it is hiding all nodes including "root node"

    Pane elementsContent = (Pane) getParent();
    for (Node node : elementsContent.getChildren()) {
            node.managedProperty().set(true);
            node.setVisible(false);
    }

Body:
I am not absolutly sure where your problem exactly is, but I created a small example which will hopefully help you. The button which should not change visibility (here: certain text) is simply filtered out every time.

package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.util.Optional;
import java.util.Random;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        VBox vBox = new VBox();

        Random random = new Random();
        int randomIndex = random.nextInt(10);

        String chosen = "The Chosen One", simple = "Simple Button";

        for (int i = 0; i < 10; i++) {

            Button button = new Button(simple);

            if (i == randomIndex)
                button.setText(chosen);

            vBox.getChildren().add(button);

            button.setOnAction(event -> {

                Button clickedButton = (Button) event.getSource();

                if (clickedButton.getText().equals(chosen)) {

                    // Save visibility status of the simple buttons:
                    Optional<Boolean> visible = vBox.getChildren().stream()
                            .filter(node -> node instanceof Button)
                            .map(node -> (Button) node)
                            .filter(btn -> !btn.getText().equals(chosen))
                            .findFirst().map(Button::isVisible);

                    // Change visibility of the buttons except the filtered chosen one:
                    vBox.getChildren().stream()
                            .filter(node -> node instanceof Button)
                            .map(node -> (Button) node)
                            .filter(btn -> !btn.getText().equals(chosen))
                            .forEach(btn -> btn.setVisible(!btn.isVisible()));

                    // Change the (not so) chosen one:
                    if (visible.isPresent() && !visible.get()) {
                        int nextIndex = random.nextInt(10);
                        for (int j = 0; j < vBox.getChildren().size(); j++) {
                            if (vBox.getChildren().get(j) instanceof Button) {
                                Button btn = (Button) vBox.getChildren().get(j);
                                if (j == nextIndex)
                                    btn.setText(chosen);
                                else
                                    btn.setText(simple);
                            }
                        }
                        vBox.requestFocus();
                    }
                }
            });
        }

        primaryStage.setScene(new Scene(vBox));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
Arduino-Makefile: Compiler can't compile the user library cpp files
I am trying to use https://github.com/sudar/Arduino-Makefile for Arduino on Raspberry Pi with some user cpp libraries but it can not compile and show the error below.

/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -mmcu=atmega2560
  -Wl,--gc-sections -Os -flto -fuse-linker-plugin -o build-mega-atmega2560/toprint.elf build-mega-atmega2560/toprint.ino.o
  build-mega-atmega2560/libcore.a -lc -lm
  /tmp/cc1J77Gh.ltrans0.ltrans.o: In function main':
  <artificial>:(.text.startup+0x4be): undefined reference to
  Str2let::~Str2let()' collect2: error: ld returned 1 exit status make:
  *** [/home/pi/Desktop/demo1_may9/Arduino/toprint/Arduino-Makefile/Arduino.mk:1673:
  build-mega-atmega2560/toprint.elf] Error 1

My configuration file is as

```<code>ARDUINO_DIR   = /usr/share/arduino
MONITOR_PORT  = /dev/ttyACM*
USER_LIB_PATH = /home/pi/sketchbook/libraries

#BOARD_SUB   = mega2560 #replaced by below
MCU = atmega2560

# Define Atmega2560
BOARD_TAG    = mega
BOARD_SUB    = atmega2560

AVRDUDE      = /usr/share/arduino/hardware/tools/avr
</code>```

include /home/pi/Desktop/demo1_may9/Arduino/toprint/Arduino-Makefile/Arduino.mk
Does anyone know what happened?

The same code can run on Mac but just not Pi.

答: solved it by using the case[2] in this post. Just don't define the USER_LIB_PATH and put all the files in the same location as .ino and Makefile.

Body:
I am trying to use https://github.com/sudar/Arduino-Makefile for Arduino on Raspberry Pi with some user cpp libraries but it can not compile and show the error below.

/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -mmcu=atmega2560
  -Wl,--gc-sections -Os -flto -fuse-linker-plugin -o build-mega-atmega2560/toprint.elf build-mega-atmega2560/toprint.ino.o
  build-mega-atmega2560/libcore.a -lc -lm
  /tmp/cc1J77Gh.ltrans0.ltrans.o: In function main':
  <artificial>:(.text.startup+0x4be): undefined reference to
  Str2let::~Str2let()' collect2: error: ld returned 1 exit status make:
  *** [/home/pi/Desktop/demo1_may9/Arduino/toprint/Arduino-Makefile/Arduino.mk:1673:
  build-mega-atmega2560/toprint.elf] Error 1

My configuration file is as

ARDUINO_DIR   = /usr/share/arduino
MONITOR_PORT  = /dev/ttyACM*
USER_LIB_PATH = /home/pi/sketchbook/libraries

#BOARD_SUB   = mega2560 #replaced by below
MCU = atmega2560

# Define Atmega2560
BOARD_TAG    = mega
BOARD_SUB    = atmega2560

AVRDUDE      = /usr/share/arduino/hardware/tools/avr

include /home/pi/Desktop/demo1_may9/Arduino/toprint/Arduino-Makefile/Arduino.mk
Does anyone know what happened?

The same code can run on Mac but just not Pi.


问:
How to include stubs contracts from project dependency
How do you define the project dependency to include the -stubs jar?

For instance I have a multi module project.

I have my contracts project that contains all the stubs.

Then in project a I do

```<code>implementation(project(":contracts"))
</code>```

This doesn't put the stubs jar on the class path.

How do I specify the project dependency to bring in the stubs jar?

答:
Ok so the only way for me to get this to work was the following.

In the contracts module build.gradle.kts(this is using kotlin DSL):

```<code>val stubs by configurations.creating {
  isCanBeConsumed = true
  isCanBeResolved = false
}

artifacts {
  add("stubs", tasks.verifierStubsJar.get())
}
</code>```

Then on the consumer side:

```<code>testImplementation(project(":libs:contracts", "stubs"))
</code>```

Using testImplementation is important here. If you only do runtime, the jars in contract module need to be prebuilt. Using testImplementation forces the dependency to be built at the time you build the project (i.e like you do when executing a test)

Body:
How do you define the project dependency to include the -stubs jar?

For instance I have a multi module project.

I have my contracts project that contains all the stubs.

Then in project a I do

implementation(project(":contracts"))

This doesn't put the stubs jar on the class path.

How do I specify the project dependency to bring in the stubs jar?

Body:
Ok so the only way for me to get this to work was the following.

In the contracts module build.gradle.kts(this is using kotlin DSL):

val stubs by configurations.creating {
  isCanBeConsumed = true
  isCanBeResolved = false
}

artifacts {
  add("stubs", tasks.verifierStubsJar.get())
}

Then on the consumer side:

testImplementation(project(":libs:contracts", "stubs"))

Using testImplementation is important here. If you only do runtime, the jars in contract module need to be prebuilt. Using testImplementation forces the dependency to be built at the time you build the project (i.e like you do when executing a test)


问:
Windows 10 IoT Core - netsh http not found
Running

```<code>netsh http add sslcert hostnameport=xxx:443 appid= 'XXX' certhash=XXX certstorename=MY clientcertnegotiation=enable
</code>```

I get

The following command was not found: http add sslcert hostnameport=xxx:443 appid= 'XXX' certhash=XXX certstorename=MY clientcertnegotiation=enable

Seems that "http" doesn't exist in netsh of Windows 10 IoT Core.

Any workaround to solve it?

答:
Windows IoT Core doest not support netsh http command. If you want to import the ssl certificate on Windows IoT Core. You can use following command:

Copy cert to C:\ on the device.

PS C:> Enter-PSSession -ComputerName -Credential Administrator

[]: PS C:\Data\Users\Administrator\Documents> cd C:\

[]: PS C:>Set-Location -Path cert:\LocalMachine\Root

[]: PS Cert:\LocalMachine\Root> Import-Certificate -Filepath C:***.pem, if your certificate file is pfx, you can use Import-PfxCertificate command instead.

In addition, you can also import the certificate using programming. More information please see here.

Body:
Running

netsh http add sslcert hostnameport=xxx:443 appid= 'XXX' certhash=XXX certstorename=MY clientcertnegotiation=enable

I get

The following command was not found: http add sslcert hostnameport=xxx:443 appid= 'XXX' certhash=XXX certstorename=MY clientcertnegotiation=enable

Seems that "http" doesn't exist in netsh of Windows 10 IoT Core.

Any workaround to solve it?


问:
Create a compress function in Python?
I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I've been able to count the first character but not any others.

Ex:

```<code>>>> compress("ddaaaff")
'd2a3f2'

 def compress(s):
     count=0

     for i in range(0,len(s)):
         if s[i] == s[i-1]:
             count += 1
         c = s.count(s[i])

     return str(s[i]) + str(c)
</code>```

答:
```<code>def compress(val):
    print(len(val))
    end=0
    count=1
    result=""
    for i in range(0,len(val)-1):
        #print(val[i],val[i+1])
        if val[i]==val[i+1]:
            count=count+1
            #print(count,val[i])
        elif val[i]!=val[i+1]:
            #print(end,i)
            result=result+val[end]+str(count)
            end=i+1
            count=1
    result=result+val[-1]+str(count)
    return result
res=compress("I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I've been able to count the first character but not any others.")
print(len(res))
</code>```

Title: Create a compress function in Python?

Body:
I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I've been able to count the first character but not any others.

Ex:

>>> compress("ddaaaff")
'd2a3f2'

 def compress(s):
     count=0

     for i in range(0,len(s)):
         if s[i] == s[i-1]:
             count += 1
         c = s.count(s[i])

     return str(s[i]) + str(c)


问:
How to use children editor on a list component's dialog on AEM?
I am trying to enable children editor on a list component's dialog to allow users to add custom component into it, like the carousel component from core.

I use AEM 6.5, and the sling:resourceSuperType is list from core.

My .context.xml of the component is as follow:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root
    xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
    xmlns:cq="http://www.day.com/jcr/cq/1.0"
    xmlns:jcr="http://www.jcp.org/jcr/1.0"
    cq:isContainer="{Boolean}true"
    jcr:primaryType="cq:Component"
    jcr:title="List"
    sling:resourceSuperType="core/wcm/components/list/v2/list"
    componentGroup="MyContent"
    teaserDelegate="thisPackage/components/content/teaser/v1/teaser" />
```

<p>The HTML file of the list component, which is named "list.html" is as follow:</p>

<pre class="lang-xml prettyprint-override"><code><sly data-sly-use.list="com.thisPackage.aem.dna.core.models.v1.List"
     data-sly-use.template="core/wcm/components/commons/v1/templates.html">

  <sly data-sly-resource="${resource.path @ resourceType='wcm/foundation/components/parsys/newpar', appendPath='/*', decorationTagName='div', cssClassName='new section aem-Grid-newComponent'}"
       data-sly-test="${wcmmode.edit || wcmmode.preview}">
  </sly>
</sly>
</code>```

I could open the component's dialog on edit mode. however, if I add new components to the new children editor on dialog and try to close the dialog. I can't close the dialog.
The error message is:

org.apache.sling.api.resource.PersistenceException: Unable to commit changes to session
```

I followed the example in "github.com/adobe/aem-core-wcm-components/issues/696", and move editConfig from carousel to my list component. But, it didn't solve the issue.

What can I do?

答:
This is not working because the servlet which is responsible for updating data is of resourceType = core/wcm/components/carousel/v1/carousel

You can see in the network call that XHR request is sent to the server which has url like :

```<code> http://localhost:4202/content/we-retail/language-masters/en/jcr:content/root/responsivegrid/carousel.container.html
</code>```

As you can see a selector container is sent and underlaying servlet :

```<code>   https://github.com/adobe/aem-core-wcm-components/blob/master/bundles/core/src/main/java/com/adobe/cq/wcm/core/components/internal/servlets/ContainerServlet.java
</code>```

is listening to only core component resource-type.

In your case it is custom component, hence resource type does not match and hence you get the error.

Two things are possible:

1: Quick and easy is to just use sling:resourceSuperType = core/wcm/components/carousel/v1/carousel

Create custom clientlibs same as this:

/apps/core/wcm/components/commons/editor/dialog/childreneditor/v1/childreneditor/clientlibs

but change var POST_SUFFIX = ".container.html"; to your own selector

and then create your own servlet (registered to your own defined selector) same as the core component.

Hope it helps!

Body:
I am trying to enable children editor on a list component's dialog to allow users to add custom component into it, like the carousel component from core.

I use AEM 6.5, and the sling:resourceSuperType is list from core.

My .context.xml of the component is as follow:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root
    xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
    xmlns:cq="http://www.day.com/jcr/cq/1.0"
    xmlns:jcr="http://www.jcp.org/jcr/1.0"
    cq:isContainer="{Boolean}true"
    jcr:primaryType="cq:Component"
    jcr:title="List"
    sling:resourceSuperType="core/wcm/components/list/v2/list"
    componentGroup="MyContent"
    teaserDelegate="thisPackage/components/content/teaser/v1/teaser" />

The HTML file of the list component, which is named "list.html" is as follow:

<sly data-sly-use.list="com.thisPackage.aem.dna.core.models.v1.List"
     data-sly-use.template="core/wcm/components/commons/v1/templates.html">

  <sly data-sly-resource="${resource.path @ resourceType='wcm/foundation/components/parsys/newpar', appendPath='/*', decorationTagName='div', cssClassName='new section aem-Grid-newComponent'}"
       data-sly-test="${wcmmode.edit || wcmmode.preview}">
  </sly>
</sly>

I could open the component's dialog on edit mode. however, if I add new components to the new children editor on dialog and try to close the dialog. I can't close the dialog.
The error message is:

org.apache.sling.api.resource.PersistenceException: Unable to commit changes to session

I followed the example in "github.com/adobe/aem-core-wcm-components/issues/696", and move editConfig from carousel to my list component. But, it didn't solve the issue.

What can I do?

Body:
This is not working because the servlet which is responsible for updating data is of resourceType = core/wcm/components/carousel/v1/carousel

You can see in the network call that XHR request is sent to the server which has url like :

 http://localhost:4202/content/we-retail/language-masters/en/jcr:content/root/responsivegrid/carousel.container.html

As you can see a selector container is sent and underlaying servlet :

   https://github.com/adobe/aem-core-wcm-components/blob/master/bundles/core/src/main/java/com/adobe/cq/wcm/core/components/internal/servlets/ContainerServlet.java

is listening to only core component resource-type.

In your case it is custom component, hence resource type does not match and hence you get the error.

Two things are possible:

1: Quick and easy is to just use sling:resourceSuperType = core/wcm/components/carousel/v1/carousel

Create custom clientlibs same as this:

/apps/core/wcm/components/commons/editor/dialog/childreneditor/v1/childreneditor/clientlibs

but change var POST_SUFFIX = ".container.html"; to your own selector

and then create your own servlet (registered to your own defined selector) same as the core component.

Hope it helps!


问:
SSIS consolidate and concatenate multiple rows into single rows without using SQL
I am trying to accomplish something that is pretty easy to do in SQL, but seemingly very challenging to do in SSIS without using SQL.  Basically, I need to consolidate and concatenate a field of a many-to-one relationship.

Given entities:  [Contract Item] (many) to (one) [Account]

There is a field [ari_productsummary] that contains the product listed on the Contract Item entity.  We want to write that value to the Account as [ari_activecontractitems].  However, an Account may have more than one Contract Item record associated to it, in which case, we want to concatenate those values.  We also only want the distinct values to be concatenated (distinct rows already solved within my data flow).

This can be accomplished by writing to a temporary table, and then using a query or view to obtain the summarized results as followed.  I created a SQL table called TESTTABLE that contains the [ari_productsummary] from the Contract Item entity along with the referring [accountid] to map it back to Account.  I then wrote the following query as a view:

```<code>SELECT distinct accountid,
        (SELECT TT2.ari_productsummary + '; '
                FROM TESTTABLE TT2
                WHERE TT2.accountid = TT.accountid
                FOR XML PATH ('')
            ) AS 'ari_activecontractitems'
FROM TESTTABLE TT
</code>```

Executing that Query provides me the results that I want, which I can then use for importing into the Account entity as shown below:

But how do I do this in a SSIS dataflow without writing to a SQL table as a temporary placeholder for the data??  I want to do the entire process inside one dataflow container, without using a temporary SQL table/view.  The whole summarization process needs to be done on the fly:

Does anyone have a solution that doesn't require a temporary SQL table/view/query, but is contained entirely within the data flow?

I am using VS 2017 and the KingswaySoft Dynamic CRM 365 ETL toolset to develop my solution/package.

答:
Spit balling here as I don't Dynamics nor do I have the custom components.

Data Flow 1 - Contract aggregation

The purpose of this data flow is to replicate your logic in the elegant query you provided and shove that into a Cache Connection Manager (see Notes for 2008+ at the end)

KingswaySoft Dynamics Source -> Script Task -> Cache Transform

If you want to keep the sort in there, do it before the script task. The implementation I'll take with the Script Task is that it's fully blocking - that is all the rows must arrive before it can send any on. Tasks like the Merge Join are only partially blocking because the requirement of sorted data means that once you no longer have a match for the current item, you can send it on down the pipeline.

The Script Task is going to be asynchronous transformation. You'll have two output columns, your key accountid and your new derived column of ari_activecontractitems. That column will might need to be big - you'll know your data best but if it's a blob type in Dynamics (> 4k unicode or > 8k ascii characters) then you'll have to define the data type as DT_TEXT/DT_NTEXT

As inputs, you'll select accountid and ari_productsummary from your source.

The code should be pretty easy. We're going to accumulate the inbound data into a Dictionary.

```<code>    //  member variable
    Dictionary<string, List<string>> accumulator;
</code>```

The PreProcess method, we'll tack this in there to initialize our variable

```<code>    // initialize in PreProcess method
    accumulator = new Dictionary<string, List<string>>();
</code>```

In the OnBufferRowSent (name approx)

```<code>    // simulate the inbound queue
    // row_id would be something like Rows.row_id
    if (!accumulator.ContainsKey(row_id))
    {
        // Create an empty dictionary for our list
        accumulator.Add(row_id, new List<string>());
    }

    // add it if we don't have it
    if (!accumulator[row_id].Contains(invoice))
    {
        accumulator[row_id].Add(invoice);
    }
</code>```

Once you get the signal sent of no more data available, that's when you start buffering output data. The auto generated code will have placeholders for all this.

```<code>    // This is how we shove data out the pipe
    foreach(var kvp in accumulator)
    {
        // approximately thus
        OutputBuffer1.AddRow();
        OutputBuffer1.row_id = kvp.Key;
        OutputBuffer1.ari_productsummary = string.Join("; ",  kvp.Value);

    }
</code>```

Body:
I am trying to accomplish something that is pretty easy to do in SQL, but seemingly very challenging to do in SSIS without using SQL.  Basically, I need to consolidate and concatenate a field of a many-to-one relationship.

Given entities:  [Contract Item] (many) to (one) [Account]

There is a field [ari_productsummary] that contains the product listed on the Contract Item entity.  We want to write that value to the Account as [ari_activecontractitems].  However, an Account may have more than one Contract Item record associated to it, in which case, we want to concatenate those values.  We also only want the distinct values to be concatenated (distinct rows already solved within my data flow).

This can be accomplished by writing to a temporary table, and then using a query or view to obtain the summarized results as followed.  I created a SQL table called TESTTABLE that contains the [ari_productsummary] from the Contract Item entity along with the referring [accountid] to map it back to Account.  I then wrote the following query as a view:

SELECT distinct accountid,
        (SELECT TT2.ari_productsummary + '; '
                FROM TESTTABLE TT2
                WHERE TT2.accountid = TT.accountid
                FOR XML PATH ('')
            ) AS 'ari_activecontractitems'
FROM TESTTABLE TT

Executing that Query provides me the results that I want, which I can then use for importing into the Account entity as shown below:

But how do I do this in a SSIS dataflow without writing to a SQL table as a temporary placeholder for the data??  I want to do the entire process inside one dataflow container, without using a temporary SQL table/view.  The whole summarization process needs to be done on the fly:

Does anyone have a solution that doesn't require a temporary SQL table/view/query, but is contained entirely within the data flow?

I am using VS 2017 and the KingswaySoft Dynamic CRM 365 ETL toolset to develop my solution/package.

Body:
Spit balling here as I don't Dynamics nor do I have the custom components.

Data Flow 1 - Contract aggregation

The purpose of this data flow is to replicate your logic in the elegant query you provided and shove that into a Cache Connection Manager (see Notes for 2008+ at the end)

KingswaySoft Dynamics Source -> Script Task -> Cache Transform

If you want to keep the sort in there, do it before the script task. The implementation I'll take with the Script Task is that it's fully blocking - that is all the rows must arrive before it can send any on. Tasks like the Merge Join are only partially blocking because the requirement of sorted data means that once you no longer have a match for the current item, you can send it on down the pipeline.

The Script Task is going to be asynchronous transformation. You'll have two output columns, your key accountid and your new derived column of ari_activecontractitems. That column will might need to be big - you'll know your data best but if it's a blob type in Dynamics (> 4k unicode or > 8k ascii characters) then you'll have to define the data type as DT_TEXT/DT_NTEXT

As inputs, you'll select accountid and ari_productsummary from your source.

The code should be pretty easy. We're going to accumulate the inbound data into a Dictionary.

    //  member variable
    Dictionary<string, List<string>> accumulator;

The PreProcess method, we'll tack this in there to initialize our variable

    // initialize in PreProcess method
    accumulator = new Dictionary<string, List<string>>();

In the OnBufferRowSent (name approx)

    // simulate the inbound queue
    // row_id would be something like Rows.row_id
    if (!accumulator.ContainsKey(row_id))
    {
        // Create an empty dictionary for our list
        accumulator.Add(row_id, new List<string>());
    }

    // add it if we don't have it
    if (!accumulator[row_id].Contains(invoice))
    {
        accumulator[row_id].Add(invoice);
    }

Once you get the signal sent of no more data available, that's when you start buffering output data. The auto generated code will have placeholders for all this.

    // This is how we shove data out the pipe
    foreach(var kvp in accumulator)
    {
        // approximately thus
        OutputBuffer1.AddRow();
        OutputBuffer1.row_id = kvp.Key;
        OutputBuffer1.ari_productsummary = string.Join("; ",  kvp.Value);

    }


问:
traffic manager Azure endpoint public IP address
We have 2 IP addresses with DNS name but in different Azure subscription. Currently we want to add both Public IP address in one traffic manager endpoint.

But when we start to select public IP address, it only display candidate IP address in current subscription, while can't see IP address in other subscripion.

Is there any way that can add Public IP address in other subscription to this traffic manager endpoint?

Thanks.

答:
We can make this through PowerShell CLI:

New-AzTrafficManagerEndpoint -EndpointStatus Enabled -Name "EndpointName" -ProfileName "TrafficManagerProfileName" -ResourceGroupName "ResourceGroupName" -Type AzureEndpoints -Priority  -TargetResourceId ""


问:
Android How Do I Place ICON (ie Search Icon) inside content area of EditText or AutoCompleteTextView
Thats it how do I place an icon inside text area as background of EditText or AutoCompleteTextView?   </p>

答:
You can use

```<code>android:backgroud="@drawable/somedrawable"
</code>```

from your XML layout, or

```<code>View.setBackgroundResource(int resId)
</code>```

from your activity code. this works for most View types including composites.

If you need to position the icon relative to the edit text, you should put both of them (the edit text, and an image view for the icon) inside a layout view, such as a relative layout. This allows you to position them with respect to each other however you like. Explaining how relative layout works is outside the scope of what can be covered here. Just Google for it and you'll find lots of good example.

http://developer.android.com/reference/android/widget/RelativeLayout.html

Selvin's answer may also work for you (android:drawableRight=...). This is simpler, but obviously less flexible than putting the elements in a layout.

Body:
You can use

android:backgroud="@drawable/somedrawable"

from your XML layout, or

View.setBackgroundResource(int resId)

from your activity code. this works for most View types including composites.

If you need to position the icon relative to the edit text, you should put both of them (the edit text, and an image view for the icon) inside a layout view, such as a relative layout. This allows you to position them with respect to each other however you like. Explaining how relative layout works is outside the scope of what can be covered here. Just Google for it and you'll find lots of good example.

http://developer.android.com/reference/android/widget/RelativeLayout.html

Selvin's answer may also work for you (android:drawableRight=...). This is simpler, but obviously less flexible than putting the elements in a layout.


问:
How to compare with optimal effort whether 2 JAVA NESTED COLLECTIONS of this format List<Map<String, Object>> are equal
How to compare with optimal effort whether 2 JAVA NESTED COLLECTIONS of this format List<Map<String, Object>> are equal

In List<Map<String, Object>> the Object can be List or Map

I need to write unit tests to compare the values of nested collection object parsed from a json and the expected value (another collection which I manually create).
I can do this iteratively by going deep to each of the objects and compare them against the values from the other collection.

But this approach seems to be very tedious since I have to iterate each different test cases.

Is there any other efficient approach?

答:
This is exactly what assertEquals is for.

```<code>assertEquals(expected, actual);
</code>```

The will make it difficult to debug when things go wrong though.

Depending on how your code is structured, you might be better off using a mock for the json parsing part, and validating only that your code is passing in the expected values to the parser.

If nothing else, instead of building up the second collection, why not just assert the values there? If you're manually "creating" the expected collection, you can instead manually check the returned collection.

Body:
This is exactly what assertEquals is for.

assertEquals(expected, actual);

The will make it difficult to debug when things go wrong though.

Depending on how your code is structured, you might be better off using a mock for the json parsing part, and validating only that your code is passing in the expected values to the parser.

If nothing else, instead of building up the second collection, why not just assert the values there? If you're manually "creating" the expected collection, you can instead manually check the returned collection.