问:
How can i Convert My SQL Query To Linq w/ not equals?
This is my sql query ;

```<code>select * from kirala inner join saatler on Kirala.Tarih = '2020-05-31' and Kirala.Onay = 'true' and Kirala.SaatID != saatler.ID
</code>```

i was convert this ;

```<code>var kirala2 = from t1 in _context.Kirala
                          join t2 in _context.Saatler on t1.SaatID equals t2.ID
                          where t1.Tarih == "2020-05-31" && t1.Onay == true && t1.YatID == id
                          select new Saatler { Saat = t2.Saat, ID = t2.ID };
</code>```

But this is not working for me because t1.SaatID equals t2.ID i cant use not equals what else can I do
 ?

答:
You can just move all the conditions in the join to a where</p>

```<code>var kirala2 = from t1 in _context.Kirala
              from t2 in _context.Saatler
              where t1.SaatID != t2.ID
                    && t1.Tarih == "2020-05-31"
                    && t1.Onay == true
                    && t1.YatID == id
              select new Saatler { Saat = t2.Saat, ID = t2.ID };
</code>```

Body:
This is my sql query ;

select * from kirala inner join saatler on Kirala.Tarih = '2020-05-31' and Kirala.Onay = 'true' and Kirala.SaatID != saatler.ID

i was convert this ;

var kirala2 = from t1 in _context.Kirala
                          join t2 in _context.Saatler on t1.SaatID equals t2.ID
                          where t1.Tarih == "2020-05-31" && t1.Onay == true && t1.YatID == id
                          select new Saatler { Saat = t2.Saat, ID = t2.ID };

But this is not working for me because t1.SaatID equals t2.ID i cant use not equals what else can I do
 ?

Body:
You can just move all the conditions in the join to a where

var kirala2 = from t1 in _context.Kirala
              from t2 in _context.Saatler
              where t1.SaatID != t2.ID
                    && t1.Tarih == "2020-05-31"
                    && t1.Onay == true
                    && t1.YatID == id
              select new Saatler { Saat = t2.Saat, ID = t2.ID };


来源: stackexchange

问:
how can an attacker circumvent this
```<code>< select name = " user [ role ]" id = " user_role " >
< option disabled = " disabled " value =" admin " > admin </ option >
< option disabled = " disabled " value =" lecturer " > lecturer </ option >
< option value =" student " > student </ option >
</ select >
</code>```

i was asked to find the vulnerability in the code snippet for a class

I tried to put this into an HTML viewer but the result is just the same code snippet. So i couldnt figure out how this would look on an actual website. I am guessing its just clicking a button, and the buttons for admin and lecturer are disabled?

we have only learned about injections and bufferoverflow in this class. Since this is only clicking on a button i dont understand how an attacker could circumvent this? since there is no input he needs to type in?

edit: they mentioned that this is on the client-side. I read somewhere that injection attacks should be prevented from the server-side.. could this be the case for this attack as well?

答:
If you remove the spaces in your tags, it should appear when you open it in a web browser.

```<code><select name = " user [ role ]" id = " user_role ">
<option disabled = " disabled " value =" admin "> admin </option>
<option disabled = " disabled " value =" lecturer "> lecturer </option>
<option value =" student "> student </option >
</select>
</code>```

I believe that is part of a form and an attacker could view the source and use the form method carry out an attack in which he acts as the admin or lecturer.
Check this out, it may help.

ContentLicense: CC BY-SA 4.0

Title: how can an attacker circumvent this

Body:
< select name = " user [ role ]" id = " user_role " >
< option disabled = " disabled " value =" admin " > admin </ option >
< option disabled = " disabled " value =" lecturer " > lecturer </ option >
< option value =" student " > student </ option >
</ select >

i was asked to find the vulnerability in the code snippet for a class

I tried to put this into an HTML viewer but the result is just the same code snippet. So i couldnt figure out how this would look on an actual website. I am guessing its just clicking a button, and the buttons for admin and lecturer are disabled?

we have only learned about injections and bufferoverflow in this class. Since this is only clicking on a button i dont understand how an attacker could circumvent this? since there is no input he needs to type in?

edit: they mentioned that this is on the client-side. I read somewhere that injection attacks should be prevented from the server-side.. could this be the case for this attack as well?

Body:
If you remove the spaces in your tags, it should appear when you open it in a web browser.

<select name = " user [ role ]" id = " user_role ">
<option disabled = " disabled " value =" admin "> admin </option>
<option disabled = " disabled " value =" lecturer "> lecturer </option>
<option value =" student "> student </option >
</select>

I believe that is part of a form and an attacker could view the source and use the form method carry out an attack in which he acts as the admin or lecturer.
Check this out, it may help.


问:
keycloak - realm resolution based on username (email address)
I'm working on a multi tenant project where usernames are actually their email addresses and the domain of the email serves as a tenant identifier.

Now in keycloak I'll have different realms per tenant, but I want to have a single login page for all tenants and the actual realm that will do the authentication to be somehow resolved by the username (email address).

How do I go about doing that?

I found a thread on the mailing list (that I cant find now...) that discussed the same problem. It was something along the lines of - create a main realm that will "proxy" to the others, but I'm not quite sure how to do that.

答:
The idea from the mailing list is to write a service (let's say auth-redirector.example.com) that has a single input field for email, finds realm based on domain and redirects to that realm's keycloak endpoint (e.g. auth.example.com/auth/realms/realm-name/etc…) while keeping all GET params.

You can find examples of direct login/registration URLs here: https://lists.jboss.org/pipermail/keycloak-user/2016-July/007045.html

One usability problem is that users would have to provide their email twice, I have not yet found a way to pass the username via the login URL.

ContentLicense: CC BY-SA 3.0


问:
What is the compopt equivalent in zsh that modifies the current completion options?
I am writing an auto completion script for zsh that I want to enable nospace on certain conditions. The bash equivalent script would look like this

```<code>_my_completion(){
  if something; then
    compopt -o nospace
  fi
}

complete -F _my_completion <exec>
</code>```

How do I achieve the same goal in zsh?

答:
The similar effect can be done using -S '' as compadd argument, as you can see:

_my_completion(){
  # Here you can access ${words[@]}, $BUFFER, $CURSOR, $NAME, $CURRENT...
  if something; then
    completions_array=(foo bar baz)

    # `-S ''` is the equivalent of `compopt -o nospace`
    compadd -S '' -a completions_array
  fi
}

compdef _my_completion <exec>
```

If you're familiar with bash completions, you can see how zsh completions compare in this script that loads the bash completions in ZSH.

Body:
I am writing an auto completion script for zsh that I want to enable nospace on certain conditions. The bash equivalent script would look like this

_my_completion(){
  if something; then
    compopt -o nospace
  fi
}

complete -F _my_completion <exec>

How do I achieve the same goal in zsh?

Body:
The similar effect can be done using -S '' as compadd argument, as you can see:

_my_completion(){
  # Here you can access ${words[@]}, $BUFFER, $CURSOR, $NAME, $CURRENT...
  if something; then
    completions_array=(foo bar baz)

    # `-S ''` is the equivalent of `compopt -o nospace`
    compadd -S '' -a completions_array
  fi
}

compdef _my_completion <exec>

If you're familiar with bash completions, you can see how zsh completions compare in this script that loads the bash completions in ZSH.


问:
How does escaping a literal dot work for sed
The following sed command

```<code>echo '.' | sed "s/\\./foo/"
</code>```

substitutes . with foo, as expected. However, if we escape the non-alphanumeric . in the above command

```<code>echo '.' | sed "s/\\\./foo/"
</code>```

prints barely ., whereas foo is expected. sed should match the character . literally, but it doesn't. I cannot understand what is happening with the dot. I believe that I should simply put a backslash in front of every non-alphanumeric character in bash, if a string is double-quoted. A dot is a non-alphanumeric character so what is wrong about escaping it and why does it produce a different result?

答:
This is because how backslashes work in bash double quote " escaping.

```<code>echo "\\"
\
echo "\."
\.
echo "s/\\./foo/"
s/\./foo/
echo "s/\\\./foo/"
s/\\./foo/
</code>```

From man bash:

Within double quotes, the backslash retains its special meaning only when
followed by one of the following characters: $, `, ", \,or <newline>.
```

<p>So in the first case, sed gets <code>s/\./foo/</code> and interprets it as "replace a dot with foo". In the second case sed gets <code>s/\\./foo/</code> and interprets it as "replace a backslash and one other character with foo.</p>

<p>You better use single quote escaping in this case:</p>

```echo 's/./foo/'
s/./foo/
echo 's/\./foo/'
s/\./foo/
```

which is probably what you wanted.

Body:
The following sed command

echo '.' | sed "s/\\./foo/"

substitutes . with foo, as expected. However, if we escape the non-alphanumeric . in the above command

echo '.' | sed "s/\\\./foo/"

prints barely ., whereas foo is expected. sed should match the character . literally, but it doesn't. I cannot understand what is happening with the dot. I believe that I should simply put a backslash in front of every non-alphanumeric character in bash, if a string is double-quoted. A dot is a non-alphanumeric character so what is wrong about escaping it and why does it produce a different result?

Body:
This is because how backslashes work in bash double quote " escaping.

echo "\\"
\
echo "\."
\.
echo "s/\\./foo/"
s/\./foo/
echo "s/\\\./foo/"
s/\\./foo/

From man bash:

Within double quotes, the backslash retains its special meaning only when
followed by one of the following characters: $, `, ", \,or <newline>.

So in the first case, sed gets s/\./foo/ and interprets it as "replace a dot with foo". In the second case sed gets s/\\./foo/ and interprets it as "replace a backslash and one other character with foo.

You better use single quote escaping in this case:

echo 's/./foo/'
s/./foo/
echo 's/\./foo/'
s/\./foo/

which is probably what you wanted.


问:
How to make a list of numbers from a txt file in python?
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

```<code>L=[52,2,103,592,2090,34452,0,1]
</code>```

The best I have managed to do so far is:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)
</code>```

which returns:

```<code>L=['52','2','103','592','2090','34452','0','1']

</code>```

but the ' around the numbers bother me.

Any help is appreciated.

答:
try the following:

```<code>with open('s.txt') as num:
    numbers = num.read()
    n= numbers.split()
    lst = []
    for x in range(len(n)):
        nu = n[x]
        lst.append(int(nu))
    print(lst)
</code>```

output:

```<code>[1, 2, 3, 3, 4, 5, 6]
</code>```

Body:
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Body:
try the following:

with open('s.txt') as num:
    numbers = num.read()
    n= numbers.split()
    lst = []
    for x in range(len(n)):
        nu = n[x]
        lst.append(int(nu))
    print(lst)

output:

[1, 2, 3, 3, 4, 5, 6]


问:
Java summing numbers in an array using threads: using a new variable as a lock in a synchronized block: the difference
I have an array of numbers that I sum using threads. To avoid the race condition issue, the block of code that increments the sum variables is wrapped in synchronized. At first I wrapped it in synchronized (this) and it worked fine.

However, I'm trying to understand what happens when something other than this is passed as a lock value. I tried to chance the lock to synchronized (new Object()), so that the lock value is different each time it executes. But it continued to work fine, although I'd expect it to break, because now the value - reference of the lock object changes each time:

```<code>public class SumNumbersCommon {
    private static int totalSum;
    private static int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public static void main(String[] args) throws  Exception  {
        System.out.printf("Usual sum: %,d\n", sum(numbers));

        int left = numbers.length / 2;
        Thread leftThread = new Thread(new SummerThread(0, left));
        Thread rightThread = new Thread(new SummerThread(left + 1, numbers.length - 1));

        leftThread.start();
        rightThread.start();

        leftThread.join();
        rightThread.join();

        System.out.printf("total sum: %,d\n", totalSum);

    }

    static class SummerThread implements Runnable  {
        private int min;
        private int max;

        public SummerThread(int min, int max)  {
            this.min = min;
            this.max = max;
        }

        @Override
        public void run() {
            for (int i = min; i <= max; i++)  {
                synchronized (new Object()) {
                    totalSum += numbers[i];
                }
            }
        }
    }

    public static int sum(int[] numbers)  {
        int result = 0;
        for (int n: numbers)  {
            result += n;
        }
        return result;
    }

}
</code>```

Why does it still work? In which cases would I use anything other than synchronized (this)?

答:
Your threads are performing just a few trivial computations, so you don't have a chance to observe the data race. If you run the threads longer, you should observe inconsistencies.

synchronized(this) will use the monitor on this, so any other synchronized block and all synchronized methods of this will be serialized. In this particular example, synchronized(this) would be meaningless because this for both threads would be different. You need a shared object for locking.

synchronized(obj) can be used to control synchronization in a more fine-grained manner. Instead of blocking all synchronized methods of the object, this will only affect synchronized blocks that use obj as the locking object. This can be used in, for instance, modifying only a subset of the object state, or modifying some other shared state that is not part of the object state.

Body:
I have an array of numbers that I sum using threads. To avoid the race condition issue, the block of code that increments the sum variables is wrapped in synchronized. At first I wrapped it in synchronized (this) and it worked fine.

However, I'm trying to understand what happens when something other than this is passed as a lock value. I tried to chance the lock to synchronized (new Object()), so that the lock value is different each time it executes. But it continued to work fine, although I'd expect it to break, because now the value - reference of the lock object changes each time:

public class SumNumbersCommon {
    private static int totalSum;
    private static int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public static void main(String[] args) throws  Exception  {
        System.out.printf("Usual sum: %,d\n", sum(numbers));

        int left = numbers.length / 2;
        Thread leftThread = new Thread(new SummerThread(0, left));
        Thread rightThread = new Thread(new SummerThread(left + 1, numbers.length - 1));

        leftThread.start();
        rightThread.start();

        leftThread.join();
        rightThread.join();

        System.out.printf("total sum: %,d\n", totalSum);

    }

    static class SummerThread implements Runnable  {
        private int min;
        private int max;

        public SummerThread(int min, int max)  {
            this.min = min;
            this.max = max;
        }

        @Override
        public void run() {
            for (int i = min; i <= max; i++)  {
                synchronized (new Object()) {
                    totalSum += numbers[i];
                }
            }
        }
    }

    public static int sum(int[] numbers)  {
        int result = 0;
        for (int n: numbers)  {
            result += n;
        }
        return result;
    }

}

Why does it still work? In which cases would I use anything other than synchronized (this)?


问:
did not find expected key (line 93, column 9), context while parsing a block mapping (line 84, column 9)"
i Own A Minecraft Bedrock PocketMine-MP Server, Today i Started Making The Crates, i Looked In Console To Be Sure There isn't Any Problem but i Saw This Error:

```<code>did not find expected key (line 93, column 9), context while parsing a
 block mapping (line 84, column 9)"
</code>```

I Don't Know What is Wrong With This File But i Hope i Will Resolve it as Soon as Possible. Thanks
My Crates.yml File is:

```<code>crates:
  Common:
    drops:
      - id: 339
        meta: 0
        amount: 1
        chance: 20
        name: "5000$"
        type: command
        commands:
         - "givemoney {PLAYER} 5000"
         - "Say §e{PLAYER} Just Won §25000$§e From A Common Crate!"
      - id: 131
        meta: 0
        amount: 1
        chance: 12
        name: "Common Key"
        type: command
        commands:
         - "key Common 1 {PLAYER}"
         - "Say §e{PLAYER} Just Won a §2Common Crate Key §eFrom a Common Crate!"
      - id: 304
        meta: 0
        amount: 1
        chance: 50
        commands:
         - "Say §e{PLAYER} Just Won a §2Chainmail Leggings §eFrom a Common Crate!"
    amount: 1
    floating-text: "Common Crate"
  Uncommon:
    drops:
      - id: 307
        meta: 0
        amount: 1
        chance: 20
        commands:
         - "Say §e{PLAYER} Just Won a §2Iron Chestplate §eFrom a Uncommon Crate!"
      - id: 131
        meta: 0
        amount: 2
        chance: 15
        name: "2 Common Keys"
        type: command
        commands:
         - "Say §e{PLAYER} Just Won§2 2 Common Keys §eFrom a Uncommon Crate!"
         - "Key Common 2 {PLAYER}"
      - id: 339
        meta: 0
        amount: 1
        chance: 30
        name: "20000$"
        type: command
        commands:
         - "Say §e{PLAYER} Just Won §220000 $§e From a Uncommon Crate!"
         - "givemoney {PLAYER} 20000"
      - id: 373
        meta: 30
        amount: 3
        chance: 10
        commands:
         - "Say {PLAYER} Just Won §22 Regeneration Potion II For 22 Seconds §eFrom a Uncommon Crate"
      - id: 438
        meta: 36
        amount: 1
        chance: 10
        commands:
         - "Say {PLAYER} Just Won a §2Splash Winter II Potion For 30 Seconds§e From A Uncommon Crate!"
    amount: 1
    floating-text: "Uncommon Crate"
  Vote:
    drops:
      - id: 368
        meta: 0
        amount: 4
        chance: 35
        commands:
         - "Say §e{PLAYER} Just Won§2 4 Ender Pearls §eFrom a Vote Crate!"
      - id: 322
        meta: 0
        amount: 2
        chance: 15
        commands:
         - "Say §e{PLAYER} Just Won 2 Golden Apples From a Vote Crate!"
      - id: 276
        meta: 0
        amount: 1
        chance: 50
        enchantments:
         - name: "Sharpness"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won a §2Diamond Sword With Sharpness 1 §2From a Vote Crate!"
        - id: 311
          meta: 0
          amount: 1
          chance: 9
          enchantments:
           - name: "Protection"
             level: 1
          commands:
           - "Say §e{PLAYER} Just Won §2Diamond Leggings With Protection 2§e From a Vote Crate!"
       - id: 438
         meta: 12
         amount: 3
         chance: 25
         commands:
          - "Say §e{PLAYER} Just Won §23 Fire Resistance Splash Potions §eFrom a Vote Crate!"
       - id: 339
         meta: 0
         amount: 1
         chance: 40
         name: "250000 $"
         type: command
         commands:
          - "givemoney {PLAYER} 25000"
          - "Say §e{PLAYER} Just Won §225000 $§e From A Vote Crate!"
    amount: 1
    floating-text: "Vote Crate"
  Mythic:
    drops:
      - id: 264
        meta: 0
        amount: 16
        chance: 35
      - id: 388
        meta: 0
        amount: 16
        chance: 15
      - id: 322
        meta: 0
        amount: 16
        chance: 50
    amount: 1
    commands: ["say {PLAYER} has opened an Mythic Crate"]
    floating-text: "Mythic Crate"
  Legendary:
    drops:
      - id: 278
        meta: 0
        amount: 1
        chance: 10
        name: "Telepathic Pickaxe"
        lore: "Items mined are transported into your inventory"
        enchantments:
          - name: "telepathy"
            level: 1
      - id: 49
        meta: 0
        amount: 32
        chance: 15
      - id: 466
        meta: 0
        amount: 16
        chance: 70
      - id: 7
        meta: 0
        amount: 5
        chance: 5
    amount: 1
    commands: ["say {PLAYER} has opened an Legendary Crate"]
    floating-text: "Legendary Crate"
</code>```

If you Could Take 10 Minutes out of Your Life To Help Me Find Whats Wrong i Will Be Very Grateful! Thanks Again!

答:
Line 93 in context (the last line is line 93):

      - id: 276
        meta: 0
        amount: 1
        chance: 50
        enchantments:
         - name: "Sharpness"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won a §2Diamond Sword With Sharpness 1 §2From a Vote Crate!"
        - id: 311
```

<p>The list item indicator (<code>-</code>) of line 93 is on the level of the <em>mapping</em> started at line 84 (<code>id: 276</code>). You get the error because you cannot put a list item into a mapping. The error message tells you it expected a key (of the mapping) when it encountered something else (the list item indicator).</p>

<p>To fix the error, put the line (<code>- id: 311</code>) on the same indentation level as the previous list items:</p>

<pre class="lang-yaml prettyprint-override"><code>      - id: 276
        meta: 0
        amount: 1
        chance: 50
        enchantments:
         - name: "Sharpness"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won a §2Diamond Sword With Sharpness 1 §2From a Vote Crate!"
      - id: 311
        meta: 0
        amount: 1
        chance: 9
        enchantments:
         - name: "Protection"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won §2Diamond Leggings With Protection 2§e From a Vote Crate!"
      - id: 438
        # ...
</code>```

- id: 438 and the following - id: 339 also have a wrong indentation.

Body:
i Own A Minecraft Bedrock PocketMine-MP Server, Today i Started Making The Crates, i Looked In Console To Be Sure There isn't Any Problem but i Saw This Error:

did not find expected key (line 93, column 9), context while parsing a
 block mapping (line 84, column 9)"

I Don't Know What is Wrong With This File But i Hope i Will Resolve it as Soon as Possible. Thanks
My Crates.yml File is:

crates:
  Common:
    drops:
      - id: 339
        meta: 0
        amount: 1
        chance: 20
        name: "5000$"
        type: command
        commands:
         - "givemoney {PLAYER} 5000"
         - "Say §e{PLAYER} Just Won §25000$§e From A Common Crate!"
      - id: 131
        meta: 0
        amount: 1
        chance: 12
        name: "Common Key"
        type: command
        commands:
         - "key Common 1 {PLAYER}"
         - "Say §e{PLAYER} Just Won a §2Common Crate Key §eFrom a Common Crate!"
      - id: 304
        meta: 0
        amount: 1
        chance: 50
        commands:
         - "Say §e{PLAYER} Just Won a §2Chainmail Leggings §eFrom a Common Crate!"
    amount: 1
    floating-text: "Common Crate"
  Uncommon:
    drops:
      - id: 307
        meta: 0
        amount: 1
        chance: 20
        commands:
         - "Say §e{PLAYER} Just Won a §2Iron Chestplate §eFrom a Uncommon Crate!"
      - id: 131
        meta: 0
        amount: 2
        chance: 15
        name: "2 Common Keys"
        type: command
        commands:
         - "Say §e{PLAYER} Just Won§2 2 Common Keys §eFrom a Uncommon Crate!"
         - "Key Common 2 {PLAYER}"
      - id: 339
        meta: 0
        amount: 1
        chance: 30
        name: "20000$"
        type: command
        commands:
         - "Say §e{PLAYER} Just Won §220000 $§e From a Uncommon Crate!"
         - "givemoney {PLAYER} 20000"
      - id: 373
        meta: 30
        amount: 3
        chance: 10
        commands:
         - "Say {PLAYER} Just Won §22 Regeneration Potion II For 22 Seconds §eFrom a Uncommon Crate"
      - id: 438
        meta: 36
        amount: 1
        chance: 10
        commands:
         - "Say {PLAYER} Just Won a §2Splash Winter II Potion For 30 Seconds§e From A Uncommon Crate!"
    amount: 1
    floating-text: "Uncommon Crate"
  Vote:
    drops:
      - id: 368
        meta: 0
        amount: 4
        chance: 35
        commands:
         - "Say §e{PLAYER} Just Won§2 4 Ender Pearls §eFrom a Vote Crate!"
      - id: 322
        meta: 0
        amount: 2
        chance: 15
        commands:
         - "Say §e{PLAYER} Just Won 2 Golden Apples From a Vote Crate!"
      - id: 276
        meta: 0
        amount: 1
        chance: 50
        enchantments:
         - name: "Sharpness"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won a §2Diamond Sword With Sharpness 1 §2From a Vote Crate!"
        - id: 311
          meta: 0
          amount: 1
          chance: 9
          enchantments:
           - name: "Protection"
             level: 1
          commands:
           - "Say §e{PLAYER} Just Won §2Diamond Leggings With Protection 2§e From a Vote Crate!"
       - id: 438
         meta: 12
         amount: 3
         chance: 25
         commands:
          - "Say §e{PLAYER} Just Won §23 Fire Resistance Splash Potions §eFrom a Vote Crate!"
       - id: 339
         meta: 0
         amount: 1
         chance: 40
         name: "250000 $"
         type: command
         commands:
          - "givemoney {PLAYER} 25000"
          - "Say §e{PLAYER} Just Won §225000 $§e From A Vote Crate!"
    amount: 1
    floating-text: "Vote Crate"
  Mythic:
    drops:
      - id: 264
        meta: 0
        amount: 16
        chance: 35
      - id: 388
        meta: 0
        amount: 16
        chance: 15
      - id: 322
        meta: 0
        amount: 16
        chance: 50
    amount: 1
    commands: ["say {PLAYER} has opened an Mythic Crate"]
    floating-text: "Mythic Crate"
  Legendary:
    drops:
      - id: 278
        meta: 0
        amount: 1
        chance: 10
        name: "Telepathic Pickaxe"
        lore: "Items mined are transported into your inventory"
        enchantments:
          - name: "telepathy"
            level: 1
      - id: 49
        meta: 0
        amount: 32
        chance: 15
      - id: 466
        meta: 0
        amount: 16
        chance: 70
      - id: 7
        meta: 0
        amount: 5
        chance: 5
    amount: 1
    commands: ["say {PLAYER} has opened an Legendary Crate"]
    floating-text: "Legendary Crate"

If you Could Take 10 Minutes out of Your Life To Help Me Find Whats Wrong i Will Be Very Grateful! Thanks Again!

Body:
Line 93 in context (the last line is line 93):

      - id: 276
        meta: 0
        amount: 1
        chance: 50
        enchantments:
         - name: "Sharpness"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won a §2Diamond Sword With Sharpness 1 §2From a Vote Crate!"
        - id: 311

The list item indicator (-) of line 93 is on the level of the mapping started at line 84 (id: 276). You get the error because you cannot put a list item into a mapping. The error message tells you it expected a key (of the mapping) when it encountered something else (the list item indicator).

To fix the error, put the line (- id: 311) on the same indentation level as the previous list items:

      - id: 276
        meta: 0
        amount: 1
        chance: 50
        enchantments:
         - name: "Sharpness"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won a §2Diamond Sword With Sharpness 1 §2From a Vote Crate!"
      - id: 311
        meta: 0
        amount: 1
        chance: 9
        enchantments:
         - name: "Protection"
           level: 1
        commands:
         - "Say §e{PLAYER} Just Won §2Diamond Leggings With Protection 2§e From a Vote Crate!"
      - id: 438
        # ...

- id: 438 and the following - id: 339 also have a wrong indentation.


问:
NoReverseMatch at
I've got this issue trying to redirect after submitting a form:

NoReverseMatch at /app_blog/blog/1/blog_update/

Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['app_blog/blog/(?P[0-9]+)/blog_detail/$']

views.py:

```<code>from django.shortcuts import render, redirect
# from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib import messages

from app_users.decorators import unauthenticated_user, allowed_users

from .models import BlogPost
from .forms import BlogUpdateForm

@login_required(login_url='app_users:login')
@allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
    posts = BlogPost.objects.all()
    context = {'title': 'Blog', 'posts': posts}
    return render(request, 'app_blog/blog.html', context)

def blog_detail(request, pk):
    user_post = BlogPost.objects.get(id=pk)
    context = {'title': 'Blog', 'user_post': user_post}
    return render(request, 'app_blog/blog_detail.html', context)

def blog_user_detail(request, pk):
    user_detail = BlogPost.objects.get(id=pk)
    user_type = user_detail.author.groups.all()[0].name.capitalize()
    context = {'title': 'Blog', 'user_detail': user_detail, 'user_type': user_type}
    return render(request, 'app_blog/blog_user_detail.html', context)

def blog_update(request, pk):
    if request.method == 'POST':
        blog_update = BlogUpdateForm(request.POST, instance=BlogPost.objects.get(id=pk))
        if blog_update.is_valid():
            blog_update.save()
            messages.success(request, 'Your blog-post has been updated!')
            return redirect('app_blog:blog_detail')
    else:
        blog_update = BlogUpdateForm(instance=BlogPost.objects.get(id=pk))
    context = {'title': 'Blog', 'blog_update': blog_update}
    return render(request, 'app_blog/blog_update.html', context)
</code>```

urls.py:

```<code>from django.urls import path
from .views import *

app_name = 'app_blog'

urlpatterns = [
    path('blog/', blog, name='blog'),
    path('blog/<int:pk>/blog_detail/', blog_detail, name='blog_detail'),
    path('blog/<int:pk>/user_details/', blog_user_detail, name='blog_user_detail'),
    path('blog/<int:pk>/blog_update/', blog_update, name='blog_update'),
]
</code>```

models.py:

```<code>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class BlogPost(models.Model):
    title = models.CharField(max_length=100, null=True)
    content = models.TextField(null=True)
    date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
</code>```

blog_detail.html:

{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

                    {{ user_post.author }}
                    {{ user_post.date_posted|date:"d F, Y" }}
                    {% if user_post.author == request.user %}

                            Update
                            Delete

                    {% endif %}

{{ user_post.title }}

{{ user_post.content|safe }}

{% endblock %}```
</div>
</div>
</p>
<p><em><strong>blog_update.html:</strong></em></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

<br>
<div class="card card-body container">
    <div class="card-deck">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <h5 style="text-align: left;">{{ user.username }}:</h5>
        <div class="card card-body">
            <form action="" method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">If you wish to update your blog-post:</legend>
                    {{ blog_update|crispy }}
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info  btn-sm btn-block" style="width: 150px; align-self: center;" type="submit">Update Details</button>
                </div>
            </form>
        </div>
    </div>
</div>
<br>

{% endblock %}</code>```

答:
In blog update view -You did not pass the id of the blog post in redirect .
use HttpResponseRedirect and pass the id of the blog where you want to redirect.</p>

```<code>return HttpResponseRedirect(reverse('app_blog:blog_detail',args=[pk]))
</code>```

Title: NoReverseMatch at

Body:
I've got this issue trying to redirect after submitting a form:

NoReverseMatch at /app_blog/blog/1/blog_update/

Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['app_blog/blog/(?P[0-9]+)/blog_detail/$']

views.py:

from django.shortcuts import render, redirect
# from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib import messages

from app_users.decorators import unauthenticated_user, allowed_users

from .models import BlogPost
from .forms import BlogUpdateForm

@login_required(login_url='app_users:login')
@allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
    posts = BlogPost.objects.all()
    context = {'title': 'Blog', 'posts': posts}
    return render(request, 'app_blog/blog.html', context)

def blog_detail(request, pk):
    user_post = BlogPost.objects.get(id=pk)
    context = {'title': 'Blog', 'user_post': user_post}
    return render(request, 'app_blog/blog_detail.html', context)

def blog_user_detail(request, pk):
    user_detail = BlogPost.objects.get(id=pk)
    user_type = user_detail.author.groups.all()[0].name.capitalize()
    context = {'title': 'Blog', 'user_detail': user_detail, 'user_type': user_type}
    return render(request, 'app_blog/blog_user_detail.html', context)

def blog_update(request, pk):
    if request.method == 'POST':
        blog_update = BlogUpdateForm(request.POST, instance=BlogPost.objects.get(id=pk))
        if blog_update.is_valid():
            blog_update.save()
            messages.success(request, 'Your blog-post has been updated!')
            return redirect('app_blog:blog_detail')
    else:
        blog_update = BlogUpdateForm(instance=BlogPost.objects.get(id=pk))
    context = {'title': 'Blog', 'blog_update': blog_update}
    return render(request, 'app_blog/blog_update.html', context)

urls.py:

from django.urls import path
from .views import *

app_name = 'app_blog'

urlpatterns = [
    path('blog/', blog, name='blog'),
    path('blog/<int:pk>/blog_detail/', blog_detail, name='blog_detail'),
    path('blog/<int:pk>/user_details/', blog_user_detail, name='blog_user_detail'),
    path('blog/<int:pk>/blog_update/', blog_update, name='blog_update'),
]

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class BlogPost(models.Model):
    title = models.CharField(max_length=100, null=True)
    content = models.TextField(null=True)
    date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

blog_detail.html:

{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

                    {{ user_post.author }}
                    {{ user_post.date_posted|date:"d F, Y" }}
                    {% if user_post.author == request.user %}

                            Update
                            Delete

                    {% endif %}

{{ user_post.title }}

{{ user_post.content|safe }}

{% endblock %}

blog_update.html:

{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

{{ user.username }}:

            <form action="" method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">If you wish to update your blog-post:</legend>
                    {{ blog_update|crispy }}
                </fieldset>

                    <button class="btn btn-outline-info  btn-sm btn-block" style="width: 150px; align-self: center;" type="submit">Update Details</button>

            </form>

{% endblock %}

Body:
In blog update view -You did not pass the id of the blog post in redirect .
use HttpResponseRedirect and pass the id of the blog where you want to redirect.

return HttpResponseRedirect(reverse('app_blog:blog_detail',args=[pk]))


问:
Why wildfly17 server show 403 where jboss 6.X work perfectly in my System?
I use jboss 6.x to deploy war file (EMC.war) and jboss server work perfectly in eclipse with JRE1.8.0_241.

After changing server form jboss 6.X to wildfly 17, message always show 403 forbidden when using simple example.

I change wildfly version form 8 to 18, but http message still show 4.3 forbidden

There is my code.

My url is http://localhost:8080/EMC/

enviroment：
Eclipse
JRE 1.8.0_241
wildfly 17

Thanks!

答:
I'm surprised that the code you're showing worked at all.

Your application should be in it's own class.  Something like:

```<code>@ApplicationPath("/rest")
public class BaseApplication extends Application {
    // intentionally empty
}
</code>```

is sufficient.  Note that in this example I'm setting the base of the JAX-RS URL path.  Every URL will contain my web-app name and this path.  This path can be "/" if you'd like. Then, place your service code in it's own class like you have.  Do not extend Application for each service.

Body:
I'm surprised that the code you're showing worked at all.

Your application should be in it's own class.  Something like:

@ApplicationPath("/rest")
public class BaseApplication extends Application {
    // intentionally empty
}

is sufficient.  Note that in this example I'm setting the base of the JAX-RS URL path.  Every URL will contain my web-app name and this path.  This path can be "/" if you'd like. Then, place your service code in it's own class like you have.  Do not extend Application for each service.


问:
Screen does not get widgets
I have a screen that loads some widgets according to a csv. But the screen just gets empty.

```<code>Column(
   children: getPlates(),
),
</code>```

```<code>  List<Widget> getPlates() {
    List<Widget> listWidgets = [];
    listWidgets.add(Text('dew'));
    loadAsset('assets/Postres.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });
    setState(() {

    });
    return listWidgets;
  }

  Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }
</code>```

I think it is because of the async method loadAsset that returns something when the screen is already bult. I tried loading it in initState but only works if I press hot reload

答:
As the assets are loaded asynchronously, they will not be populated in the synchronous getPlates function. You have a couple options here:

Use FutureBuilder. It is a very easy-to-use and powerful widget. This would be the approach I would recommend.

Make your getPlates() function async so you can use the async and await keyword, although I am not sure that is what you are looking for here as I am guessing you reference it from the build method.

Fix your current code; it has a bug. You setState after the then call. The correct approach is wrapping the listWidgets.add inside the setState, like so:

```<code>loadAsset('assets/Postres.csv').then((dynamic output) {
// Add the setState here like so
setState(() {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
});
    });
</code>```

Regardless of what method you pick to fix this--you probably shouldn't start loading the csv in the build method. Consider starting the load in your initState method.

Title: Screen does not get widgets

Body:
I have a screen that loads some widgets according to a csv. But the screen just gets empty.

Column(
   children: getPlates(),
),

  List<Widget> getPlates() {
    List<Widget> listWidgets = [];
    listWidgets.add(Text('dew'));
    loadAsset('assets/Postres.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });
    setState(() {

    });
    return listWidgets;
  }

  Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }

I think it is because of the async method loadAsset that returns something when the screen is already bult. I tried loading it in initState but only works if I press hot reload

Body:
As the assets are loaded asynchronously, they will not be populated in the synchronous getPlates function. You have a couple options here:

Use FutureBuilder. It is a very easy-to-use and powerful widget. This would be the approach I would recommend.

Make your getPlates() function async so you can use the async and await keyword, although I am not sure that is what you are looking for here as I am guessing you reference it from the build method.

Fix your current code; it has a bug. You setState after the then call. The correct approach is wrapping the listWidgets.add inside the setState, like so:

loadAsset('assets/Postres.csv').then((dynamic output) {
// Add the setState here like so
setState(() {
      List<String> list = output.split('\n');
      listWidgets.add(Text('holaaaa'));
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
});
    });

Regardless of what method you pick to fix this--you probably shouldn't start loading the csv in the build method. Consider starting the load in your initState method.


问:
how to get full path with os.walk function in python
i am using os.walk to find directories, but it does not show the full path

code:

```<code>for root, subdirs, files in os.walk(path):
    print(subdirs)
</code>```

I assign system/ value to path.

Expected output:
system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that

答:
Here is what you should do:</p>

```<code>import os
for root,subdirs,files in os.walk(path):
    for file in files:
        print(os.path.join(root,file))
</code>```

Body:
i am using os.walk to find directories, but it does not show the full path

code:

for root, subdirs, files in os.walk(path):
    print(subdirs)

I assign system/ value to path.

Expected output:
system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that

Body:
Here is what you should do:

import os
for root,subdirs,files in os.walk(path):
    for file in files:
        print(os.path.join(root,file))


问:
Getting table name with the select query of the same table
I am trying to get the table name within the sql query that I am writing to get data from the same table, for example

Table_one

TABLE_TWO

So while doing this query ```Select * from table_one UNION Select * from table_two```
the result that i get is the data of two tables in one table like this:

But what I need that one more column to come in the table to see the data is coming from which table as following

答:
Use union all:

```<code>select id, name, age, 'table_one' as tabel_name
from table_one
union all
select id, name, age, 'table_two'
from table_two
</code>```

Body:
I am trying to get the table name within the sql query that I am writing to get data from the same table, for example

Table_one

TABLE_TWO

So while doing this query
Select * from table_one UNION Select * from table_two

the result that i get is the data of two tables in one table like this:

But what I need that one more column to come in the table to see the data is coming from which table as following

Body:
Use union all:

select id, name, age, 'table_one' as tabel_name
from table_one
union all
select id, name, age, 'table_two'
from table_two


问:
How can i load a bigquery table to dataproc cluster
I am new to dataproc cluster and PySpark so, in the process of looking for codes to load table from bigquery to the cluster, i came across the code below and was unable to figure out what all am i suppose to change for my usecase in this code and what are we providing as an input in the input directory</p>

```<code>from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
import subprocess

sc = SparkContext()
spark = SparkSession(sc)

bucket = spark._jsc.hadoopConfiguration().get('fs.gs.system.bucket')
project = spark._jsc.hadoopConfiguration().get('fs.gs.project.id')
input_directory = 'gs://{}/hadoop/tmp/bigquery/pyspark_input'.format(bucket)

conf = {
    'mapred.bq.project.id': project,
    'mapred.bq.gcs.bucket': bucket,
    'mapred.bq.temp.gcs.path': input_directory,
    'mapred.bq.input.project.id': 'dataset_new',
    'mapred.bq.input.dataset.id': 'retail',
    'mapred.bq.input.table.id': 'market',
}
</code>```

答:
You are trying to use Hadoop BigQuery connector, for Spark you should use Spark BigQuery connector.

To read data from BigQuery you can follow an example:

# Use the Cloud Storage bucket for temporary BigQuery export data used
# by the connector.
bucket = "[bucket]"
spark.conf.set('temporaryGcsBucket', bucket)

# Load data from BigQuery.
words = spark.read.format('bigquery') \
  .option('table', 'bigquery-public-data:samples.shakespeare') \
  .load()
words.createOrReplaceTempView('words')

# Perform word count.
word_count = spark.sql(
    'SELECT word, SUM(word_count) AS word_count FROM words GROUP BY word')
word_count.show()
```

Body:
I am new to dataproc cluster and PySpark so, in the process of looking for codes to load table from bigquery to the cluster, i came across the code below and was unable to figure out what all am i suppose to change for my usecase in this code and what are we providing as an input in the input directory

from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
import subprocess

sc = SparkContext()
spark = SparkSession(sc)

bucket = spark._jsc.hadoopConfiguration().get('fs.gs.system.bucket')
project = spark._jsc.hadoopConfiguration().get('fs.gs.project.id')
input_directory = 'gs://{}/hadoop/tmp/bigquery/pyspark_input'.format(bucket)

conf = {
    'mapred.bq.project.id': project,
    'mapred.bq.gcs.bucket': bucket,
    'mapred.bq.temp.gcs.path': input_directory,
    'mapred.bq.input.project.id': 'dataset_new',
    'mapred.bq.input.dataset.id': 'retail',
    'mapred.bq.input.table.id': 'market',
}


答:
try this

```<code>txtfile=open('file.txt')
L=[]
for line in txtfile:
    L.append(line.rstrip())

a = L[0].split(',')
print sorted(a, key = int)
</code>```

much better if you closed that file while opening using with

```<code>with open('file.txt') as txtfile:

     b = [x for x in txtfile]
     c = b[0].split(',')
     print sorted(list(map(int, c)))
</code>```

Title: How to make a list of numbers from a txt file in python?

Body:
try this

txtfile=open('file.txt')
L=[]
for line in txtfile:
    L.append(line.rstrip())

a = L[0].split(',')
print sorted(a, key = int)

much better if you closed that file while opening using with

with open('file.txt') as txtfile:

     b = [x for x in txtfile]
     c = b[0].split(',')
     print sorted(list(map(int, c)))


问:
TS will not infer possible undefined when destructuring empty array
When looking at the inferred type of destructured element, it will assume the array is never empty.

```<code>const x: number[] = [];
const [first] = x; // first inferred as number

console.log(first); // undefined

if (first !== undefined) {
    // ...
}

</code>```

Playground Link

This leads to an interesting behavior with TSLint rule "strict-type-predicates" for example, that will mark the if statement as always true, while it's in fact isn't.

Am I missing something and it's normal behavior?

答:
UPDATE for TypeScript 4.1

It is still the intended behavior that undefined is not included in the domain of index signature properties, for the reasons listed below.  However, since this is an oft-requested feature, the TypeScript team has (somewhat grudgingly?) relented and added the --noUncheckedIndexedAccess compiler flag.  If you enable that (and it is neither enabled by default, nor included in the --strict compiler flag, so you need to do it explicitly), you will start getting the behavior you presumably want.

Note that this is actually not exactly the same as adding undefined yourself.  Indexed access will add undefined:

```<code>// --noUncheckedIndexedAccess is enabled

const x: number[] = [];
const [first] = x; // number | undefined

console.log(first); // undefined

if (first !== undefined) {
    first.toFixed(); // okay
}
</code>```

But for..of loops and array functional programming methods will still act as though undefined is not possible (that is: as if sparse arrays do not exist):

```<code>for (const n of x) {
    n.toFixed(); // no error, yay!
}

x.map(n => n.toFixed()); // no error, yay!
</code>```

So possibly you want to enable that flag.  Keep in mind that some common array/dictionary manipulation techniques may still be "annoying", which is why it isn't part of the --strict family.

Playground link to code

ORIGINAL ANSWER

It's the intended behavior. See microsoft/TypeScript#13778 for more information.  This issue is a request to allow index signature property types to automatically include undefined in their domain, and while the issue is still open, it is fairly clear that it will not be implemented.  See this comment for example.

It is not a design goal of TypeScript (see #3 on the list) for the type system to be perfectly sound or correct (despite the heartache that people like me feel when we think about this too much; I've joked before about starting a TypeScript Unsoundness Support Group to help people deal with this).  Instead, there's a tradeoff between correctness and usability.

The language maintainers note that there's a lot of real-world code out there which indexes into arrays without checking for possible undefined values everywhere, and that enforcing this check would turn a simple for-loop into a tedious exercise of either performing checks or using type assertions.  The problem is (see this comment) that the compiler cannot easily tell the difference between safe and unsafe indexes into array types.  So either the compiler assume that the property won't be undefined and have false negatives from the compiler when that assumption is wrong, as happens now.... or, assume the property might be undefined and have false positives from the compiler when the indexing operation is actually safe.  The argument by the language maintainers is that such false positives would happen so often that developers would condition themselves to ignore the errors entirely, thus making it just as useless as the current situation while being more annoying.  So they will leave it as it is now.

If you want, you can always add undefined to the element type yourself, assuming such issues are more likely to show up for you in your use cases:

```<code>const x: (number | undefined)[] = [];
const [first] = x; // number | undefined

console.log(first); // undefined

if (first !== undefined) {
    first.toFixed(); // okay
}
</code>```

but keep in mind that you'll run into the annoying situation if your use cases follow the normal patterns:

```<code>for (const n of x) {
    n.toFixed(); // error, annoying
    if (typeof n !== "undefined") n.toFixed(); // okay
    n!.toFixed(); // okay
}

x.map(n => n.toFixed()); // error, annoying
x.filter((n): n is number => typeof n !== "undefined").filter(n => n.toFixed()); // okay
x.map(n => n!.toFixed()); // okay
</code>```

Okay, hope that helps; good luck!

Playground link to code

Body:
When looking at the inferred type of destructured element, it will assume the array is never empty.

const x: number[] = [];
const [first] = x; // first inferred as number

console.log(first); // undefined

if (first !== undefined) {
    // ...
}

Playground Link

This leads to an interesting behavior with TSLint rule "strict-type-predicates" for example, that will mark the if statement as always true, while it's in fact isn't.

Am I missing something and it's normal behavior?

Body:
UPDATE for TypeScript 4.1

It is still the intended behavior that undefined is not included in the domain of index signature properties, for the reasons listed below.  However, since this is an oft-requested feature, the TypeScript team has (somewhat grudgingly?) relented and added the --noUncheckedIndexedAccess compiler flag.  If you enable that (and it is neither enabled by default, nor included in the --strict compiler flag, so you need to do it explicitly), you will start getting the behavior you presumably want.

Note that this is actually not exactly the same as adding undefined yourself.  Indexed access will add undefined:

// --noUncheckedIndexedAccess is enabled

const x: number[] = [];
const [first] = x; // number | undefined

console.log(first); // undefined

if (first !== undefined) {
    first.toFixed(); // okay
}

But for..of loops and array functional programming methods will still act as though undefined is not possible (that is: as if sparse arrays do not exist):

for (const n of x) {
    n.toFixed(); // no error, yay!
}

x.map(n => n.toFixed()); // no error, yay!

So possibly you want to enable that flag.  Keep in mind that some common array/dictionary manipulation techniques may still be "annoying", which is why it isn't part of the --strict family.

Playground link to code

ORIGINAL ANSWER

It's the intended behavior. See microsoft/TypeScript#13778 for more information.  This issue is a request to allow index signature property types to automatically include undefined in their domain, and while the issue is still open, it is fairly clear that it will not be implemented.  See this comment for example.

It is not a design goal of TypeScript (see #3 on the list) for the type system to be perfectly sound or correct (despite the heartache that people like me feel when we think about this too much; I've joked before about starting a TypeScript Unsoundness Support Group to help people deal with this).  Instead, there's a tradeoff between correctness and usability.

The language maintainers note that there's a lot of real-world code out there which indexes into arrays without checking for possible undefined values everywhere, and that enforcing this check would turn a simple for-loop into a tedious exercise of either performing checks or using type assertions.  The problem is (see this comment) that the compiler cannot easily tell the difference between safe and unsafe indexes into array types.  So either the compiler assume that the property won't be undefined and have false negatives from the compiler when that assumption is wrong, as happens now.... or, assume the property might be undefined and have false positives from the compiler when the indexing operation is actually safe.  The argument by the language maintainers is that such false positives would happen so often that developers would condition themselves to ignore the errors entirely, thus making it just as useless as the current situation while being more annoying.  So they will leave it as it is now.

If you want, you can always add undefined to the element type yourself, assuming such issues are more likely to show up for you in your use cases:

const x: (number | undefined)[] = [];
const [first] = x; // number | undefined

console.log(first); // undefined

if (first !== undefined) {
    first.toFixed(); // okay
}

but keep in mind that you'll run into the annoying situation if your use cases follow the normal patterns:

for (const n of x) {
    n.toFixed(); // error, annoying
    if (typeof n !== "undefined") n.toFixed(); // okay
    n!.toFixed(); // okay
}

x.map(n => n.toFixed()); // error, annoying
x.filter((n): n is number => typeof n !== "undefined").filter(n => n.toFixed()); // okay
x.map(n => n!.toFixed()); // okay

Okay, hope that helps; good luck!

Playground link to code


问:
How to parse and load an ontology in Python?
I have an ontology in an 'owl' file (nif.owl).
I am familiar with Java, but it kept crashing; therefore, I tried using Python.
However, since I have not used Python before, I am not sure if I am loading the ontology correctly!

Here is the part that I believe is related to loading the ontology:

```<code>g = rdflib.Graph()
g.parse ('nif.owl', format='xml')
nif = rdflib.Namespace('http://purl.org/nif/ontology/nif.owl')
g.bind('nif', nif)
</code>```

I believe the problem is where the g.parse sets the format to 'xml'. I think maybe the 'xml' is wrong.

I have also attached the header of the ontology file as an image.

The reason I think there is a mistake with the code is the result I get which I showed in the image below:

Thanks!

PS: Below is the full code in case there is something wrong with it:

```<code>import logging
import rdflib
import time

logging.basicConfig()
logger = logging.getLogger('logger')
logger.warning('The system may break down')

start_time = time.time()

g = rdflib.Graph()
g.parse ('nif.owl', format='xml')
nif = rdflib.Namespace('http://purl.org/nif/ontology/nif.owl')
g.bind('nif', nif)
query = """
select distinct ?p
where { ?s ?p ?o}
        LIMIT 5
        """
result = g.query(query)
print(result.serialize(format='csv'))

print("--- %s seconds ---" % (time.time() - start_time))
</code>```

答: There is nothing wrong with your code except that the format should be format='application/rdf+xml'.

Body:
I have an ontology in an 'owl' file (nif.owl).
I am familiar with Java, but it kept crashing; therefore, I tried using Python.
However, since I have not used Python before, I am not sure if I am loading the ontology correctly!

Here is the part that I believe is related to loading the ontology:

g = rdflib.Graph()
g.parse ('nif.owl', format='xml')
nif = rdflib.Namespace('http://purl.org/nif/ontology/nif.owl')
g.bind('nif', nif)

I believe the problem is where the g.parse sets the format to 'xml'. I think maybe the 'xml' is wrong.

I have also attached the header of the ontology file as an image.

The reason I think there is a mistake with the code is the result I get which I showed in the image below:

Thanks!

PS: Below is the full code in case there is something wrong with it:

import logging
import rdflib
import time

logging.basicConfig()
logger = logging.getLogger('logger')
logger.warning('The system may break down')

start_time = time.time()

g = rdflib.Graph()
g.parse ('nif.owl', format='xml')
nif = rdflib.Namespace('http://purl.org/nif/ontology/nif.owl')
g.bind('nif', nif)
query = """
select distinct ?p
where { ?s ?p ?o}
        LIMIT 5
        """
result = g.query(query)
print(result.serialize(format='csv'))

print("--- %s seconds ---" % (time.time() - start_time))


问:
how to create a DF from a DF based on a condition
My current DF looks like this

```<code>Combinations               Count
1   ('IDLY', 'VADA')       3734
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
10  ('IDLY', 'POORI')       1297
11  ('COFFEE', 'TEA')       1179
13  ('DOSA', 'VADA')        1141
15  ('CHAPPATHI', 'IDLY')   1070
16  ('COFFEE', 'SAMOSA')    1061
17  ('COFFEE', 'IDLY')      1016
18  ('POORI', 'VADA')       1008
</code>```

Lets say I filter by the keyword 'DOSA' from above data frame I get the below OP

```<code>    Combinations           Count
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
13  ('DOSA', 'VADA')        1141
</code>```

But I would like the output to be like the df below(which has ignored the filter key word as its common,

```<code>    Combinations    Count
6   IDLY            2020
9   CHAPPATHI       1297
13  VADA            1141
</code>```

What concept of pandas needs to be used here? How can this be achieved?

答:
```<code>d = df[df['Combinations'].transform(lambda x: 'DOSA' in x)].copy()
d['Combinations'] = d['Combinations'].apply(lambda x: set(x).difference(['DOSA']).pop())
print(d)
</code>```

Prints:

```<code>   ID Combinations  Count
1   6         IDLY   2020
2   9    CHAPPATHI   1297
5  13         VADA   1141
</code>```

Body:
My current DF looks like this

Combinations               Count
1   ('IDLY', 'VADA')       3734
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
10  ('IDLY', 'POORI')       1297
11  ('COFFEE', 'TEA')       1179
13  ('DOSA', 'VADA')        1141
15  ('CHAPPATHI', 'IDLY')   1070
16  ('COFFEE', 'SAMOSA')    1061
17  ('COFFEE', 'IDLY')      1016
18  ('POORI', 'VADA')       1008

Lets say I filter by the keyword 'DOSA' from above data frame I get the below OP

    Combinations           Count
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
13  ('DOSA', 'VADA')        1141

But I would like the output to be like the df below(which has ignored the filter key word as its common,

    Combinations    Count
6   IDLY            2020
9   CHAPPATHI       1297
13  VADA            1141

What concept of pandas needs to be used here? How can this be achieved?

Body:
d = df[df['Combinations'].transform(lambda x: 'DOSA' in x)].copy()
d['Combinations'] = d['Combinations'].apply(lambda x: set(x).difference(['DOSA']).pop())
print(d)

Prints:

   ID Combinations  Count
1   6         IDLY   2020
2   9    CHAPPATHI   1297
5  13         VADA   1141


问:
Is there a way to access the files in my phone which is connected to PC through python?
I want to filter 'my music' folder present in my mobile(Manufacturer: Realme, Os:Oreo ) through python.

```<code>import os
os.chdir(r'E:')   # I am able to change between C and E drive.
os.chdir(r'This PC\realme 3 Pro\Internal shared storage')  #throwing below error.
</code>```

FileNotFoundError: [WinError 3] The system cannot find the path specified:

I heard about that latest phones support MTP and PTP prtocols to transfer but not UMS.

Can anyone guide me how to get list of files that are present in the phone which is connected to PC.

答:
"This PC" is not a valid path. A Windows path should always start with one letter (ex: C:\, D:\, E:\, etc).
So if your phone is mounted to the E drive you should access it like this:</p>

```<code>os.chdir(r'E:\realm 3 Pro\...')
</code>```

Body:
I want to filter 'my music' folder present in my mobile(Manufacturer: Realme, Os:Oreo ) through python.

import os
os.chdir(r'E:')   # I am able to change between C and E drive.
os.chdir(r'This PC\realme 3 Pro\Internal shared storage')  #throwing below error.

FileNotFoundError: [WinError 3] The system cannot find the path specified:

I heard about that latest phones support MTP and PTP prtocols to transfer but not UMS.

Can anyone guide me how to get list of files that are present in the phone which is connected to PC.

Body:
"This PC" is not a valid path. A Windows path should always start with one letter (ex: C:\, D:\, E:\, etc).
So if your phone is mounted to the E drive you should access it like this:

os.chdir(r'E:\realm 3 Pro\...')


问:
How to send a static video file from one browser to another browser using webRTC?
I want to send a static video file from one browser to another browser and want to play that file after receiving it on the second browser using webRTC. I'm newbie to webRTC and don't have any idea about that. Just want to create a simple demo without any server.
I'm creating this demo in angular 9.</p>

答:
I want to share the file from one browser to another browser like Mozilla to Chrome

You need some form of discovery first, a shared point of contact—like a signaling server on the LAN—between Firefox and Chrome, or be willing to provide the handshake manually through cut'n'paste.

Servers are hard to demo, so here's a manual cut'n'paste demo (open in both browsers):

(Disclaimer: this won't look like most WebRTC code. For that see this answer instead)

const config = {iceServers: [{urls: "stun:stun.1.google.com:19302"}]};
const pc = new RTCPeerConnection(config);

pc.onsignalingstatechange = () => div.innerText = pc.signalingState;
pc.oniceconnectionstatechange = () => div.innerText = pc.iceConnectionState;

copyOffer.onclick = async () => {
  if (pc.signalingState != "stable") return;
  const streams = [new MediaStream()];
  for (const kind of ["video","audio"]) pc.addTransceiver(kind, {streams});
  await pc.setLocalDescription();
  pc.onicecandidate = e => {
    if (e.candidate) return;
    offer.focus();
    offer.value = pc.localDescription.sdp;
    offer.select();
    document.execCommand("copy");
    answer.placeholder = "Paste answer here";
  };
};

offer.onkeyup = async e => {
  if (pc.signalingState != "stable") return;
  await pc.setRemoteDescription({type: "offer", sdp: offer.value});
  await pc.setLocalDescription();
  pc.onicecandidate = e => {
    if (e.candidate) return;
    answer.focus();
    answer.value = pc.localDescription.sdp;
    answer.select();
    document.execCommand("copy");
  };
};

answer.onkeyup = async e => {
  if (pc.signalingState != "have-local-offer") return;
  await pc.setRemoteDescription({type: "answer", sdp: answer.value});
}

browse.onchange = async () => {
  try {
    video.src = URL.createObjectURL(browse.files[0]);
    if (!video.captureStream) video.captureStream = video.mozCaptureStream;
    const stream = video.captureStream();
    await video.play();
    const [vid, aud] =  pc.getTransceivers();
    await Promise.all([
      vid.sender.replaceTrack(stream.getVideoTracks()[0]),
      aud.sender.replaceTrack(stream.getAudioTracks()[0])
    ]);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
};
pc.ontrack = ({track, streams}) => {
  video.srcObject = streams[0];
  track.onunmute = () => video.play();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table><td>
1. On side A: <button id="copyOffer">Copy offer</button><br>
2. On side B: <textarea id="offer" placeholder="Paste offer here"></textarea><br>
3. On side A: <textarea id="answer"></textarea><br>
4. <input type="file" id="browse" accept="video/*"/><br>
5. Step 4 can be repeated<br>
<div id="div"></div></td><td>
<video id="video" width="300" controls></video></td></table></code>```

This should work across the internet—modulo symmetric NATs—provided you exchange the offer/answer in a reasonable amount of time.

Body:
I want to share the file from one browser to another browser like Mozilla to Chrome

You need some form of discovery first, a shared point of contact—like a signaling server on the LAN—between Firefox and Chrome, or be willing to provide the handshake manually through cut'n'paste.

Servers are hard to demo, so here's a manual cut'n'paste demo (open in both browsers):

(Disclaimer: this won't look like most WebRTC code. For that see this answer instead)

const config = {iceServers: [{urls: "stun:stun.1.google.com:19302"}]};
const pc = new RTCPeerConnection(config);

pc.onsignalingstatechange = () => div.innerText = pc.signalingState;
pc.oniceconnectionstatechange = () => div.innerText = pc.iceConnectionState;

copyOffer.onclick = async () => {
  if (pc.signalingState != "stable") return;
  const streams = [new MediaStream()];
  for (const kind of ["video","audio"]) pc.addTransceiver(kind, {streams});
  await pc.setLocalDescription();
  pc.onicecandidate = e => {
    if (e.candidate) return;
    offer.focus();
    offer.value = pc.localDescription.sdp;
    offer.select();
    document.execCommand("copy");
    answer.placeholder = "Paste answer here";
  };
};

offer.onkeyup = async e => {
  if (pc.signalingState != "stable") return;
  await pc.setRemoteDescription({type: "offer", sdp: offer.value});
  await pc.setLocalDescription();
  pc.onicecandidate = e => {
    if (e.candidate) return;
    answer.focus();
    answer.value = pc.localDescription.sdp;
    answer.select();
    document.execCommand("copy");
  };
};

answer.onkeyup = async e => {
  if (pc.signalingState != "have-local-offer") return;
  await pc.setRemoteDescription({type: "answer", sdp: answer.value});
}

browse.onchange = async () => {
  try {
    video.src = URL.createObjectURL(browse.files[0]);
    if (!video.captureStream) video.captureStream = video.mozCaptureStream;
    const stream = video.captureStream();
    await video.play();
    const [vid, aud] =  pc.getTransceivers();
    await Promise.all([
      vid.sender.replaceTrack(stream.getVideoTracks()[0]),
      aud.sender.replaceTrack(stream.getAudioTracks()[0])
    ]);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
};
pc.ontrack = ({track, streams}) => {
  video.srcObject = streams[0];
  track.onunmute = () => video.play();
};

<table><td>
1. On side A: <button id="copyOffer">Copy offer</button><br>
2. On side B: <textarea id="offer" placeholder="Paste offer here"></textarea><br>
3. On side A: <textarea id="answer"></textarea><br>
4. <input type="file" id="browse" accept="video/*"/><br>
5. Step 4 can be repeated<br>
<div id="div"></div></td><td>
<video id="video" width="300" controls></video></td></table>

This should work across the internet—modulo symmetric NATs—provided you exchange the offer/answer in a reasonable amount of time.


问:
H2 DB persistence.mv.db file size increases even on data cleanup in CordApp
Persistence.mv.db size increases even on wiping out old data. And after size increases more than 71 Mb it gives handshake timeout(netty connection). Nodes stop responding to REST services.
We have cleared data from tables like NODE_MESSAGE_IDS, NODE_OUR_KEY_PAIRS, due to large number of hoping between six nodes. And generation of temporary key pairs for a session. And similarly many other tables, e.g. node_transactions, even after clearing them, size increases.
And also when we declare:
val session = serviceHub.jdbcSession()
"session.autoCommit is false" everytime. Also I tries to set its value to true, and execute sql queries.But it did not decrease database size.

This is in reference to the same project. We solved pagination issue by removing the data from tables but DB size still increases. So it is not completely solved:-
Buffer overflow issue when rows in vault is more than 200

答:
There might be issue with your flows, as the node is doing a lot of checkpointing. </p>

<p>Besides that I cannot think of any other scenarios to cause the database to constantly growing.  </p>

Body:
There might be issue with your flows, as the node is doing a lot of checkpointing.

Besides that I cannot think of any other scenarios to cause the database to constantly growing.


问:
How to get a Sagemaker notebook onto GitHub?
I have a Sagemaker notebook that I would like to move to a GitHub repository. I thought perhaps I should download the files locally, then I can easily push to git. But I cannot figure out how to download the folder to my local computer. Then I though, perhaps there is a way using the AWS CLI to move directly from Sagemaker to git? I've made many google searches that are unable to answer my question.</p>

答:
You can actually setup your notebook in SageMaker with a link to GitHub.

You can then launch a Notebook instance that will pull in your Notebook, whilst allowing you to commit the changes that you've made and push to your remote repository.

Further instructions: https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-repo.html


问:
Enable copy button title on long press on the button
I have UIButton for an address in my tableview cell. When I tap on it once; I open google map with the direction no problem. Now, I want to provide the option for long gesture so if you hold your finger on the button, it provides the option to copy the address which is in the title of the button. This is my code:

```<code>@IBOutlet weak var addressBtn: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()

    addLongPressGesture()
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizer.State.began {

        // how do I make it possible to copy the title of the button here? The address is already inserted as the title of the button

    }
}

func addLongPressGesture(){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 0.5
    self.addressBtn.addGestureRecognizer(longPress)
}
</code>```

This is where on one tap it goes to the map with no problem; so I have no issue here but just fyi:
    @IBAction func addressClicked(_ sender: Any) {

```<code>    if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {

        let street = order.street.replacingOccurrences(of: " ", with: "+")
        let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")

        if street == "" || order.city == "" || order.province == "" || postalCode == ""{
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
        } else {
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
        }

        } else {
            NSLog("Can't use comgooglemaps://")
        }
    }
</code>```

答:
I figured it out with the following code: </p>

```<code>//Create the AlertController and add Its action like button in Actionsheet
        let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    actionSheetControllerIOS8.view.tintColor = AppColors.Blue

    let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
    }
    actionSheetControllerIOS8.addAction(cancelActionButton)

    let saveActionButton = UIAlertAction(title: "Open Google Map", style: .default)
    { _ in

        if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {

            let street = order.street.replacingOccurrences(of: " ", with: "+")
            let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")

            if street == "" || order.city == "" || order.province == "" || postalCode == ""{
                UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
            } else {
                UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
            }

        } else {
            NSLog("Can't use comgooglemaps://")
        }
    }
    actionSheetControllerIOS8.addAction(saveActionButton)

    let deleteActionButton = UIAlertAction(title: "Copy Address", style: .default)
    { _ in

        let address = "\(order.street), \(order.city), \(order.province), \(order.postalCode)"
        let pasteBoard = UIPasteboard.general
        pasteBoard.string = address

    }
    actionSheetControllerIOS8.addAction(deleteActionButton)
    self.present(actionSheetControllerIOS8, animated: true, completion: nil)
    }
</code>```

Body:
I have UIButton for an address in my tableview cell. When I tap on it once; I open google map with the direction no problem. Now, I want to provide the option for long gesture so if you hold your finger on the button, it provides the option to copy the address which is in the title of the button. This is my code:

@IBOutlet weak var addressBtn: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()

    addLongPressGesture()
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizer.State.began {

        // how do I make it possible to copy the title of the button here? The address is already inserted as the title of the button

    }
}

func addLongPressGesture(){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 0.5
    self.addressBtn.addGestureRecognizer(longPress)
}

This is where on one tap it goes to the map with no problem; so I have no issue here but just fyi:
    @IBAction func addressClicked(_ sender: Any) {

    if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {

        let street = order.street.replacingOccurrences(of: " ", with: "+")
        let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")

        if street == "" || order.city == "" || order.province == "" || postalCode == ""{
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
        } else {
            UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
        }

        } else {
            NSLog("Can't use comgooglemaps://")
        }
    }

Body:
I figured it out with the following code:

//Create the AlertController and add Its action like button in Actionsheet
        let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    actionSheetControllerIOS8.view.tintColor = AppColors.Blue

    let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
    }
    actionSheetControllerIOS8.addAction(cancelActionButton)

    let saveActionButton = UIAlertAction(title: "Open Google Map", style: .default)
    { _ in

        if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {

            let street = order.street.replacingOccurrences(of: " ", with: "+")
            let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")

            if street == "" || order.city == "" || order.province == "" || postalCode == ""{
                UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
            } else {
                UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
            }

        } else {
            NSLog("Can't use comgooglemaps://")
        }
    }
    actionSheetControllerIOS8.addAction(saveActionButton)

    let deleteActionButton = UIAlertAction(title: "Copy Address", style: .default)
    { _ in

        let address = "\(order.street), \(order.city), \(order.province), \(order.postalCode)"
        let pasteBoard = UIPasteboard.general
        pasteBoard.string = address

    }
    actionSheetControllerIOS8.addAction(deleteActionButton)
    self.present(actionSheetControllerIOS8, animated: true, completion: nil)
    }


问:
Validating input value from console without exiting loop C#
Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:

```<code>Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(true)
{
 if(amount < 1 || amount > 5)
 {
     Console.WriteLine("Please enter a value between 1-5");
     break;
 }
}
</code>```

The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?

cheers.

答:
I haven't tested it but slightly refactored your code as below, it should do what you want:

```<code>Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(amount < 1 || amount > 5)
{
    Console.WriteLine("Please enter a value between 1-5");
    amount = Convert.ToInt32(Console.ReadLine());
}
</code>```

EDIT: if you want to safely check whether it is an integer value, you can use the below version of code:

```<code>    Console.WriteLine("How many dices would you like to throw?");
    var input = Console.ReadLine();

    while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
    {
        Console.WriteLine("Please enter a value between 1-5");
        input = Console.ReadLine();
    }
</code>```

Body:
Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(true)
{
 if(amount < 1 || amount > 5)
 {
     Console.WriteLine("Please enter a value between 1-5");
     break;
 }
}

The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?

cheers.

Body:
I haven't tested it but slightly refactored your code as below, it should do what you want:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(amount < 1 || amount > 5)
{
    Console.WriteLine("Please enter a value between 1-5");
    amount = Convert.ToInt32(Console.ReadLine());
}

EDIT: if you want to safely check whether it is an integer value, you can use the below version of code:

    Console.WriteLine("How many dices would you like to throw?");
    var input = Console.ReadLine();

    while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
    {
        Console.WriteLine("Please enter a value between 1-5");
        input = Console.ReadLine();
    }


问:
Python virtualenv bin scripts always exit with code 1
I have a virtualenv with some scripts/applications that come packaged with my application.

Suppose it looks something like this:

ls /venv/bin/

```<code>activate
myscript
python
...
</code>```

When I run myscript with either

```<code>/venv/bin/python /venv/bin/myscript
</code>```

or

```<code>/venv/bin/myscript
</code>```

I properly execute myscript; however, the returned exit status is coming back with 1 when I know it is succeeding.

myscript is being copied to /bin via entry_point scripts in setup.py:

```<code>entry_points={
        'console_scripts': [
        'myscript=myscript.__main__:main',
      ],
},
</code>```

I see that the actual version of myscript copied over has some extra code in it that could be corrupting the exit.

Is there a proper way to run packages that exist in the /venv/bin to avoid bad exit codes?

Extra info:

The executable itself looks like:

```<code>from myscript.__main__ import main
if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())
</code>```

答:
The issue was a result of the myscript.py code. In this file, the code exits when it hits:

return "Something that the user would see"

When myscript.py is run directly from the terminal, its exit code is 0.

When it is invoked within a separate file (in my case, the wrapper script that is packaged as a console_scripts), its exit code is 1. The code is called with this line (with main being myscript.py):

sys.exit(main())

I believe this is because sys exit takes any non 0 returned value as exit code 1 (exception).

Changing my code in myscript.py to log the output instead of return it, fixed the exit code issue.

Body:
I have a virtualenv with some scripts/applications that come packaged with my application.

Suppose it looks something like this:

ls /venv/bin/

activate
myscript
python
...

When I run myscript with either

/venv/bin/python /venv/bin/myscript

or

/venv/bin/myscript

I properly execute myscript; however, the returned exit status is coming back with 1 when I know it is succeeding.

myscript is being copied to /bin via entry_point scripts in setup.py:

entry_points={
        'console_scripts': [
        'myscript=myscript.__main__:main',
      ],
},

I see that the actual version of myscript copied over has some extra code in it that could be corrupting the exit.

Is there a proper way to run packages that exist in the /venv/bin to avoid bad exit codes?

Extra info:

The executable itself looks like:

from myscript.__main__ import main
if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())


问:
How to make a list of numbers from a txt file in python?
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

```<code>L=[52,2,103,592,2090,34452,0,1]
</code>```

The best I have managed to do so far is:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)
</code>```

which returns:

```<code>L=['52','2','103','592','2090','34452','0','1']

</code>```

but the ' around the numbers bother me.

Any help is appreciated.

答:
If you want to covert them to Integers, you can use the int(string) function in Python.

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(int(line.rstrip()))

print(L)
</code>```

According to the official Python documentation, a shorter and "more elegant" solution if you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

```<code>yourList = open("filename.txt").readlines()
</code>```

Just as a recomendation:

Also you might want to consider storing data on an a JSON file. The good thing about it, is that you can use it to communicate between applications that are written in another language.

From the docs:

Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

Body:
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Body:
If you want to covert them to Integers, you can use the int(string) function in Python.

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(int(line.rstrip()))

print(L)

According to the official Python documentation, a shorter and "more elegant" solution if you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

yourList = open("filename.txt").readlines()

Just as a recomendation:

Also you might want to consider storing data on an a JSON file. The good thing about it, is that you can use it to communicate between applications that are written in another language.

From the docs:

Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.


问:
Jmeter non-gui more request than gui issue
Hay Guys, I'm trying to use JMeter(5.3) non-GUI and GUI mode to do loading test, but in the same condition I get different request test.

For example, if I calling default.aspx and setting

Users : 1, Loop Count: infinite, Duration: 3s

In GUI mode summary report, I'll get

Lable : default.aspx.aspx-1, Sample : 2, Average: 854

But in non-GUI mode, I'll get

Lable : default.aspx.aspx-1, Sample : 2, Average: 622

Lable : default.aspx.aspx-1-0, Sample : 2, Average: 33

Lable : default.aspx.aspx-1-1, Sample : 2, Average: 588

Why I have 2 more data -0 and -1 on the non-GUI result?

I didn't change any setting and config when using non-GUI mode, does anyone can explain this question? Thanks.

答:
My expectation is that this is due to redirection, i.e. very first response has HTTP Status code of 3xx and you're getting 3 lines in the .jtl results file like:

Sum of response times of lines 2 and 3

Redirection result

Redirection target result

Something like this in the View Results Tree listener:

The behaviour is absolutely expected and for instance if you generate HTML Reporting Dasbhoard out of the .jtl results file like:

```<code>jmeter -g /path/to/jtl/result/file -o /path/to/dashboard/folder
</code>```

you will see only 1 sampler there

However if you plan to continue using Summary Report listener for results analysis and don't want to observe these redirection responses there just set jmeter.save.saveservice.subresults property to false, it can be done in 2 ways:

Pass the property via -J command-line argument like:

```<code>jmeter -Jjmeter.save.saveservice.subresults=false -n -t test.jmx -l result.jtl
</code>```

Add the following line to user.properties file:

```<code>jmeter.save.saveservice.subresults=false
</code>```

More information Apache JMeter Properties Customization Guide

Body:
My expectation is that this is due to redirection, i.e. very first response has HTTP Status code of 3xx and you're getting 3 lines in the .jtl results file like:

Sum of response times of lines 2 and 3

Redirection result

Redirection target result

Something like this in the View Results Tree listener:

The behaviour is absolutely expected and for instance if you generate HTML Reporting Dasbhoard out of the .jtl results file like:

jmeter -g /path/to/jtl/result/file -o /path/to/dashboard/folder

you will see only 1 sampler there

However if you plan to continue using Summary Report listener for results analysis and don't want to observe these redirection responses there just set jmeter.save.saveservice.subresults property to false, it can be done in 2 ways:

Pass the property via -J command-line argument like:

jmeter -Jjmeter.save.saveservice.subresults=false -n -t test.jmx -l result.jtl

Add the following line to user.properties file:

jmeter.save.saveservice.subresults=false

More information Apache JMeter Properties Customization Guide


问:
Sliver Appbar [Collapsing Toolbar] animate title from left to center in Flutter
Here is my Build method for collapsing toolbar:-

```<code>     @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: CustomScrollView(
        controller: controller,
        slivers: <Widget>[
          SliverAppBar(
            pinned: true,
            expandedHeight: appBarHeight,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
              ),
              onPressed: () => null,
            ),
            floating: true,
            flexibleSpace: FlexibleSpaceBar(

          titlePadding: EdgeInsets.only(left:leftV , bottom:bottomV ),
          title: Text(
            "Title ",
            style: TextStyle(
              color: Colors.black,
              fontSize: 16.0,
            ),
          ),
        ),
      ),
      SliverList(delegate:
          SliverChildBuilderDelegate((BuildContext context, int index) {
        return ListTile(title: Text("Flutter / $index"));
      }))
    ],
  ),
);
}
</code>```

As per the doc I got solution to remove padding :-

/// By default the value of this property is
    /// EdgeInsetsDirectional.only(start: 72, bottom: 16) if the title is
    /// not centered, EdgeInsetsDirectional.only(start 0, bottom: 16) otherwise.
    final EdgeInsetsGeometry titlePadding;

But I got the output as :-

I want to center the title when the app bar is totally  collapsed.

Issue has been filed in github also check here.

答:
I managed to get a solution with a ScrollController.

Example Result Gif

I used this next function:

```<code>double get _horizontalTitlePadding {
    const kBasePadding = 15.0;
    const kMultiplier = 0.5;

    if (_scrollController.hasClients) {
      if (_scrollController.offset < (kExpandedHeight / 2)) {
        // In case 50%-100% of the expanded height is viewed
        return kBasePadding;
      }

      if (_scrollController.offset > (kExpandedHeight - kToolbarHeight)) {
        // In case 0% of the expanded height is viewed
        return (kExpandedHeight / 2 - kToolbarHeight) * kMultiplier +
            kBasePadding;
      }

      // In case 0%-50% of the expanded height is viewed
      return (_scrollController.offset - (kExpandedHeight / 2)) * kMultiplier +
          kBasePadding;
    }

    return kBasePadding;
}
</code>```

And I used it inside of my SilverAppBar titlePadding:

```<code>  child: Scaffold(
      body: CustomScrollView(
    controller: _scrollController,
    slivers: <Widget>[
      SliverAppBar(
        pinned: true,
        expandedHeight: kExpandedHeight,
        flexibleSpace: FlexibleSpaceBar(
          titlePadding: EdgeInsets.symmetric(
              vertical: 16.0, horizontal: _horizontalTitlePadding),
</code>```

Just make sure to initialize the controller in initState():

```<code>_scrollController = ScrollController()..addListener(() => setState(() {}));
</code>```

Body:
Here is my Build method for collapsing toolbar:-

     @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: CustomScrollView(
        controller: controller,
        slivers: <Widget>[
          SliverAppBar(
            pinned: true,
            expandedHeight: appBarHeight,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
              ),
              onPressed: () => null,
            ),
            floating: true,
            flexibleSpace: FlexibleSpaceBar(

          titlePadding: EdgeInsets.only(left:leftV , bottom:bottomV ),
          title: Text(
            "Title ",
            style: TextStyle(
              color: Colors.black,
              fontSize: 16.0,
            ),
          ),
        ),
      ),
      SliverList(delegate:
          SliverChildBuilderDelegate((BuildContext context, int index) {
        return ListTile(title: Text("Flutter / $index"));
      }))
    ],
  ),
);
}

As per the doc I got solution to remove padding :-

/// By default the value of this property is
    /// EdgeInsetsDirectional.only(start: 72, bottom: 16) if the title is
    /// not centered, EdgeInsetsDirectional.only(start 0, bottom: 16) otherwise.
    final EdgeInsetsGeometry titlePadding;

But I got the output as :-

I want to center the title when the app bar is totally  collapsed.

Issue has been filed in github also check here.

Body:
I managed to get a solution with a ScrollController.

Example Result Gif

I used this next function:

double get _horizontalTitlePadding {
    const kBasePadding = 15.0;
    const kMultiplier = 0.5;

    if (_scrollController.hasClients) {
      if (_scrollController.offset < (kExpandedHeight / 2)) {
        // In case 50%-100% of the expanded height is viewed
        return kBasePadding;
      }

      if (_scrollController.offset > (kExpandedHeight - kToolbarHeight)) {
        // In case 0% of the expanded height is viewed
        return (kExpandedHeight / 2 - kToolbarHeight) * kMultiplier +
            kBasePadding;
      }

      // In case 0%-50% of the expanded height is viewed
      return (_scrollController.offset - (kExpandedHeight / 2)) * kMultiplier +
          kBasePadding;
    }

    return kBasePadding;
}

And I used it inside of my SilverAppBar titlePadding:

  child: Scaffold(
      body: CustomScrollView(
    controller: _scrollController,
    slivers: <Widget>[
      SliverAppBar(
        pinned: true,
        expandedHeight: kExpandedHeight,
        flexibleSpace: FlexibleSpaceBar(
          titlePadding: EdgeInsets.symmetric(
              vertical: 16.0, horizontal: _horizontalTitlePadding),

Just make sure to initialize the controller in initState():

_scrollController = ScrollController()..addListener(() => setState(() {}));