问:
How to declare a global variable in a module
In the main program I have

```<code>import medallia_utils
from collections import defaultdict
Opers   = defaultdict(int)
</code>```

Later on in this program, I will be calling a function in medallia_utils called word_checker.

I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global.

When I do this inside of medallia_utils:

```<code>def word_checker(name, comment):
    import re
    from collections import defaultdict
    global Opers
</code>```

The system says

```<code>NameError: global name 'Opers' is not defined
</code>```

I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing

```<code>global Opers
</code>```

or

```<code>global __Opers__
</code>```

but nothing working so far. I get the same error.

What is the syntax fix to get this to work?

答:
you need to make the variable hold something after you declare it as global eg.</p>

```<code>global name
name = 'bob'
</code>```

Body:
In the main program I have

import medallia_utils
from collections import defaultdict
Opers   = defaultdict(int)

Later on in this program, I will be calling a function in medallia_utils called word_checker.

I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global.

When I do this inside of medallia_utils:

def word_checker(name, comment):
    import re
    from collections import defaultdict
    global Opers

The system says

NameError: global name 'Opers' is not defined

I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing

global Opers

or

global __Opers__

but nothing working so far. I get the same error.

What is the syntax fix to get this to work?

Body:
you need to make the variable hold something after you declare it as global eg.

global name
name = 'bob'


来源: stackexchange

问:
Insert Multiple Rows If Not Exists
I have two tables. Table A and Table B. Table A has some unique id's already existing. I want to insert a new custom row into Table A where those rows for my condition exist in Table B and not in Table A. How do I insert all rows from Table B that don't exist in Table A? I am looking for MSSQL solution.

I have tried the following two forms but neither seem to work:

Example A:

```<code>INSERT into TableA
(
    Id,
    Selection1,
    Selection2,
    Selection3
)
SELECT
(
    Id,  /* this field comes from TableB */
     0,
     0,
     1
)
from TableB
where NOT EXISTS ( SELECT * FROM TableA
                INNER JOIN TableB
                ON TableA.Id = TableB.ID)
</code>```

Example B

```<code>IF NOT EXISTS ( SELECT * FROM TableA
        INNER JOIN TableB
        ON TableA.Id = TableB.Id)

    INSERT into TableA
    (
        Id,
        Selection1,
        Selection2,
        Selection3
    )
    SELECT
    (
        Id,  /* this field comes from TableB */
         0,
         0,
         1
    )
    from TableB
</code>```

答:
You are very close with the first query.  The problem is the JOIN in the subquery:

```<code>INSERT into TableA (Id, Selection1, Selection2, Selection3)
    SELECT Id, /* this field comes from TableB */, 0, 0, 1
    from TableB b
    where NOT EXISTS (SELECT 1
                      FROM TableA a
                      WHERE a.Id = b.ID
                     );
</code>```

Notes:

Table aliases make the query easier to write and to read.

Columns called Selection1, etc. are suspicious.  You should probably be putting three rows into a "selections" table of some sort.

ContentLicense: CC BY-SA 3.0

Title: Insert Multiple Rows If Not Exists

Body:
I have two tables. Table A and Table B. Table A has some unique id's already existing. I want to insert a new custom row into Table A where those rows for my condition exist in Table B and not in Table A. How do I insert all rows from Table B that don't exist in Table A? I am looking for MSSQL solution.

I have tried the following two forms but neither seem to work:

Example A:

INSERT into TableA
(
    Id,
    Selection1,
    Selection2,
    Selection3
)
SELECT
(
    Id,  /* this field comes from TableB */
     0,
     0,
     1
)
from TableB
where NOT EXISTS ( SELECT * FROM TableA
                INNER JOIN TableB
                ON TableA.Id = TableB.ID)

Example B

IF NOT EXISTS ( SELECT * FROM TableA
        INNER JOIN TableB
        ON TableA.Id = TableB.Id)

    INSERT into TableA
    (
        Id,
        Selection1,
        Selection2,
        Selection3
    )
    SELECT
    (
        Id,  /* this field comes from TableB */
         0,
         0,
         1
    )
    from TableB

Body:
You are very close with the first query.  The problem is the JOIN in the subquery:

INSERT into TableA (Id, Selection1, Selection2, Selection3)
    SELECT Id, /* this field comes from TableB */, 0, 0, 1
    from TableB b
    where NOT EXISTS (SELECT 1
                      FROM TableA a
                      WHERE a.Id = b.ID
                     );

Notes:

Table aliases make the query easier to write and to read.

Columns called Selection1, etc. are suspicious.  You should probably be putting three rows into a "selections" table of some sort.


问:
How To Organize An Array By Key String with Integer
How would I be able to organize the below array into another array using the integer value provided in the array object key?

```<code>[
  {
     "itemQty_0": "443"
   },
   {
     "itemDescription_0": "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"
   },
   {
      "itemCapCheckbox_0": "on"
   },
   {
     "itemQty_1": "44"
   },
   {
     "itemDescription_1": "44"
   }
]
</code>```

How can I organize this array into another array that looks like this?

```<code>items: [{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
},{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
 }]
</code>```

答:
```<code> const result = [];

 for(const obj of items){
   const keyId = Object.keys(obj)[0], [key, id] = keyId.split("_");
   if(result[id]){
     result[id][key] = obj[keyId];
   }else{
     result[id] = { [key] : obj[keyId] };
   }
 }
</code>```

Body:
How would I be able to organize the below array into another array using the integer value provided in the array object key?

[
  {
     "itemQty_0": "443"
   },
   {
     "itemDescription_0": "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"
   },
   {
      "itemCapCheckbox_0": "on"
   },
   {
     "itemQty_1": "44"
   },
   {
     "itemDescription_1": "44"
   }
]

How can I organize this array into another array that looks like this?

items: [{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
},{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
 }]


问:
copy specific text to copy another text in javascript
I want to make it like when i copy something i'll get something else on the clipboard.

```<code>document.addEventListener('copy', function(e){
  if(e.clipboardData.getData('Text').toString()==="@Trolluminati")
  e.clipboardData.setData ("Text", "<@325608201175433216>");
  e.preventDefault();
});
</code>```

Idk, how to make it so it will change the last copy of this specific text to the other one.

Right now it just keeps the same copied text and does not change it.

答:
Here's some code that might be helpful</p>

```<code>if (document.queryCommandSupported('copy')) {
      var textArea = document.createElement("textarea");
      textArea.style.position = 'fixed';
      textArea.style.top = '0';
      textArea.style.left = '0';
      textArea.style.width = '2em';
      textArea.style.height = '2em';
      textArea.style.padding = '0';
      textArea.style.border = 'none';
      textArea.style.outline = 'none';
      textArea.style.boxShadow = 'none';
      textArea.style.background = 'transparent';
      textArea.value = INSERT WHATEVER YOU WANT TO COPY HERE
      document.body.appendChild(textArea);
      textArea.select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
      } catch (err) {
        console.log('Oops, unable to copy');
      }
      document.body.removeChild(textArea);
    }
</code>```

Body:
I want to make it like when i copy something i'll get something else on the clipboard.

document.addEventListener('copy', function(e){
  if(e.clipboardData.getData('Text').toString()==="@Trolluminati")
  e.clipboardData.setData ("Text", "<@325608201175433216>");
  e.preventDefault();
});

Idk, how to make it so it will change the last copy of this specific text to the other one.

Right now it just keeps the same copied text and does not change it.

Body:
Here's some code that might be helpful

if (document.queryCommandSupported('copy')) {
      var textArea = document.createElement("textarea");
      textArea.style.position = 'fixed';
      textArea.style.top = '0';
      textArea.style.left = '0';
      textArea.style.width = '2em';
      textArea.style.height = '2em';
      textArea.style.padding = '0';
      textArea.style.border = 'none';
      textArea.style.outline = 'none';
      textArea.style.boxShadow = 'none';
      textArea.style.background = 'transparent';
      textArea.value = INSERT WHATEVER YOU WANT TO COPY HERE
      document.body.appendChild(textArea);
      textArea.select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
      } catch (err) {
        console.log('Oops, unable to copy');
      }
      document.body.removeChild(textArea);
    }


问:
Emulating static constructors for templated classes

I would like to have a templated class with a static data member, and initialize it by emulating a "static constructor." For a non-templated class, this has already been answered (see static constructors in C++? I need to initialize private static objects and What is a static constructor?). However, none of the answers seem to work for a templated class.

The following is an example that tries to adapt the "static constructor" idiom from the previous answers to a templated class. (Note that the example is simply initializing an int and could be written without such constructors; however, I require a general solution.)

```<code>#include <iostream>

struct Foo
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Foo..." << std::endl;
            x = 1;
        }
    } initializer;
};
int Foo::x;
Foo::init Foo::initializer;

template<int N>
struct Bar
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Bar..." << std::endl;
            x = N;
        }
    } initializer;
};

template<int N>
int Bar<N>::x;
template<int N>
typename Bar<N>::init Bar<N>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}
</code>```

This outputs:

```<code>Initializing Foo...
1
0
</code>```

But I expected it to output:

```<code>Initializing Foo...
Initializing Bar...
1
1
</code>```

Is this an example of the "static initialization order fiasco?"

答:
You need to explictly instantiate initializer:

```<code>[...]
template<int N>
typename Bar<N>::init Bar<N>::initializer;

template
typename Bar<1>::init Bar<1>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}
</code>```

The reason is that Bar<1>::x does not depends on Bar<1>::initializer. So the compiler does not instantiate it as you do not use it. Actualy, initializer initialization does not initialize x. x is first zero initialized, then if initializer is instantiated, x is assigned a new value.

There are no risk of static initialization fiasco as long as initializer is instantiated in the same translation unit as the one where x is instantiated. So it is certainly a good idea to explictly instantiate x too.

Alternatively you could declare these variables as static locals:

```<code>#include <iostream>
template<int N>
struct Bar
{
    static int x()
      {
      static int x_val;
      static struct init
        {
        init()
          {
          std::cout << "Initializing Bar..." << std::endl;
          x_val = N;
          }
        } initializer;//indeed this circumvolution is no more needed.
      return x_val;
      }
};
int main(){
    std::cout << Bar<1>::x() << std::endl;
}
</code>```

But if the initialization is not trivial, the generated code inside x() may be under optimized.

Depending on your problem, you could also define x as a wrapper around an int:

```<code>class int_inited{
  int val;
  public:
  int_inited(){
    std::cout << "Perfoming initialization" << std::endl;
    val=42;
    }
  operator int&(){
    return val;
    }
  operator const int &() const{
    return val;
    }
  };

template<class N>
struct Bar{
  static int_inited x;
  [...];
</code>```

Body:
I would like to have a templated class with a static data member, and initialize it by emulating a "static constructor." For a non-templated class, this has already been answered (see static constructors in C++? I need to initialize private static objects and What is a static constructor?). However, none of the answers seem to work for a templated class.

The following is an example that tries to adapt the "static constructor" idiom from the previous answers to a templated class. (Note that the example is simply initializing an int and could be written without such constructors; however, I require a general solution.)

#include <iostream>

struct Foo
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Foo..." << std::endl;
            x = 1;
        }
    } initializer;
};
int Foo::x;
Foo::init Foo::initializer;

template<int N>
struct Bar
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Bar..." << std::endl;
            x = N;
        }
    } initializer;
};

template<int N>
int Bar<N>::x;
template<int N>
typename Bar<N>::init Bar<N>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}

This outputs:

Initializing Foo...
1
0

But I expected it to output:

Initializing Foo...
Initializing Bar...
1
1

Is this an example of the "static initialization order fiasco?"

Body:
You need to explictly instantiate initializer:

[...]
template<int N>
typename Bar<N>::init Bar<N>::initializer;

template
typename Bar<1>::init Bar<1>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}

The reason is that Bar<1>::x does not depends on Bar<1>::initializer. So the compiler does not instantiate it as you do not use it. Actualy, initializer initialization does not initialize x. x is first zero initialized, then if initializer is instantiated, x is assigned a new value.

There are no risk of static initialization fiasco as long as initializer is instantiated in the same translation unit as the one where x is instantiated. So it is certainly a good idea to explictly instantiate x too.

Alternatively you could declare these variables as static locals:

#include <iostream>
template<int N>
struct Bar
{
    static int x()
      {
      static int x_val;
      static struct init
        {
        init()
          {
          std::cout << "Initializing Bar..." << std::endl;
          x_val = N;
          }
        } initializer;//indeed this circumvolution is no more needed.
      return x_val;
      }
};
int main(){
    std::cout << Bar<1>::x() << std::endl;
}

But if the initialization is not trivial, the generated code inside x() may be under optimized.

Depending on your problem, you could also define x as a wrapper around an int:

class int_inited{
  int val;
  public:
  int_inited(){
    std::cout << "Perfoming initialization" << std::endl;
    val=42;
    }
  operator int&(){
    return val;
    }
  operator const int &() const{
    return val;
    }
  };

template<class N>
struct Bar{
  static int_inited x;
  [...];


问:
How to make the unsubscribe link in Outlook work for newsletters?
We send out email newsletters and automated confirmation emails to users of our websites. Each email has an unsubscribe link in the email footer and each recipient opted in to receive emails.

Outlook webmail has the unsubscribe link above the body of the email in the following form:

Getting too much email from #SENDER#? You can unsubscribe

Clicking on the link opens a dialog window with following content:

Block this sender

[SENDER] hasn't given us any information to help you unsubscribe, so we'll block everything sent from the following sender: [EMAIL_ADDRESS]

[×] Also delete everything from [SENDER] in my Inbox folder

I search the internet and even contacted the Outlook support and asked them what info they need from us to help recepients unsubscribe from our emails. After several email exchanges the Outlook support concluded that they have no idea how to change Outlook's unsubscribe link, what information we should give them and how we should give them the information.

Can anyone please advise or point me to the right direction please? Thanks.

答: You're confusing a couple of things here. First, while outlook.com is a Microsoft domain, Outlook itself is an entirely different thing, and people can be using Outlook as their mail program regardless of what domain they have. You won't know what client people are using for email, or what server they use to access it. Second, you say that email communication is vital for your websites. Banning people from your newsletters doesn't help that situation in the least. People using the various Microsoft services that you mention have no trouble receiving and participating in those email communications. What you don't touch on, is what software you're using for your newsletters. THAT is where your problem probably is. If you go to that domain.com/unsubscribe URL, what does that page do/look like? There are 2 usual links for a List-Unsubscribe header. One is a mailto: link such as unsub-list-12345@domain.com, where any email to that address performs an unsubscription. For the web link version, it needs to be a link to a page that automatically unsubscribes the user (so the link would need to be customized with variables such as the mailing list).</p>


问:
How do I create tag with certain commits and push it to origin?
Say the current log in my gerrit looks like the following:

commit10 (master)

commit9

commit8

commit7

commit6 v1.72.0

commit5

commit4 v1.71.0

commit3

commit2

commit1

My goal is to create a new tag (v1.73.0) that should contain commit8 and commit9 and push it to origin. I was told to create a new local branch based on the latest stable tag and cherry-pick the necessary commits and tag it up. However, I am having some problem pushing the tag up to master.

Here's what I've done:

create local branch based on the latest tag: git checkout -b branchforv1.73.0 v1.72.0

cherry-pick commit8 and commit9

create new tag: git tag v1.73.0

...so now, how do I push v1.73.0 to master?

Result:

commit10 (master)

commit7

commit9 v1.73.0

commit8

commit6 v1.72.0

commit5

commit4 v1.71.0

commit3

commit2

commit1

答:
Here is a concrete example:</p>

```<code>git add .
git commit -m "some description"
git tag v0.1.9 # or any other text
git push origin master # push the commit
git push --tags origin # push the tags
</code>```

Body:
Here is a concrete example:

git add .
git commit -m "some description"
git tag v0.1.9 # or any other text
git push origin master # push the commit
git push --tags origin # push the tags


问:
Change write location for neo4j-admin import
I'm trying to import around 300G of csv data to neo4j using the neo4j-admin import tool. However, the directory in which neo4j is stored does not have that much space available.

How do I change the directory that the import tool writes to? I tried:

```<code>--database= /new/directory/my.graphdb
</code>```

but got the following:

```<code>'database' should be a name but you seem to have specified a path:
</code>```

Can anyone explain how to do this?

答:
As a quick workaround, you can use the (deprecated) neo4j-import tool that has a --into argument. For an example, see the "Super Fast Batch Importer For Huge Datasets" section of the CSV Import Guide:

```<code>bin/neo4j-import --into retail.db --id-type string \
                 --nodes:Customer customers.csv --nodes products.csv  \
                 --nodes orders_header.csv,orders1.csv,orders2.csv \
                 --relationships:CONTAINS order_details.csv \
                 --relationships:ORDERED customer_orders_header.csv,orders1.csv,orders2.csv
</code>```

Body:
I'm trying to import around 300G of csv data to neo4j using the neo4j-admin import tool. However, the directory in which neo4j is stored does not have that much space available.

How do I change the directory that the import tool writes to? I tried:

--database= /new/directory/my.graphdb

but got the following:

'database' should be a name but you seem to have specified a path:

Can anyone explain how to do this?

Body:
As a quick workaround, you can use the (deprecated) neo4j-import tool that has a --into argument. For an example, see the "Super Fast Batch Importer For Huge Datasets" section of the CSV Import Guide:

bin/neo4j-import --into retail.db --id-type string \
                 --nodes:Customer customers.csv --nodes products.csv  \
                 --nodes orders_header.csv,orders1.csv,orders2.csv \
                 --relationships:CONTAINS order_details.csv \
                 --relationships:ORDERED customer_orders_header.csv,orders1.csv,orders2.csv


问:
What version of Jackson does spring-boot use?
I am trying to make sure I am using spring-boot and Jackson in a safe way. There is a deserialization bug in some versions of Jackson (source: https://github.com/FasterXML/jackson-databind/issues/1599).

By default Spring Security does not perform deserialization using Jackson, so this is an explicit choice of the user (source: https://pivotal.io/security/cve-2017-4995).

If Jackson is used to perform deserialization, versions 2.7, 2.8, 2.8.9 and 2.7.9.1, as well as 2.9.0.pr3 are patched (source: see cowtowncoder commented on Apr 13, https://github.com/FasterXML/jackson-databind/issues/1599) and not vulnerable to the bug.

Is it safe, then to perform deserialization using the version of Jackson that is part of spring, spring-boot, or Spring Security?

答:
Every version of SpringBoot uses a vulnerable version of the Jackson API, since there really is no version that is not at least partially suceptable to attack. It can happen if you allow untrusted and third party data to be de-serialized into generic collections(Map<>, List<>. etc). Even if you are adding generics to these structures in you code, those generics are compile time only, and cannot enforce typing in the JVM runtime.

If you are accessing an external restful api, then you will have to implement your own typing. If you are using RestTemplate, this will have to be manually set on the object mapper it uses.

FYI: SpringBoot also uses a vulnerable version of logback. Just update to the latest version by explicitly including it in your build.


问:
Running web application on local host
I wrote a web-application which is using java library SOCIAL AUTH for oauth .
For this i need to generate a secret with oauth provider like google,twitter .

while generating the key i gave the location of  site eg: www.xyz.com .
Now these oauth provider are retuning their response at the location www.xyz.com

But i want to test my application on localhost wheather is going fine or not.So while runnning on localhost oauth provider is coming as null .

IS there any way by which i can use do by which i can say my tomcat to take the properties or response from www.xyz.com  .So that it ll be able to read the response coming from oauth provider

答:
One trick for these types of situations is to temporarily change your /etc/hosts file (if you're on Linux or Mac) so that www.xyz.com points to your localhost.  That is, put the following line in the file:

```<code>127.0.0.1    www.xyz.com
</code>```

Then, when the remote site redirects you back to www.xyz.com, that will resolve to localhost.  You just have to remember to comment out this line in /etc/hosts whenever you want to access the real production system.

(You can do the same thing on Windows, but I can't remember where the equivalent of /etc/hosts is on Windows, and I don't have access to a Windows box right now.)

ContentLicense: CC BY-SA 2.5

Title: Running web application on local host

Body:
One trick for these types of situations is to temporarily change your /etc/hosts file (if you're on Linux or Mac) so that www.xyz.com points to your localhost.  That is, put the following line in the file:

127.0.0.1    www.xyz.com

Then, when the remote site redirects you back to www.xyz.com, that will resolve to localhost.  You just have to remember to comment out this line in /etc/hosts whenever you want to access the real production system.

(You can do the same thing on Windows, but I can't remember where the equivalent of /etc/hosts is on Windows, and I don't have access to a Windows box right now.)


问:
Is unlocking a lock_guard manually undefined/bad design?
I've got code thats something like this:

```<code>do {
    lock_guard<mutex> lck(globalMtx);
    auto itr = someMap.end();
    for (/*conditions*/){
        //do stuff with itr and someMap
        // if a certain condition is met, we exit function with a return
        // globalMtx needs to be unlocked at that time
    }
    if (itr == someMap.end()){
        // I need to unlock the globalMtx here
        globalMtx.unlock()
        // A command is sent to modify someMap before we try again
        this_thread::sleep_for( chrono::seconds( 5 ) );
    } else {
        break;
    }
} while (true);
</code>```

As you can see in the if scope, I need to unlock the globalMtx so that I can modify "someMap" before going through it again. I've read in many threads/forums/whatever that manually locking a mutex using mutex.lock()/unlock() is a bad idea and typically never done anymore with c++11 or above.

So what can I do in this case to control the mutex as I need, while still preventing any case where leaving the scope keeps the mutex locked?

答: Write a wrapper like lock_guard that tracks whether the mutex is held or not and only unlocks on destruction if it is held The wrapper should likely have both an unlock and relock (which is a no-op if the lock is already held)..</p>

Body:
I've got code thats something like this:

do {
    lock_guard<mutex> lck(globalMtx);
    auto itr = someMap.end();
    for (/*conditions*/){
        //do stuff with itr and someMap
        // if a certain condition is met, we exit function with a return
        // globalMtx needs to be unlocked at that time
    }
    if (itr == someMap.end()){
        // I need to unlock the globalMtx here
        globalMtx.unlock()
        // A command is sent to modify someMap before we try again
        this_thread::sleep_for( chrono::seconds( 5 ) );
    } else {
        break;
    }
} while (true);

As you can see in the if scope, I need to unlock the globalMtx so that I can modify "someMap" before going through it again. I've read in many threads/forums/whatever that manually locking a mutex using mutex.lock()/unlock() is a bad idea and typically never done anymore with c++11 or above.

So what can I do in this case to control the mutex as I need, while still preventing any case where leaving the scope keeps the mutex locked?


问:
Build an net461 app includ framework dlls in build
when I build a class library build of the 4.6.1 framework it includes in the build all the dll of the framework that I use, but I imagine that the dlls that already are of the framework should not be generated for the build folder, can help me ?

答: I removed the Microsoft.Extensions.etc references from the nuget and that solved the problem, some of the packages should accuse dependency of the .netstandard, which in turn brought all the dlls of the framework built on it</p>


问:
verify (bitwise) if a value matches multiple specific flags of an enum
I would like to check if a value corresponds to a set of flags (from an enum or object alike).

Right now, I have come up with the following function in javascript (praise the snippet :3):

function hasFlags(flags, value) {
    let s = flags.reduce((sum, v) => sum += v, 0);

    return (s & value) === s
}

FLAGS = {
    STEP_0: 1 << 0,
    STEP_1: 1 << 1,
    STEP_2: 1 << 2,
    STEP_3: 1 << 3,
    STEP_4: 1 << 4,
    STEP_5: 1 << 5,
    STEP_6: 1 << 6,
    STEP_7: 1 << 7
}

const needed = [
    FLAGS.STEP_2,
    FLAGS.STEP_3,
    FLAGS.STEP_6,
]

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true
// etc...```
</div>
</div>
</p>

<p>In python the function would look like this:</p>

```def hasFlags(flags, value):
    s = sum(flags)
    return (s & value) == s

print hasFlags((4,8,64), 4)  # False
print hasFlags((4,8,64), 4+8+64)  # True
# ...
```

Is there a better way (that is, more idiomatic ... or more pythonic) to do this same verification?

Edit: Solutions in both python and javascript are appreciated, but I am  especially looking for an algorithm (whatever the language), as I've searched a lot across the web and never found any, while it seems to me that it's a common problem.

答:
One option in Python is a set of flags, where flags are elements of (for example) an enumeration from the enum module. This also has the benefit of the subset operator already being defined, so you can just do needed <= flags.

Your final code would look something like this:

```<code>from enum import Enum

class Flags(enum.Enum):
  flag0 = {0}
  flag1 = {1}
  flag2 = {2}
  ...

def has_flags(needed, flags):
  return needed <= flags

needed = Flags.flag2 |
         Flags.flag3 |
         Flags.flag6

print(has_flags(needed, Flags.flag2)) #false
print(has_flags(needed, Flags.flag3)) #false
...
</code>```

Body:
I would like to check if a value corresponds to a set of flags (from an enum or object alike).

Right now, I have come up with the following function in javascript (praise the snippet :3):

function hasFlags(flags, value) {
    let s = flags.reduce((sum, v) => sum += v, 0);

    return (s & value) === s
}

FLAGS = {
    STEP_0: 1 << 0,
    STEP_1: 1 << 1,
    STEP_2: 1 << 2,
    STEP_3: 1 << 3,
    STEP_4: 1 << 4,
    STEP_5: 1 << 5,
    STEP_6: 1 << 6,
    STEP_7: 1 << 7
}

const needed = [
    FLAGS.STEP_2,
    FLAGS.STEP_3,
    FLAGS.STEP_6,
]

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true
// etc...

In python the function would look like this:

def hasFlags(flags, value):
    s = sum(flags)
    return (s & value) == s

print hasFlags((4,8,64), 4)  # False
print hasFlags((4,8,64), 4+8+64)  # True
# ...

Is there a better way (that is, more idiomatic ... or more pythonic) to do this same verification?

Edit: Solutions in both python and javascript are appreciated, but I am  especially looking for an algorithm (whatever the language), as I've searched a lot across the web and never found any, while it seems to me that it's a common problem.

Body:
One option in Python is a set of flags, where flags are elements of (for example) an enumeration from the enum module. This also has the benefit of the subset operator already being defined, so you can just do needed <= flags.

Your final code would look something like this:

from enum import Enum

class Flags(enum.Enum):
  flag0 = {0}
  flag1 = {1}
  flag2 = {2}
  ...

def has_flags(needed, flags):
  return needed <= flags

needed = Flags.flag2 |
         Flags.flag3 |
         Flags.flag6

print(has_flags(needed, Flags.flag2)) #false
print(has_flags(needed, Flags.flag3)) #false
...


问:
mapping through an array
I have an array called enquiries
Im trying to map through it like this:

```<code>enquiries.map(enquiry => enquiry.firstName)
</code>```

I get the following error:

```<code>TypeError: enquiries.map is not a function
</code>```

Here is output for console.log(enquiries)

```<code>{enquiries: Array(2)}
  enquiries:Array(2)
  0:{_id: "5a28364d5a36f4556af34741",
     firstName: "jonny",
     surname: "rotten",
     telephoneNumber: 859937,
     gender: ""male"", …}
  1:{id: "5a283e4c5a36f4556af34742",
     firstName: "bob",
     surname: "hoskins",
     telephoneNumber: 939483948,
     gender: "male", …}
</code>```

答:
The first {enquiries: Array(2)} implies that the logged element is an object that contains a key named enquiries.

So if your logged variable is also enquiries then you need

```<code>let firstNames = enquiries.enquiries.map(enquiry=>enquiry.firstName);
</code>```

Also to return the firstName from your arrow function, you need to either use {} and return inside it, or skip the {} altogether for an implicit return.

Title: mapping through an array

Body:
I have an array called enquiries
Im trying to map through it like this:

enquiries.map(enquiry => enquiry.firstName)

I get the following error:

TypeError: enquiries.map is not a function

Here is output for console.log(enquiries)

{enquiries: Array(2)}
  enquiries:Array(2)
  0:{_id: "5a28364d5a36f4556af34741",
     firstName: "jonny",
     surname: "rotten",
     telephoneNumber: 859937,
     gender: ""male"", …}
  1:{id: "5a283e4c5a36f4556af34742",
     firstName: "bob",
     surname: "hoskins",
     telephoneNumber: 939483948,
     gender: "male", …}

Body:
The first {enquiries: Array(2)} implies that the logged element is an object that contains a key named enquiries.

So if your logged variable is also enquiries then you need

let firstNames = enquiries.enquiries.map(enquiry=>enquiry.firstName);

Also to return the firstName from your arrow function, you need to either use {} and return inside it, or skip the {} altogether for an implicit return.


问:
JSF 2 modal panel
How can i make a modal panel in JSF 2?
I tried using javascript as in:
http://www.pat-burt.com/web-development/how-to-do-a-css-popup-without-opening-a-new-window/

and a jquery plugin called SimpleModal.

but the modal panel at best appears for a split of a second and then disappears.
So how can i achieve a modal panel in pure JSF 2 (no richfaces or such)?
Thanks in advance.

答:
How are you calling your modal panel? If you are using a commandButton / commandLink with the onclick event, then you will have to finish your call by return false;, like that:

```<code><h:commandButton onclick="popup('...'); return false;" ...>
</code>```

If you do not set this, then the popup will appear, and then a request is sent to the server. The page will finally be refreshed, which will close this popup.

Title: JSF 2 modal panel

Body:
How are you calling your modal panel? If you are using a commandButton / commandLink with the onclick event, then you will have to finish your call by return false;, like that:

<h:commandButton onclick="popup('...'); return false;" ...>

If you do not set this, then the popup will appear, and then a request is sent to the server. The page will finally be refreshed, which will close this popup.


问:
TSQL IF/ELSE or CASE (UPSERT)
Not sure if IF/ELSE is the right way to go for the following. It always returns ELSE so it seems its not working correctly.

```<code>IF ((SELECT COUNT(CAST(StudentuserID AS int)) FROM StudentAttendance WHERE StudentUserID=1)>0)
PRINT 'Yes'
ELSE
PRINT 'No'
</code>```

This test should result in yes as the data is 8>0

I will be replacing PRINT with an UPDATE ELSE INSERT statement.

```<code>IF ((SELECT COUNT(CAST(StudentuserID AS int)) FROM StudentAttendance WHERE StudentUserID=1)>0)
UPDATE StudentAttendance
SET
CID = CAST('[querystring:CID]' AS int),
CalendarEventID = CAST('[querystring:CEID]' AS int),
StudentUserID = CAST('[StudentUserID]' AS int),
Attendance = '[Attendance]'
ELSE
INSERT INTO StudentAttendance
(CID,CalendarEventID,StudentUserID,Attendance)
VALUES
(CAST('[querystring:CID]' AS int), CAST('[querystring:CEID]' AS int), CAST('[StudentsUserID]' AS int),'[Attendance]')
</code>```

答:
It looks like your IF/ELSE would work fine (it looks like you're doing this for one record in a stored procedure or something?). If it's currently returning 'No' and you don't think it should be, I'd perhaps do a more basic check on your table, e.g.:

```<code>SELECT *
FROM StudentAttendance
WHERE StudentUserID = 1
</code>```

You can also use a MERGE statement for this, and you can use multiple source tables by joining them within the USING part. Here is a basic example of that:

```<code>DECLARE @A table (Aid int, value int)
DECLARE @B table (Aid int, Cid int)
DECLARE @C table (Cid int, value int)

INSERT INTO @A VALUES (1, 1)
INSERT INTO @B VALUES (1, 2)
INSERT INTO @B VALUES (2, 3)
INSERT INTO @C VALUES (2, 4)
INSERT INTO @C VALUES (3, 6)
;

SELECT *
FROM @A
;

MERGE INTO @A tgt
USING (SELECT B.Aid, B.Cid, C.value FROM @B B JOIN @C C ON B.Cid = C.Cid) src
ON tgt.Aid = src.Aid

WHEN MATCHED THEN UPDATE
SET tgt.value = src.value

WHEN NOT MATCHED THEN
INSERT
(
    Aid
    , value
)

VALUES
(
    src.Aid
    , src.value
)
;

SELECT *
FROM @A
;
</code>```

Title: TSQL IF/ELSE or CASE (UPSERT)

Body:
Not sure if IF/ELSE is the right way to go for the following. It always returns ELSE so it seems its not working correctly.

IF ((SELECT COUNT(CAST(StudentuserID AS int)) FROM StudentAttendance WHERE StudentUserID=1)>0)
PRINT 'Yes'
ELSE
PRINT 'No'

This test should result in yes as the data is 8>0

I will be replacing PRINT with an UPDATE ELSE INSERT statement.

IF ((SELECT COUNT(CAST(StudentuserID AS int)) FROM StudentAttendance WHERE StudentUserID=1)>0)
UPDATE StudentAttendance
SET
CID = CAST('[querystring:CID]' AS int),
CalendarEventID = CAST('[querystring:CEID]' AS int),
StudentUserID = CAST('[StudentUserID]' AS int),
Attendance = '[Attendance]'
ELSE
INSERT INTO StudentAttendance
(CID,CalendarEventID,StudentUserID,Attendance)
VALUES
(CAST('[querystring:CID]' AS int), CAST('[querystring:CEID]' AS int), CAST('[StudentsUserID]' AS int),'[Attendance]')

Body:
It looks like your IF/ELSE would work fine (it looks like you're doing this for one record in a stored procedure or something?). If it's currently returning 'No' and you don't think it should be, I'd perhaps do a more basic check on your table, e.g.:

SELECT *
FROM StudentAttendance
WHERE StudentUserID = 1

You can also use a MERGE statement for this, and you can use multiple source tables by joining them within the USING part. Here is a basic example of that:

DECLARE @A table (Aid int, value int)
DECLARE @B table (Aid int, Cid int)
DECLARE @C table (Cid int, value int)

INSERT INTO @A VALUES (1, 1)
INSERT INTO @B VALUES (1, 2)
INSERT INTO @B VALUES (2, 3)
INSERT INTO @C VALUES (2, 4)
INSERT INTO @C VALUES (3, 6)
;

SELECT *
FROM @A
;

MERGE INTO @A tgt
USING (SELECT B.Aid, B.Cid, C.value FROM @B B JOIN @C C ON B.Cid = C.Cid) src
ON tgt.Aid = src.Aid

WHEN MATCHED THEN UPDATE
SET tgt.value = src.value

WHEN NOT MATCHED THEN
INSERT
(
    Aid
    , value
)

VALUES
(
    src.Aid
    , src.value
)
;

SELECT *
FROM @A
;


答:
You can reduce the array to a Map, and collect properties with the same index into an object. Then spread the map values back to an array.

To find the key, you can use Object#keys to get an array of keys, and take the 1st (and only one). Then split the key by underscore to get the property name, and the index.

const items = [{"itemQty_0":"443"},{"itemDescription_0":"Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"},{"itemCapCheckbox_0":"on"},{"itemQty_1":"44"},{"itemDescription_1":"44"}];

const result = [...items.reduce((m, o) => {
  const oKey = Object.keys(o)[0]; // get the key

  const [prop, index] = oKey.split('_'); // get the prop name and the index

  m.has(index) || m.set(index, {}); // if index doesn't exist in the map, and a new entry

  m.get(index)[prop] = o[oKey]; // get the object by the index, and assign the value to the prop

  return m;
}, new Map()).values()];

console.log(result);```

Title: How To Organize An Array By Key String with Integer

Body:
How would I be able to organize the below array into another array using the integer value provided in the array object key?

[
  {
     "itemQty_0": "443"
   },
   {
     "itemDescription_0": "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"
   },
   {
      "itemCapCheckbox_0": "on"
   },
   {
     "itemQty_1": "44"
   },
   {
     "itemDescription_1": "44"
   }
]

How can I organize this array into another array that looks like this?

items: [{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
},{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
 }]


问:
Prevent list containing an image from breaking
I have the following lay-out on my website: List of products

This is actually the Woocommerce product list which is an unordered list.

The HTML of the list looks something like this:

```<code><div class="widget widget_woocommerce_ndbproducts">
  <ul class="product_list_widget">
    <li>
      <a href="https://www.slagerijrudi.be/product/broodje-ham/" title="Broodje Ham">
      <img src="//www.slagerijrudi.be/wp-content/plugins/woocommerce/assets/images/placeholder.png" alt="Placeholder" width="180" class="woocommerce-placeholder wp-post-image" height="180">Broodje Ham</a>
      <span class="woocommerce-Price-amount amount">
        <span class="woocommerce-Price-currencySymbol">€</span>
        2,85
      </span>
    </li>
    <li>...</li>
    <li>...</li>
  </ul>
</div>
</code>```

In order to have this list in 4 columns on desktop, I've added the following CSS:

```<code>@media screen and (min-width: 1025px) {
  .four-columns ul.product_list_widget {
      -moz-column-count: 4;
      -moz-column-gap: 20px;
      -webkit-column-count: 4;
      -webkit-column-gap: 20px;
      column-count: 4;
      column-gap: 20px;
  }
}
</code>```

However, as you can see by the red arrows in my screenshot, the
 item gets a line break, which is not desired as the picture & price/text are no longer together this way.

Any ideas on how to prevent this?
If you want to test: this is the link.

答:
Edit, new solution:

Now that I've had a look at it live, because each
 other than the first one has a padding-top of 15px, the padding is what's pushing your second column down. If you can situate it so that the top item in every column doesn't have a padding-top, it should resolve your problem without needing anything extra and then you wouldn't have to worry about solving the line breaking itself. It's more of a padding/height issue than a line-break issue.

A min-height on your
 could also be a potential solution, but if you want the items to align better, solving the padding problem would be preferred.

Body:
I have the following lay-out on my website: List of products

This is actually the Woocommerce product list which is an unordered list.

The HTML of the list looks something like this:

      Broodje Ham

        €
        2,85

...

...

In order to have this list in 4 columns on desktop, I've added the following CSS:

@media screen and (min-width: 1025px) {
  .four-columns ul.product_list_widget {
      -moz-column-count: 4;
      -moz-column-gap: 20px;
      -webkit-column-count: 4;
      -webkit-column-gap: 20px;
      column-count: 4;
      column-gap: 20px;
  }
}

However, as you can see by the red arrows in my screenshot, the
 item gets a line break, which is not desired as the picture & price/text are no longer together this way.

Any ideas on how to prevent this?
If you want to test: this is the link.

Body:
Edit, new solution:

Now that I've had a look at it live, because each <li> other than the first one has a padding-top of 15px, the padding is what's pushing your second column down. If you can situate it so that the top item in every column doesn't have a padding-top, it should resolve your problem without needing anything extra and then you wouldn't have to worry about solving the line breaking itself. It's more of a padding/height issue than a line-break issue.

A min-height on your <ul> could also be a potential solution, but if you want the items to align better, solving the padding problem would be preferred.


问:
Visual Studio 2015 IIS Express issue applicationhost.config
I have converted VS 2010 web application project to VS 2015. The published application to development server looks fine, but I cannot run locally. I see various posts to fix applicationhost.config file but I do not seem to find the issue. Please suggest if you can see what to fix. This is from applicationhost.config under my project directory:  ~\MyReporting.vs\config</p>

```<code>   <sites>
        <site name="WebSite1" id="1" serverAutoStart="true">
            <application path="/">
                <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation=":8080:localhost" />
            </bindings>
        </site>
        <site name="MyReporting-Site" id="2">
            <application path="/" applicationPool="Clr4IntegratedAppPool">
                <virtualDirectory path="/" physicalPath="C:\Users\<User>\Documents\My Web Sites\MyReporting-Site3" />
                <virtualDirectory path="/DART" physicalPath="C:\Projects\Jupiter\Databases\DART_40\DART" />
            </application>
            <application path="/DART/MyReporting" applicationPool="Clr4ClassicAppPool">
                <virtualDirectory path="/" physicalPath="C:\Projects\Jupiter\Databases\DART_40\DART\MyReporting" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation="*:17588:localhost" />
            </bindings>
        </site>
        <siteDefaults>
            <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
            <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
        </siteDefaults>
        <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
        <virtualDirectoryDefaults allowSubDirConfig="true" />
    </sites>
</code>```

答:
I created a WebApp project in VS 2015 that I wanted to debug locally.

Of course when I built, the results went into $(ProjectDir)\bin, but VS would modify the applicationhost.config to run in the root $(ProjectDir). As a result, I would get 404 errors for my generated files.
I tried several suggestions, such as:

Using <UseGlobalApplicationHostFile>
But that just changed which applicationhost.config was modified.

Using 'Override application root URL'
But contrary to posts I found, it did update the physicalPath.

Modifying several properties under <WebProjectProperties>
But I couldn't find anything that would work.

I finally found a work-around that is good enough for me:

Right-click on the Solution and select Add -> Existing Web Site...

Select your Project's Output folder.

Right-click on the Solution and select Project Dependencies...

For "Projects:" select the Web App Project.

Turn on the checkbox for your Web Project and click OK.

Right-click on the new Web Project and select "Set as StartUp Project".

Now, when you Run your solution, it will launch the code in the Output folder.

Unfortunately, when you try to debug, you have to set your breakpoints in the Web Project files, then modifications have to be done in the Web App Project files, but that is the best solution I have been able to come up with.

NOTE:

One time I did this, it named my new Web Project the same name as my Web App Project. As such, when trying to set dependencies I couldn't tell which was which.
To deal with this:

Before step 3 above, temporarily rename your Web App Project
 (I couldn't figure out how to rename my Web Project.)

After step 6:

Close the Solution

Manually rename the .csproj file back to the original name.

In a text editor, open your .sln file, find the temp name and change it back.

For example, change:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyTempName", "folder\MyTempName.csproj"

to:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyOriginalName", "folder\MyOriginalName.csproj"

Reopen the Solution.

Good Luck!

Body:
I have converted VS 2010 web application project to VS 2015. The published application to development server looks fine, but I cannot run locally. I see various posts to fix applicationhost.config file but I do not seem to find the issue. Please suggest if you can see what to fix. This is from applicationhost.config under my project directory:  ~\MyReporting.vs\config

   <sites>
        <site name="WebSite1" id="1" serverAutoStart="true">
            <application path="/">
                <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation=":8080:localhost" />
            </bindings>
        </site>
        <site name="MyReporting-Site" id="2">
            <application path="/" applicationPool="Clr4IntegratedAppPool">
                <virtualDirectory path="/" physicalPath="C:\Users\<User>\Documents\My Web Sites\MyReporting-Site3" />
                <virtualDirectory path="/DART" physicalPath="C:\Projects\Jupiter\Databases\DART_40\DART" />
            </application>
            <application path="/DART/MyReporting" applicationPool="Clr4ClassicAppPool">
                <virtualDirectory path="/" physicalPath="C:\Projects\Jupiter\Databases\DART_40\DART\MyReporting" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation="*:17588:localhost" />
            </bindings>
        </site>
        <siteDefaults>
            <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
            <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
        </siteDefaults>
        <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
        <virtualDirectoryDefaults allowSubDirConfig="true" />
    </sites>


问:
Adjust width of input field to its input

<input type="text" value="1" style="min-width:1px;" />```

This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?

I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.

If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.

答:
This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:

```<code><input [style.width.ch]="value.length" [(ngModel)]="value" />
</code>```

It automatically updates via the character units in Jani's answer.

ContentLicense: CC BY-SA 4.0

Body:
<input type="text" value="1" style="min-width:1px;" />

This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?

I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.

If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.

Body:
This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:

<input [style.width.ch]="value.length" [(ngModel)]="value" />

It automatically updates via the character units in Jani's answer.


问:
How to attach event to dynamically added HTML element?
I have a scenario where I am getting an HTML tring from the backend and I am rendering that string on HTML with [innerHTML]. I have string link this:

Please click on (click)='openMyFunction()' open dialog

I am able to get the string rendered with the help of Angular sanitize pipe, but the click handler is not working. I know as its added dynamically the click event is not getting triggered.

Can anyone provide me a small example where I can make this click even working?

答:
If you can get the new DOM element by its id or its class name, you can assign the event with element.addEventListener:

```<code>this.container.nativeElement.innerHTML = "<a class='mylink'>Click to show message</a>";

let children = document.getElementsByClassName("mylink");

for (let i = 0; i < children.length; i++) {
    children[i].addEventListener("click", (event: Event) => {
        alert("Hello world!");
    });
}
</code>```

You can see an example in this plunker.

Body:
I have a scenario where I am getting an HTML tring from the backend and I am rendering that string on HTML with [innerHTML]. I have string link this:

Please click on <a (click)='openMyFunction()' open dialog

I am able to get the string rendered with the help of Angular sanitize pipe, but the click handler is not working. I know as its added dynamically the click event is not getting triggered.

Can anyone provide me a small example where I can make this click even working?

Body:
If you can get the new DOM element by its id or its class name, you can assign the event with element.addEventListener:

this.container.nativeElement.innerHTML = "<a class='mylink'>Click to show message</a>";

let children = document.getElementsByClassName("mylink");

for (let i = 0; i < children.length; i++) {
    children[i].addEventListener("click", (event: Event) => {
        alert("Hello world!");
    });
}

You can see an example in this plunker.


问:
How To Organize An Array By Key String with Integer
How would I be able to organize the below array into another array using the integer value provided in the array object key?

```<code>[
  {
     "itemQty_0": "443"
   },
   {
     "itemDescription_0": "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est"
   },
   {
      "itemCapCheckbox_0": "on"
   },
   {
     "itemQty_1": "44"
   },
   {
     "itemDescription_1": "44"
   }
]
</code>```

How can I organize this array into another array that looks like this?

```<code>items: [{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
},{
   itemDescription: stringValue,
   itemQty: integerValue,
   itemCapCheckBox: 'on/off'
 }]
</code>```

答:
You could reduce the array by splitting the key for key and index part.

var array = [{ itemQty_0: "443" }, { itemDescription_0: "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est" }, { itemCapCheckbox_0: "on" }, { itemQty_1: "44" }, { itemDescription_1: "44" }],
    grouped = array.reduce(function (r, o) {
        var key = Object.keys(o)[0],
            keys = key.split('_');

        r[keys[1]] = r[keys[1]] || {};
        r[keys[1]][keys[0]] = o[key];
        return r;
    }, []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could reduce the array by splitting the key for key and index part.

var array = [{ itemQty_0: "443" }, { itemDescription_0: "Et aspernatur aspernatur qui sed ut do enim vel dignissimos libero nisi aut adipisci pariatur Est" }, { itemCapCheckbox_0: "on" }, { itemQty_1: "44" }, { itemDescription_1: "44" }],
    grouped = array.reduce(function (r, o) {
        var key = Object.keys(o)[0],
            keys = key.split('_');

        r[keys[1]] = r[keys[1]] || {};
        r[keys[1]][keys[0]] = o[key];
        return r;
    }, []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
c# Given 2 numbers X and Y, make X approach Y but not surpass it
I've been racking my brains for ages trying to work out a good formula for this.

Essentially what i want is given 2 numbers X and Y, I would like X to approach Y but not surpass it depending on the difference between the 2 numbers.

Both X and Y are floats between 0 and 1.

Examples:

X = 0 Y = 1. X should become about 0.7-0.8 ish.

X = 0.5 Y = 1 X should become between 0.8-0.9.

X = 0.9 y = 1 X should become 0.97 ish.

Heres what i've tried:

(1-X) * Y = Just gives linear progression....

0.08/(1.1-(Y-X)) - Better.. but gives a value 0.13 when the difference is 0.5, 0.8 when the difference is 1 and 0.4 when the difference is 0.9.... not quite what i wanted...

Any ideas guys?

Thanks,

Phil.

答:
I would suggest:

```<code>Single x = 0.0f;
Single y = 1.0f;

Single z = x + ((y - x) * 0.75f);

Console.WriteLine(z.ToString("N4")); // 0.7500
</code>```

For x = 0.5 it gives 0.8750.

For x = 0.9 it gives 0.9750.

In order to tweak the result and make it as close as possible to your expectations, just play with the scalar 0.75f.

Working environment:

```<code>public static void Main(string[] args)
{
    Single y = 1.0f;
    Single scalar = 0.75f;

    Console.WriteLine(Calculate(0.0f,y,scalar).ToString("N4"));
    Console.WriteLine(Calculate(0.5f,y,scalar).ToString("N4"));
    Console.WriteLine(Calculate(0.9f,y,scalar).ToString("N4"));
}

public static Single Calculate(Single x, Single y, Single scalar)
{
    return x + ((y - x) * scalar);
}
</code>```

What you are trying to implement looks to me line a sort of linear interpolation.

Body:
I would suggest:

Single x = 0.0f;
Single y = 1.0f;

Single z = x + ((y - x) * 0.75f);

Console.WriteLine(z.ToString("N4")); // 0.7500

For x = 0.5 it gives 0.8750.

For x = 0.9 it gives 0.9750.

In order to tweak the result and make it as close as possible to your expectations, just play with the scalar 0.75f.

Working environment:

public static void Main(string[] args)
{
    Single y = 1.0f;
    Single scalar = 0.75f;

    Console.WriteLine(Calculate(0.0f,y,scalar).ToString("N4"));
    Console.WriteLine(Calculate(0.5f,y,scalar).ToString("N4"));
    Console.WriteLine(Calculate(0.9f,y,scalar).ToString("N4"));
}

public static Single Calculate(Single x, Single y, Single scalar)
{
    return x + ((y - x) * scalar);
}

What you are trying to implement looks to me line a sort of linear interpolation.


答:
No, you should not call std::mutex::unlock() directly in this case, as std::lock_guard destructor would call std::mutex::unlock() again and that would lead to UB. You can use std::unique_lock instead, which is not lightweight as std::lock_guard but allows you to call unlock() on it:

```<code>std::unique_lock<mutex> lck(globalMtx);
...
lck.unlock(); // lck object is aware that globalMtx is released and would do nothing in it's dtor after this
</code>```

Title: Is unlocking a lock_guard manually undefined/bad design?

Body:
I've got code thats something like this:

do {
    lock_guard<mutex> lck(globalMtx);
    auto itr = someMap.end();
    for (/*conditions*/){
        //do stuff with itr and someMap
        // if a certain condition is met, we exit function with a return
        // globalMtx needs to be unlocked at that time
    }
    if (itr == someMap.end()){
        // I need to unlock the globalMtx here
        globalMtx.unlock()
        // A command is sent to modify someMap before we try again
        this_thread::sleep_for( chrono::seconds( 5 ) );
    } else {
        break;
    }
} while (true);

As you can see in the if scope, I need to unlock the globalMtx so that I can modify "someMap" before going through it again. I've read in many threads/forums/whatever that manually locking a mutex using mutex.lock()/unlock() is a bad idea and typically never done anymore with c++11 or above.

So what can I do in this case to control the mutex as I need, while still preventing any case where leaving the scope keeps the mutex locked?

Body:
No, you should not call std::mutex::unlock() directly in this case, as std::lock_guard destructor would call std::mutex::unlock() again and that would lead to UB. You can use std::unique_lock instead, which is not lightweight as std::lock_guard but allows you to call unlock() on it:

std::unique_lock<mutex> lck(globalMtx);
...
lck.unlock(); // lck object is aware that globalMtx is released and would do nothing in it's dtor after this


答:
Yes that is a bad idea, as the lock_guard will still unlock the mutex when it is destroyed, so the mutex will end up being unlocked twice. This results in undefined behaviour (i.e. crash if you're lucky).

Instead, use a std::unique_lock. This has an unlock() method, which not only calls the unlock method of the underlying mutex but also guarantees that the unique_lock object will not unlock the mutex a second time.


问:
SQL joining two columns on two strings
I am trying two join two columns on certain strings.  The only problem is that one for one of the columns contains a lot of text, and the string I want to join on is in the middle of this text.  For example:

Column_a (from table_a) contains:  x

Column_b (from table_b)contains:   tuv xyz abc

I want to be able to join on "x".  What can I use to accomplish this?
  Here is my basic code.

```<code>select
    *
from (
    select
    *
    from table_a

) ta
left join (
    select
        *
    from table_b
) tb
on bd.person = ttp.login
and ('tuv: ' || ta.column_a like '%tuv: %' || tb.column_b || '%')
</code>```

This returns no result, the two tables will not join.

答:
Concatenate the shorter string with the wildcard symbols and then use LIKE against the longer string. Note double-ended wildcards searches are not efficient and this will be an "expensive" query.

SQL Fiddle

PostgreSQL 9.6 Schema Setup:

```<code>CREATE TABLE table_a
    (Column_a varchar(20))
;

INSERT INTO table_a    (Column_a) VALUES    ('x');

CREATE TABLE table_b
    (Column_b varchar(20))
;

INSERT INTO table_b    (Column_b) VALUES    ('tuv xyz abc');
</code>```

Query 1:

```<code>select
    *
from table_a a
left join table_b b on b.column_b like ('%' || a.column_a || '%')
</code>```

Results:

```<code>| column_a |    column_b |
|----------|-------------|
|        x | tuv xyz abc |
</code>```

Title: SQL joining two columns on two strings

Body:
I am trying two join two columns on certain strings.  The only problem is that one for one of the columns contains a lot of text, and the string I want to join on is in the middle of this text.  For example:

Column_a (from table_a) contains:  x

Column_b (from table_b)contains:   tuv xyz abc

I want to be able to join on "x".  What can I use to accomplish this?
  Here is my basic code.

select
    *
from (
    select
    *
    from table_a

) ta
left join (
    select
        *
    from table_b
) tb
on bd.person = ttp.login
and ('tuv: ' || ta.column_a like '%tuv: %' || tb.column_b || '%')

This returns no result, the two tables will not join.

Body:
Concatenate the shorter string with the wildcard symbols and then use LIKE against the longer string. Note double-ended wildcards searches are not efficient and this will be an "expensive" query.

SQL Fiddle

PostgreSQL 9.6 Schema Setup:

CREATE TABLE table_a
    (Column_a varchar(20))
;

INSERT INTO table_a    (Column_a) VALUES    ('x');

CREATE TABLE table_b
    (Column_b varchar(20))
;

INSERT INTO table_b    (Column_b) VALUES    ('tuv xyz abc');

Query 1:

select
    *
from table_a a
left join table_b b on b.column_b like ('%' || a.column_a || '%')

Results:

| column_a |    column_b |
|----------|-------------|
|        x | tuv xyz abc |


问:
How to explode space-separated column?
I have a sample dataframe in Spark Scala which contains one column and many other columns 50+ and need to explode id :

example data:

```<code>id             name   address
234 435 567    auh    aus
345 123        muji   uk
</code>```

output data:

```<code>id             name   address
234            auh    aus
435            auh    aus
567            auh    aus
345            muji   uk
123            muji   uk
</code>```

Title: How to explode space-separated column?

Body:
I have a sample dataframe in Spark Scala which contains one column and many other columns 50+ and need to explode id :

example data:

id             name   address
234 435 567    auh    aus
345 123        muji   uk

output data:

id             name   address
234            auh    aus
435            auh    aus
567            auh    aus
345            muji   uk
123            muji   uk

Body:
Try this:

import org.apache.spark.sql.functions._

scala> df.withColumn("id", explode(split($"id", " "))).show
+---+----+-------+
| id|name|address|
+---+----+-------+
|234| auh|    aus|
|435| auh|    aus|
|567| auh|    aus|
|345|muji|     uk|
|123|muji|     uk|
+---+----+-------+


问:
Add a delay or sleep to an array of promises in nodejs
I have a promise chain problem I have been grappling with.  I make a call out to an external api that returns me data that I need to process and ingest into a mongo database. I am using nodejs and mongodb with express.  Anyway, the calls to the api are working ok, the problem is that I am making tons of them at once.  I want to slow them down, like make all the calls for one set. Wait a minute. Make all the calls for the next set.  If this was a known amount of sets I would just promise chain them.  I dont know how many sets there are so I am looping through them.  I think the closure is the problem but cant work around it. on to the example code!</p>

```<code>  function readApi(carFactory){
    var promise = new Promise(function(resolve, reject) {
      // call out to api, get set of car data from factory1

      console.log(carFactory);
      if (true) {
        console.log('resolved');
        resolve("Stuff worked!"+carFactory);
      }
      else {
        reject(Error("It broke"));
      }
    });
    return promise;
  }

  function manager(){

    //singular call
    readApi("this is a singular test").then(returnedThing=>{
      console.log(returnedThing); //Stuff worked! this is a singular test
    });

    let dynamicList = ["carFactory1", "carFactory2","carFactory3","carFactory..N"];
    let readApiAction = [];
    dynamicList.forEach(carIter=>{
      readApiAction.push(readApi(carIter));
    });
    //ok so now I got an array of promise objects.
    //I want to call the first one, wait 1 minute and then call the next one.

    //originally I was calling promise.all, but there is no way to get at
    //each promise to pause them out so this code is what I am looking to fix
    let results= Promise.all(readApiAction);
    results.then(data=>{
      data.forEach(resolvedData=>{
        console.log(resolvedData); //Stuff worked carFactory1, etc...
      });
    });

    //singular call with timeout, this does not work, each one called at the same time
    let readApiActionTimeouts = [];
    dynamicList.forEach(carIter=>{
      setTimeout(callingTimeout(carIter), 6000);
    });
  }

  //just a function to call the promise in a timeout
  //this fails with this  - TypeError: "callback" argument must be a function
  function callingTimeout(carIter){
    readApi(carIter).then(returnedThing=>{
      console.log("timeout version"+returnedThing);
    });
  }
</code>```

答:
A bit on theory. Native Promise.all just groups promises. They're still executed simultaneously (in async way, though, as all JS code, but along each other). This means that it will still congest the API and perform a lot of calls.

Another thing to note is that if you want to delay a promise, you have to delay its return value (e.g. resolve). In order to do so, you may use setTimeout INSIDE new Promise (just look below for more explanation).

Set timeout is asynchronous. It does not work as in other languages (it does not just pause execution). Setting fixed timeout in your code just caused to move ALL the executions by 6s. They still happened in parallel (in different ticks, though, but it's a small difference). Try e.g. generating different timeouts for each one in the loop - you'll notice that they're happening in a different time BUT! This is not a good solution for promisified code!

And now - time for practical answer!

If you use Bluebird, it has a special method to add delay or timeout to each promise. Without it, you would have to write a wrapper around Promise, e.g. resolving it after a particular amount of time and then use it with Promise.all.

First solution (bluebird):

```<code>function delayMyPromise(myPromise, myDelay);
  return Promise.delay(myDelay).then(function() {
    return myPromise;
  });
});
</code>```

and then in your code:

```<code>return Promise.all(delayMyPromise(promise1, 1000), delayMyPromise(promise2, 2000)); // Notice different delays, you may generate them programatically
</code>```

Or even cooler, you can use Promise.map from Bluebird instead of Promise.all that has a special concurrency setting so you may force your promises to be executed in particular sequence, e.g. 2 at a time.
This is how I did it on my previous project :)

More here:

http://bluebirdjs.com/docs/api/promise.delay.html

http://bluebirdjs.com/docs/api/map.html

Pure native Promise implementation:

```<code>function delayMyPromise(myPromise, myDelay) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      return resolve(myPromise);
    }, myDelay);
  });
}
</code>```

I'd, however, heavily recommend first approach if you don't mind using Bluebird. It's like lodash for Promises and it's really fast :)

Body:
I have a promise chain problem I have been grappling with.  I make a call out to an external api that returns me data that I need to process and ingest into a mongo database. I am using nodejs and mongodb with express.  Anyway, the calls to the api are working ok, the problem is that I am making tons of them at once.  I want to slow them down, like make all the calls for one set. Wait a minute. Make all the calls for the next set.  If this was a known amount of sets I would just promise chain them.  I dont know how many sets there are so I am looping through them.  I think the closure is the problem but cant work around it. on to the example code!

  function readApi(carFactory){
    var promise = new Promise(function(resolve, reject) {
      // call out to api, get set of car data from factory1

      console.log(carFactory);
      if (true) {
        console.log('resolved');
        resolve("Stuff worked!"+carFactory);
      }
      else {
        reject(Error("It broke"));
      }
    });
    return promise;
  }

  function manager(){

    //singular call
    readApi("this is a singular test").then(returnedThing=>{
      console.log(returnedThing); //Stuff worked! this is a singular test
    });

    let dynamicList = ["carFactory1", "carFactory2","carFactory3","carFactory..N"];
    let readApiAction = [];
    dynamicList.forEach(carIter=>{
      readApiAction.push(readApi(carIter));
    });
    //ok so now I got an array of promise objects.
    //I want to call the first one, wait 1 minute and then call the next one.

    //originally I was calling promise.all, but there is no way to get at
    //each promise to pause them out so this code is what I am looking to fix
    let results= Promise.all(readApiAction);
    results.then(data=>{
      data.forEach(resolvedData=>{
        console.log(resolvedData); //Stuff worked carFactory1, etc...
      });
    });

    //singular call with timeout, this does not work, each one called at the same time
    let readApiActionTimeouts = [];
    dynamicList.forEach(carIter=>{
      setTimeout(callingTimeout(carIter), 6000);
    });
  }

  //just a function to call the promise in a timeout
  //this fails with this  - TypeError: "callback" argument must be a function
  function callingTimeout(carIter){
    readApi(carIter).then(returnedThing=>{
      console.log("timeout version"+returnedThing);
    });
  }

Body:
A bit on theory. Native Promise.all just groups promises. They're still executed simultaneously (in async way, though, as all JS code, but along each other). This means that it will still congest the API and perform a lot of calls.

Another thing to note is that if you want to delay a promise, you have to delay its return value (e.g. resolve). In order to do so, you may use setTimeout INSIDE new Promise (just look below for more explanation).

Set timeout is asynchronous. It does not work as in other languages (it does not just pause execution). Setting fixed timeout in your code just caused to move ALL the executions by 6s. They still happened in parallel (in different ticks, though, but it's a small difference). Try e.g. generating different timeouts for each one in the loop - you'll notice that they're happening in a different time BUT! This is not a good solution for promisified code!

And now - time for practical answer!

If you use Bluebird, it has a special method to add delay or timeout to each promise. Without it, you would have to write a wrapper around Promise, e.g. resolving it after a particular amount of time and then use it with Promise.all.

First solution (bluebird):

function delayMyPromise(myPromise, myDelay);
  return Promise.delay(myDelay).then(function() {
    return myPromise;
  });
});

and then in your code:

return Promise.all(delayMyPromise(promise1, 1000), delayMyPromise(promise2, 2000)); // Notice different delays, you may generate them programatically

Or even cooler, you can use Promise.map from Bluebird instead of Promise.all that has a special concurrency setting so you may force your promises to be executed in particular sequence, e.g. 2 at a time.
This is how I did it on my previous project :)

More here:

http://bluebirdjs.com/docs/api/promise.delay.html

http://bluebirdjs.com/docs/api/map.html

Pure native Promise implementation:

function delayMyPromise(myPromise, myDelay) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      return resolve(myPromise);
    }, myDelay);
  });
}

I'd, however, heavily recommend first approach if you don't mind using Bluebird. It's like lodash for Promises and it's really fast :)


问:
Programmatically detecting "most important content" on a page
What work, if any, has been done to automatically determine the most important data within an html document? As an example, think of your standard news/blog/magazine-style website, containing navigation (with submenu's possibly), ads, comments, and the prize - our article/blog/news-body.

How would you determine what information on a news/blog/magazine is the primary data in an automated fashion?

Note: Ideally, the method would work with well-formed markup, and terrible markup. Whether somebody uses paragraph tags to make paragraphs, or a series of breaks.

答:
As Readability is not available anymore:

If you're only interested in the outcome, you use Readability's successor Mercury, a web service.

If you're interested in some code how this can be done and prefer JavaScript, then there is Mozilla's Readability.js, which is used for Firefox's Reader View.

If you prefer Java, you can take a look at Crux, which does also pretty good job.

Or if Kotlin is more your language, then you can take a look at Readability4J, a port of above's Readability.js.