问:
Why is ONE basic arithmetic operation in for loop body executed SLOWER THAN TWO arithmetic operations?
While I experimented with measuring time of execution of arithmetic operations, I came across very strange behavior. A code block containing a for loop with one arithmetic operation in the loop body was always executed slower than an identical code block, but with two arithmetic operations in the for loop body. Here is the code I ended up testing:

```<code>#include <iostream>
#include <chrono>

#define NUM_ITERATIONS 100000000

int main()
{
    // Block 1: one operation in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=31;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    // Block 2: two operations in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=17; y-=37;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    return 0;
}
</code>```

I tested this with different levels of code optimization (-O0,-O1,-O2,-O3), with different online compilers (for example onlinegdb.com), on my work machine, on my hame PC and laptop, on RaspberryPi and on my colleague's computer. I rearranged these two code blocks, repeated them, changed constants, changed operations (+, -, <<, =, etc.), changed integer types. But I always got similar result: the block with one line in loop is SLOWER than block with two lines:

1.05681 seconds. x,y = 3100000000,0

  0.90414 seconds. x,y = 1700000000,-3700000000

I checked the assembly output on https://godbolt.org/ but everything looked like I expected: second block just had one more operation in assembly output.

Three operations always behaved as expected: they are slower than one and faster than four. So why two operations produce such an anomaly?

Edit:

Let me repeat: I have such behaviour on all of my Windows and Unix machines with code not optimized. I looked at assembly I execute (Visual Studio, Windows) and I see the instructions I want to test there. Anyway if the loop is optimized away, there is nothing I ask about in the code which left. I added that optimizations notice in the question to avoid "do not measure not optimized code" answers because optimizations is not what I ask about. The question is actually why my computers execute two operations faster than one, first of all in code where these operations are not optimized away. The difference in time of execution is 5-25% on my tests (quite noticeable).

答:
Processors are so complex these days that we can only guess.

The assembly emitted by your compiler is not what is really executed. The microcode/firmware/whatever of your CPU will interpret it and turn it into instructions for its execution engine, much like JIT languages such as C# or java do.

One thing to consider here is that for each loop, there is not 1 or 2 instructions, but n + 2, as you also increment and compare i to your number of iteration. In the vast majority of case it wouldn't matter, but here it does, as the loop body is so simple.

Let's see the assembly :

Some defines:

```<code>#define NUM_ITERATIONS 1000000000ll
#define X_INC 17
#define Y_INC -31
</code>```

C/C++ :

```<code>for (long i = 0; i < NUM_ITERATIONS; i++) { x+=X_INC; }
</code>```

ASM :

```<code>    mov     QWORD PTR [rbp-32], 0
.L13:
    cmp     QWORD PTR [rbp-32], 999999999
    jg      .L12
    add     QWORD PTR [rbp-24], 17
    add     QWORD PTR [rbp-32], 1
    jmp     .L13
.L12:
</code>```

C/C++ :

```<code>for (long i = 0; i < NUM_ITERATIONS; i++) {x+=X_INC; y+=Y_INC;}
</code>```

ASM:

```<code>    mov     QWORD PTR [rbp-80], 0
.L21:
    cmp     QWORD PTR [rbp-80], 999999999
    jg      .L20
    add     QWORD PTR [rbp-64], 17
    sub     QWORD PTR [rbp-72], 31
    add     QWORD PTR [rbp-80], 1
    jmp     .L21
.L20:
</code>```

So both Assemblies look pretty similar. But then let's think twice : modern CPUs have ALUs which operate on values which are wider than their register size. So there is a chance than in the first case, the operation on x and i are done on the same computing unit. But then you have to read i again, as you put a condition on the result of this operation. And reading means waiting.

So, in the first case, to iterate on x, the CPU might have to be in sync with the iteration on i.

In the second case, maybe x and y are treated on a different unit than the one dealing with i. So in fact, your loop body runs in parallel than the condition driving it. And there goes your CPU computing and computing until someone tells it to stop. It doesn't matter if it goes too far, going back a few loops is still fine compared to the amount of time it just gained.

So, to compare what we want to compare (one operation vs two operations), we should try to get i out of the way.

One solution is to completely get rid of it by using a while loop:
C/C++:

```<code>while (x < (X_INC * NUM_ITERATIONS)) { x+=X_INC; }
</code>```

ASM:

```<code>.L15:
    movabs  rax, 16999999999
    cmp     QWORD PTR [rbp-40], rax
    jg      .L14
    add     QWORD PTR [rbp-40], 17
    jmp     .L15
.L14:
</code>```

An other one is to use the antequated "register" C keyword:
C/C++:

```<code>register long i;
for (i = 0; i < NUM_ITERATIONS; i++) { x+=X_INC; }
</code>```

ASM:

```<code>    mov     ebx, 0
.L17:
    cmp     rbx, 999999999
    jg      .L16
    add     QWORD PTR [rbp-48], 17
    add     rbx, 1
    jmp     .L17
.L16:
</code>```

Here are my results:

x1 for: 10.2985 seconds. x,y = 17000000000,0

x1 while: 8.00049 seconds. x,y = 17000000000,0

x1 register-for: 7.31426 seconds. x,y = 17000000000,0

x2 for: 9.30073 seconds. x,y = 17000000000,-31000000000

x2 while: 8.88801 seconds. x,y = 17000000000,-31000000000

x2 register-for :8.70302 seconds. x,y = 17000000000,-31000000000

Code is here: https://onlinegdb.com/S1lAANEhI

Body:
While I experimented with measuring time of execution of arithmetic operations, I came across very strange behavior. A code block containing a for loop with one arithmetic operation in the loop body was always executed slower than an identical code block, but with two arithmetic operations in the for loop body. Here is the code I ended up testing:

#include <iostream>
#include <chrono>

#define NUM_ITERATIONS 100000000

int main()
{
    // Block 1: one operation in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=31;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    // Block 2: two operations in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=17; y-=37;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    return 0;
}

I tested this with different levels of code optimization (-O0,-O1,-O2,-O3), with different online compilers (for example onlinegdb.com), on my work machine, on my hame PC and laptop, on RaspberryPi and on my colleague's computer. I rearranged these two code blocks, repeated them, changed constants, changed operations (+, -, <<, =, etc.), changed integer types. But I always got similar result: the block with one line in loop is SLOWER than block with two lines:

1.05681 seconds. x,y = 3100000000,0

  0.90414 seconds. x,y = 1700000000,-3700000000

I checked the assembly output on https://godbolt.org/ but everything looked like I expected: second block just had one more operation in assembly output.

Three operations always behaved as expected: they are slower than one and faster than four. So why two operations produce such an anomaly?

Edit:

Let me repeat: I have such behaviour on all of my Windows and Unix machines with code not optimized. I looked at assembly I execute (Visual Studio, Windows) and I see the instructions I want to test there. Anyway if the loop is optimized away, there is nothing I ask about in the code which left. I added that optimizations notice in the question to avoid "do not measure not optimized code" answers because optimizations is not what I ask about. The question is actually why my computers execute two operations faster than one, first of all in code where these operations are not optimized away. The difference in time of execution is 5-25% on my tests (quite noticeable).

Body:
Processors are so complex these days that we can only guess.

The assembly emitted by your compiler is not what is really executed. The microcode/firmware/whatever of your CPU will interpret it and turn it into instructions for its execution engine, much like JIT languages such as C# or java do.

One thing to consider here is that for each loop, there is not 1 or 2 instructions, but n + 2, as you also increment and compare i to your number of iteration. In the vast majority of case it wouldn't matter, but here it does, as the loop body is so simple.

Let's see the assembly :

Some defines:

#define NUM_ITERATIONS 1000000000ll
#define X_INC 17
#define Y_INC -31

C/C++ :

for (long i = 0; i < NUM_ITERATIONS; i++) { x+=X_INC; }

ASM :

    mov     QWORD PTR [rbp-32], 0
.L13:
    cmp     QWORD PTR [rbp-32], 999999999
    jg      .L12
    add     QWORD PTR [rbp-24], 17
    add     QWORD PTR [rbp-32], 1
    jmp     .L13
.L12:

C/C++ :

for (long i = 0; i < NUM_ITERATIONS; i++) {x+=X_INC; y+=Y_INC;}

ASM:

    mov     QWORD PTR [rbp-80], 0
.L21:
    cmp     QWORD PTR [rbp-80], 999999999
    jg      .L20
    add     QWORD PTR [rbp-64], 17
    sub     QWORD PTR [rbp-72], 31
    add     QWORD PTR [rbp-80], 1
    jmp     .L21
.L20:

So both Assemblies look pretty similar. But then let's think twice : modern CPUs have ALUs which operate on values which are wider than their register size. So there is a chance than in the first case, the operation on x and i are done on the same computing unit. But then you have to read i again, as you put a condition on the result of this operation. And reading means waiting.

So, in the first case, to iterate on x, the CPU might have to be in sync with the iteration on i.

In the second case, maybe x and y are treated on a different unit than the one dealing with i. So in fact, your loop body runs in parallel than the condition driving it. And there goes your CPU computing and computing until someone tells it to stop. It doesn't matter if it goes too far, going back a few loops is still fine compared to the amount of time it just gained.

So, to compare what we want to compare (one operation vs two operations), we should try to get i out of the way.

One solution is to completely get rid of it by using a while loop:
C/C++:

while (x < (X_INC * NUM_ITERATIONS)) { x+=X_INC; }

ASM:

.L15:
    movabs  rax, 16999999999
    cmp     QWORD PTR [rbp-40], rax
    jg      .L14
    add     QWORD PTR [rbp-40], 17
    jmp     .L15
.L14:

An other one is to use the antequated "register" C keyword:
C/C++:

register long i;
for (i = 0; i < NUM_ITERATIONS; i++) { x+=X_INC; }

ASM:

    mov     ebx, 0
.L17:
    cmp     rbx, 999999999
    jg      .L16
    add     QWORD PTR [rbp-48], 17
    add     rbx, 1
    jmp     .L17
.L16:

Here are my results:

x1 for: 10.2985 seconds. x,y = 17000000000,0

x1 while: 8.00049 seconds. x,y = 17000000000,0

x1 register-for: 7.31426 seconds. x,y = 17000000000,0

x2 for: 9.30073 seconds. x,y = 17000000000,-31000000000

x2 while: 8.88801 seconds. x,y = 17000000000,-31000000000

x2 register-for :8.70302 seconds. x,y = 17000000000,-31000000000

Code is here: https://onlinegdb.com/S1lAANEhI


来源: stackexchange

问:
python appending dictionaries to lists causes keyError
I am trying to make a list that adds dictionaries to it.
I have done this many times but can't seem to find out why this happens. It should add the dictionary to the list and continue to the code but returns the error KeyError: '"id"'

Here is my code
raid_damage.append("""{"id":{}, "damage":{}, "taken":{}, "streak":{}}""".format(str(user), str(damage_dealt), str(damage_taken), "1"))

I have tried using ' in place of " (whilst removing the triple quotes) and using eval() but still the exact same error

Any Ideas?

答:
Welcome! Here is a solution with no ''' '''

raid_damage.append({"id": user, "damage":damage_dealt, "taken":damage_taken, "streak":streak})

ContentLicense: CC BY-SA 4.0


问:
anti-bias algorithm for rating a resturant
i am working on a restaurant app  that user can rate a restaurant in logic for example the rating equation for 10 people is as followed:
user can rate from 1 to 5
9 had rated 5
1 had rated 1
the equation is ((9*5)+(1*1))/10(sum of people)=46/10=4.6
the answer is 4.6 which is unfair because 1 person low rate make the result to go down to 4.6 in my opinion the result should be 4.9 i searched and found something called Algorithmic bias i didn't understand it well , zomato app company found a solution for this cases like to be fair in low rating and fake ratings

so can anyone help me with a fair equation or algorithm

答: The root cause of the problem is that the rating scale is subjective - and hence affected by cognitive biases of the users. Therefore the best solution would be a different rating approach, such as the Elo system - users would be asked to compare their most recently visited restaurant with the one they had visited before, thus creating a true rank-ordering of restaurants (which could allow stars to be redefined as quintiles). This article discusses the issue and possible solutions in much greater detail: https://www.linkedin.com/pulse/how-build-truly-5-star-user-rating-tobias-baer/</p>


问:
Unable to connect the sql database using azure
I have a SQL Server in Azure which is created using a simple ARM template. When I connect to the SQL Server using my sqladmin credentials I am able to connect to it fine. I am using SQL Server Management Studio for this.

However, When I use any of the following highlighted options, I am seeing an error message.

The Error I am seeing is as shown below, its a pop-up window but I am pasting the text in it for easy reference.

```<code>TITLE: Connect to Server
------------------------------
Cannot connect to abcd-core-sql.database.windows.net.
------------------------------
ADDITIONAL INFORMATION:
</code>```

```<code>**Login failed for user '<token-identified principal>'. (Microsoft SQL Server, Error: 18456)**
</code>```

```<code>For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476
</code>```

I would appreciate if anyone can comment on if I am missing anything in creating a SQL Server using the ARM template.In other words is there anything else that needs to be included in the config to get the azure ad authentication working for a sql db in azure.

```<code>    {
        "type": "Microsoft.Sql/servers",
        "name": "[variables('sql_name')]",
        "apiVersion": "2015-05-01-preview",
        "location": "eastus2",
        "properties": {
            "administratorLogin": "[parameters('admin')]",
            "administratorLoginPassword": "[parameters('passwd')]",
            "version": "[variables('sqlversion')]"
        }
    },
</code>```

答:
You must configure an Azure Active Directory Admin for the instance before you can connect with AAD credentials or create any AAD Database Users.  See Configure and manage Azure AD authentication with Azure SQL

Once you've set the AAD Administrator, connect as the AAD Admin or a member of the AAD Security Group set as the AAD Admin and Create contained users mapped to Azure AD identities, eg

```<code>CREATE USER [bob@contoso.com] FROM EXTERNAL PROVIDER;
</code>```

or

```<code>CREATE USER [ICU Nurses] FROM EXTERNAL PROVIDER;
</code>```

Body:
I have a SQL Server in Azure which is created using a simple ARM template. When I connect to the SQL Server using my sqladmin credentials I am able to connect to it fine. I am using SQL Server Management Studio for this.

However, When I use any of the following highlighted options, I am seeing an error message.

The Error I am seeing is as shown below, its a pop-up window but I am pasting the text in it for easy reference.

TITLE: Connect to Server
------------------------------
Cannot connect to abcd-core-sql.database.windows.net.
------------------------------
ADDITIONAL INFORMATION:

**Login failed for user '<token-identified principal>'. (Microsoft SQL Server, Error: 18456)**

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476

I would appreciate if anyone can comment on if I am missing anything in creating a SQL Server using the ARM template.In other words is there anything else that needs to be included in the config to get the azure ad authentication working for a sql db in azure.

    {
        "type": "Microsoft.Sql/servers",
        "name": "[variables('sql_name')]",
        "apiVersion": "2015-05-01-preview",
        "location": "eastus2",
        "properties": {
            "administratorLogin": "[parameters('admin')]",
            "administratorLoginPassword": "[parameters('passwd')]",
            "version": "[variables('sqlversion')]"
        }
    },

Body:
You must configure an Azure Active Directory Admin for the instance before you can connect with AAD credentials or create any AAD Database Users.  See Configure and manage Azure AD authentication with Azure SQL

Once you've set the AAD Administrator, connect as the AAD Admin or a member of the AAD Security Group set as the AAD Admin and Create contained users mapped to Azure AD identities, eg

CREATE USER [bob@contoso.com] FROM EXTERNAL PROVIDER;

or

CREATE USER [ICU Nurses] FROM EXTERNAL PROVIDER;


问:
Redirecting nginx to another server with apache2
I have been fiddling around with nginx for a while now and wanted to add a nextcloud server to it. I already use Gitlab and YouTrack as servers which run well if i just try to access them like domain.com/gitlab for gitlab and domain.com/youtrack for youtrack. Now I wanted to add nextcloud to it and wanted to access it with domain.com/nextcloud. I can enter that in the browser but I only get the local ip back.

For more information: I use nginx (VM) for redirecting the urls to the according VMs (I use VMs as servers). I used the location /nextcloud/ block for it as for the others but didn't have any success. Everytime I enter domain.com/nextcloud/ it redirects to the website BUT in the address search is entered for example 192.168.178.54/nextclout/

The Nextcloud server uses apache for listening on the port.

With that I am not able to access the Nextcloud website out of my local network. Can anyone help me with it? If some information are needed just tell me and I will try to add them.

Thank you for everything!~

答:
This isn't caused by nginx or Apache, but rather how DNS, which is working how it should. Your domain likely only has an Apex (or A) record for the nginx server ip, and obviously your Apache server is going to have a different ip. You could make another Apex record for the Apache server, but then both servers would have to forward traffic between the two depending on the path, as connecting computer will just choose one of the two records at random (This is known as a round robin dns and is used to build a very simple load balancer).

What you're looking to do should be implemented using subdomains instead ie, gitlab.domain.com, youtrack.domain.com, nextcloud.domain.com. Each subdomain would have its own Apex record, gitlab and youtrack pointing to the nginx ip, and nextcloud to the Apache server.

Paths are intended to be used as a navigation system to the proper page once the correct server has already been found.


问:
Having some problems understanding why its not slicing my string
```<code>describe('China UnionPay', function() {
  let expect = chai.expect;

  for (var prefix = 624; prefix <= 626; prefix++) {
    for (let j = 17; j <= 19; j++) {
      let cardNum = `${prefix}7891123456789`;
      (function(prefix) {
        it(`it has a prefix of ${prefix} and a length of ${j}`, function() {
          //  console.log(`${cardNum.slice(0,j)}`)
          console.log('typeof cardNum', typeof cardNum, '    ', 'length of string =>', j, 'card is not the length of j?', cardNum.slice(0, j))

          expect(detectNetwork(cardNum.slice(0, j))).to.equal('China UnionPay');
        })
      })(prefix)
    }
  }
})
</code>```

What I would like this code to do is to take the cardNum and slice from 0 to the length of what j is currently at. I already added the prefix to the front but not sure why it's not returning a slice portion of cardNum and returning the whole thing?

答:
Value of j in your code ranges between 17 and 19. While length of your string i.e.
var cardNum is 13 characters + 3 characters of var prefix. So basically length of your resulting cardNum variable is 16.
Syntax of slice function is str_name.slice(startPointPosition, endPointPosition);
And in the code above endPointPosition i.e. value of var j is always greater than total length of cardNum.
If you change value of j to less than 16 you can see the change.

Body:
describe('China UnionPay', function() {
  let expect = chai.expect;

  for (var prefix = 624; prefix <= 626; prefix++) {
    for (let j = 17; j <= 19; j++) {
      let cardNum = `${prefix}7891123456789`;
      (function(prefix) {
        it(`it has a prefix of ${prefix} and a length of ${j}`, function() {
          //  console.log(`${cardNum.slice(0,j)}`)
          console.log('typeof cardNum', typeof cardNum, '    ', 'length of string =>', j, 'card is not the length of j?', cardNum.slice(0, j))

          expect(detectNetwork(cardNum.slice(0, j))).to.equal('China UnionPay');
        })
      })(prefix)
    }
  }
})

What I would like this code to do is to take the cardNum and slice from 0 to the length of what j is currently at. I already added the prefix to the front but not sure why it's not returning a slice portion of cardNum and returning the whole thing?


问:
HTTP GET request to get binary content of an XML file
I'm trying to get the binary content of an XML file through HTTP but the server just want to give me kind of interpreted format (wich removes \r for every \r\n).

My HTTP GET request is simple : "GET http://%s%s%s HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n"

It works for extention except .xml. And if I change the .xml in .notxml, it works.

So, I'm looking for a way to the binary content without any change in the file.

Thank you in advance.

答: The problem is on the server.  When you ask it for an XML file it looks in a table that maps extensions to Mime-Types. In the default case, the mime-type for XML is either text/xml or application/xml, both of which are considered text formats and subject to line-ending translation.  To get a binary stream for XML you have to find a way to force the server to treat it as binary instead of text. This means changing the server configuration or using a different extension that is treated as binary.

ContentLicense: CC BY-SA 3.0


问:
How to group by key and retrieve keys from the grouped elements?
I'm trying to group and sum dicts from a DataFrame like this:

```<code>dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pandas.DataFrame(dt).groupby('is_cumulative')
result = df.sum()
</code>```

The result is:

```<code>               discount_value
is_cumulative
False                      10
True                       20
</code>```

But i need to get all "code" key used to sum the final resultt, e.g:

```<code>result['discount_value'][True]  # 20
# how to get the codes "x" and "x1"?
</code>```

答:
Is this what you're looking for:</p>

```<code>df = pd.DataFrame(dt)
df = df.groupby(by=['is_cumulative']).agg({'code': ','.join, 'discount_value': 'sum'})
print(df)
print('codes = {}'.format(df.loc[True]['code']))

               code  discount_value
is_cumulative
False            x2              10
True           x,x1              20

codes = x,x1
</code>```

Body:
I'm trying to group and sum dicts from a DataFrame like this:

dt = [
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x'},
    {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'},
    {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}
]

df = pandas.DataFrame(dt).groupby('is_cumulative')
result = df.sum()

The result is:

               discount_value
is_cumulative
False                      10
True                       20

But i need to get all "code" key used to sum the final resultt, e.g:

result['discount_value'][True]  # 20
# how to get the codes "x" and "x1"?

Body:
Is this what you're looking for:

df = pd.DataFrame(dt)
df = df.groupby(by=['is_cumulative']).agg({'code': ','.join, 'discount_value': 'sum'})
print(df)
print('codes = {}'.format(df.loc[True]['code']))

               code  discount_value
is_cumulative
False            x2              10
True           x,x1              20

codes = x,x1


问:
Special grid or flexbox layout: Issues with inserting text in boxes
I worked for a few hours on this:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  width: 100vw;
  height: 100vh;
}

body {
  background-color: blue;
}

.content {
  padding: 27px;
  grid-column-gap: 27px;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
}

.area {
  overflow: scroll;
  width: 100%;
  background-color: white;
  height: calc(100vh - 27px * 2);
}

.left_area {
  grid-column-start: 1;
  grid-column-end: 6;
}

.right_area {
  grid-column-start: 6;
  grid-column-end: 11;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}

.top_right_area {
  grid-column-start: 2;
  grid-column-end: 6;
  height: calc(200% - 27px);
}

.bottom_right_area {
  bottom: 0;
  grid-column-start: 1;
  grid-column-end: 11;
  height: 200px;
  align-self: end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">

  <div class="area left_area">
  </div>

  <div class="right_area">

    <div class="area top_right_area">
    </div>

    <div class="area bottom_right_area">
    </div>

  </div>

</div></code>```

This is how it should look like:

In the white boxes should be text.

The problem is: If you insert text in the areas, it destroys the layout. The text should be scrollable. I also tried to do it with flexbox, but I didn't find a solution.

Would be so thankful for help!

答:
Your code is a bit complex. You can simplify it like below:

body {
  background-color: blue;
  margin: 0;
}

.content {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-gap: 27px;
  height: 100vh;
  padding: 27px;
  box-sizing:border-box;
}

.content > * {
  overflow: auto;
  background-color: white;
  grid-column:span 5;
}

.left_area {
  grid-row:span 2;
}

.top_right_area {
  grid-column:span 4/-1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="left_area">
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy. Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</div>

  <div class="top_right_area">
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</div>

  <div class="bottom_right_area">
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.
</div>
</div></code>```

Body:
I worked for a few hours on this:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  width: 100vw;
  height: 100vh;
}

body {
  background-color: blue;
}

.content {
  padding: 27px;
  grid-column-gap: 27px;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
}

.area {
  overflow: scroll;
  width: 100%;
  background-color: white;
  height: calc(100vh - 27px * 2);
}

.left_area {
  grid-column-start: 1;
  grid-column-end: 6;
}

.right_area {
  grid-column-start: 6;
  grid-column-end: 11;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
}

.top_right_area {
  grid-column-start: 2;
  grid-column-end: 6;
  height: calc(200% - 27px);
}

.bottom_right_area {
  bottom: 0;
  grid-column-start: 1;
  grid-column-end: 11;
  height: 200px;
  align-self: end;
}

This is how it should look like:

In the white boxes should be text.

The problem is: If you insert text in the areas, it destroys the layout. The text should be scrollable. I also tried to do it with flexbox, but I didn't find a solution.

Would be so thankful for help!

Body:
Your code is a bit complex. You can simplify it like below:

body {
  background-color: blue;
  margin: 0;
}

.content {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-gap: 27px;
  height: 100vh;
  padding: 27px;
  box-sizing:border-box;
}

.content > * {
  overflow: auto;
  background-color: white;
  grid-column:span 5;
}

.left_area {
  grid-row:span 2;
}

.top_right_area {
  grid-column:span 4/-1;
}

<div class="content">
  <div class="left_area">
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy. Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</div>

  <div class="top_right_area">
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</div>

  <div class="bottom_right_area">
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.
  Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.
</div>
</div>


问:
pandas convert delta time column into one sole unit time
I am working with a pandas dataframe where i have a deltatime column with values like:

{'deltatime': 0 days 09:06:30   , 0 days 00:30:34, 2 days 23:07:14  }

How can I convert those times into a single unit, like minutes, or hours but a single one in order to better visualize those times in a graph.
Some idea?

here:
https://pandas.pydata.org/pandas-docs/stable/user_guide/timedeltas.html

it does not clarify how to simple change units

答:
You can use the total_seconds() method of a timedelta to get its duration in seconds:

```<code>seconds = [t.total_seconds() for t in df['deltatime']]
</code>```

And then convert the units if desired:

```<code>#to hours, i.e. 3600 seconds
hours = [t.total_seconds()/3600 for t in df['deltatime']]
</code>```

Body:
You can use the total_seconds() method of a timedelta to get its duration in seconds:

seconds = [t.total_seconds() for t in df['deltatime']]

And then convert the units if desired:

#to hours, i.e. 3600 seconds
hours = [t.total_seconds()/3600 for t in df['deltatime']]


问:
How do I change the language of moment.js?
I am trying to change the language of the date which is being set by moment.js. The default one is English, but I want to set the German language. These is what I tried:

```<code>var now = moment().format("LLL").lang("de");
</code>```

It’s giving NaN.

```<code>var now = moment("de").format("LLL");
</code>```

This isn’t even reacting.

```<code>var now = moment().format("LLL", "de");
</code>```

No change: this is still producing a result in English.

How is this possible?

答:
After struggling, this worked for me for moment v2.26.0:

```<code>import React from "react";
import moment from "moment";
import frLocale from "moment/locale/fr";
import esLocale from "moment/locale/es";

export default function App() {
  moment.locale('fr', [frLocale, esLocale]) // can pass in 'en', 'fr', or 'es'

  let x = moment("2020-01-01 00:00:01");
  return (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}
</code>```

You can pass in en, fr or es. If you wanted another language, you'd have to import the locale and add it to the array.

If you only need to support one language it is a bit simpler:

```<code>import React from "react";
import moment from "moment";
import "moment/locale/fr"; //always use French

export default function App() {
  let x = moment("2020-01-01 00:00:01");
  return (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}
</code>```

-- UPDATE --

In one case, importing all the locale files like above would resort in the last imported locale always being used (i.e. "es" in the above example), even though I was setting it to "fr".  The solution that seems to work is:

```<code>import moment from 'moment';
import 'moment/min/locales';

...

moment.locale('fr');
</code>```

Body:
I am trying to change the language of the date which is being set by moment.js. The default one is English, but I want to set the German language. These is what I tried:

var now = moment().format("LLL").lang("de");

It’s giving NaN.

var now = moment("de").format("LLL");

This isn’t even reacting.

var now = moment().format("LLL", "de");

No change: this is still producing a result in English.

How is this possible?

Body:
After struggling, this worked for me for moment v2.26.0:

import React from "react";
import moment from "moment";
import frLocale from "moment/locale/fr";
import esLocale from "moment/locale/es";

export default function App() {
  moment.locale('fr', [frLocale, esLocale]) // can pass in 'en', 'fr', or 'es'

  let x = moment("2020-01-01 00:00:01");
  return (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}

You can pass in en, fr or es. If you wanted another language, you'd have to import the locale and add it to the array.

If you only need to support one language it is a bit simpler:

import React from "react";
import moment from "moment";
import "moment/locale/fr"; //always use French

export default function App() {
  let x = moment("2020-01-01 00:00:01");
  return (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}

-- UPDATE --

In one case, importing all the locale files like above would resort in the last imported locale always being used (i.e. "es" in the above example), even though I was setting it to "fr".  The solution that seems to work is:

import moment from 'moment';
import 'moment/min/locales';

...

moment.locale('fr');


答:
You can do:

```<code>df['deltatime'] = pd.to_timedelta(df['deltatime']).dt.total_seconds()
</code>```

Output:

```<code>   deltatime
0    32790.0
1     1834.0
2   256034.0
</code>```

You can also perform arithmetic operations on timedelta:

```<code># convert to hours
pd.to_timedelta(df['deltatime']) / pd.to_timedelta('1H')
</code>```

Output:

```<code>0     9.108333
1     0.509444
2    71.120556
Name: deltatime, dtype: float64
</code>```

Title: pandas convert delta time column into one sole unit time

Body:
I am working with a pandas dataframe where i have a deltatime column with values like:

{'deltatime': 0 days 09:06:30   , 0 days 00:30:34, 2 days 23:07:14  }

How can I convert those times into a single unit, like minutes, or hours but a single one in order to better visualize those times in a graph.
Some idea?

here:
https://pandas.pydata.org/pandas-docs/stable/user_guide/timedeltas.html

it does not clarify how to simple change units

Body:
You can do:

df['deltatime'] = pd.to_timedelta(df['deltatime']).dt.total_seconds()

Output:

   deltatime
0    32790.0
1     1834.0
2   256034.0

You can also perform arithmetic operations on timedelta:

# convert to hours
pd.to_timedelta(df['deltatime']) / pd.to_timedelta('1H')

Output:

0     9.108333
1     0.509444
2    71.120556
Name: deltatime, dtype: float64


问:
Can't click button on tkinter
I am new to tkinter and I am having trouble with buttons on the python GUI. I create the buttons and the function behind it but I am unable to click the button. Can someone tell me what I am doing wrong? The UI comes up and I can see the button I just can't click it.</p>

```<code>import tkinter as tk

from tkinter import filedialog, Text

import os

#main
root = tk.Tk()

def addApp():
    filename = filedialog.askopenfilename(initialir= "/", title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))

canvas = tk.Canvas(root, height=700, width=700, bg="#33F9FF")

canvas.pack()

frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx = 0.1, rely = 0.1)

openFile = tk.Button(root, text = "Open File", padx = 10, pady = 5, fg="black",
                     bg="#33F9FF", command="addApp")

openFile.pack()

runApps = tk.Button(root, text = "Run Apps", padx = 10, pady = 5, fg="black",
                    bg="#33F9FF")

runApps.pack()

root.mainloop()
</code>```

答:
There's also one more mistake:

def addApp():
    filename = filedialog.askopenfilename(initialdir= '/', title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))
```

Title: Can't click button on tkinter

Body:
I am new to tkinter and I am having trouble with buttons on the python GUI. I create the buttons and the function behind it but I am unable to click the button. Can someone tell me what I am doing wrong? The UI comes up and I can see the button I just can't click it.

import tkinter as tk

from tkinter import filedialog, Text

import os

#main
root = tk.Tk()

def addApp():
    filename = filedialog.askopenfilename(initialir= "/", title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))

canvas = tk.Canvas(root, height=700, width=700, bg="#33F9FF")

canvas.pack()

frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx = 0.1, rely = 0.1)

openFile = tk.Button(root, text = "Open File", padx = 10, pady = 5, fg="black",
                     bg="#33F9FF", command="addApp")

openFile.pack()

runApps = tk.Button(root, text = "Run Apps", padx = 10, pady = 5, fg="black",
                    bg="#33F9FF")

runApps.pack()

root.mainloop()


问:
What does registering a DLL do?
I know how to register dlls but I've never really been sure why I'm doing it or under what conditions a dll must be registered.  Could somebody explain or point me to some documentation?  </p>

答: Simply see the source code of regsvr32.exe</p>

OwnerDisplayName: stimms

ContentLicense: CC BY-SA 2.5

Title: What does registering a DLL do?

LastEditorDisplayName: gbjbaanb


问:
cant create a trigger - sql server 2008
I'm trying the following :

```<code>CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    IF (NEW.grade > 20)
    BEGIN
    grade = 3
    END

GO
</code>```

and my table looks like :

Enrollment(course#, QYear, SUID,
  units, Grade)

dont know why this error showing :

```<code>Msg 102, Level 15, State 1, Procedure checkgrade, Line 7
Incorrect syntax near 'grade'.
</code>```

答:
There are a few problems.

You need to use the Inserted meta table which covers the newly updated/inserted rows.
You need to perform a proper update as the trigger executes after the update/insert, not in the middle of it.

This might be closer to what's required:

```<code> CREATE TRIGGER checkgrade ON
    [Homework4part3].[dbo].[Enrollment]
    FOR INSERT
    AS
    BEGIN
        SET NOCOUNT ON

        Update e
        set grade = 3
        from
            [Homework4part3].[dbo].[Enrollment] e
            join Inserted i on e.SUID = i.SUID and e.[course#] = i.[course#]
        where i.grade > 20

    END
</code>```

Note: this is untested, and I've guessed as to the primary key columns on your table.

Title: cant create a trigger - sql server 2008

Body:
I'm trying the following :

CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    IF (NEW.grade > 20)
    BEGIN
    grade = 3
    END

GO

and my table looks like :

Enrollment(course#, QYear, SUID,
  units, Grade)

dont know why this error showing :

Msg 102, Level 15, State 1, Procedure checkgrade, Line 7
Incorrect syntax near 'grade'.

Body:
There are a few problems.

You need to use the Inserted meta table which covers the newly updated/inserted rows.
You need to perform a proper update as the trigger executes after the update/insert, not in the middle of it.

This might be closer to what's required:

 CREATE TRIGGER checkgrade ON
    [Homework4part3].[dbo].[Enrollment]
    FOR INSERT
    AS
    BEGIN
        SET NOCOUNT ON

        Update e
        set grade = 3
        from
            [Homework4part3].[dbo].[Enrollment] e
            join Inserted i on e.SUID = i.SUID and e.[course#] = i.[course#]
        where i.grade > 20

    END

Note: this is untested, and I've guessed as to the primary key columns on your table.


问:
JCombobox disable item selection (make combo readonly)
I'd like to create a readonly combobox. The user should not be able to select another item from the popup list. That means that the popup list should not open or should be empty.

I see the following solutions:

Set a ComboBox model with only one item (the current selected item) so when the user clicks on the arrow button, an empty list is presented.

Add a PopupMenuListener and in the popupMenuWillBecomeVisible hide the menu. This is problematic: We have to call combo.hidePopup(); from within a SwingUtilities.invokeLater()

The empty model approach seems a little bit clunky. The second approach shows the popup list for a fraction of a second, short enough to be noticed. This is very ugly.

Is there a third solution?

EDIT: Implemented solution:

I implemented the suggested method from splungebob and here is my code for future reference:

```<code>private void makeComboReadonly() {
  Component editorComponent = box.getEditor().getEditorComponent();
  if (editorComponent instanceof JTextField) {
    ((JTextField) editorComponent).setEditable(false);
  }

  for (Component childComponent : box.getComponents()) {
    if (childComponent instanceof AbstractButton) {
      childComponent.setEnabled(false);
      final MouseListener[] listeners = childComponent.getListeners(MouseListener.class);
      for (MouseListener listener : listeners) {
        childComponent.removeMouseListener(listener);
      }
    }
  }

  final MouseListener[] mouseListeners = box.getListeners(MouseListener.class);
  for (MouseListener listener : mouseListeners) {
    box.removeMouseListener(listener);
  }

  final KeyListener[] keyListeners = box.getListeners(KeyListener.class);
  for (KeyListener keyListener : keyListeners) {
    box.removeKeyListener(keyListener);
  }

  box.setFocusable(false);

  //box.getActionMap().clear(); //no effect
  //box.getInputMap().clear();
}
</code>```

The only problem is the Key-Event Alt-Down which oppens the popup menu even if I remove all the key listeners and clear the action map. I circumvent this problem by making the combo non focusable. Not ideal but good enough (-:

答:
splungebob provides the perfect solution.  Here is his comments turned into code so that you can grab it and go:</p>

```<code>private void setJComboBoxReadOnly(JComboBox jcb)
{
   JTextField jtf = (JTextField)jcb.getEditor().getEditorComponent();
   jtf.setEditable(false);

   MouseListener[] mls = jcb.getMouseListeners();
   for (MouseListener listener : mls)
      jcb.removeMouseListener(listener);

   Component[] comps = jcb.getComponents();
   for (Component c : comps)
   {
      if (c instanceof AbstractButton)
      {
         AbstractButton ab = (AbstractButton)c;
         ab.setEnabled(false);

         MouseListener[] mls2 = ab.getMouseListeners();
         for (MouseListener listener : mls2)
            ab.removeMouseListener(listener);
      }
   }
}
</code>```

Body:
I'd like to create a readonly combobox. The user should not be able to select another item from the popup list. That means that the popup list should not open or should be empty.

I see the following solutions:

Set a ComboBox model with only one item (the current selected item) so when the user clicks on the arrow button, an empty list is presented.

Add a PopupMenuListener and in the popupMenuWillBecomeVisible hide the menu. This is problematic: We have to call combo.hidePopup(); from within a SwingUtilities.invokeLater()

The empty model approach seems a little bit clunky. The second approach shows the popup list for a fraction of a second, short enough to be noticed. This is very ugly.

Is there a third solution?

EDIT: Implemented solution:

I implemented the suggested method from splungebob and here is my code for future reference:

private void makeComboReadonly() {
  Component editorComponent = box.getEditor().getEditorComponent();
  if (editorComponent instanceof JTextField) {
    ((JTextField) editorComponent).setEditable(false);
  }

  for (Component childComponent : box.getComponents()) {
    if (childComponent instanceof AbstractButton) {
      childComponent.setEnabled(false);
      final MouseListener[] listeners = childComponent.getListeners(MouseListener.class);
      for (MouseListener listener : listeners) {
        childComponent.removeMouseListener(listener);
      }
    }
  }

  final MouseListener[] mouseListeners = box.getListeners(MouseListener.class);
  for (MouseListener listener : mouseListeners) {
    box.removeMouseListener(listener);
  }

  final KeyListener[] keyListeners = box.getListeners(KeyListener.class);
  for (KeyListener keyListener : keyListeners) {
    box.removeKeyListener(keyListener);
  }

  box.setFocusable(false);

  //box.getActionMap().clear(); //no effect
  //box.getInputMap().clear();
}

The only problem is the Key-Event Alt-Down which oppens the popup menu even if I remove all the key listeners and clear the action map. I circumvent this problem by making the combo non focusable. Not ideal but good enough (-:

Body:
splungebob provides the perfect solution.  Here is his comments turned into code so that you can grab it and go:

private void setJComboBoxReadOnly(JComboBox jcb)
{
   JTextField jtf = (JTextField)jcb.getEditor().getEditorComponent();
   jtf.setEditable(false);

   MouseListener[] mls = jcb.getMouseListeners();
   for (MouseListener listener : mls)
      jcb.removeMouseListener(listener);

   Component[] comps = jcb.getComponents();
   for (Component c : comps)
   {
      if (c instanceof AbstractButton)
      {
         AbstractButton ab = (AbstractButton)c;
         ab.setEnabled(false);

         MouseListener[] mls2 = ab.getMouseListeners();
         for (MouseListener listener : mls2)
            ab.removeMouseListener(listener);
      }
   }
}


问:
Outlook Com Add-in using Office 365
I have a c# COM Add-in developed for Outlook that was created years ago in Visual Studio 2010.  It was installed on a computer using Office 2010 and works fine.  We are now migrating to Office 365.  I installed the Add-in and in Outlook's "File".."Options".."Add-ins" it is listed under the "Inactive Application Add-ins".  When I click on the Go button under the "Manage" - "COM Add-ins", the add-in is listed but not checked.  When I check it, it shows "Load Behavior:  Not loaded.  A runtime error occurred during the loading of the COM Add-in."  The old Add-in was compiled as 32 bit and I tried to install it as that, then recompiled it as a 64 bit app and installed that but it gives me the same message.  Should COM Add-ins work in Office/Outlook 365?  Is there something that needs to be updated?</p>

答:
Should COM Add-ins work in Office/Outlook 365?

Yes, they should work correctly. There were no breaking changes.

Microsoft Office applications can disable VSTO Add-ins that behave unexpectedly. If an application does not load your VSTO Add-in, the application might have hard disabled or soft disabled your VSTO Add-in.

Hard disabling can occur when a VSTO Add-in causes the application to close unexpectedly. It might also occur on your development computer if you stop the debugger while the Startup event handler in your VSTO Add-in is executing.

Soft disabling can occur when a VSTO Add-in produces an error that does not cause the application to unexpectedly close. For example, an application might soft disable a VSTO Add-in if it throws an unhandled exception while the Startup event handler is executing.

When you re-enable a soft-disabled VSTO Add-in, the application immediately attempts to load the VSTO Add-in. If the problem that initially caused the application to soft disable the VSTO Add-in has not been fixed, the application will soft disable the VSTO Add-in again.

Is there something that needs to be updated?

You need to check add-in prerequisites, make sure that all of them were installed correctly. Then try to log all startup operations and see where an exception is thrown.

If you use VSTO, make sure that you did all the steps described in the Deploy an Office solution by using Windows Installer article.

Title: Outlook Com Add-in using Office 365


问:
Automated deployment to azure using wix installer
I have a wix installer project which installs my Web API (c#) project into local IIS. Are there any out of the box support facility for installing a web API as Azure Web app on Azure using WIX installer? If the answer is no, are there any existing powershell scripts for automating the task partially or entirely?</p>

答:
One option is to run it in a Windows Container Web App in Azure App Service.

Here is the info on how to Run a custom Windows container in Azure App Service:
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-get-started-windows-container

You will need to run your wix installer as part of the dockerfile, just make sure you wait for the installer to complete


问:
WinRT app calling win32 c++ dll sending parameters
Hey all this is the first time working with C++ so be kind :)

I have made a WinRT app that, since of some type of "sandbox" it does for those apps I am unable to access anything outside of that (like what I want to access - my desktop app.

So reading here and there I found out that if you make a C++ Dll and call it from the WinRT app then that would allow you to make calls outside of the "sandbox". But there's a little problem there.

I am currently getting an error of:

Error CS1660  Cannot convert lambda expression to type 'string' because it is not a delegate type.

Using this code here:

```<code>void Header_Click(object sender, RoutedEventArgs e)
{
    DisplayFromDLL("tester", s =>
    {
        // response is returned in s - do what you want with it
    });
}
</code>```

The DisplayFromDLL is where its tossing that error from. More so the "s".

So the C# code I have to call the dll with looks like this:

```<code>public sealed partial class GroupedItemsPage : Page
{
    [DllImport("Win32Project1.dll", EntryPoint = "DisplayFromDLL", CallingConvention = CallingConvention.StdCall)]
    public static extern void DisplayFromDLL(string name, String response);

    void Header_Click(object sender, RoutedEventArgs e)
    {
        DisplayFromDLL("tester", s =>
        {
            // response is returned in s
        });
    }
</code>```

And the C++ dll code:

```<code>extern "C"
{
    __declspec(dllexport) void DisplayFromDLL(const char name)
    {
        MessageBox("name is: " + name, "Msg title", MB_OK | MB_ICONQUESTION);
    }
}
</code>```

So some help would be great to see what side is causing the error and what the situation fixing it might be.

答:
Your definition (in the DLL), the declaration (on the c# side) and the actual calls do not match at all.

Your function as defined takes a single char, your declaration says it takes two strings, but your call provides a string and a function.

Make it so that all of these match.

Body:
Hey all this is the first time working with C++ so be kind :)

I have made a WinRT app that, since of some type of "sandbox" it does for those apps I am unable to access anything outside of that (like what I want to access - my desktop app.

So reading here and there I found out that if you make a C++ Dll and call it from the WinRT app then that would allow you to make calls outside of the "sandbox". But there's a little problem there.

I am currently getting an error of:

Error CS1660  Cannot convert lambda expression to type 'string' because it is not a delegate type.

Using this code here:

void Header_Click(object sender, RoutedEventArgs e)
{
    DisplayFromDLL("tester", s =>
    {
        // response is returned in s - do what you want with it
    });
}

The DisplayFromDLL is where its tossing that error from. More so the "s".

So the C# code I have to call the dll with looks like this:

public sealed partial class GroupedItemsPage : Page
{
    [DllImport("Win32Project1.dll", EntryPoint = "DisplayFromDLL", CallingConvention = CallingConvention.StdCall)]
    public static extern void DisplayFromDLL(string name, String response);

    void Header_Click(object sender, RoutedEventArgs e)
    {
        DisplayFromDLL("tester", s =>
        {
            // response is returned in s
        });
    }

And the C++ dll code:

extern "C"
{
    __declspec(dllexport) void DisplayFromDLL(const char name)
    {
        MessageBox("name is: " + name, "Msg title", MB_OK | MB_ICONQUESTION);
    }
}

So some help would be great to see what side is causing the error and what the situation fixing it might be.


问:
How to convert from timestamp to date in Qt?
I have a Unix timestamp and I need to convert it to human readable date + time. How can it be done in Qt?</p>

答:
As mentioned, instead of using the obsolete _t members here is a working example (Qt 5).

```<code>qint64 llTS=1591132400;
QString szFull=QDateTime::fromSecsSinceEpoch(llTS).toString("dddd d MMMM yyyy hh:mm:ss");
</code>```

szFull: Tuesday 2 June 2020 23:13:20

Source: QDateTime (Qt 5)

Date formatting: QDate

Time formatting: QTime

Body:
As mentioned, instead of using the obsolete _t members here is a working example (Qt 5).

qint64 llTS=1591132400;
QString szFull=QDateTime::fromSecsSinceEpoch(llTS).toString("dddd d MMMM yyyy hh:mm:ss");

szFull: Tuesday 2 June 2020 23:13:20

Source: QDateTime (Qt 5)

Date formatting: QDate

Time formatting: QTime


问:
How to copy a file while it is being used by another process
Is it possible to copy a file which is being using by another process at the same time?

I ask because when i am trying to copy the file using the following code an exception is raised:

```<code> System.IO.File.Copy(s, destFile, true);
</code>```

The exception raised is:

The process cannot access the file 'D:\temp\1000000045.zip' because it is being used by another process.

I do not want to create a new file, I just want to copy it or delete it. Is this possible?

答:
Try:</p>

```<code>var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destinationFilePath, true);
</code>```

Body:
Is it possible to copy a file which is being using by another process at the same time?

I ask because when i am trying to copy the file using the following code an exception is raised:

 System.IO.File.Copy(s, destFile, true);

The exception raised is:

The process cannot access the file 'D:\temp\1000000045.zip' because it is being used by another process.

I do not want to create a new file, I just want to copy it or delete it. Is this possible?

Body:
Try:

var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destinationFilePath, true);


问:
Reason for "referenced before assignment" warning for variables in trivial sequence of conditions
Is there any good reason for the Local variable 's' might be referenced before assignment warning in this trivial piece of code:

def nonsense():
    condition = True
    if condition:
        s = "I am set."

    if condition:
        print(s)
```

Screenshot from PyCharm 2019.2.6:

Remarks:

I have experienced this issue in more complex (and useful) situations, but I want to point out that it even occurs in this trivial case of two identical conditions in a row.

My naive assumption is that condition can not change between the two if statements under any circumstances. If this is true, I consider the warning a limitation of static code analysis.

optional sub-question: What are your best practices for workarounds? Bloating the code by setting s in all cases, though not required?

答:
Is there any good reason for the Local variable 's' might be referenced before assignment warning in this trivial piece of code:

Not really. It's just that the IDE thinks that since the assignment/initialisation s='I am set' takes place inside a condition if condition: (not caring what the condition is), it might be possible that the assignment did not take place. And thus the warning.

IDE's are not that intelligent after all!!

Body:
Is there any good reason for the Local variable 's' might be referenced before assignment warning in this trivial piece of code:

def nonsense():
    condition = True
    if condition:
        s = "I am set."

    if condition:
        print(s)

Screenshot from PyCharm 2019.2.6:

Remarks:

I have experienced this issue in more complex (and useful) situations, but I want to point out that it even occurs in this trivial case of two identical conditions in a row.

My naive assumption is that condition can not change between the two if statements under any circumstances. If this is true, I consider the warning a limitation of static code analysis.

optional sub-question: What are your best practices for workarounds? Bloating the code by setting s in all cases, though not required?


问:
Which Object Oriented design is a better pick when one subclass calls another?
In my scenario, we offer multiple plans to customers. (planA, planB, planC etc.) planA is lower than planB and planB is lower than planC. A customer can move from lower plan to higher plan but not vice-versa. If a customer is on planA and wants to 'activate' planB, then planA must be cancelled. Essentially, a plan can be 'activated' and 'deactivated'. I had 2 designs in mind.

```<code>interface Plan {
   activate();
   deactivate();
}
</code>```

This interface will be inherited by each plans' (planA, planB, planC, etc). The activate method would be inherited and look something like this:

```<code>activate() {
   Plan planToCancel = getLowerGradePlanToCancel()
   planToCancel.cancel();
   // perform business logic to activate plan.
}
</code>```

Option B is something similar to strategy pattern: I have 2 interfaces:

```<code>interface Activate {
  activate();
}

interface Deactivate {
  deactivate()
}
</code>```

Each of the plans will inherit those interfaces. Then my business logic would look something like this:

```<code>activatePlan(planName, planToDeactivate) {
  Activate activate = Factory.getActivateInstanceForPlan(planName);
  DeActivate dectivate = Factory.getActivateInstanceForPlan(planToDeactivate);
  deactivate.deactivate();
  activate.activate();
}
</code>```

Of the two designs which one is more appropriate (Object Oriented) and why ? The only thing in code that is likely to change is more plans will be added in future.

答:
I have a different approach in mind where you have a class that manages all the plans, while plan interface is encapsulated and only reveals the necessary of its API.
I think this approach will have minimal code modification for each added Plan, moreover, it can prevent user from making mistakes (e.g. downgrading a plan).

The essential interfaces:

```<code>interface Plan {
    public Plan next();
    public boolean isActivated();
    // for debug purposes
    public String planDescription();
}

interface PlansManager {
        public Plan nextPlan(Plan current);
}
</code>```

The basic idea is to have some SemiConcretePlan class which implements the static (mutual) behaviour in all plans, the public API is next & isActivated while activate and cancel methods private (you don't want the user to cancel a plan without switching to the next or to activated a cancelled one be keeping a previous Plan pointer on it) and only the PlansManager or the Plan itself will handle the activation and cancellation, PlansManager activates the first plan and returns it and next method uses PlansManager to get the next and only the SemiConcertePlan activate the current and cancels the previous Plan.

Here the SemiConcertePlan:

```<code>abstract class SemiConcretePlan implements Plan {
    private PlansManager m_plansManager;
    private boolean m_isActivated;
    private int m_id;
    private static int s_idGenerator = 0, s_firstActivatedId = 1;

    public SemiConcretePlan(PlansManager plansManager){
        m_plansManager = plansManager;
        m_id = generateId();
        m_isActivated = (m_id == s_firstActivatedId);
    }

    private int generateId() {
        return ++s_idGenerator;
    }

    private void activatePlan() {
        this.m_isActivated = true;
    }

    private void cancelPlan() {
        this.m_isActivated = false;
    }

    public boolean isActivated() {
        return this.m_isActivated;
    }

    public Plan next() {
        this.cancelPlan();
        SemiConcretePlan nextPlan = (SemiConcretePlan) m_plansManager.nextPlan(this);
        nextPlan.activatePlan();

        return nextPlan;
    }

    public boolean equals(Object other) {
        if (this == other)
                return true;
        if (other == null || !(other instanceof SemiConcretePlan) || this.hashCode() != other.hashCode())
                return false;
        SemiConcretePlan otherPlan = ((SemiConcretePlan) other);
        if (m_id != ((SemiConcretePlan) otherPlan).m_id)
                return false;

        return true;
    }

    public abstract int hashCode();
    public abstract String planDescription();
}
</code>```

planDescription method is an example of dynamic method, hashCode is needed for class PlansManager to hash plans in map which map current plan to higher (next) plan.

Here is the AscedingPlansManager class:

```<code>class AscedingPlansManager implements PlansManager{
    private List<Plan> m_plansList;
    private Map<Plan, Plan> m_planToHigherPlanMapping;

    public AscedingPlansManager() {
        m_plansList = new LinkedList();
        m_planToHigherPlanMapping = new HashMap();
        Plan[] plans = {
                new PlanA(this),
                new PlanB(this),
                new PlanC(this),
                new PlanD(this)
        };

        for(int i = 0; i < plans.length - 1; ++i) {
            m_plansList.add(plans[i]);
            m_planToHigherPlanMapping.put(plans[i], plans[i+1]);
        }

        m_plansList.add(plans[plans.length - 1]);
        m_planToHigherPlanMapping.put(plans[plans.length - 1], plans[plans.length - 1]);
    }

    public Plan nextPlan(Plan current) {
        return m_planToHigherPlanMapping.getOrDefault(current, null);
    }

    private void activatePlan(Plan plan) {
        try {
            Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("activatePlan");
            privateActivateMethod.setAccessible(true);
            privateActivateMethod.invoke(plan);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelAll() {
        for(Plan plan: m_plansList)
            try {
                Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("cancelPlan");
                privateActivateMethod.setAccessible(true);
                privateActivateMethod.invoke(plan);
            } catch(Exception e) {
                e.printStackTrace();
            }
    }

    public Plan firstPlan() {
        Plan first = m_plansList.get(0);
        this.activatePlan(first);

        return first;
    }

    public boolean[] plansToActivationState() {
        boolean[] ret = new boolean[m_plansList.size()];
        int index = 0;
        for(Plan plan: m_plansList)
            ret[index++] = plan.isActivated();

        return ret;
    }
}
</code>```

I know that this is huge code, but I think it will make add plans easy, you will only need to change the hashCode method, the sequence of the plans can be changed in the constructor of AscedingPlansManager or creating a different manger class from scratch.

Here is the full code, you can see how little changes I needed to do for class PlanD:

import java.util.;
import java.lang.reflect.;

```<code>interface Plan {
    public Plan next();
    public boolean isActivated();
    // for debug purposes
    public String planDescription();
}

interface PlansManager {
        public Plan nextPlan(Plan current);
}

abstract class SemiConcretePlan implements Plan {
    private PlansManager m_plansManager;
    private boolean m_isActivated;
    private int m_id;
    private static int s_idGenerator = 0, s_firstActivatedId = 1;

    public SemiConcretePlan(PlansManager plansManager){
        m_plansManager = plansManager;
        m_id = generateId();
        m_isActivated = (m_id == s_firstActivatedId);
    }

    private int generateId() {
        return ++s_idGenerator;
    }

    private void activatePlan() {
        this.m_isActivated = true;
    }

    private void cancelPlan() {
        this.m_isActivated = false;
    }

    public boolean isActivated() {
        return this.m_isActivated;
    }

    public Plan next() {
        this.cancelPlan();
        SemiConcretePlan nextPlan = (SemiConcretePlan) m_plansManager.nextPlan(this);
        nextPlan.activatePlan();

        return nextPlan;
    }

    public boolean equals(Object other) {
        if (this == other)
                return true;
        if (other == null || !(other instanceof SemiConcretePlan) || this.hashCode() != other.hashCode())
                return false;
        SemiConcretePlan otherPlan = ((SemiConcretePlan) other);
        if (m_id != ((SemiConcretePlan) otherPlan).m_id)
                return false;

        return true;
    }

    public abstract int hashCode();
    public abstract String planDescription();
}

class AscedingPlansManager implements PlansManager{
    private List<Plan> m_plansList;
    private Map<Plan, Plan> m_planToHigherPlanMapping;

    public AscedingPlansManager() {
        m_plansList = new LinkedList();
        m_planToHigherPlanMapping = new HashMap();
        Plan[] plans = {
                new PlanA(this),
                new PlanB(this),
                new PlanC(this),
                new PlanD(this)
        };

        for(int i = 0; i < plans.length - 1; ++i) {
            m_plansList.add(plans[i]);
            m_planToHigherPlanMapping.put(plans[i], plans[i+1]);
        }

        m_plansList.add(plans[plans.length - 1]);
        m_planToHigherPlanMapping.put(plans[plans.length - 1], plans[plans.length - 1]);
    }

    public Plan nextPlan(Plan current) {
        return m_planToHigherPlanMapping.getOrDefault(current, null);
    }

    private void activatePlan(Plan plan) {
        try {
            Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("activatePlan");
            privateActivateMethod.setAccessible(true);
            privateActivateMethod.invoke(plan);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelAll() {
        for(Plan plan: m_plansList)
            try {
                Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("cancelPlan");
                privateActivateMethod.setAccessible(true);
                privateActivateMethod.invoke(plan);
            } catch(Exception e) {
                e.printStackTrace();
            }
    }

    public Plan firstPlan() {
        Plan first = m_plansList.get(0);
        this.activatePlan(first);

        return first;
    }

    public boolean[] plansToActivationState() {
        boolean[] ret = new boolean[m_plansList.size()];
        int index = 0;
        for(Plan plan: m_plansList)
            ret[index++] = plan.isActivated();

        return ret;
    }
}

class PlanA extends SemiConcretePlan {
    public PlanA(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 1;
    }

    public String planDescription() {
        return "This is PlanA";
    }
}

class PlanB extends SemiConcretePlan {
    public PlanB(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 2;
    }

    public String planDescription() {
        return "This is PlanB";
    }
}

class PlanC extends SemiConcretePlan {
    public PlanC(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 3;
    }

    public String planDescription() {
        return "This is PlanC";
    }
}

class PlanD extends SemiConcretePlan {
    public PlanD(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 4;
    }

    public String planDescription() {
        return "This is PlanD";
    }
}

public class Main{
         public static void main(String []args){
                AscedingPlansManager ascedingPlansManager = new AscedingPlansManager();
                Plan currentPlan = ascedingPlansManager.firstPlan();

                int i = 0, maxIterations = 5;
                while((++i) <= maxIterations) {
                    System.out.println(currentPlan.planDescription());
                    System.out.println(Arrays.toString(ascedingPlansManager.plansToActivationState()));
                    currentPlan = currentPlan.next();
                }

                ascedingPlansManager.cancelAll();
                System.out.println("After canceling all plans");
                System.out.println(Arrays.toString(ascedingPlansManager.plansToActivationState()));
         }
}
</code>```

I still not sure of my implementation, I usually access private method in c++ with friend modifier, if you want to discuss anything feel free to do so.

Body:
In my scenario, we offer multiple plans to customers. (planA, planB, planC etc.) planA is lower than planB and planB is lower than planC. A customer can move from lower plan to higher plan but not vice-versa. If a customer is on planA and wants to 'activate' planB, then planA must be cancelled. Essentially, a plan can be 'activated' and 'deactivated'. I had 2 designs in mind.

interface Plan {
   activate();
   deactivate();
}

This interface will be inherited by each plans' (planA, planB, planC, etc). The activate method would be inherited and look something like this:

activate() {
   Plan planToCancel = getLowerGradePlanToCancel()
   planToCancel.cancel();
   // perform business logic to activate plan.
}

Option B is something similar to strategy pattern: I have 2 interfaces:

interface Activate {
  activate();
}

interface Deactivate {
  deactivate()
}

Each of the plans will inherit those interfaces. Then my business logic would look something like this:

activatePlan(planName, planToDeactivate) {
  Activate activate = Factory.getActivateInstanceForPlan(planName);
  DeActivate dectivate = Factory.getActivateInstanceForPlan(planToDeactivate);
  deactivate.deactivate();
  activate.activate();
}

Of the two designs which one is more appropriate (Object Oriented) and why ? The only thing in code that is likely to change is more plans will be added in future.

Body:
I have a different approach in mind where you have a class that manages all the plans, while plan interface is encapsulated and only reveals the necessary of its API.
I think this approach will have minimal code modification for each added Plan, moreover, it can prevent user from making mistakes (e.g. downgrading a plan).

The essential interfaces:

interface Plan {
    public Plan next();
    public boolean isActivated();
    // for debug purposes
    public String planDescription();
}

interface PlansManager {
        public Plan nextPlan(Plan current);
}

The basic idea is to have some SemiConcretePlan class which implements the static (mutual) behaviour in all plans, the public API is next & isActivated while activate and cancel methods private (you don't want the user to cancel a plan without switching to the next or to activated a cancelled one be keeping a previous Plan pointer on it) and only the PlansManager or the Plan itself will handle the activation and cancellation, PlansManager activates the first plan and returns it and next method uses PlansManager to get the next and only the SemiConcertePlan activate the current and cancels the previous Plan.

Here the SemiConcertePlan:

abstract class SemiConcretePlan implements Plan {
    private PlansManager m_plansManager;
    private boolean m_isActivated;
    private int m_id;
    private static int s_idGenerator = 0, s_firstActivatedId = 1;

    public SemiConcretePlan(PlansManager plansManager){
        m_plansManager = plansManager;
        m_id = generateId();
        m_isActivated = (m_id == s_firstActivatedId);
    }

    private int generateId() {
        return ++s_idGenerator;
    }

    private void activatePlan() {
        this.m_isActivated = true;
    }

    private void cancelPlan() {
        this.m_isActivated = false;
    }

    public boolean isActivated() {
        return this.m_isActivated;
    }

    public Plan next() {
        this.cancelPlan();
        SemiConcretePlan nextPlan = (SemiConcretePlan) m_plansManager.nextPlan(this);
        nextPlan.activatePlan();

        return nextPlan;
    }

    public boolean equals(Object other) {
        if (this == other)
                return true;
        if (other == null || !(other instanceof SemiConcretePlan) || this.hashCode() != other.hashCode())
                return false;
        SemiConcretePlan otherPlan = ((SemiConcretePlan) other);
        if (m_id != ((SemiConcretePlan) otherPlan).m_id)
                return false;

        return true;
    }

    public abstract int hashCode();
    public abstract String planDescription();
}

planDescription method is an example of dynamic method, hashCode is needed for class PlansManager to hash plans in map which map current plan to higher (next) plan.

Here is the AscedingPlansManager class:

class AscedingPlansManager implements PlansManager{
    private List<Plan> m_plansList;
    private Map<Plan, Plan> m_planToHigherPlanMapping;

    public AscedingPlansManager() {
        m_plansList = new LinkedList();
        m_planToHigherPlanMapping = new HashMap();
        Plan[] plans = {
                new PlanA(this),
                new PlanB(this),
                new PlanC(this),
                new PlanD(this)
        };

        for(int i = 0; i < plans.length - 1; ++i) {
            m_plansList.add(plans[i]);
            m_planToHigherPlanMapping.put(plans[i], plans[i+1]);
        }

        m_plansList.add(plans[plans.length - 1]);
        m_planToHigherPlanMapping.put(plans[plans.length - 1], plans[plans.length - 1]);
    }

    public Plan nextPlan(Plan current) {
        return m_planToHigherPlanMapping.getOrDefault(current, null);
    }

    private void activatePlan(Plan plan) {
        try {
            Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("activatePlan");
            privateActivateMethod.setAccessible(true);
            privateActivateMethod.invoke(plan);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelAll() {
        for(Plan plan: m_plansList)
            try {
                Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("cancelPlan");
                privateActivateMethod.setAccessible(true);
                privateActivateMethod.invoke(plan);
            } catch(Exception e) {
                e.printStackTrace();
            }
    }

    public Plan firstPlan() {
        Plan first = m_plansList.get(0);
        this.activatePlan(first);

        return first;
    }

    public boolean[] plansToActivationState() {
        boolean[] ret = new boolean[m_plansList.size()];
        int index = 0;
        for(Plan plan: m_plansList)
            ret[index++] = plan.isActivated();

        return ret;
    }
}

I know that this is huge code, but I think it will make add plans easy, you will only need to change the hashCode method, the sequence of the plans can be changed in the constructor of AscedingPlansManager or creating a different manger class from scratch.

Here is the full code, you can see how little changes I needed to do for class PlanD:

import java.util.;
import java.lang.reflect.;

interface Plan {
    public Plan next();
    public boolean isActivated();
    // for debug purposes
    public String planDescription();
}

interface PlansManager {
        public Plan nextPlan(Plan current);
}

abstract class SemiConcretePlan implements Plan {
    private PlansManager m_plansManager;
    private boolean m_isActivated;
    private int m_id;
    private static int s_idGenerator = 0, s_firstActivatedId = 1;

    public SemiConcretePlan(PlansManager plansManager){
        m_plansManager = plansManager;
        m_id = generateId();
        m_isActivated = (m_id == s_firstActivatedId);
    }

    private int generateId() {
        return ++s_idGenerator;
    }

    private void activatePlan() {
        this.m_isActivated = true;
    }

    private void cancelPlan() {
        this.m_isActivated = false;
    }

    public boolean isActivated() {
        return this.m_isActivated;
    }

    public Plan next() {
        this.cancelPlan();
        SemiConcretePlan nextPlan = (SemiConcretePlan) m_plansManager.nextPlan(this);
        nextPlan.activatePlan();

        return nextPlan;
    }

    public boolean equals(Object other) {
        if (this == other)
                return true;
        if (other == null || !(other instanceof SemiConcretePlan) || this.hashCode() != other.hashCode())
                return false;
        SemiConcretePlan otherPlan = ((SemiConcretePlan) other);
        if (m_id != ((SemiConcretePlan) otherPlan).m_id)
                return false;

        return true;
    }

    public abstract int hashCode();
    public abstract String planDescription();
}

class AscedingPlansManager implements PlansManager{
    private List<Plan> m_plansList;
    private Map<Plan, Plan> m_planToHigherPlanMapping;

    public AscedingPlansManager() {
        m_plansList = new LinkedList();
        m_planToHigherPlanMapping = new HashMap();
        Plan[] plans = {
                new PlanA(this),
                new PlanB(this),
                new PlanC(this),
                new PlanD(this)
        };

        for(int i = 0; i < plans.length - 1; ++i) {
            m_plansList.add(plans[i]);
            m_planToHigherPlanMapping.put(plans[i], plans[i+1]);
        }

        m_plansList.add(plans[plans.length - 1]);
        m_planToHigherPlanMapping.put(plans[plans.length - 1], plans[plans.length - 1]);
    }

    public Plan nextPlan(Plan current) {
        return m_planToHigherPlanMapping.getOrDefault(current, null);
    }

    private void activatePlan(Plan plan) {
        try {
            Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("activatePlan");
            privateActivateMethod.setAccessible(true);
            privateActivateMethod.invoke(plan);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelAll() {
        for(Plan plan: m_plansList)
            try {
                Method privateActivateMethod = SemiConcretePlan.class.getDeclaredMethod("cancelPlan");
                privateActivateMethod.setAccessible(true);
                privateActivateMethod.invoke(plan);
            } catch(Exception e) {
                e.printStackTrace();
            }
    }

    public Plan firstPlan() {
        Plan first = m_plansList.get(0);
        this.activatePlan(first);

        return first;
    }

    public boolean[] plansToActivationState() {
        boolean[] ret = new boolean[m_plansList.size()];
        int index = 0;
        for(Plan plan: m_plansList)
            ret[index++] = plan.isActivated();

        return ret;
    }
}

class PlanA extends SemiConcretePlan {
    public PlanA(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 1;
    }

    public String planDescription() {
        return "This is PlanA";
    }
}

class PlanB extends SemiConcretePlan {
    public PlanB(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 2;
    }

    public String planDescription() {
        return "This is PlanB";
    }
}

class PlanC extends SemiConcretePlan {
    public PlanC(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 3;
    }

    public String planDescription() {
        return "This is PlanC";
    }
}

class PlanD extends SemiConcretePlan {
    public PlanD(PlansManager plansManager) {
        super(plansManager);
    }

    public int hashCode() {
        return 4;
    }

    public String planDescription() {
        return "This is PlanD";
    }
}

public class Main{
         public static void main(String []args){
                AscedingPlansManager ascedingPlansManager = new AscedingPlansManager();
                Plan currentPlan = ascedingPlansManager.firstPlan();

                int i = 0, maxIterations = 5;
                while((++i) <= maxIterations) {
                    System.out.println(currentPlan.planDescription());
                    System.out.println(Arrays.toString(ascedingPlansManager.plansToActivationState()));
                    currentPlan = currentPlan.next();
                }

                ascedingPlansManager.cancelAll();
                System.out.println("After canceling all plans");
                System.out.println(Arrays.toString(ascedingPlansManager.plansToActivationState()));
         }
}

I still not sure of my implementation, I usually access private method in c++ with friend modifier, if you want to discuss anything feel free to do so.


问:
SignalR in ASP.NET empty website not working
I am very new to the term SignalR . I was try to configure the signalR into my empty website and Added following code.

In App_Code

```<code>  using Microsoft.Owin;
  using Owin;

  [assembly: OwinStartup(typeof(Super.App_Code.Startup))]

  namespace Super.App_Code
  {
     public class Startup
     {
         public static void Configuration(IAppBuilder app)
         {
             app.MapSignalR();

         }
     }
  }
</code>```

and the hub class Inside App_Code

```<code>namespace Super.App_Code
{
[HubName("toastHub")]
 public class ToastHub : Hub
{
    public void BroadcastToast(string type ,string msg)
    {
        Clients.All.sendToast(type , msg);
    }
}
}
</code>```

and in Default.aspx

```<code><head runat="server">
<title></title>
<link rel="stylesheet" href="content/toastr.min.css" />

<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-2.4.1.js" type="text/javascript"></script>
<script src="Scripts/toastr.min.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("#SuccessLink").click(function () {
            console.log("Success Click");
            $.connection.toastHub.client.broadcastToast('success', 'you have done');
        });

        $("#ErrorLink").click(function () {
            console.log("Error Click");
            $.connection.toastHub.client.broadcastToast("error", "you have not done");
        });

        $.connection.hub.start().done(function () {
            console.log('SignalR connected');
        })
        .fail(function (data) {
            console.log('SignalR failed to connect: ' + data);
        });

        $.connection.toastHub.client.sendToast = function (type, msg) {
            console.log("sendToast Called");
            toastr[type](msg);
        };
    });
 </script>
 </head>
 <body>
 <form id="form1" runat="server">
    <div>
        <a id="SuccessLink" style="color: lightgreen">Success Toast</a><br />
        <a id="ErrorLink" style="color: red">Error Toast</a>
    </div>

  </form>
  </body>
  </html>
</code>```

but when i run my website the javascript console says this when click on one of the  tag

```<code>  SignalR connected
  Default.aspx:20 Success Click
  Default.aspx:21 Uncaught TypeError: $.connection.toastHub.client.broadcastToast is not a function
      at HTMLAnchorElement.<anonymous> (Default.aspx:21)
      at HTMLAnchorElement.handle (jquery-1.6.4.js:3001)
      at HTMLAnchorElement.eventHandle (jquery-1.6.4.js:2635)
</code>```

Am i doing anything wrong please help me any help would be greatful .i am totally new to SignalR .

signalr/hub

```<code>if (typeof ($.signalR) !== "function") {
    throw new Error("SignalR: SignalR is not loaded. Please ensure         jquery.signalR-x.js is referenced before ~/signalr/js.");
}

var signalR = $.signalR;

function makeProxyCallback(hub, callback) {
    return function () {
        // Call the client hub method
        callback.apply(hub, $.makeArray(arguments));
    };
}

function registerHubProxies(instance, shouldSubscribe) {
    var key, hub, memberKey, memberValue, subscriptionMethod;

    for (key in instance) {
        if (instance.hasOwnProperty(key)) {
            hub = instance[key];

            if (!(hub.hubName)) {
                // Not a client hub
                continue;
            }

            if (shouldSubscribe) {
                // We want to subscribe to the hub events
                subscriptionMethod = hub.on;
            } else {
                // We want to unsubscribe from the hub events
                subscriptionMethod = hub.off;
            }

            // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
            for (memberKey in hub.client) {
                if (hub.client.hasOwnProperty(memberKey)) {
                    memberValue = hub.client[memberKey];

                    if (!$.isFunction(memberValue)) {
                        // Not a client hub function
                        continue;
                    }

                    // Use the actual user-provided callback as the "identity" value for the registration.
                    subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue), memberValue);
                }
            }
        }
    }
}

$.hubConnection.prototype.createHubProxies = function () {
    var proxies = {};
    this.starting(function () {
        // Register the hub proxies as subscribed
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, true);

        this._registerSubscribedHubs();
    }).disconnected(function () {
        // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, false);
    });

    proxies['toastHub'] = this.createHubProxy('toastHub');
    proxies['toastHub'].client = { };
    proxies['toastHub'].server = {
    };

    return proxies;
};

signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));
</code>```

答:
Looks to me like you need to just change the calls to broadcastToast from client to server. As that method is in the Hub and so requires the server instead.

$.connection.toastHub.client.broadcastToast
To
 $.connection.toastHub.server.broadcastToast

Body:
I am very new to the term SignalR . I was try to configure the signalR into my empty website and Added following code.

In App_Code

  using Microsoft.Owin;
  using Owin;

  [assembly: OwinStartup(typeof(Super.App_Code.Startup))]

  namespace Super.App_Code
  {
     public class Startup
     {
         public static void Configuration(IAppBuilder app)
         {
             app.MapSignalR();

         }
     }
  }

and the hub class Inside App_Code

namespace Super.App_Code
{
[HubName("toastHub")]
 public class ToastHub : Hub
{
    public void BroadcastToast(string type ,string msg)
    {
        Clients.All.sendToast(type , msg);
    }
}
}

and in Default.aspx

<title></title>
<link rel="stylesheet" href="content/toastr.min.css" />

 <form id="form1" runat="server">

        Success Toast

        Error Toast

  </form>

but when i run my website the javascript console says this when click on one of the  tag

  SignalR connected
  Default.aspx:20 Success Click
  Default.aspx:21 Uncaught TypeError: $.connection.toastHub.client.broadcastToast is not a function
      at HTMLAnchorElement.<anonymous> (Default.aspx:21)
      at HTMLAnchorElement.handle (jquery-1.6.4.js:3001)
      at HTMLAnchorElement.eventHandle (jquery-1.6.4.js:2635)

Am i doing anything wrong please help me any help would be greatful .i am totally new to SignalR .

signalr/hub

if (typeof ($.signalR) !== "function") {
    throw new Error("SignalR: SignalR is not loaded. Please ensure         jquery.signalR-x.js is referenced before ~/signalr/js.");
}

var signalR = $.signalR;

function makeProxyCallback(hub, callback) {
    return function () {
        // Call the client hub method
        callback.apply(hub, $.makeArray(arguments));
    };
}

function registerHubProxies(instance, shouldSubscribe) {
    var key, hub, memberKey, memberValue, subscriptionMethod;

    for (key in instance) {
        if (instance.hasOwnProperty(key)) {
            hub = instance[key];

            if (!(hub.hubName)) {
                // Not a client hub
                continue;
            }

            if (shouldSubscribe) {
                // We want to subscribe to the hub events
                subscriptionMethod = hub.on;
            } else {
                // We want to unsubscribe from the hub events
                subscriptionMethod = hub.off;
            }

            // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
            for (memberKey in hub.client) {
                if (hub.client.hasOwnProperty(memberKey)) {
                    memberValue = hub.client[memberKey];

                    if (!$.isFunction(memberValue)) {
                        // Not a client hub function
                        continue;
                    }

                    // Use the actual user-provided callback as the "identity" value for the registration.
                    subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue), memberValue);
                }
            }
        }
    }
}

$.hubConnection.prototype.createHubProxies = function () {
    var proxies = {};
    this.starting(function () {
        // Register the hub proxies as subscribed
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, true);

        this._registerSubscribedHubs();
    }).disconnected(function () {
        // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
        // (instance, shouldSubscribe)
        registerHubProxies(proxies, false);
    });

    proxies['toastHub'] = this.createHubProxy('toastHub');
    proxies['toastHub'].client = { };
    proxies['toastHub'].server = {
    };

    return proxies;
};

signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));