问:
Output of pow() function in C++ is not giving accurate answer
The user will give an integer input. I have to find the mod after squaring it. But when I give a big integer, pow() gives the wrong answer. How can I fix that?

#include<bits/stdc++.h>

using namespace std;

int main()
{
    //ios_base:: sync_with_stdio(false);
    //cin.tie(NULL);
    int t;
    cin >> t;
    for(int i = 0; i < t; i++)
    {
        long long n;
        cin >> n;

        long long sn = 0;
        sn = pow(n, 2);
        long long v = pow(10, 9) + 7;

        cout << sn % v << endl;
    }
}
```

答:
The trick to solve this problem is computing the modulus earlier. Modular arithmetic offers some opportunities for this.

For this question note that (a * b) % m == (a % m) * (b % m).

Moreover 1000000007^2 does still fit within a 64 bit int, so the result will at all times be small enough.

Hence the relevant part of the code could look as follows

const int64_t m = 1000000007;
int64_t n;
cin>>n;

n = n % m;
int64_t sn = n * n;
sn = sn % m;

cout << sn << endl;
```


来源: stackexchange

问:
ADLS to Azure Storage Sync Using AzCopy
Looking for some help to resolve the errors I'm facing. Let me explain the scenario. I'm trying to sync one of the ADLS Gen2 container to Azure BLOB Storage. I have AzCopy 10.4.3, I'm using Azcopy Sync to do this. I'm using the command below

azcopy sync 'https://ADLSGen2.blob.core.windows.net/testsamplefiles/SAMPLE' 'https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE' --recursive

When I run this command I'm getting below error

```<code>REQUEST/RESPONSE (Try=1/71.0063ms, OpTime=110.9373ms) -- RESPONSE SUCCESSFULLY RECEIVED
   PUT https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet?blockid=ZDQ0ODlkYzItN2N2QzOWJm&comp=block&timeout=901
   X-Ms-Request-Id: [378ca837-d01e-0031-4f48-34cfc2000000]

ERR: [P#0-T#0] COPYFAILED: https://ADLSGen2.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet: 404 : 404 The specified resource does not exist.. When Staging block from URL. X-Ms-Request-Id: [378ca837-d01e-0031-4f48-34cfc2000000]

   Dst: https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet
REQUEST/RESPONSE (Try=1/22.9854ms, OpTime=22.9854ms) -- RESPONSE SUCCESSFULLY RECEIVED
   GET https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet?blocklisttype=all&comp=blocklist&timeout=31
   X-Ms-Request-Id: [378ca84e-d01e-0031-6148-34cfc2000000]
</code>```

So far I checked and ensured below things

I logged into correct tenant while logging into AzCopy

Storage Blob Data Contributor role was granted to my AD credentials

Not sure what else I'm missing as the file exists in the source and I'm getting the same error. I tried with SAS but I received different error though. I cannot proceed with SAS due to the vendor policy so I need to ensure this is working with oAuth. Any inputs is really appreciated.

答:
For the 404 error, you may check if there is any typo in the command and the path /testsamplefiles/SAMPLE exists on both source and destination account. Also, please note that from the tips.

Use single quotes in all command shells except for the Windows Command
  Shell (cmd.exe). If you're using a Windows Command Shell (cmd.exe),
  enclose path arguments with double quotes ("") instead of single
  quotes ('').

From azcopy sync supported scenario:

Azure Blob <-> Azure Blob (Source must include a SAS or is publicly
  accessible; either SAS or OAuth authentication can be used for
  destination)

We must provide include a SAS token in the source, but I tried the below code with AD authentication.

```<code>azcopy sync "https://[account].blob.core.windows.net/[container]/[path/to/blob]?[SAS]" "https://[account].blob.core.windows.net/[container]/[path/to/blob]"
</code>```

but got the same 400 error as the Github issue.

Thus, in this case, after my validation, you could use this command to sync one of the ADLS Gen2 container to Azure BLOB Storage without executing azcopy login. If you have login in, you can run azcopy logout.

```<code>azcopy sync "https://nancydl.blob.core.windows.net/container1/sample?sv=xxx" "https://nancytestdiag244.blob.core.windows.net/container1/sample?sv=xxx" --recursive --s2s-preserve-access-tier=false
</code>```

ContentLicense: CC BY-SA 4.0

Title: ADLS to Azure Storage Sync Using AzCopy

Body:
Looking for some help to resolve the errors I'm facing. Let me explain the scenario. I'm trying to sync one of the ADLS Gen2 container to Azure BLOB Storage. I have AzCopy 10.4.3, I'm using Azcopy Sync to do this. I'm using the command below

azcopy sync 'https://ADLSGen2.blob.core.windows.net/testsamplefiles/SAMPLE' 'https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE' --recursive

When I run this command I'm getting below error

REQUEST/RESPONSE (Try=1/71.0063ms, OpTime=110.9373ms) -- RESPONSE SUCCESSFULLY RECEIVED
   PUT https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet?blockid=ZDQ0ODlkYzItN2N2QzOWJm&comp=block&timeout=901
   X-Ms-Request-Id: [378ca837-d01e-0031-4f48-34cfc2000000]

ERR: [P#0-T#0] COPYFAILED: https://ADLSGen2.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet: 404 : 404 The specified resource does not exist.. When Staging block from URL. X-Ms-Request-Id: [378ca837-d01e-0031-4f48-34cfc2000000]

   Dst: https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet
REQUEST/RESPONSE (Try=1/22.9854ms, OpTime=22.9854ms) -- RESPONSE SUCCESSFULLY RECEIVED
   GET https://AzureBlobStorage.blob.core.windows.net/testsamplefiles/SAMPLE/SampleFile.parquet?blocklisttype=all&comp=blocklist&timeout=31
   X-Ms-Request-Id: [378ca84e-d01e-0031-6148-34cfc2000000]

So far I checked and ensured below things

I logged into correct tenant while logging into AzCopy

Storage Blob Data Contributor role was granted to my AD credentials

Not sure what else I'm missing as the file exists in the source and I'm getting the same error. I tried with SAS but I received different error though. I cannot proceed with SAS due to the vendor policy so I need to ensure this is working with oAuth. Any inputs is really appreciated.

Body:
For the 404 error, you may check if there is any typo in the command and the path /testsamplefiles/SAMPLE exists on both source and destination account. Also, please note that from the tips.

Use single quotes in all command shells except for the Windows Command
  Shell (cmd.exe). If you're using a Windows Command Shell (cmd.exe),
  enclose path arguments with double quotes ("") instead of single
  quotes ('').

From azcopy sync supported scenario:

Azure Blob <-> Azure Blob (Source must include a SAS or is publicly
  accessible; either SAS or OAuth authentication can be used for
  destination)

We must provide include a SAS token in the source, but I tried the below code with AD authentication.

azcopy sync "https://[account].blob.core.windows.net/[container]/[path/to/blob]?[SAS]" "https://[account].blob.core.windows.net/[container]/[path/to/blob]"

but got the same 400 error as the Github issue.

Thus, in this case, after my validation, you could use this command to sync one of the ADLS Gen2 container to Azure BLOB Storage without executing azcopy login. If you have login in, you can run azcopy logout.

azcopy sync "https://nancydl.blob.core.windows.net/container1/sample?sv=xxx" "https://nancytestdiag244.blob.core.windows.net/container1/sample?sv=xxx" --recursive --s2s-preserve-access-tier=false


问:
How to show the category on the frontend with using django tag template?
I am the beginner of writing program and using Django, now I would like to display the category on the front-end. I have created a foreign-key which named “topic” as a category. It is successfully access to the topic(sub-category) and the post (by using pk)by entering URL. Although the URL config is work but I have no idea how to put it on the front-end by using template tag. I would like to create a catalog and when I clicked to the certain catalog then will show these posts which under the specific “topic”. I learned Django by the book “Django for beginners” and “Django for professional” however it does not cover such topic. And I watch online tutorial and I very confused and frustrated.  (My Django version is 3.0.0)

Thanks for your help :)

The Article URL like that http://127.0.0.1:8000/django/1
                                                Topic (FK)    (Post PK)

My Model

```<code>from django.db import models
from ckeditor.fields import RichTextField

class Topic(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, default='self.name')

    def get_absolute_url(self):
        return reverse('topic',
                       args=[self.slug])

    def __str__(self):
        return self.name

class Post(models.Model):
    title =  models.CharField(max_length=50)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    content = RichTextField()
    topic = models.ForeignKey(Topic, default=1, on_delete=models.SET_DEFAULT)

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

View

```<code>from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class Home(ListView):
   model = Post
   template_name = 'home.html'

class TopicList(ListView):
   model = Post
   template_name = 'topiclist.html'

class PostDetail(DetailView):
   model = Post
   template_name = 'detail.html'
# Create your views here.
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class Home(ListView):
   model = Post
   template_name = 'home.html'

class TopicList(ListView):
   model = Post
   template_name = 'topiclist.html'

class PostDetail(DetailView):
   model = Post
   template_name = 'detail.html'
</code>```

urls

```<code>from django.urls import path
from .views import Home, PostDetail, TopicList

urlpatterns = [
   path('', Home.as_view(), name='home'),
   path('<slug:topic>/<int:pk>', PostDetail.as_view(), name='detail'),
   path('<slug:topic>/', TopicList.as_view(), name='topiclist'),
</code>```

答:
You would write a view where you filter the rows where topic is matched. Then pass the returned query to your template:

```<code>Topic = Topic.objects.get(name = 'coding')
Posts = Post.objects.filter(topic=Topic)
return render(request, 'catalog.html', {'posts': Posts})
</code>```

Then in your template file:

```<code>{% for post in posts %}
    <li>{{ post.title }}</li>
{% endfor %}
</code>```

Body:
I am the beginner of writing program and using Django, now I would like to display the category on the front-end. I have created a foreign-key which named “topic” as a category. It is successfully access to the topic(sub-category) and the post (by using pk)by entering URL. Although the URL config is work but I have no idea how to put it on the front-end by using template tag. I would like to create a catalog and when I clicked to the certain catalog then will show these posts which under the specific “topic”. I learned Django by the book “Django for beginners” and “Django for professional” however it does not cover such topic. And I watch online tutorial and I very confused and frustrated.  (My Django version is 3.0.0)

Thanks for your help :)

The Article URL like that http://127.0.0.1:8000/django/1
                                                Topic (FK)    (Post PK)

My Model

from django.db import models
from ckeditor.fields import RichTextField

class Topic(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, default='self.name')

    def get_absolute_url(self):
        return reverse('topic',
                       args=[self.slug])

    def __str__(self):
        return self.name

class Post(models.Model):
    title =  models.CharField(max_length=50)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    content = RichTextField()
    topic = models.ForeignKey(Topic, default=1, on_delete=models.SET_DEFAULT)

    def __str__(self):
        return self.title

View

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class Home(ListView):
   model = Post
   template_name = 'home.html'

class TopicList(ListView):
   model = Post
   template_name = 'topiclist.html'

class PostDetail(DetailView):
   model = Post
   template_name = 'detail.html'
# Create your views here.
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post

class Home(ListView):
   model = Post
   template_name = 'home.html'

class TopicList(ListView):
   model = Post
   template_name = 'topiclist.html'

class PostDetail(DetailView):
   model = Post
   template_name = 'detail.html'

urls

from django.urls import path
from .views import Home, PostDetail, TopicList

urlpatterns = [
   path('', Home.as_view(), name='home'),
   path('<slug:topic>/<int:pk>', PostDetail.as_view(), name='detail'),
   path('<slug:topic>/', TopicList.as_view(), name='topiclist'),

Body:
You would write a view where you filter the rows where topic is matched. Then pass the returned query to your template:

Topic = Topic.objects.get(name = 'coding')
Posts = Post.objects.filter(topic=Topic)
return render(request, 'catalog.html', {'posts': Posts})

Then in your template file:

{% for post in posts %}
    <li>{{ post.title }}</li>
{% endfor %}


问:
pidgine messages to all
```<code>ejabberd 16.01-2
client Pidgin 2.13.0 (libpurple 2.13.0)
</code>```

I send message to all user if user is offline will not receive a message.

I want to send a message to everyone (mod_announce) via pidgin 2.13.0 (offline and online). Message to offline users is not saved.

```<code>mod_offline is running
auth_method: internal
</code>```

答: I update ejabberd to 20.01 and all is OK now.</p>

Title: pidgine messages to all

Body:
ejabberd 16.01-2
client Pidgin 2.13.0 (libpurple 2.13.0)

I send message to all user if user is offline will not receive a message.

I want to send a message to everyone (mod_announce) via pidgin 2.13.0 (offline and online). Message to offline users is not saved.

mod_offline is running
auth_method: internal


问:
Chai - Assert that all elements in the array are equal to a given value with
I have this array of strings:

```<code>[ "apple", "apple", "apple", "apple", "apple", "apple", ]
</code>```

Is it possible to make an assertion with Chai that all elements in the array are equal to the certain value?

```<code>arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple", ]
expectedFruit = "apple"

expect(arrayFromApiResponse).to ???
</code>```

I need to test that each value in the arrayFromApiResponse is "apple"

I found this https://github.com/chaijs/Chai-Things

Seems like with this library it can be accomplished like this:

```<code>expect(arrayFromApiResponse).should.all.be.a(expectedFruit)
</code>```

But is it possible to achieve this without additional library? Maybe I can make some changes to arrayFromApiResponse so it can be validated by Chai?

UPD:
I have updated the question title to prevent marking my question as duplicate with reference to this type of questions:
Check if all values of array are equal

答:
const arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple"]
const expectedFruit = "apple"
```

<p>You can do this with <code>filter()</code> but the most efficient would be a good old <code>for</code> loop: </p>

<pre class="lang-js prettyprint-override"><code>function test(arr, val){
  for(let i=0; i<arrayFromApiResponse.length; i++){
    if(arr[i] !== val) {
      return false;
    }
  }

  return true;
}
</code>```

The reason this is more efficient is that this function will terminate as soon as it sees a value which doesn't equal the expected value. Other functions will traverse the entire array, which can be extremely inefficient. Use it like this:

expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);
```

Body:
I have this array of strings:

[ "apple", "apple", "apple", "apple", "apple", "apple", ]

Is it possible to make an assertion with Chai that all elements in the array are equal to the certain value?

arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple", ]
expectedFruit = "apple"

expect(arrayFromApiResponse).to ???

I need to test that each value in the arrayFromApiResponse is "apple"

I found this https://github.com/chaijs/Chai-Things

Seems like with this library it can be accomplished like this:

expect(arrayFromApiResponse).should.all.be.a(expectedFruit)

But is it possible to achieve this without additional library? Maybe I can make some changes to arrayFromApiResponse so it can be validated by Chai?

UPD:
I have updated the question title to prevent marking my question as duplicate with reference to this type of questions:
Check if all values of array are equal

Body:
const arrayFromApiResponse = [ "apple", "apple", "apple", "apple", "apple", "apple"]
const expectedFruit = "apple"

You can do this with filter() but the most efficient would be a good old for loop:

function test(arr, val){
  for(let i=0; i<arrayFromApiResponse.length; i++){
    if(arr[i] !== val) {
      return false;
    }
  }

  return true;
}

The reason this is more efficient is that this function will terminate as soon as it sees a value which doesn't equal the expected value. Other functions will traverse the entire array, which can be extremely inefficient. Use it like this:

expect(test(arrayFromApiResponse, expectedFruit)).toBe(true);


问:
Apache2 ServerName and ServerAlias not working
On a nearly fresh Ubuntu 20.04 LTS computer, I would like to set up a virtual host on my local machine. So I created a index.html under /var/www/test/ with the following content:
you have entered a test page

I have set up a test.conf file under /etc/apache2/sites-available/

with the following content:

```<code><VirtualHost *:80>
    ServerAdmin webmaster@zhihu.com
    DocumentRoot /var/www/test/
    ServerName zhihu.com
    ServerAlias www.zhihu.com
    <Directory /var/www/test/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

The localhost is working:

/etc/hosts config is probably working as indicated by ping

```<code>ping zhihu.com
PING zhihu.com (127.0.1.1) 56(84) bytes of data.
64 bytes from xxx (127.0.1.1): icmp_seq=1 ttl=64 time=0.045 ms

</code>```

but browser cannot bring me to the domain which should now be hosted in /var/www/test/.

I have also a2ensite test.conf and a2dissite 000-default.conf and service apache2 reload

So I think the only possible place for error to occur is ServerName and ServerAlias. Why are they not working?

答: Could you please enable VirtualHost using a2ensite and access site in incognito mode.</p>

Body:
On a nearly fresh Ubuntu 20.04 LTS computer, I would like to set up a virtual host on my local machine. So I created a index.html under /var/www/test/ with the following content:
you have entered a test page

I have set up a test.conf file under /etc/apache2/sites-available/

with the following content:

<VirtualHost *:80>
    ServerAdmin webmaster@zhihu.com
    DocumentRoot /var/www/test/
    ServerName zhihu.com
    ServerAlias www.zhihu.com
    <Directory /var/www/test/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

The localhost is working:

/etc/hosts config is probably working as indicated by ping

ping zhihu.com
PING zhihu.com (127.0.1.1) 56(84) bytes of data.
64 bytes from xxx (127.0.1.1): icmp_seq=1 ttl=64 time=0.045 ms

but browser cannot bring me to the domain which should now be hosted in /var/www/test/.

I have also a2ensite test.conf and a2dissite 000-default.conf and service apache2 reload

So I think the only possible place for error to occur is ServerName and ServerAlias. Why are they not working?


问:
C#:checking existing record in database Mysql
HI.I searched this question inform and I found solution to change column property Unique Index.Now If I try to insert same record   cmd.ExecuteNonQuery() gives error that record exist ,but how can use this exception to give user a message that record exist and must enter new one ?  I am trying to make some thing like

```<code>if(cmd.ExecuteNonQuery() !=true )
{
 MessageBox.Show("User Exists");
}
</code>```

But I dont know what returns cmd.ExecuteNonQuery() ?

Or I must get records using reader in table and compare them with text in Textfiel?

答:
```<code>               cmd.CommandText = "Select * from Emp";
               cmd.CommandType = CommandType.Text;
               cmd.Connection = con;
               DartaReader dr;
               dr = cmd.ExecuteReader();
               while (dr.Read())
               {//textbox contain the id or name which you want to check in table
                    if (dr[0].ToString() == textBox1.Text)
                    {
                        MessageBox.Show("Record is Already Exist");
                        con.Close();
                        break;
                    }
              }
</code>```

<p>by using above code I found the existence of record from  database table. </p>

ContentLicense: CC BY-SA 2.5

Body:
HI.I searched this question inform and I found solution to change column property Unique Index.Now If I try to insert same record   cmd.ExecuteNonQuery() gives error that record exist ,but how can use this exception to give user a message that record exist and must enter new one ?  I am trying to make some thing like

if(cmd.ExecuteNonQuery() !=true )
{
 MessageBox.Show("User Exists");
}

But I dont know what returns cmd.ExecuteNonQuery() ?

Or I must get records using reader in table and compare them with text in Textfiel?

Body:
               cmd.CommandText = "Select * from Emp";
               cmd.CommandType = CommandType.Text;
               cmd.Connection = con;
               DartaReader dr;
               dr = cmd.ExecuteReader();
               while (dr.Read())
               {//textbox contain the id or name which you want to check in table
                    if (dr[0].ToString() == textBox1.Text)
                    {
                        MessageBox.Show("Record is Already Exist");
                        con.Close();
                        break;
                    }
              }

by using above code I found the existence of record from  database table.

ContentLicense: CC BY-SA 3.0


问:
how can I overcome "ValueError: Shapes (None, 1) and (None, 7) are incompatible"
I am new to Keras and CNN. I am working on an assignment to build a CNN for predicting face emotions. I built the model as per the assignment but while compiling the model I get "ValueError: Shapes (None, 1) and (None, 7) are incompatible". Can someone help me how to resolve this?

Pasting my code below for reference:

'''

```<code>model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = 5,input_shape = (48,48,1)))
model.add(Conv2D(filters=64, kernel_size=5,strides=(1, 1), padding='valid'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2),strides=1, padding='valid'))
model.add(Activation('relu'))

model.add(Conv2D(filters = 128, kernel_size = 5))
model.add(Conv2D(filters = 128, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(filters = 256, kernel_size = 5))
model.add(Conv2D(filters = 256, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dense(128))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(7,activation='softmax'))
</code>```

'''
'Then tried to compile'
'''

```<code>model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(input_array, output_array, batch_size = 64, epochs= 20, validation_split=0.10,)
</code>```

'''
'This gives the error'
'ValueError: Shapes (None, 1) and (None, 7) are incompatible'
'I am using google colab for this'

答:
You are most likely using your labels sparsely encoded, like [0,1,2,3,4,5,6] instead of a one-hot-encoded form.

Your solution is to choose from one of the below:

Use the one-hot-encoded form, i.e. transform each label to an array of length == number_of_classes. That is, for 0 you would have [1,0,0,0,0,0,0] for 1 you would have [0,1,0,0,0,0,0] etc.

Use sparse_categorical_crossentropy. If you use this loss functions, the OHE step is done behind the scenes and you no longer need to process your input training + validation labels.

Body:
I am new to Keras and CNN. I am working on an assignment to build a CNN for predicting face emotions. I built the model as per the assignment but while compiling the model I get "ValueError: Shapes (None, 1) and (None, 7) are incompatible". Can someone help me how to resolve this?

Pasting my code below for reference:

'''

model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = 5,input_shape = (48,48,1)))
model.add(Conv2D(filters=64, kernel_size=5,strides=(1, 1), padding='valid'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2),strides=1, padding='valid'))
model.add(Activation('relu'))

model.add(Conv2D(filters = 128, kernel_size = 5))
model.add(Conv2D(filters = 128, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(filters = 256, kernel_size = 5))
model.add(Conv2D(filters = 256, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dense(128))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(7,activation='softmax'))

'''
'Then tried to compile'
'''

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(input_array, output_array, batch_size = 64, epochs= 20, validation_split=0.10,)

'''
'This gives the error'
'ValueError: Shapes (None, 1) and (None, 7) are incompatible'
'I am using google colab for this'


问:
Is there a deadlock in following situation and what could be the solution to prevent it?
I have a FileLogger class which logs messages to a txt file. My intention is to make the FileLogger class thread safe so that multiple threads could write log messages in a thread safe manner. I have a lock object to allow only one thread to write at a moment.

Also in the same application I have a GlobalExceptionHandler class which handles all expected and unexpected exceptions. The handling of exceptions is all about logging in a file. So, the GlobalExceptionHandler will eventually call FileLogger Log method to log to file. In terms of code it can be shown as:

```<code>class FileLogger {

  ...

  public void Log(string logOrigin, string message, LogLevel logLevel) {
    //some code
    lock (logWriteLock) {
        try {
          using (var logFileStream = File.Open(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)) {
            logFileStream.Write(messageBytes, 0, messageBytes.Length);
            logFileStream.Flush();
          }
        } catch (Exception ex) {
          globalExceptionHandler.HandleException(ex);
        }
      }
  }

}

class GlobalExceptionHandler {

  public void HandleException(Exception ex) {
    //some code
    fileLogger.Log(...);
  }
}
</code>```

My understanding:

The lock logWriteLock is acquired by the thread, then it tries to open the file and write to it. The happy scenario will be fine but if there is an exception while trying to write, then the control will go to HandleException method which will be executed by the same thread.The HandleException will again call Log. Since the thread already has the lock, it can reenter and then reattempt to write to file. This will go on and on.

Is my understanding correct? Or will the lock be released as soon as we hit the line globalExceptionHandler.HandleException(ex) (as we have reached the end of critical section and the method HandleException does not explicitly lock on logWriteLock)?

I have a gut feeling that I have circular references and deadlock will happen.

Also if there is a deadlock, then what could be the possible solution. Do we need an extra file just to log the exceptions in FileLogger (which i think is not a good idea as we lead to unnecessary complexity of design)?

答:
Or will the lock be released as soon as we hit the line
  globalExceptionHandler.HandleException(ex) (as we have reached the end
  of critical section and the method HandleException does not explicitly
  lock on logWriteLock)?

You are still inside the lock section, doesn't matter the level of depth you get into when calling methods from lock section.

So you will loop inside forever while holding the lock.

When logging fails, there is no reason to try to log exception as it will probably fail too. So either have another kind of logger or send the notification so you can react when such a problem occurs.

Body:
I have a FileLogger class which logs messages to a txt file. My intention is to make the FileLogger class thread safe so that multiple threads could write log messages in a thread safe manner. I have a lock object to allow only one thread to write at a moment.

Also in the same application I have a GlobalExceptionHandler class which handles all expected and unexpected exceptions. The handling of exceptions is all about logging in a file. So, the GlobalExceptionHandler will eventually call FileLogger Log method to log to file. In terms of code it can be shown as:

class FileLogger {

  ...

  public void Log(string logOrigin, string message, LogLevel logLevel) {
    //some code
    lock (logWriteLock) {
        try {
          using (var logFileStream = File.Open(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)) {
            logFileStream.Write(messageBytes, 0, messageBytes.Length);
            logFileStream.Flush();
          }
        } catch (Exception ex) {
          globalExceptionHandler.HandleException(ex);
        }
      }
  }

}

class GlobalExceptionHandler {

  public void HandleException(Exception ex) {
    //some code
    fileLogger.Log(...);
  }
}

My understanding:

The lock logWriteLock is acquired by the thread, then it tries to open the file and write to it. The happy scenario will be fine but if there is an exception while trying to write, then the control will go to HandleException method which will be executed by the same thread.The HandleException will again call Log. Since the thread already has the lock, it can reenter and then reattempt to write to file. This will go on and on.

Is my understanding correct? Or will the lock be released as soon as we hit the line globalExceptionHandler.HandleException(ex) (as we have reached the end of critical section and the method HandleException does not explicitly lock on logWriteLock)?

I have a gut feeling that I have circular references and deadlock will happen.

Also if there is a deadlock, then what could be the possible solution. Do we need an extra file just to log the exceptions in FileLogger (which i think is not a good idea as we lead to unnecessary complexity of design)?


问:
Extracting discrete timestamp values of a dataset from a continous timestamps
I have a dataset with data points every minute, lets say df_cont with Value having cumulatively increasing numbers

```<code>                Value
datetimeindex
09:00:00         34
09:01:00         45
09:02:00         48
09:03:00         50
.                .
.                .
.                .
18:58:00         55
18:59:00         65
19:00:00         68
</code>```

I have another dataset with just time values, let's say df_time

```<code>Time_1       Time_2
09:05:00     09:15:00
10:05:00     10:25:00
11:55:00     12:15:00
17:05:00     17:15:00
</code>```

Now, the difference has to be found out for "Value" in the timestamp of the difference in time between Time_1 and Time_2.

I can do this manually by using the DateTime functionality

```<code>df_cont["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.max() - df["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.min()
</code>```

However, was unable to this automatically for all the difference of timestamps by either looping or using some other functions of pandas. Any help would be greatly appreciated.

答:
You have to join based on time_1 and time_2 and then calculate the difference. You might have to reset index in your case.</p>

```<code>df_cont = pd.DataFrame({'time':[1, 2, 3, 4, 5, 6], 'Value':[45, 48, 53, 55, 60, 64]})
df_time = pd.DataFrame({'time1':[1, 2, 5], 'time2':[3, 4, 6]})

df = (df_time.merge(df_cont.rename(columns={'time':'time1', 'Value':'value1'}), on='time1')
                  .merge(df_cont.rename(columns={'time':'time2', 'Value':'value2'}), on='time2'))

df['value_diff'] = df['value2'] - df['value1']
</code>```

Body:
I have a dataset with data points every minute, lets say df_cont with Value having cumulatively increasing numbers

                Value
datetimeindex
09:00:00         34
09:01:00         45
09:02:00         48
09:03:00         50
.                .
.                .
.                .
18:58:00         55
18:59:00         65
19:00:00         68

I have another dataset with just time values, let's say df_time

Time_1       Time_2
09:05:00     09:15:00
10:05:00     10:25:00
11:55:00     12:15:00
17:05:00     17:15:00

Now, the difference has to be found out for "Value" in the timestamp of the difference in time between Time_1 and Time_2.

I can do this manually by using the DateTime functionality

df_cont["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.max() - df["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.min()

However, was unable to this automatically for all the difference of timestamps by either looping or using some other functions of pandas. Any help would be greatly appreciated.

Body:
You have to join based on time_1 and time_2 and then calculate the difference. You might have to reset index in your case.

df_cont = pd.DataFrame({'time':[1, 2, 3, 4, 5, 6], 'Value':[45, 48, 53, 55, 60, 64]})
df_time = pd.DataFrame({'time1':[1, 2, 5], 'time2':[3, 4, 6]})

df = (df_time.merge(df_cont.rename(columns={'time':'time1', 'Value':'value1'}), on='time1')
                  .merge(df_cont.rename(columns={'time':'time2', 'Value':'value2'}), on='time2'))

df['value_diff'] = df['value2'] - df['value1']


问:
Unity uploading ingame stats to a website
I want to make a Unity game that sends ingame stats to a website, Like how many times a player has shot, how many kills the play has. ect.

my question is is this even possible using Unity? if yes what tools do I need?

答:
If you already have a backend for your game analytics, then you can just call their API endpoints using UnityWebRequest.

using UnityEngine.Networking;
...
IEnumerator LogEvent(kills, shots) {
    WWWForm form = new WWWForm();
    form.AddField("kills", kills);
    form.AddField("shots", shots);

    using (UnityWebRequest www = UnityWebRequest.Post("http://www.my-server.com/myform", form))
    {
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError) {
            Debug.Log(www.error);
        } else {
            Debug.Log("Form upload complete!");
        }
    }
}
...
public void GameOver() {
    ...
    StartCoroutine(LogEvent(10, 100));
}
```

You can use some Analytics SDKs for that such as Firebase Analytics, Google Analytics, AppsFlyer, and so on.

https://firebase.google.com/docs/analytics/unity/start
https://developers.google.com/analytics/devguides/collection/unity/v4/devguide

In my experience, Firebase is the best one as it supports other tools like Storage, Authentication, ...

Body:
If you already have a backend for your game analytics, then you can just call their API endpoints using UnityWebRequest.

using UnityEngine.Networking;
...
IEnumerator LogEvent(kills, shots) {
    WWWForm form = new WWWForm();
    form.AddField("kills", kills);
    form.AddField("shots", shots);

    using (UnityWebRequest www = UnityWebRequest.Post("http://www.my-server.com/myform", form))
    {
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError) {
            Debug.Log(www.error);
        } else {
            Debug.Log("Form upload complete!");
        }
    }
}
...
public void GameOver() {
    ...
    StartCoroutine(LogEvent(10, 100));
}

You can use some Analytics SDKs for that such as Firebase Analytics, Google Analytics, AppsFlyer, and so on.

https://firebase.google.com/docs/analytics/unity/start
https://developers.google.com/analytics/devguides/collection/unity/v4/devguide

In my experience, Firebase is the best one as it supports other tools like Storage, Authentication, ...


问:
How to update Auto generated time stamp in Spring boot
I am making use of Auditing with Spring Data JPA to automatically update the created by time stamp. I have a requirement, where i have to migrate some data for which the created by date should be updated with the value am setting through the application. I have debugged the code, the values are setting properly. But while calling

fooRepository.save(fooEntity)

The created by is getting overridden by the auto generated time stamp.
Is it possible to override the value?

I am also having a @Transactional annotation in Service level. While debugging i can see the date is getting replaced on the Entity returned by the save repository method.

答:
It is not a better way but you can follow.
First, create the entity

```<code>fooRepository.saveAndFlush(fooEntity);
</code>```

and then update the createdAt data then save the entity again.

```<code>fooEntity.setCreatedAt(yourTime);
fooRepository.saveAndFlush(fooEntity);
</code>```

Body:
It is not a better way but you can follow.
First, create the entity

fooRepository.saveAndFlush(fooEntity);

and then update the createdAt data then save the entity again.

fooEntity.setCreatedAt(yourTime);
fooRepository.saveAndFlush(fooEntity);


问:
how to create horizontal spinner+timer like this?

is it possible to create a design something like this?
any help regarding this would be very helpful for me.the functionality i want is to rotate the wheel left-to-right or right to left for selecting time...yellow is selection color and red is shows the remaining time when countdown is running

答:
See my video
http://www.youtube.com/watch?v=4acFshAlGJ8

I have use
https://lh3.googleusercontent.com/-WZEDMSmfrK0/TeeD93t8qYI/AAAAAAAAAKw/X9D6jRkLfLk/s800/MUKScale.png
image as Scale in the scrollView this is an incomplete example just to show how can it is achievable.

here is some helpful piece of code,
in this approx everything is static but for the real work one should to work more,

```<code>   - (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:scrollView];

    UIImageView *backImgg = [[UIImageView alloc] initWithFrame:CGRectMake(x,y,886,15)];
    [backImgg setImage: [UIImage imageNamed:@"MUKScale.png"]];//Image in the link above
    [scrollView addSubview:backImgg];
    [backImgg release];

    [scrollView setContentSize:CGSizeMake(886,15)];
    return;
}

NSTimer *timer ;
float timeSet =0 ;
-(IBAction) btnPressed
{
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(showTimeInLbl) userInfo:nil repeats:YES];
}

-(void)showTimeInLbl
{
    CGRect visibleRect;
    visibleRect.origin = scrollView.contentOffset;
    visibleRect.size = scrollView.contentSize;
    NSLog( @"Visible rect: %@", NSStringFromCGRect(visibleRect) );

    float time = visibleRect.origin.x / 8;
    timeSet = time;
    lblTime.text = [NSString stringWithFormat:@"%f",time];

    [UIView animateWithDuration: .1
                     animations: ^{
                         [scrollView setContentOffset:CGPointMake(visibleRect.origin.x - 8,0) animated:NO];
                     }completion: ^(BOOL finished){

                     }
     ];

    timeSet-=0.1;

    lblTime.text = [NSString stringWithFormat:@"%f",timeSet];

    if(timeSet<=0)
    {
        [timer invalidate];
        lblTime.text = @"0";

        [UIView animateWithDuration: .1
                         animations: ^{
                             [scrollView setContentOffset:CGPointMake(0,0) animated:NO];
                         }completion: ^(BOOL finished){

                         }
         ];
    }

}
</code>```

Body:
See my video
http://www.youtube.com/watch?v=4acFshAlGJ8

I have use
https://lh3.googleusercontent.com/-WZEDMSmfrK0/TeeD93t8qYI/AAAAAAAAAKw/X9D6jRkLfLk/s800/MUKScale.png
image as Scale in the scrollView this is an incomplete example just to show how can it is achievable.

here is some helpful piece of code,
in this approx everything is static but for the real work one should to work more,

   - (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:scrollView];

    UIImageView *backImgg = [[UIImageView alloc] initWithFrame:CGRectMake(x,y,886,15)];
    [backImgg setImage: [UIImage imageNamed:@"MUKScale.png"]];//Image in the link above
    [scrollView addSubview:backImgg];
    [backImgg release];

    [scrollView setContentSize:CGSizeMake(886,15)];
    return;
}

NSTimer *timer ;
float timeSet =0 ;
-(IBAction) btnPressed
{
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(showTimeInLbl) userInfo:nil repeats:YES];
}

-(void)showTimeInLbl
{
    CGRect visibleRect;
    visibleRect.origin = scrollView.contentOffset;
    visibleRect.size = scrollView.contentSize;
    NSLog( @"Visible rect: %@", NSStringFromCGRect(visibleRect) );

    float time = visibleRect.origin.x / 8;
    timeSet = time;
    lblTime.text = [NSString stringWithFormat:@"%f",time];

    [UIView animateWithDuration: .1
                     animations: ^{
                         [scrollView setContentOffset:CGPointMake(visibleRect.origin.x - 8,0) animated:NO];
                     }completion: ^(BOOL finished){

                     }
     ];

    timeSet-=0.1;

    lblTime.text = [NSString stringWithFormat:@"%f",timeSet];

    if(timeSet<=0)
    {
        [timer invalidate];
        lblTime.text = @"0";

        [UIView animateWithDuration: .1
                         animations: ^{
                             [scrollView setContentOffset:CGPointMake(0,0) animated:NO];
                         }completion: ^(BOOL finished){

                         }
         ];
    }

}


问:
I change my BackgroundImage with a randomElement from an Array but its zoomed in and not fitting perfectly
I have an array with my Image-names and a button. When I click on the button, the background-image schould get chaged. All is working but the pictures are a little bit zoomed and are not scaled to screen size.

```<code>import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var imagesArray = ["1", "2", "3", "4"]

    @IBAction func changeBackgroundImageButton_Tapped(_ sender: UIButton) {

        if let randomImage = imagesArray.randomElement(){

            view.backgroundColor = UIColor(patternImage: UIImage(named: randomImage)!)
        }

    }

}
</code>```

So what should I do that the background-images are not zoomed and scaled perfectly? Thanks!

答:
To change background image of your view randomly, there is minor changes - that will update your background image and also it will not hide your button. </p>

```<code>
@IBAction func changeBackground_Tapped(_ sender: Any) {

        UIGraphicsBeginImageContext(view.frame.size)
        UIImage(named: imagesArray.randomElement() ?? "1")?.draw(in: view.bounds)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if let image = image {
            view.backgroundColor = UIColor(patternImage: image)
        }

}

</code>```

<p>Hope it will solve your issue. </p>

Body:
I have an array with my Image-names and a button. When I click on the button, the background-image schould get chaged. All is working but the pictures are a little bit zoomed and are not scaled to screen size.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var imagesArray = ["1", "2", "3", "4"]

    @IBAction func changeBackgroundImageButton_Tapped(_ sender: UIButton) {

        if let randomImage = imagesArray.randomElement(){

            view.backgroundColor = UIColor(patternImage: UIImage(named: randomImage)!)
        }

    }

}

So what should I do that the background-images are not zoomed and scaled perfectly? Thanks!

Body:
To change background image of your view randomly, there is minor changes - that will update your background image and also it will not hide your button.

@IBAction func changeBackground_Tapped(_ sender: Any) {

        UIGraphicsBeginImageContext(view.frame.size)
        UIImage(named: imagesArray.randomElement() ?? "1")?.draw(in: view.bounds)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if let image = image {
            view.backgroundColor = UIColor(patternImage: image)
        }

}

Hope it will solve your issue.


问:
Groupby and keep only groups that contain values within a list
hello I have a df such as

```<code>list_vales_regex=['ABC',DEF']
Groups Names
G1 ABC_9
G1 ZTY_2
G1 SGG56
G1 BBCHU
G1 DEFE_8
G2 ABC_6
G2 GGDY
G3 ABC_6
G3 DEF98
G3 DEF89
G4 DEF_09
G4 DGE7
G5 DGGE22
G5 DGGE23
</code>```

and I would like to keep only groups that do contain both (ABC and DEF Names)

Here in the exemple only G1 and G3 have ot be kept.
Does someone have an idea ?

答:
First get values by list to helper Series by Series.str.extract with | for join values for regex or and then compare values converted to sets per groups in GroupBy.transform:

```<code>list_vales_regex=['ABC','DEF']

s = df['Names'].str.extract(f'({"|".join(list_vales_regex)})', expand=False)
df = df[s.groupby(df['Groups']).transform(lambda x: set(x) >= set(list_vales_regex))]
print (df)
  Groups   Names
0     G1   ABC_9
1     G1   ZTY_2
2     G1   SGG56
3     G1   BBCHU
4     G1  DEFE_8
7     G3   ABC_6
8     G3   DEF98
9     G3   DEF89
</code>```

Or filter by GroupBy.transform with DataFrameGroupBy.nunique (if not large data, because slowier):

```<code>df = df[s.groupby(df['Groups']).transform('nunique').ge(2)]
</code>```

Another approach is find groups with matched all values of list in list comprehension with np.logical_and.reduce for test if match at least one value by Series.any, then filter groups by first value of list by L[0] and pass to Series.isin:

```<code>list_vales_regex=['ABC','DEF']

L = [df.set_index('Groups')['Names'].str.contains(x).any(level=0) for x in list_vales_regex]

df = df[df['Groups'].isin(L[0].index[np.logical_and.reduce(L)])]
print (df)
  Groups   Names
0     G1   ABC_9
1     G1   ZTY_2
2     G1   SGG56
3     G1   BBCHU
4     G1  DEFE_8
7     G3   ABC_6
8     G3   DEF98
9     G3   DEF89
</code>```

Details:

```<code>print (np.logical_and.reduce(L))
[ True False  True False False]

print (L[0].index[np.logical_and.reduce(L)])
Index(['G1', 'G3'], dtype='object', name='Groups')
</code>```

Body:
hello I have a df such as

list_vales_regex=['ABC',DEF']
Groups Names
G1 ABC_9
G1 ZTY_2
G1 SGG56
G1 BBCHU
G1 DEFE_8
G2 ABC_6
G2 GGDY
G3 ABC_6
G3 DEF98
G3 DEF89
G4 DEF_09
G4 DGE7
G5 DGGE22
G5 DGGE23

and I would like to keep only groups that do contain both (ABC and DEF Names)

Here in the exemple only G1 and G3 have ot be kept.
Does someone have an idea ?

Body:
First get values by list to helper Series by Series.str.extract with | for join values for regex or and then compare values converted to sets per groups in GroupBy.transform:

list_vales_regex=['ABC','DEF']

s = df['Names'].str.extract(f'({"|".join(list_vales_regex)})', expand=False)
df = df[s.groupby(df['Groups']).transform(lambda x: set(x) >= set(list_vales_regex))]
print (df)
  Groups   Names
0     G1   ABC_9
1     G1   ZTY_2
2     G1   SGG56
3     G1   BBCHU
4     G1  DEFE_8
7     G3   ABC_6
8     G3   DEF98
9     G3   DEF89

Or filter by GroupBy.transform with DataFrameGroupBy.nunique (if not large data, because slowier):

df = df[s.groupby(df['Groups']).transform('nunique').ge(2)]

Another approach is find groups with matched all values of list in list comprehension with np.logical_and.reduce for test if match at least one value by Series.any, then filter groups by first value of list by L[0] and pass to Series.isin:

list_vales_regex=['ABC','DEF']

L = [df.set_index('Groups')['Names'].str.contains(x).any(level=0) for x in list_vales_regex]

df = df[df['Groups'].isin(L[0].index[np.logical_and.reduce(L)])]
print (df)
  Groups   Names
0     G1   ABC_9
1     G1   ZTY_2
2     G1   SGG56
3     G1   BBCHU
4     G1  DEFE_8
7     G3   ABC_6
8     G3   DEF98
9     G3   DEF89

Details:

print (np.logical_and.reduce(L))
[ True False  True False False]

print (L[0].index[np.logical_and.reduce(L)])
Index(['G1', 'G3'], dtype='object', name='Groups')


问:
How to use IEnumerable function in shared class accross project
I have a common IEnumerable function that I need to use in every controller on my asp,net web mvc application. I have created a SharedClass folder and a public class CommonMethods.

```<code>using System.Collections.Generic; using System.Web.Mvc;
namespace LearnWeb.SharedClass
{
public class CommonMethods
{
    public IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
    {
        // Create an empty list to hold result of the operation
        var selectList = new List<SelectListItem>();

        // For each string in the 'elements' variable, create a new SelectListItem object
        // that has both its Value and Text properties set to a particular value.
        // This will result in MVC rendering each item as:
        //     <option value="State Name">State Name</option>
        foreach (var element in elements)
        {
            selectList.Add(new SelectListItem
            {
                Value = element,
                Text = element
            });
        }
        return selectList;
    }
}
}
</code>```

I have a controller class StockController and I want to use the above common Method inside it. But I'm not able to reference it correctly. Please guide.

```<code>using System.Collections.Generic;
using System.Web.Mvc;
using LearnWeb.Models;
using LearnWeb.SharedClass.CommonMethods;

namespace LearnWeb.Controllers
{
public class StockController : Controller
{
/ GET: Stock
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult NewStock()
    {
        ViewBag.Message = "Enter new stock details.";
        var model = new StockModel();
        model.items = GetSelectListItems(items); //trying to call the commonMethods.GetSelectListItems
        return View(model);
    }
 }
</code>```

I have declared both the class and the function as public and added reference but not able to link in the controller class.

Regards,
NewB

答:
Firstly, the using statement should be:

```<code>namespace LearnWeb.SharedClass;
</code>```

Just the namespace.  Note that I find the name a bit disingenuous as a namespace should not really contain the word class.  Anyway, that aside, your CommonMethods class should be marked as static:

```<code>public static class CommonMethods
</code>```

And the method itself should be marked as static:

```<code>public static IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
</code>```

You can then call it like this in your code:

```<code>model.items = CommonMethods.GetSelectListItems(items);
</code>```

Body:
I have a common IEnumerable function that I need to use in every controller on my asp,net web mvc application. I have created a SharedClass folder and a public class CommonMethods.

using System.Collections.Generic; using System.Web.Mvc;
namespace LearnWeb.SharedClass
{
public class CommonMethods
{
    public IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
    {
        // Create an empty list to hold result of the operation
        var selectList = new List<SelectListItem>();

        // For each string in the 'elements' variable, create a new SelectListItem object
        // that has both its Value and Text properties set to a particular value.
        // This will result in MVC rendering each item as:
        //     <option value="State Name">State Name</option>
        foreach (var element in elements)
        {
            selectList.Add(new SelectListItem
            {
                Value = element,
                Text = element
            });
        }
        return selectList;
    }
}
}

I have a controller class StockController and I want to use the above common Method inside it. But I'm not able to reference it correctly. Please guide.

using System.Collections.Generic;
using System.Web.Mvc;
using LearnWeb.Models;
using LearnWeb.SharedClass.CommonMethods;

namespace LearnWeb.Controllers
{
public class StockController : Controller
{
/ GET: Stock
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult NewStock()
    {
        ViewBag.Message = "Enter new stock details.";
        var model = new StockModel();
        model.items = GetSelectListItems(items); //trying to call the commonMethods.GetSelectListItems
        return View(model);
    }
 }

I have declared both the class and the function as public and added reference but not able to link in the controller class.

Regards,
NewB

Body:
Firstly, the using statement should be:

namespace LearnWeb.SharedClass;

Just the namespace.  Note that I find the name a bit disingenuous as a namespace should not really contain the word class.  Anyway, that aside, your CommonMethods class should be marked as static:

public static class CommonMethods

And the method itself should be marked as static:

public static IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)

You can then call it like this in your code:

model.items = CommonMethods.GetSelectListItems(items);


问:
Cannot add 'pandas_profiling' into SQL Server using sqlmlutils
I was trying to install some module (i.e. pandas_profiling) in SQL Server so I can run the script directly from there. I was utilizing a Microsoft tool called 'sqlmlutils' to achieve this, but it returned an error specifically when I tried to install pandas_profiling (in fact another library called 'text-tools' was successfully installed. Here is the Python script to install the module to SQL Server:

```<code>import sqlmlutils
connection = sqlmlutils.ConnectionInfo(server="localhost", database="SQLAI")
sqlmlutils.SQLPackageManager(connection).install("pandas-profiling")
</code>```

Here is the traceback:

```<code>Traceback (most recent call last):

  File "<ipython-input-2-e8db1d445900>", line 1, in <module>
    runfile('C:/Users/BusinessUser/Desktop/abc.py', wdir='C:/Users/BusinessUser/Desktop')

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/BusinessUser/Desktop/abc.py", line 3, in <module>
    sqlmlutils.SQLPackageManager(connection).install("pandas_profiling")

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\sqlpackagemanager.py", line 74, in install
    self._install_from_pypi(package, upgrade, version, install_dependencies, scope, out_file=out_file)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\sqlpackagemanager.py", line 151, in _install_from_pypi
    self._install_from_file(target_package_file, scope, upgrade, out_file=out_file)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\sqlpackagemanager.py", line 171, in _install_from_file
    required_installs = resolver.get_required_installs(target_package_requirements)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\dependencyresolver.py", line 34, in get_required_installs
    self._server_packages, requirement.name, spec)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\dependencyresolver.py", line 60, in _check_if_installed_package_meets_spec
    return getattr(operator, operator_map[op_str])(LooseVersion(installed_version), LooseVersion(req_version))

  File "C:\Users\BusinessUser\Anaconda3\lib\distutils\version.py", line 46, in __eq__
    c = self._cmp(other)

  File "C:\Users\BusinessUser\Anaconda3\lib\distutils\version.py", line 337, in _cmp
    if self.version < other.version:

TypeError: '<' not supported between instances of 'int' and 'str'
</code>```

I just want to ask if anyone has ever gotten the same error. Any help is much appreciated!

答:
me too.

My solution is to uninstall and install it again.

Body:
I was trying to install some module (i.e. pandas_profiling) in SQL Server so I can run the script directly from there. I was utilizing a Microsoft tool called 'sqlmlutils' to achieve this, but it returned an error specifically when I tried to install pandas_profiling (in fact another library called 'text-tools' was successfully installed. Here is the Python script to install the module to SQL Server:

import sqlmlutils
connection = sqlmlutils.ConnectionInfo(server="localhost", database="SQLAI")
sqlmlutils.SQLPackageManager(connection).install("pandas-profiling")

Here is the traceback:

Traceback (most recent call last):

  File "<ipython-input-2-e8db1d445900>", line 1, in <module>
    runfile('C:/Users/BusinessUser/Desktop/abc.py', wdir='C:/Users/BusinessUser/Desktop')

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/BusinessUser/Desktop/abc.py", line 3, in <module>
    sqlmlutils.SQLPackageManager(connection).install("pandas_profiling")

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\sqlpackagemanager.py", line 74, in install
    self._install_from_pypi(package, upgrade, version, install_dependencies, scope, out_file=out_file)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\sqlpackagemanager.py", line 151, in _install_from_pypi
    self._install_from_file(target_package_file, scope, upgrade, out_file=out_file)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\sqlpackagemanager.py", line 171, in _install_from_file
    required_installs = resolver.get_required_installs(target_package_requirements)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\dependencyresolver.py", line 34, in get_required_installs
    self._server_packages, requirement.name, spec)

  File "C:\Users\BusinessUser\Anaconda3\lib\site-packages\sqlmlutils\packagemanagement\dependencyresolver.py", line 60, in _check_if_installed_package_meets_spec
    return getattr(operator, operator_map[op_str])(LooseVersion(installed_version), LooseVersion(req_version))

  File "C:\Users\BusinessUser\Anaconda3\lib\distutils\version.py", line 46, in __eq__
    c = self._cmp(other)

  File "C:\Users\BusinessUser\Anaconda3\lib\distutils\version.py", line 337, in _cmp
    if self.version < other.version:

TypeError: '<' not supported between instances of 'int' and 'str'

I just want to ask if anyone has ever gotten the same error. Any help is much appreciated!


问:
Karma - ChangeDetectorRef detectChanges mocking
I have an issue with cdr.detectChanges() in my test. I have an error happening when it's called and I don't have any information, I just get this error :

ZoneAwareError@webpack:///~/zone.js/dist/zone.js:923:0 <-
  config/karma-shim.js:108645:28
      invokeTask@webpack:///~/zone.js/dist/zone.js:398:0 <- config/karma-shim.js:108120:36
      onInvokeTask@webpack:///~/zone.js/dist/proxy.js:103:0 <- config/karma-shim.js:107642:49

Is there a way to make detectChanges work?

I also tried something else by trying to make detectChanges do nothing by defining cdr in my test component configuration like this :

```<code>cdr = {
  detectChanges: () => {}
}
</code>```

and then in the providers { provide: ChangeDetectorRef, useValue: cdr }, but when I console.info the cdr in the method tested it seems I still have the original cdr class.

I also tried with a fake class defined like this :

```<code>class FakeCDR {
  detectChanges(): void {

  }
}
</code>```

and then { provide: ChangeDetectorRef, useClass: FakeCDR } in the providers, but same here.

Here's my test code:

```<code>it('should create an user', fakeAsync(inject([MockBackend],
  (backend: MockBackend) => {
    fixture.detectChanges()
    tick()

    component.newUser = User.newUserDraft()
    component.newUser.email = "email@gmail.com"
    component.createUser()
    tick()

    expect(component.newUser.email).toBe(User.newUserDraft().email)
  })))
</code>```

and in createUser it's doing a service.createUser then do some stuff then cdr.detectChanges(). I did put console.info at every lines so I'm sure it's at the detectChanges that it fails.

答:
First some considerations:

ChangeDetectorRef is not provided through DI, so you cannot provide a double.

fixture.changeDetectorRef is not the same as the component provided, so you cannot use this.

fixture.debugElement.injector.get(ChangeDetectorRef) will create a new instance of the private class ViewRef (the public class ViewRef is just an alias for ViewRef$1), every time it is invoked, then the object provided to the component is another.

So my solution is:

```<code>const changeDetectorRef = fixture.debugElement.injector.get(ChangeDetectorRef);
const detectChangesSpy = spyOn(changeDetectorRef.constructor.prototype, 'detectChanges');
</code>```

Body:
I have an issue with cdr.detectChanges() in my test. I have an error happening when it's called and I don't have any information, I just get this error :

ZoneAwareError@webpack:///~/zone.js/dist/zone.js:923:0 <-
  config/karma-shim.js:108645:28
      invokeTask@webpack:///~/zone.js/dist/zone.js:398:0 <- config/karma-shim.js:108120:36
      onInvokeTask@webpack:///~/zone.js/dist/proxy.js:103:0 <- config/karma-shim.js:107642:49

Is there a way to make detectChanges work?

I also tried something else by trying to make detectChanges do nothing by defining cdr in my test component configuration like this :

cdr = {
  detectChanges: () => {}
}

and then in the providers { provide: ChangeDetectorRef, useValue: cdr }, but when I console.info the cdr in the method tested it seems I still have the original cdr class.

I also tried with a fake class defined like this :

class FakeCDR {
  detectChanges(): void {

  }
}

and then { provide: ChangeDetectorRef, useClass: FakeCDR } in the providers, but same here.

Here's my test code:

it('should create an user', fakeAsync(inject([MockBackend],
  (backend: MockBackend) => {
    fixture.detectChanges()
    tick()

    component.newUser = User.newUserDraft()
    component.newUser.email = "email@gmail.com"
    component.createUser()
    tick()

    expect(component.newUser.email).toBe(User.newUserDraft().email)
  })))

and in createUser it's doing a service.createUser then do some stuff then cdr.detectChanges(). I did put console.info at every lines so I'm sure it's at the detectChanges that it fails.

Body:
First some considerations:

ChangeDetectorRef is not provided through DI, so you cannot provide a double.

fixture.changeDetectorRef is not the same as the component provided, so you cannot use this.

fixture.debugElement.injector.get(ChangeDetectorRef) will create a new instance of the private class ViewRef (the public class ViewRef is just an alias for ViewRef$1), every time it is invoked, then the object provided to the component is another.

So my solution is:

const changeDetectorRef = fixture.debugElement.injector.get(ChangeDetectorRef);
const detectChangesSpy = spyOn(changeDetectorRef.constructor.prototype, 'detectChanges');


问:
Manually moving/rotating stuff at 30-60 fps using Core Graphics
I've a got a loop running at a separate thread updating the location and rotation of stuff, it runs at more than enough FPS and calls setNeedsDisplay on the main thread in the end. The problem is that the framework doesn't call drawRect enough times, on average i get 10 drawRect (FPS) calls per sec. I tried calling CATransaction flush but it seems to have no effect at all.

The drawing i'm doing is CGContextShowTextAtPoint. That's pretty much it, after rotating the context around and such. Is there any way for me to make it draw at a higher frequency? I wouldn't want to use openGL or cocos2d because the drawing code work pretty good.

答:
I would suggest setting up an NSTimer on the main thread to call drawRect every 1.0/30 or 1.0/60 seconds.

Maybe the code running on the separate thread is working the overall system too hard. Therefore the main thread doesn't get enough compute resources to update the view often enough. The "more than enough FPS" may be just wasted calculations if the extra frames of data are never shown. Can the separate thread pause after updating the location and rotation and wait for the main thread to update the view before calculating the next location and rotation? The NSTimer can send a message to the second thread to calculate the next frame's data.


问:
drag and drop feature in react
I am using React. I have to make draggable text field which can be resized and edited also. I have done this by using a draggable library and surrounding my text field with draggable component. So, this text field can be moved by user anywhere on the screen and he can edit it. This is similar to how we write text on ppts.

Now i want to also save this location of textfield on the screen in database, so that when user comes back to the webpage again, the textfield is displayed on its previous location with the entered details. I though of using x and y coordinates, but it will change with screen sizes, so i dont think it is efficient.

Is their any other way, like storing the DOM, or what concept is used by powerpoints to do this? I am using mongodb as database and nodejs as backend language.

Later on, i want to add additional features like, drag and drop image component, so that user can put images in it, add drag and drop buttons. Any idea will be highly appreciated.

答:
A possible solution to the problem could be that you store the x- and y-coordinates relative to a base size, e.g. 1920x1080, and then calculate which x- and y-coordinates should be displayed relative to the base size that you already set.

e.g.

```<code>let x = viewportWidth / baseWidth * dbX;
let y = viewportHeight / baseHeight * dbY;
</code>```

Title: drag and drop feature in react

Body:
A possible solution to the problem could be that you store the x- and y-coordinates relative to a base size, e.g. 1920x1080, and then calculate which x- and y-coordinates should be displayed relative to the base size that you already set.

e.g.

let x = viewportWidth / baseWidth * dbX;
let y = viewportHeight / baseHeight * dbY;


问:
React prop separation based on multiple Typescript interfaces
Is there a way in React to separate the props object based on an Typescript interface which extends multiple other interfaces? The other way I see, is to pass duplicate props to components that won't use them which is not the optimal solution.</p>

```<code>interface IProps extends IAProps, IBProps {}

const Component1: SFC<IProps> = (props) =>
   return (
     <Component2
         {...props} <--- only IAProps
     />
     <Component3
         {...props} <--- only IBProps
     />
  );
}
</code>```

答:
I think the simple approach of just passing two different props is a clean solution:</p>

```<code>interface IProps {
    a: IAProps;
    b: IBProps;
}

const Component1: SFC<IProps> = (props) =>
   return (
     <Component2
         {...props.a} <--- only IAProps
     />
     <Component3
         {...props.b} <--- only IBProps
     />
  );
}
</code>```

Body:
Is there a way in React to separate the props object based on an Typescript interface which extends multiple other interfaces? The other way I see, is to pass duplicate props to components that won't use them which is not the optimal solution.

interface IProps extends IAProps, IBProps {}

const Component1: SFC<IProps> = (props) =>
   return (
     <Component2
         {...props} <--- only IAProps
     />
     <Component3
         {...props} <--- only IBProps
     />
  );
}

Body:
I think the simple approach of just passing two different props is a clean solution:

interface IProps {
    a: IAProps;
    b: IBProps;
}

const Component1: SFC<IProps> = (props) =>
   return (
     <Component2
         {...props.a} <--- only IAProps
     />
     <Component3
         {...props.b} <--- only IBProps
     />
  );
}


问:
forward url with traefik v2 using docker
I want to forward url with traefik(version 2) like If I hit URL http://localhost/1 then it is forwarded to http://localhost:8081/1.

I have tried with several configuration but no one works. Please find below configuration I have done but it didn't worked.

```<code>version: "3.3"

services:
  traefik:
    image: "traefik:v2.0.0-rc3"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"
      - "8081:8081"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

  whoami:
    #image: "containous/whoami"
    #container_name: "simple-service"
    #command:
    #  - "--port=8081"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`localhost`)"
      - "traefik.http.routers.whoami.entrypoints=web"
      - "traefik.http.services.whoami.loadbalancer.server.port=8081"
</code>```

答:
I think you don't need to forward, since you have defined the loadbalancer port, add PathPrefix to your whoami routers rule should work.
Like this

```<code>- "traefik.http.routers.whoami.rule=Host(`localhost`) && PathPrefix(`/1`)"
</code>```

And if you do need forward requests, you can use middlewares.redirectregex.

```<code>- "traefik.http.routers.whoami.middlewares=whoami-redirectregex"
- "traefik.http.middlewares.whoami-redirectregex.redirectregex.regex=^http://localhost/(.*)"
- "traefik.http.middlewares.whoami-redirectregex.redirectregex.replacement=http://localhost:8081/$${1}"

</code>```

FYI. middleware docs

Body:
I want to forward url with traefik(version 2) like If I hit URL http://localhost/1 then it is forwarded to http://localhost:8081/1.

I have tried with several configuration but no one works. Please find below configuration I have done but it didn't worked.

version: "3.3"

services:
  traefik:
    image: "traefik:v2.0.0-rc3"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"
      - "8081:8081"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

  whoami:
    #image: "containous/whoami"
    #container_name: "simple-service"
    #command:
    #  - "--port=8081"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`localhost`)"
      - "traefik.http.routers.whoami.entrypoints=web"
      - "traefik.http.services.whoami.loadbalancer.server.port=8081"

Body:
I think you don't need to forward, since you have defined the loadbalancer port, add PathPrefix to your whoami routers rule should work.
Like this

- "traefik.http.routers.whoami.rule=Host(`localhost`) && PathPrefix(`/1`)"

And if you do need forward requests, you can use middlewares.redirectregex.

- "traefik.http.routers.whoami.middlewares=whoami-redirectregex"
- "traefik.http.middlewares.whoami-redirectregex.redirectregex.regex=^http://localhost/(.*)"
- "traefik.http.middlewares.whoami-redirectregex.redirectregex.replacement=http://localhost:8081/$${1}"

FYI. middleware docs


问:
Is a drag-over checkbox list useful?
A while ago I created a drag-over check box list which allows you to check many check boxes in a single gesture. Do you think it is viable and usable on the web where people might not know how to use it. The default behaviour still works for the individual check boxes.</p>

答:
The demo definitely needs a few enhancements to make it even a little bit useful (although I am not sure if it would be enough):

Allow the dragging to start somewhere that is not a check box.

Allow selection by dragging over the labels as well.

This problem seems similar to the action of selecting multiple files in a file explorer like Windows Explorer. Maybe it can work like the action of selecting multiple files by dragging a rectangle shape around the items to be selected (select one corner, drag to the other corner)? This has the advantage of being similar to an interface element that people may already be familiar with.

OwnerDisplayName: Jonathan Parker

Title: Is a drag-over checkbox list useful?

OwnerDisplayName: Angela


问:
How to access functions from different "Action" in QTP?
I have some code in Action1 item. I have added Action2 where I want to store some common function but if I call it from Action1, it does not work.
I just want to create some "global actions" that will be reusable.
Thanks</p>

答: May be having a "Function library" and have your functions defined there would be easier.</p>


问:
IndexedDB doesn't work with Android App for Microsoft Teams
I have developed a SharePoint WebPart that I'm using as app in Teams. From this WebPart I call an external site (http://xxxx/example.html) to store some data with indexedDB.

```<code> public async render() {
      this.domElement.innerHTML = `<iframe src="http://xxxx/example.html?token=xxxxxxxx"/>`;
 }
</code>```

If I try to use this app in Teams from Chrome, Firefox... and with the desktop app all works fine but I have discovered an error when I try to use the application with the android app for Teams.

What can I do to work with the indexedDB from the android app for Teams?

This is the code of the external site (http://xxxx/example.html) that I'm invoking from the WebPart:

If I try to use the app in the Android app for Teams I have the following error:

'It is necessary for the correct functioning of the app to allow access to IndexedDB.'

In other cases: Desktop App, using navigators... works fine. From my point of view is something relative to the way that the Android App handle the indexedDB.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example</title>
</head>
<body>

<script>

  var tableName = '_test';
  var key = 'a2B2MSmQa1';
  var mydb;
  var entry = getEntry();
  var stringEntry = JSON.stringify(entry);

  function getEntry() {
    // prepare authentication info
    var token = findGetParameter('token');
    var user = getUserFromJwt(token);
    console.log('Received request to log in with token: ' + token + ' and user: ' + user);

    return [{
      "AnyeP3Hy11": btoa(user),
      "bcdW7Sibfo": "",
      "AE1RLE62l3": true,
      "Tx22M4zx51": btoa(token),
      "1l2i483Zx5": false
    }];
  }

  function getUserFromJwt(token) {
    var payload = token.split('.')[1];
    var claims = JSON.parse(atob(payload));

    return claims.email;
  }

  function saveTokenDataWebSql() {
    mydb.transaction(function (t) {
      t.executeSql('select * from ' + tableName + ' where key = ?', [key], function (transaction, data) {
        if (!data.rows.length) {
          // if authentication info doesn't already exists -> create it it
          mydb.transaction(function (t) {
            t.executeSql('insert into ' + tableName + '(key, value) values (?, ?)', [key, stringEntry], goToApp);
            console.log('Inserted entry');
          });
        } else {
          // if authentication info already exists -> replace it
          mydb.transaction(function (t) {
            t.executeSql('update ' + tableName + ' set value = ? where key = ?', [stringEntry, key], goToApp);
            console.log('Updated entry');
          });
        }
      });
    });
  }

  function saveTokenDataIndexedDB(objectStore) {
    objectStore.count(key).onsuccess = function (event) {
      var count = event.target.result;
      if (count !== 0) {
        // if authentication info already exists -> remove it
        objectStore.delete(key).onsuccess = function () {
          // save auth info after deletion
          objectStore.put(entry, key);
        };
      } else {
        // save auth info directly
        objectStore.put(entry, key);
      }

    };
  }

  var indexedDBWay = function () {
    console.log('Using indexedDB option');

    var request = indexedDB.open('__mydb', 2);
    request.onerror = function (event) {
      alert('It is necessary for the correct functioning of the app to allow access to IndexedDB.');
    };
    request.onsuccess = function (event) {
      mydb = event.target.result;

      try {
        console.log('Database opened, checking existence of table');
        var objectStore = mydb.transaction([tableName], 'readwrite')
          .objectStore(tableName);

        console.log('Table exists. Proceeding to save data');
        saveTokenDataIndexedDB(objectStore);

        console.log('All done, going to app');
        goToApp();
      } catch (e) {
        console.log(e);
      }
    };
  };

  var openDatabaseWay = function () {
    console.log('Using openDatabase option');

    mydb = openDatabase('__mydb', '1', 'desc', 1024 * 1024);

    console.log('Database opened, checking existence of table');

    mydb.transaction(function (t) {
      t.executeSql('select * from ' + tableName, [], function (transaction, data) {
        if (data.rows) {
          console.log('Table exists. Proceeding to save data');
          saveTokenDataWebSql();
        } else {
          console.error('App DB not present, go back to app');
          goToApp();
        }
      }, function (t, e) {
        console.log('Error while opening database', e);
        console.log('Creating database');
        createWebSqlDbTable(t, tableName, function () {
          openDatabaseWay();
        }, function (t, e) {
          console.log('Error while creating database. All hope is lost.', e);
          goToApp();
        })
      });
    });
  };

  function createWebSqlDbTable(t, tableName, callback, errorCallback) {
    t.executeSql(
      'CREATE TABLE IF NOT EXISTS ' + tableName +
      '(id INTEGER PRIMARY KEY, key unique, value)',
      [],
      callback,
      errorCallback
    );
  }

  console.log('Trying to save token data');
  var debug = location.search.indexOf('debug') !== -1;
  if(debug){
    debugger;
  }
  if (window.openDatabase) {
    openDatabaseWay();
  } else if (window.indexedDB) {
    indexedDBWay();
  } else {
    console.error('Cannot open database, go back to app');
    goToApp();
  }

</script>

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

Could somebody give me any clue?

Regards!

答:
Android loads the app on a WebView. WebViews are not as powerful / feature rich as full blown browsers. It has to be seen if WebViews support indexDB at all.

https://caniuse.com/#search=indexDB. This says IndexDB is supported Chrome for Android 81+. You can check what chrome version shows up on the webview. This is again mobile dependent. (use chrome://inspect from laptop chrome browser while your mobile is debuggable and connected)

It could also be permissions. I am not sure though. I read this somewhere. To rule this out, can you try by manually providing storage permission to teams app to verify if it solves the issue?

If these does not help, most likely it is a WebView issue or Teams has to do something to enable indexDB, if it is supported by WebView.

Body:
I have developed a SharePoint WebPart that I'm using as app in Teams. From this WebPart I call an external site (http://xxxx/example.html) to store some data with indexedDB.

 public async render() {
      this.domElement.innerHTML = `<iframe src="http://xxxx/example.html?token=xxxxxxxx"/>`;
 }

If I try to use this app in Teams from Chrome, Firefox... and with the desktop app all works fine but I have discovered an error when I try to use the application with the android app for Teams.

What can I do to work with the indexedDB from the android app for Teams?

This is the code of the external site (http://xxxx/example.html) that I'm invoking from the WebPart:

If I try to use the app in the Android app for Teams I have the following error:

'It is necessary for the correct functioning of the app to allow access to IndexedDB.'

In other cases: Desktop App, using navigators... works fine. From my point of view is something relative to the way that the Android App handle the indexedDB.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Example</title>

Could somebody give me any clue?

Regards!


问:
bash - loop through subdirectories, cat files and rename with directory name
I have a folder structure like this ...

```<code>data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz
</code>```

I need to go in to each subdirectory (e.g. B1) and perform the following:

```<code>cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz
</code>```

I'm having problems with the file naming part. I can get in directories using the following:

```<code>for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done
</code>```

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

答:
Sure, just descend into the directory.

```<code># assuming PWD = data/
for d in */; do
   (
       cd "$d"
       cat *_1.gz > "$(basename "$d")"_1.gz
       cat *_2.gz > "$(basename "$d")"_2.gz
   )
done
</code>```

how do I strip the name to create the concatenated filename?

The simplest and most portable is with basename.

Body:
I have a folder structure like this ...

data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz

I need to go in to each subdirectory (e.g. B1) and perform the following:

cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz

I'm having problems with the file naming part. I can get in directories using the following:

for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

Body:
Sure, just descend into the directory.

# assuming PWD = data/
for d in */; do
   (
       cd "$d"
       cat *_1.gz > "$(basename "$d")"_1.gz
       cat *_2.gz > "$(basename "$d")"_2.gz
   )
done

how do I strip the name to create the concatenated filename?

The simplest and most portable is with basename.


问:
Haskell : Possible cause: ‘(:)’ is applied to too many arguments
I‘ve created a nested function which fails at the third nesting. I fail to understand why this pattern holds up for the previous two nests but not the third. I'm attempting to recursively work through the list to add the items in the list together

```<code>module Nests
(nest1,nest2,nest3) where

nest1 :: (Num a) => [a] -> [a] -> [a]
nest1 _ [] = []
nest1 [] _ = []
nest1 (xs:ls1) (xt:ls2) = (xs+xt):nest1 ls1 ls2

nest2 :: (Num a) => [[a]] -> [[a]] -> [[a]]
nest2 _ [] = []
nest2 [] _ = []
nest2 (xs:ls1) (xt:ls2) = (nest1 xs xt):nest2 ls1 ls2

nest3 :: (Num a) => [[[a]]] -> [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls)
    | length ls <= 0 = []
    | otherwise = (nest2 xs xt):nest3 ls
</code>```

where compiled:

```<code>nests.hs:17:19: error:
    • Couldn't match expected type ‘[[[a]]] -> [[[a]]]’
                  with actual type ‘[[[a]]]’
    • Possible cause: ‘(:)’ is applied to too many arguments
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls
   |                   ^^^^^^^^^^^^^^^^^^^^^^

nests.hs:17:33: error:
    • Couldn't match expected type ‘[[[a]]]’
                  with actual type ‘[[[a]]] -> [[[a]]]’
    • Probable cause: ‘nest3’ is applied to too few arguments
      In the second argument of ‘(:)’, namely ‘nest3 ls’
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls
</code>```

答:
Type annotation for nest3 does not match its body.

nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] means that function takes two arguments before returning list but in the function's body you take just one argument.

You can need to fix type signature (or just drop it, GHC is able to infer it):

```<code>nest3 :: (Num a) => [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls)
    | length ls <= 0 = []
    | otherwise = (nest2 xs xt):nest3 ls
</code>```

The problem here is that the first error seems not very relevant. The second one clearly states that nest3 expects one more argument.

```<code>• Couldn't match expected type ‘[[[a]]]’
              with actual type ‘[[[a]]] -> [[[a]]]’
• Probable cause: ‘nest3’ is applied to too few arguments
</code>```

But the first one suggest that (:) is used incorrectly.

```<code>• Couldn't match expected type ‘[[[a]]] -> [[[a]]]’
              with actual type ‘[[[a]]]’
• Possible cause: ‘(:)’ is applied to too many arguments
</code>```

To understand why there are two errors and why the first one is so obscure, consider how GHC works. It tries both to infer types and match inferred types with type annotations provided by the programmer.

Knowing that (:) :: b -> [b] -> [b] we can infer that nest3 ls must be of type [b] in the expression (..) : nest3 ls. Matching this with the provided type [[[a]]] -> [[[a]]] -> [[[a]]] gives the error ‘nest3’ is applied to too few arguments.

Trying to infer type of the otherwise branch in nest3 GHC considers again the type of (:). Applied to two arguments (:) gives a list. Matching this with the provided nest3 type gives ‘(:)’ is applied to too many arguments because only by removing one of the arguments we can get an arrow type.

Body:
I‘ve created a nested function which fails at the third nesting. I fail to understand why this pattern holds up for the previous two nests but not the third. I'm attempting to recursively work through the list to add the items in the list together

module Nests
(nest1,nest2,nest3) where

nest1 :: (Num a) => [a] -> [a] -> [a]
nest1 _ [] = []
nest1 [] _ = []
nest1 (xs:ls1) (xt:ls2) = (xs+xt):nest1 ls1 ls2

nest2 :: (Num a) => [[a]] -> [[a]] -> [[a]]
nest2 _ [] = []
nest2 [] _ = []
nest2 (xs:ls1) (xt:ls2) = (nest1 xs xt):nest2 ls1 ls2

nest3 :: (Num a) => [[[a]]] -> [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls)
    | length ls <= 0 = []
    | otherwise = (nest2 xs xt):nest3 ls

where compiled:

nests.hs:17:19: error:
    • Couldn't match expected type ‘[[[a]]] -> [[[a]]]’
                  with actual type ‘[[[a]]]’
    • Possible cause: ‘(:)’ is applied to too many arguments
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls
   |                   ^^^^^^^^^^^^^^^^^^^^^^

nests.hs:17:33: error:
    • Couldn't match expected type ‘[[[a]]]’
                  with actual type ‘[[[a]]] -> [[[a]]]’
    • Probable cause: ‘nest3’ is applied to too few arguments
      In the second argument of ‘(:)’, namely ‘nest3 ls’
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls

Body:
Type annotation for nest3 does not match its body.

nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] means that function takes two arguments before returning list but in the function's body you take just one argument.

You can need to fix type signature (or just drop it, GHC is able to infer it):

nest3 :: (Num a) => [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls)
    | length ls <= 0 = []
    | otherwise = (nest2 xs xt):nest3 ls

The problem here is that the first error seems not very relevant. The second one clearly states that nest3 expects one more argument.

• Couldn't match expected type ‘[[[a]]]’
              with actual type ‘[[[a]]] -> [[[a]]]’
• Probable cause: ‘nest3’ is applied to too few arguments

But the first one suggest that (:) is used incorrectly.

• Couldn't match expected type ‘[[[a]]] -> [[[a]]]’
              with actual type ‘[[[a]]]’
• Possible cause: ‘(:)’ is applied to too many arguments

To understand why there are two errors and why the first one is so obscure, consider how GHC works. It tries both to infer types and match inferred types with type annotations provided by the programmer.

Knowing that (:) :: b -> [b] -> [b] we can infer that nest3 ls must be of type [b] in the expression (..) : nest3 ls. Matching this with the provided type [[[a]]] -> [[[a]]] -> [[[a]]] gives the error ‘nest3’ is applied to too few arguments.

Trying to infer type of the otherwise branch in nest3 GHC considers again the type of (:). Applied to two arguments (:) gives a list. Matching this with the provided nest3 type gives ‘(:)’ is applied to too many arguments because only by removing one of the arguments we can get an arrow type.


问:
Break point is not getting Hit with IE8
I am Using visual studio 2005 and web browser IE8. On debugging the code opened in IE8 ,the
Breakpoints are not getting hit. Using IE6 I am able to debug. but i don't want to use IE6
so can you suggest any solution???</p>

答:
I got the answer here :-
Why can't I debug from Visual Studio 2005 after installing IE8?</p>

Title: Break point is not getting Hit with IE8


问:
How to display result in the same line
How should I do if I want those ProductName in the same line in view. I mean without new line for each product.

This kind of way I get them every name in new line, But I want them in the same line.

```<code><div class="col-md-12">

    @foreach (var item in Model)
    {
    <div class="col-md-1">
        @Html.ActionLink(item.ProductName, "PrName", "Products", new { Id = item.ProductId }, null)
    </div>
    }
</div>
</code>```

答:
Remove div tag inside your for loop.

```<code>  @foreach (var item in Model)
        {
            @Html.ActionLink(item.ProductName, "PrName", "Products", new { Id = item.ProductId }, null)
        }
</code>```

This works out.

Title: How to display result in the same line

Body:
How should I do if I want those ProductName in the same line in view. I mean without new line for each product.

This kind of way I get them every name in new line, But I want them in the same line.

    @foreach (var item in Model)
    {

        @Html.ActionLink(item.ProductName, "PrName", "Products", new { Id = item.ProductId }, null)

    }

Body:
Remove div tag inside your for loop.

  @foreach (var item in Model)
        {
            @Html.ActionLink(item.ProductName, "PrName", "Products", new { Id = item.ProductId }, null)
        }

This works out.


问:
Stopping a subprocess in python
I have several python scripts that run at the same time with the use of the subprocess library. However, i want to be able to stop all processes when an event happens, such as the press of a button. I have tried several things, but none of them seem to work.
I'm using Windows with Python 3.8.0

Below is my code that opens all of the processes.

```<code>import subprocess
subprocess.Popen("python Program1.py")
subprocess.Popen("python Program2.py")
subprocess.Popen("python Program3.py")
subprocess.Popen("python Program4.py")
subprocess.Popen("python Program5.py")
subprocess.Popen("python Program6.py")
subprocess.Popen("python Program7.py")
</code>```

I cant figure out how to end the processes with the subprocess library or any other ones.
I have also tried the following
proc1.kill()

p.terminate()

```<code>def pkill (process_name):
    try:
        killed = os.system('tskill ' + process_name)
    except Exception as e:
        killed = 0
    return killed
pkill("PROGRAM")
</code>```

And with the one above, i have tried putting except Exception, e: And also putting pkill("PROGRAM.py") but that doesnt seem to work either.

答:
You could keep track of the launched Process Ids:</p>

```<code>import os
import subprocess

processes = []
for x in range(0,9):
    p = subprocess.Popen("python Program.py %s" % x)
    processes.append(p.pid)  # keep the processIds!

for p in processes:
    os.system('taskkill /F /PID ' + p)
</code>```

Title: Stopping a subprocess in python

Body:
I have several python scripts that run at the same time with the use of the subprocess library. However, i want to be able to stop all processes when an event happens, such as the press of a button. I have tried several things, but none of them seem to work.
I'm using Windows with Python 3.8.0

Below is my code that opens all of the processes.

import subprocess
subprocess.Popen("python Program1.py")
subprocess.Popen("python Program2.py")
subprocess.Popen("python Program3.py")
subprocess.Popen("python Program4.py")
subprocess.Popen("python Program5.py")
subprocess.Popen("python Program6.py")
subprocess.Popen("python Program7.py")

I cant figure out how to end the processes with the subprocess library or any other ones.
I have also tried the following
proc1.kill()

p.terminate()

def pkill (process_name):
    try:
        killed = os.system('tskill ' + process_name)
    except Exception as e:
        killed = 0
    return killed
pkill("PROGRAM")

And with the one above, i have tried putting except Exception, e: And also putting pkill("PROGRAM.py") but that doesnt seem to work either.

Body:
You could keep track of the launched Process Ids:

import os
import subprocess

processes = []
for x in range(0,9):
    p = subprocess.Popen("python Program.py %s" % x)
    processes.append(p.pid)  # keep the processIds!

for p in processes:
    os.system('taskkill /F /PID ' + p)


问:
Javascript invalid label error
I am sorry if this question is a repeat of someother. I have looked into some of them but they don't answer my particular question.

I get an "invalid label" error where I am printing my alert statement in the code below:

```<code>    $(document).ready(
    function(){
        if( $('map#map').length > 0 ){
            //alert('found a map!');
            $('map#map area').each($area,
                function(i, val){
                    alert('Found: ' + val ):
                }
            );
        }
    }
);
</code>```

I get the same error is I do the following: alert('Found: ' + $(this) );

Can anyone tell me why this is happening, please?

ps: the elements I am attempting to read are as follows:

```<code><map id="map" name="imgmap20116293122">
<area alt="" coords="11,76,97,127" href="" shape="rect" target="" title="" />
<area alt="" coords="12,28,96,74" href="" shape="rect" target="" title="" />
<area alt="" coords="100,28,160,73" href="" shape="rect" target="" title="" />
<area alt="" coords="162,28,221,73" href="" shape="rect" target="" title="" />
<area alt="" coords="502,239,549,282" href="" shape="rect" target="" title="" />
<area alt="" coords="473,284,554,330" href="" shape="rect" target="" title="" /-->
</code>```

答:
You've got a : instead of a ; at the end of the line. Change

```<code>alert('Found: ' + val ):
</code>```

to

```<code>alert('Found: ' + val );
</code>```

See also label @ MDC docs.

Title: Javascript invalid label error

Body:
I am sorry if this question is a repeat of someother. I have looked into some of them but they don't answer my particular question.

I get an "invalid label" error where I am printing my alert statement in the code below:

    $(document).ready(
    function(){
        if( $('map#map').length > 0 ){
            //alert('found a map!');
            $('map#map area').each($area,
                function(i, val){
                    alert('Found: ' + val ):
                }
            );
        }
    }
);

I get the same error is I do the following: alert('Found: ' + $(this) );

Can anyone tell me why this is happening, please?

ps: the elements I am attempting to read are as follows:

<map id="map" name="imgmap20116293122">
<area alt="" coords="11,76,97,127" href="" shape="rect" target="" title="" />
<area alt="" coords="12,28,96,74" href="" shape="rect" target="" title="" />
<area alt="" coords="100,28,160,73" href="" shape="rect" target="" title="" />
<area alt="" coords="162,28,221,73" href="" shape="rect" target="" title="" />
<area alt="" coords="502,239,549,282" href="" shape="rect" target="" title="" />
<area alt="" coords="473,284,554,330" href="" shape="rect" target="" title="" /-->

Body:
You've got a : instead of a ; at the end of the line. Change

alert('Found: ' + val ):

to

alert('Found: ' + val );

See also label @ MDC docs.