问:
Edit several hundred Protocol Buffer serialized messages read from database
For an operation on my application, I need to read from database & then edit several hundred Protocol Buffer serialized messages. In each PB message, there are actually 4 int fields and one boolean field, and in the new message only the the boolean field is required to be changed.

I am in doubt what would be the best way to accomplish this, and thus seeking your help & expert opinion.

I guess building the entire messages once again by creating builder objects would be rather too much expensive..

答:
I suggest you redesign your database so that the field in the protocol buffer message that you want to modify, is in a separate database column. Therefore, instead of serializing the entire protocol buffers message in one column (which is what I presume you have now in your database) you would represent it in some other way. Then you can just use a simple SQL UPDATE command.

I mean, it makes little sense to use a database designed for relational data storage, to store serialized data that needs to be updated. It gets in the way of using SQL efficiently.

Alternatively, I don't know if there are databases specialised for working with protocol buffers, but there certainly are XML databases which are purportedly specialised for processing XML documents, so you could try converting your data to XML and using one of them. It's probably overkill for this one single problem though! But if you are going to have lots of little tasks like this to perform, it might be worthwhile.

However, without more details about what your application and/or database are used for, it's difficult to say what would be best.


来源: stackexchange

问:
Django: How to delete any foreign key object that is no longer referenced
I have nested data in my Django Rest Framework app, something like this:

```<code>class Student(models.Model):
    studyGroup = models.ForeignKey(StudyGroup, on_delete=models.SET_NULL,  blank=True, null=True, related_name='student')
</code>```

Each student may have a study group; a student may have no study group.

Many students can have the same study group.

I would like to automatically delete any StudyGroup that is not referenced by any students, either because the student was deleted or because it was updated.

I think this can be done by customising the 'save' and 'delete' methods for Student, checking whether their StudyGroup is referenced by any other Student, and deleting it if is not referenced. Or perhaps more elegantly by using signals. But it feels like there should be a simpler way to do this - like an inverse of  on_delete=models.CASCADE.

Is there a way to tell the database to do this automatically? Or do I need to write the custom code?

答:
You can remove the StudyGroup objects that are no longer referenced by a Student with the following query:

```<code>StudyGroup.objects.<b>filter(students__isnull=True).delete()</b></code>```

(this given the related_name= parameter [Django-doc] of your ForeignKey [Django-doc] is set to 'students', since this is the name of the relation in reverse).

Depending on the database backend, you could implement a trigger that can perform certain actions, for example when you remove/update an Student record. But that is backend-specific.

We can add a trigger to the Student model to remove the StudyGroups without a Student when we delete or save Students:

```<code># app/signals.py

from app.models import Student
from django.db.models.signals import <b>post_delete, post_save</b>
from django.dispatch import receiver

@receiver([post_delete, post_save], sender=Student)
def update_delete_student(sender, instance, **kwargs):
    StudyGroup.objects.filter(students__isnull=True).delete()</code>```

You will need to import the signals module in your application config:

```<code># app/app.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):

    # ...

    def ready(self):
        import app.signals</code>```

But there are ways to bypass the Django signals through the ORM. For examply by using QuerySet.update [Django-doc].

Therefore it might be useful to run the method periodically, for example each day/hour. We can use celery for that [realpython] or django-periodically [GitHub].

That being said, it might not be per se the most necessary to remove the StudyGroups anyway. If you for example want to retrieve a QuerySet of StudyGroups that have at least one student, we can write this like:

```<code># StudyGroups with at least one Student
StudyGroup.objects.filter(<b>student__isnull=False</b>)<b>.distinct()</b></code>```

So instead of removing the StudyGroups, you might decide not to show these StudyGroups, like a soft delete [wiktionary]. Then you can still recover the data later on, this of course depends on the use case.

Note: the related_name of a ForeignKey is the name of the relation in reverse, so the name of the attribute of a StudyGroup to retrieve the QuerySet of Students. Therefore naming this 'studyGroup' is a bit "weird". It would also easily result in collisions if there are two or more ForeignKeys that point to StudyGroup with the same name.

ContentLicense: CC BY-SA 4.0

Body:
I have nested data in my Django Rest Framework app, something like this:

class Student(models.Model):
    studyGroup = models.ForeignKey(StudyGroup, on_delete=models.SET_NULL,  blank=True, null=True, related_name='student')

Each student may have a study group; a student may have no study group.

Many students can have the same study group.

I would like to automatically delete any StudyGroup that is not referenced by any students, either because the student was deleted or because it was updated.

I think this can be done by customising the 'save' and 'delete' methods for Student, checking whether their StudyGroup is referenced by any other Student, and deleting it if is not referenced. Or perhaps more elegantly by using signals. But it feels like there should be a simpler way to do this - like an inverse of  on_delete=models.CASCADE.

Is there a way to tell the database to do this automatically? Or do I need to write the custom code?

Body:
You can remove the StudyGroup objects that are no longer referenced by a Student with the following query:

StudyGroup.objects.filter(students__isnull=True).delete()

(this given the related_name= parameter [Django-doc] of your ForeignKey [Django-doc] is set to 'students', since this is the name of the relation in reverse).

Depending on the database backend, you could implement a trigger that can perform certain actions, for example when you remove/update an Student record. But that is backend-specific.

We can add a trigger to the Student model to remove the StudyGroups without a Student when we delete or save Students:

# app/signals.py

from app.models import Student
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver

@receiver([post_delete, post_save], sender=Student)
def update_delete_student(sender, instance, **kwargs):
    StudyGroup.objects.filter(students__isnull=True).delete()

You will need to import the signals module in your application config:

# app/app.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):

    # ...

    def ready(self):
        import app.signals

But there are ways to bypass the Django signals through the ORM. For examply by using QuerySet.update [Django-doc].

Therefore it might be useful to run the method periodically, for example each day/hour. We can use celery for that [realpython] or django-periodically [GitHub].

That being said, it might not be per se the most necessary to remove the StudyGroups anyway. If you for example want to retrieve a QuerySet of StudyGroups that have at least one student, we can write this like:

# StudyGroups with at least one Student
StudyGroup.objects.filter(student__isnull=False).distinct()

So instead of removing the StudyGroups, you might decide not to show these StudyGroups, like a soft delete [wiktionary]. Then you can still recover the data later on, this of course depends on the use case.

Note: the related_name of a ForeignKey is the name of the relation in reverse, so the name of the attribute of a StudyGroup to retrieve the QuerySet of Students. Therefore naming this 'studyGroup' is a bit "weird". It would also easily result in collisions if there are two or more ForeignKeys that point to StudyGroup with the same name.


问:
Permission denied to drop objects
Running drop owned by <username>; gives me ERROR:  permission denied to drop objects. I can login/create/insert/update/alter etc fine.

Created the db and role like so:

sudo psql -U postgres

CREATE USER <username> WITH PASSWORD '<password>';

CREATE DATABASE <dbname> OWNER <username> ;

Looking up the problem, these are some of the things I ran that did not solve the issue:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO <username>;

GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO <username>;

GRANT ALL PRIVILEGES ON DATABASE <dbname> to <username>;

GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO <username>;

答: Only the owner, or a superuser, can drop an object. There is no privilege which allows dropping of an object, hence this is not something which can be granted to others.</p>

Title: Permission denied to drop objects


问:
Why is `operator[]' needed when 'operator double*` seems to do the job
operator[] seems superfluous since operator double* seems to be enough.

Here is my code:

struct CStandardData
{
  inline operator double* () { return m_standardData; }
  //inline double& operator [] (size_t ix) { return m_standardData[ix]; }
  size_t  m_standardDataRefCnt{ 0 };
  double m_standardData[1];
} sd;
```

I use sd in all kinds of different situations including double *a = sd, sd[x] = 5.0, sd[x] >= sd[y], etc.  and regardless whether I have the operator [] commented out or defined, the code seems to work correctly.

In what situations would it be necessary to have operator []?

I probably should have added a bit of context:

I used the internal data double sd[], which was dynamically allocated, throughout a large base of code >5000 lines.  Then I needed to add allocation reference counting to this double array, because of a need to copy the object it was in, and pass a copy to the user (the double sd[] is >10000 elements so I did not want extra copies made).  This is the scheme that I devised to do that without having to modify the vast base of code using it, but was not sure if omitting operator [] could lead to any problems.

答:
sd[x] = 5.0 does not have a context for compiler to apply implicit user-defined conversion of CStandardData to double * prior to invoking operator []. If such a conversion is performed explicitly then there will be no need for overloading operator []: static_cast<double *>(sd)[x]

Also overloading operator [] seems like a good idea anyway because it will allow you to verify that passed index is valid.

Body:
operator[] seems superfluous since operator double* seems to be enough.

Here is my code:

struct CStandardData
{
  inline operator double* () { return m_standardData; }
  //inline double& operator [] (size_t ix) { return m_standardData[ix]; }
  size_t  m_standardDataRefCnt{ 0 };
  double m_standardData[1];
} sd;

I use sd in all kinds of different situations including double *a = sd, sd[x] = 5.0, sd[x] >= sd[y], etc.  and regardless whether I have the operator [] commented out or defined, the code seems to work correctly.

In what situations would it be necessary to have operator []?

I probably should have added a bit of context:

I used the internal data double sd[], which was dynamically allocated, throughout a large base of code >5000 lines.  Then I needed to add allocation reference counting to this double array, because of a need to copy the object it was in, and pass a copy to the user (the double sd[] is >10000 elements so I did not want extra copies made).  This is the scheme that I devised to do that without having to modify the vast base of code using it, but was not sure if omitting operator [] could lead to any problems.


问:
Why are serialized numpy random_state objects different when are loaded?
I'm trying to figure out why certain cross-validations using a defined set of indices, the same input data, and the same random_state in sklearn gives different results using the same LogisticRegression model hyperparameters.  My first thought was that the initial random_state may be different on subsequent runs.  Then I realized when I pickle the random_state it says the objects are different when I compare the 2 objects directly but the values in the get_state method are the same.  Why is this?

```<code>random_state = np.random.RandomState(0)
print(random_state)
# <mtrand.RandomState object at 0x12424e480>

with open("./rs.pkl", "wb") as f:
    pickle.dump(random_state, f, protocol=pickle.HIGHEST_PROTOCOL)
with open("./rs.pkl", "rb") as f:
    random_state_copy = pickle.load(f)
    print(random_state_copy)
# <mtrand.RandomState object at 0x126465240>
print(random_state == random_state_copy)
# False
print(str(random_state.get_state()) == str(random_state_copy.get_state()))
# True
</code>```

Versions:

numpy= '1.13.3',

Python='3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]')

答:
The unpickled copy of initial random state in your example actually produces the same sequence of random numbers (tested on python 3.6, numpy 1.15.4).
Probably the equality testing is not implemented for RandomState as @jasonharper pointed out. == returns False, but the states are identical in behavior.

Following code fragment inserted after your code provided in question:

```<code>a = random_state.randint(0, 10, 5)
b = random_state_copy.randint(0, 10, 5)
print(a)
print(b)
print(a==b)
</code>```

Produces:

```<code>[5 0 3 3 7]
[5 0 3 3 7]
[ True  True  True  True  True]
</code>```

So, most likely, not the RandomState makes the run results different: look for causes of differences somewhere else.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to figure out why certain cross-validations using a defined set of indices, the same input data, and the same random_state in sklearn gives different results using the same LogisticRegression model hyperparameters.  My first thought was that the initial random_state may be different on subsequent runs.  Then I realized when I pickle the random_state it says the objects are different when I compare the 2 objects directly but the values in the get_state method are the same.  Why is this?

random_state = np.random.RandomState(0)
print(random_state)
# <mtrand.RandomState object at 0x12424e480>

with open("./rs.pkl", "wb") as f:
    pickle.dump(random_state, f, protocol=pickle.HIGHEST_PROTOCOL)
with open("./rs.pkl", "rb") as f:
    random_state_copy = pickle.load(f)
    print(random_state_copy)
# <mtrand.RandomState object at 0x126465240>
print(random_state == random_state_copy)
# False
print(str(random_state.get_state()) == str(random_state_copy.get_state()))
# True

Versions:

numpy= '1.13.3',

Python='3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]')

Body:
The unpickled copy of initial random state in your example actually produces the same sequence of random numbers (tested on python 3.6, numpy 1.15.4).
Probably the equality testing is not implemented for RandomState as @jasonharper pointed out. == returns False, but the states are identical in behavior.

Following code fragment inserted after your code provided in question:

a = random_state.randint(0, 10, 5)
b = random_state_copy.randint(0, 10, 5)
print(a)
print(b)
print(a==b)

Produces:

[5 0 3 3 7]
[5 0 3 3 7]
[ True  True  True  True  True]

So, most likely, not the RandomState makes the run results different: look for causes of differences somewhere else.


问:
I get 'django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint' when I try to publish a new post
--This is my first ever question on StackOverflow. So if I violate any community rules/standards, I apologize. Though there are similar questions around, no answer helped me solve the problem I am encountering. I would say I am not good enough a programmer to figure out the solution---

When I hit publish to add a new post, I get the following error

"django.db.utils.IntegrityError: null value in column "user_id"
  violates not-null constraint DETAIL:  Failing row contains (18, s, s,
  2019-05-26 15:39:10.466636+00, null)"

I have tried passing ....ForeignKey('auth.User') and ...ForeignKey(get_user_model() on Post model (not knowing how it could even be of help to my problem.

I migrated the database from sqlite to PostgreSQL and then checked the Post table on PgAdmin to see if user_id (previously named author_id) was there and it was.

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

from django.contrib.auth import get_user_model
User = get_user_model()

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    published_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"pk": self.pk})

    class Meta:
        ordering = ['-published_date']
        unique_together = ('user',)
</code>```

and the views file:

```<code>class CreatePostView(CreateView):
    model = Post
    template_name = 'blog/addpost.html'
    fields = ('title', 'text')
</code>```

Here's the traceback:

```<code>Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/blog/addpost

Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

The above exception (null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).
) was the direct cause of the following exception:

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
  142.             return self.form_valid(form)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in form_valid
  125.         self.object = form.save()

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\forms\models.py" in save
  458.             self.instance.save()

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /blog/addpost
Exception Value: null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).
</code>```

I had created mini-blogs using Django to practice class-based-views and gain more familiarity with coding and django environment. I had followed very similar steps but encountered no such error.

Edit:
Here's the addpost.html

```<code>{% extends "base.html" %}

{% block content %}
  <form action="{% url 'add-post' %}" method="POST">
    {% csrf_token %}
    <ul>
      <p>{{request.user}}</p>is adding a post:
      <li>
        <label for="title">Post Title</label>
        <input type="text" name="title" value="" required>
        <label for="text">Post text</label>
        <input type="text" name="text" value="">
        <button type="submit" name="button">Publish</button>
        <a href="{% url 'blog-view' %}">
          <button type="submit" name="button">Cancel & Go Back</button>
        </a>
      </li>
    </ul>
  </form>
{% endblock %}
</code>```

答:
It seems that you don't pass user to Post when try to create, but user is required field.
You can override form_valid method.

```<code>class CreatePostView(CreateView):
    model = Article
    template_name = 'blog/addpost.html'
    fields = ('title', 'text')

    def form_valid(self, form):
        form.instance.user= self.request.user
        return super(CreatePostView, self).form_valid(form)
</code>```

Body:
--This is my first ever question on StackOverflow. So if I violate any community rules/standards, I apologize. Though there are similar questions around, no answer helped me solve the problem I am encountering. I would say I am not good enough a programmer to figure out the solution---

When I hit publish to add a new post, I get the following error

"django.db.utils.IntegrityError: null value in column "user_id"
  violates not-null constraint DETAIL:  Failing row contains (18, s, s,
  2019-05-26 15:39:10.466636+00, null)"

I have tried passing ....ForeignKey('auth.User') and ...ForeignKey(get_user_model() on Post model (not knowing how it could even be of help to my problem.

I migrated the database from sqlite to PostgreSQL and then checked the Post table on PgAdmin to see if user_id (previously named author_id) was there and it was.

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

from django.contrib.auth import get_user_model
User = get_user_model()

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    published_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"pk": self.pk})

    class Meta:
        ordering = ['-published_date']
        unique_together = ('user',)

and the views file:

class CreatePostView(CreateView):
    model = Post
    template_name = 'blog/addpost.html'
    fields = ('title', 'text')

Here's the traceback:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/blog/addpost

Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

The above exception (null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).
) was the direct cause of the following exception:

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
  142.             return self.form_valid(form)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in form_valid
  125.         self.object = form.save()

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\forms\models.py" in save
  458.             self.instance.save()

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /blog/addpost
Exception Value: null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).

I had created mini-blogs using Django to practice class-based-views and gain more familiarity with coding and django environment. I had followed very similar steps but encountered no such error.

Edit:
Here's the addpost.html

{% extends "base.html" %}

{% block content %}
  <form action="{% url 'add-post' %}" method="POST">
    {% csrf_token %}

{{request.user}}
is adding a post:

        Post Title
        <input type="text" name="title" value="" required>
        Post text
        <input type="text" name="text" value="">
        <button type="submit" name="button">Publish</button>

          <button type="submit" name="button">Cancel & Go Back</button>

  </form>
{% endblock %}

Body:
It seems that you don't pass user to Post when try to create, but user is required field.
You can override form_valid method.

class CreatePostView(CreateView):
    model = Article
    template_name = 'blog/addpost.html'
    fields = ('title', 'text')

    def form_valid(self, form):
        form.instance.user= self.request.user
        return super(CreatePostView, self).form_valid(form)


问:
How to stop kubectl proxy
I executed below command:

```<code>kubectl proxy --port=8081 &
kubectl proxy --port=8082 &
</code>```

and of course I have 2 accessible endpoints:

```<code>curl http://localhost:8081/api/
curl http://localhost:8082/api/
</code>```

But in the same time two running processes serving the same content.
How to stop one of these processes in "kubectl" manner?
Of course, I can kill the process but it seems to be a less elegant way...

答:
Filter (grep) all "kube" pids and kill with loop:</p>

```<code>for pid in `netstat -tulp | grep kube | awk '{print $7}' | awk -F"/" '{print $1}'| uniq`
 do
   kill -9 $pid
 done
</code>```

Title: How to stop kubectl proxy

Body:
I executed below command:

kubectl proxy --port=8081 &
kubectl proxy --port=8082 &

and of course I have 2 accessible endpoints:

curl http://localhost:8081/api/
curl http://localhost:8082/api/

But in the same time two running processes serving the same content.
How to stop one of these processes in "kubectl" manner?
Of course, I can kill the process but it seems to be a less elegant way...

Body:
Filter (grep) all "kube" pids and kill with loop:

for pid in `netstat -tulp | grep kube | awk '{print $7}' | awk -F"/" '{print $1}'| uniq`
 do
   kill -9 $pid
 done


问:
Unneccesary new line php
I have a PHP code. The code is supposed to print the output followed by a new line.
The code works fine but i have unneccesary new line at the end. There should be only one newline at the end, but my code prints several new lines. What could be the issue? Please help.

```<code><?php
  /* Read input from STDIN. Print your output to STDOUT*/
  $fp = fopen("php://stdin", "r");
  //Write code here
  $loop = 0;
  $n = 0; $arr = [];
  while(!feof($fp)) {
    $arr = []; $n = 0;
    if($loop == 0) {
      $total = fgets($fp);
    }
    else {
      if($loop%2 == 1) {
        $n = fgets($fp);
      }
      else {
        $arr = fgets($fp);
      }
    }
    if($loop > 0 && $loop%2 == 0) {
      $arr = explode(" ", $arr);
      $m = [];
      for($i = 0; $i < 1<<10; $i++) {
        $m[$i] = -1;
      }
      $n = count($arr);

      $r = 0;
      for($i = 0; $i < 1<<10; $i++) {
        $r = max($r, fd_sum($i, $m, $arr, $n));
      }

      echo $r."\n";
    }

    $loop++;
  }
  fclose($fp);

?>

<?php
  function fd_sum($i, $m, $arr, $n) {
    if($i == 0) {
      return $m[$i] = 0;
    }
    else if($m[$i] != -1) {
      return $m[$i];
    }
    else {
        $rr = 0;
        for($j = 0; $j < $n; $j++) {
          $num = (int)$arr[$j];
          $b = save($num);
          if(($i | $b) == $i) {
              $z = $i^save($num);
              $y = fd_sum($z, $m, $arr, $n);
              $v = ($y + $num);
            $rr = max($v, $rr);
          }

        }
        return $m[$i] = $rr;
    }
  }
?>

<?php
  function save($nm)
  {
    $x = 0;
    for($i = 1; $nm/$i > 0; $i *= 10) {
      $d = ($nm/$i) % 10;
      $x = $x | (1 << $d);
    }
    return $x-1;
  }

?>
</code>```

My input is

```<code>3
4
3 5 7 2
5
121 3 333 23 4
7
32 42 52 62 72 82 92
</code>```

My output is

```<code>17
458
92
-
-
-
-
</code>```

The expected output is

```<code>17
458
92
-
</code>```

Note : I have used '-' to indicate a new line

What am i doing wrong? Please help.

答:
The PHP interpreter is reading the new lines after the closing tags and just spitting it right back out as output. Removing the extra opening/closing tags should remove the extra new lines. </p>

<p>Also, php closing tags are not necessary and i recommend omitting them. </p>

```<code><?php
  /* Read input from STDIN. Print your output to STDOUT*/
  $fp = fopen("php://stdin", "r");
  //Write code here
  $loop = 0;
  $n = 0; $arr = [];
  while(!feof($fp)) {
    $arr = []; $n = 0;
    if($loop == 0) {
      $total = fgets($fp);
    }
    else {
      if($loop%2 == 1) {
        $n = fgets($fp);
      }
      else {
        $arr = fgets($fp);
      }
    }
    if($loop > 0 && $loop%2 == 0) {
      $arr = explode(" ", $arr);
      $m = [];
      for($i = 0; $i < 1<<10; $i++) {
        $m[$i] = -1;
      }
      $n = count($arr);

      $r = 0;
      for($i = 0; $i < 1<<10; $i++) {
        $r = max($r, fd_sum($i, $m, $arr, $n));
      }

      echo $r."\n";
    }

    $loop++;
  }
  fclose($fp);

  function fd_sum($i, $m, $arr, $n) {
    if($i == 0) {
      return $m[$i] = 0;
    }
    else if($m[$i] != -1) {
      return $m[$i];
    }
    else {
        $rr = 0;
        for($j = 0; $j < $n; $j++) {
          $num = (int)$arr[$j];
          $b = save($num);
          if(($i | $b) == $i) {
              $z = $i^save($num);
              $y = fd_sum($z, $m, $arr, $n);
              $v = ($y + $num);
            $rr = max($v, $rr);
          }

        }
        return $m[$i] = $rr;
    }
  }

  function save($nm)
  {
    $x = 0;
    for($i = 1; $nm/$i > 0; $i *= 10) {
      $d = ($nm/$i) % 10;
      $x = $x | (1 << $d);
    }
    return $x-1;
  }
</code>```

Title: Unneccesary new line php

Body:
I have a PHP code. The code is supposed to print the output followed by a new line.
The code works fine but i have unneccesary new line at the end. There should be only one newline at the end, but my code prints several new lines. What could be the issue? Please help.

<?php
  /* Read input from STDIN. Print your output to STDOUT*/
  $fp = fopen("php://stdin", "r");
  //Write code here
  $loop = 0;
  $n = 0; $arr = [];
  while(!feof($fp)) {
    $arr = []; $n = 0;
    if($loop == 0) {
      $total = fgets($fp);
    }
    else {
      if($loop%2 == 1) {
        $n = fgets($fp);
      }
      else {
        $arr = fgets($fp);
      }
    }
    if($loop > 0 && $loop%2 == 0) {
      $arr = explode(" ", $arr);
      $m = [];
      for($i = 0; $i < 1<<10; $i++) {
        $m[$i] = -1;
      }
      $n = count($arr);

      $r = 0;
      for($i = 0; $i < 1<<10; $i++) {
        $r = max($r, fd_sum($i, $m, $arr, $n));
      }

      echo $r."\n";
    }

    $loop++;
  }
  fclose($fp);

?>

<?php
  function fd_sum($i, $m, $arr, $n) {
    if($i == 0) {
      return $m[$i] = 0;
    }
    else if($m[$i] != -1) {
      return $m[$i];
    }
    else {
        $rr = 0;
        for($j = 0; $j < $n; $j++) {
          $num = (int)$arr[$j];
          $b = save($num);
          if(($i | $b) == $i) {
              $z = $i^save($num);
              $y = fd_sum($z, $m, $arr, $n);
              $v = ($y + $num);
            $rr = max($v, $rr);
          }

        }
        return $m[$i] = $rr;
    }
  }
?>

<?php
  function save($nm)
  {
    $x = 0;
    for($i = 1; $nm/$i > 0; $i *= 10) {
      $d = ($nm/$i) % 10;
      $x = $x | (1 << $d);
    }
    return $x-1;
  }

?>

My input is

3
4
3 5 7 2
5
121 3 333 23 4
7
32 42 52 62 72 82 92

My output is

17
458
92
-
-
-
-

The expected output is

17
458
92
-

Note : I have used '-' to indicate a new line

What am i doing wrong? Please help.

Body:
The PHP interpreter is reading the new lines after the closing tags and just spitting it right back out as output. Removing the extra opening/closing tags should remove the extra new lines.

Also, php closing tags are not necessary and i recommend omitting them.

<?php
  /* Read input from STDIN. Print your output to STDOUT*/
  $fp = fopen("php://stdin", "r");
  //Write code here
  $loop = 0;
  $n = 0; $arr = [];
  while(!feof($fp)) {
    $arr = []; $n = 0;
    if($loop == 0) {
      $total = fgets($fp);
    }
    else {
      if($loop%2 == 1) {
        $n = fgets($fp);
      }
      else {
        $arr = fgets($fp);
      }
    }
    if($loop > 0 && $loop%2 == 0) {
      $arr = explode(" ", $arr);
      $m = [];
      for($i = 0; $i < 1<<10; $i++) {
        $m[$i] = -1;
      }
      $n = count($arr);

      $r = 0;
      for($i = 0; $i < 1<<10; $i++) {
        $r = max($r, fd_sum($i, $m, $arr, $n));
      }

      echo $r."\n";
    }

    $loop++;
  }
  fclose($fp);

  function fd_sum($i, $m, $arr, $n) {
    if($i == 0) {
      return $m[$i] = 0;
    }
    else if($m[$i] != -1) {
      return $m[$i];
    }
    else {
        $rr = 0;
        for($j = 0; $j < $n; $j++) {
          $num = (int)$arr[$j];
          $b = save($num);
          if(($i | $b) == $i) {
              $z = $i^save($num);
              $y = fd_sum($z, $m, $arr, $n);
              $v = ($y + $num);
            $rr = max($v, $rr);
          }

        }
        return $m[$i] = $rr;
    }
  }

  function save($nm)
  {
    $x = 0;
    for($i = 1; $nm/$i > 0; $i *= 10) {
      $d = ($nm/$i) % 10;
      $x = $x | (1 << $d);
    }
    return $x-1;
  }


问:
Count number of occurencies of a given substring in a file, Kotlin
I have to write a function, which counts how many times does a substring occurs in the text and return a map (string - counts)

I tried to make it, using .contains, but it doesn't count multiple occurencies in a single word ("la" in "lalala"), and now I'm stuck with how to fix it.

```<code>fun countSubstrings(inputName: String, substrings: List<String>): Map<String, Int> {

    val map = mutableMapOf<String, Int>()
    var tempCounter = 0
    for (i in 0 until substrings.size) {

        for (line in File(inputName).readLines()) {

            for (word in line.split(" ")) {
                if (word.contains(substrings[i], true)) tempCounter++
            }
        }
        map.put(substrings[i], tempCounter)
        tempCounter = 0
    }
    return map
}
</code>```

So, i expect this function to count words, 2-3 char substrings and even 1 char substrings.

答:
I mean, there is StringUtils.html#countMatches which is part of Apache commons. </p>

```<code> StringUtils.countMatches(null, *)       = 0
 StringUtils.countMatches("", *)         = 0
 StringUtils.countMatches("abba", null)  = 0
 StringUtils.countMatches("abba", "")    = 0
 StringUtils.countMatches("abba", "a")   = 2
 StringUtils.countMatches("abba", "ab")  = 1
 StringUtils.countMatches("abba", "xxx") = 0
</code>```

Body:
I have to write a function, which counts how many times does a substring occurs in the text and return a map (string - counts)

I tried to make it, using .contains, but it doesn't count multiple occurencies in a single word ("la" in "lalala"), and now I'm stuck with how to fix it.

fun countSubstrings(inputName: String, substrings: List<String>): Map<String, Int> {

    val map = mutableMapOf<String, Int>()
    var tempCounter = 0
    for (i in 0 until substrings.size) {

        for (line in File(inputName).readLines()) {

            for (word in line.split(" ")) {
                if (word.contains(substrings[i], true)) tempCounter++
            }
        }
        map.put(substrings[i], tempCounter)
        tempCounter = 0
    }
    return map
}

So, i expect this function to count words, 2-3 char substrings and even 1 char substrings.

Body:
I mean, there is StringUtils.html#countMatches which is part of Apache commons.

 StringUtils.countMatches(null, *)       = 0
 StringUtils.countMatches("", *)         = 0
 StringUtils.countMatches("abba", null)  = 0
 StringUtils.countMatches("abba", "")    = 0
 StringUtils.countMatches("abba", "a")   = 2
 StringUtils.countMatches("abba", "ab")  = 1
 StringUtils.countMatches("abba", "xxx") = 0


问:
string argument in template specialization in C++
In the following code, why the 's' after the string "hello" in the last line is necessary in order to deduce the type of the argument? It is an explicit casting to a string in c++?</p>

```<code>#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <class T>
T addition(T const& a, T const& b){ return a + b;}

template <class T, size_t N>
T reduce(T const (&array)[N], T value = {}, T (*p)(T const&,T const&) = addition<T>)
{
  T res = value;
  for (int i = 0; i < N; i++) {
    res = p(res,array[i]);
  }
  return res;
}

double multiply(double const& lhs, double const& rhs)
{
    return lhs * rhs;
}

int main()
{
    double pi[]{0.0505, 0.0505, 0.0405};
    double factorial[]{1.0, 2.0, 3.0, 4.0, 5.0};
    string concat[]{" ", "world"};
    cout << reduce({1,2,3,4,5}) << endl;
    cout << reduce(pi, 3.0) << endl;
    cout << reduce(factorial, 1.0, multiply) << endl;
    cout << reduce(concat, "hello"s) << endl;
}
</code>```

答:
The s in "hello"s is the string literal operator. It returns a std::string, which means the call to reduce will match with the std::string array you are passing as the first argument.

Note that the example would not work if you had not written using namespace std; (which is not really a good idea to write).

Before C++14, you would typically write std::string("hello") instead. Even nowadays, some guidelines prefer to avoid the literals, because you have to first get access to them using using namespace and, as a single character, they may be hard to notice.

Body:
In the following code, why the 's' after the string "hello" in the last line is necessary in order to deduce the type of the argument? It is an explicit casting to a string in c++?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <class T>
T addition(T const& a, T const& b){ return a + b;}

template <class T, size_t N>
T reduce(T const (&array)[N], T value = {}, T (*p)(T const&,T const&) = addition<T>)
{
  T res = value;
  for (int i = 0; i < N; i++) {
    res = p(res,array[i]);
  }
  return res;
}

double multiply(double const& lhs, double const& rhs)
{
    return lhs * rhs;
}

int main()
{
    double pi[]{0.0505, 0.0505, 0.0405};
    double factorial[]{1.0, 2.0, 3.0, 4.0, 5.0};
    string concat[]{" ", "world"};
    cout << reduce({1,2,3,4,5}) << endl;
    cout << reduce(pi, 3.0) << endl;
    cout << reduce(factorial, 1.0, multiply) << endl;
    cout << reduce(concat, "hello"s) << endl;
}


问:
How to display my values in props array horizontally
In my React project I have to take an array from parent component and print it in child component(PrintHorizontal) horizontally.

I am using map function which renders my values vertically so I wrote join to combine array values but I am getting different value. Print is my child component

```<code>props.values=[
   {
    id:1,
    x:1
   },
   {
    id:1,
    x:1
   }
 ]

PrintHorizontal Component:
const PrintHorizontal = props => {
let list=props.values.map(value => {
    return <Print key={value.id} data={value.x} />
 });
return (
    <div>
        {list.join(' , ')}
    </div>
)
}

Print Component:
const Print = props => {
    return (
        <div>
            <Avatar>{props.data}</Avatar>  //Avatar is a component imported from materialUI
        </div>
    )
}
</code>```

I expect run values would be printed horizontally instead I am getting
[object Object],[object Object]

答:
Your Print component is wrapped inside div also it seems Avtar component add it's own div so you can simply return Avtar from print, and to parent div use display: flex to align them horizontally.

```<code>const PrintHorizontal = props => {
return (
    <div className="horizontal">
        { props.values.map(value => {
            <Print key={value.id} data={value.x} />
        })}
    </div>
)
}

const Print = props => {
    return (
            <Avatar>{props.data}</Avatar>  //Avatar is a component imported from materialUI
    )
}
</code>```

In your css file

```<code>.horizontal {
    display: flex;
    align-item: center;
}
</code>```

Body:
In my React project I have to take an array from parent component and print it in child component(PrintHorizontal) horizontally.

I am using map function which renders my values vertically so I wrote join to combine array values but I am getting different value. Print is my child component

props.values=[
   {
    id:1,
    x:1
   },
   {
    id:1,
    x:1
   }
 ]

PrintHorizontal Component:
const PrintHorizontal = props => {
let list=props.values.map(value => {
    return <Print key={value.id} data={value.x} />
 });
return (

        {list.join(' , ')}

)
}

Print Component:
const Print = props => {
    return (

            <Avatar>{props.data}</Avatar>  //Avatar is a component imported from materialUI

    )
}

I expect run values would be printed horizontally instead I am getting
[object Object],[object Object]

Body:
Your Print component is wrapped inside div also it seems Avtar component add it's own div so you can simply return Avtar from print, and to parent div use display: flex to align them horizontally.

const PrintHorizontal = props => {
return (
    <div className="horizontal">
        { props.values.map(value => {
            <Print key={value.id} data={value.x} />
        })}
    </div>
)
}

const Print = props => {
    return (
            <Avatar>{props.data}</Avatar>  //Avatar is a component imported from materialUI
    )
}

In your css file

.horizontal {
    display: flex;
    align-item: center;
}


问:
Conda-installed python3.6 sees a wrong version of conda-installed scikit-learn
Sadly, I always keep fighting with python environments. The current struggle is that my most recent python installed by anaconda does not see the most recent scikit-learn installed by anaconda.

Details:

```<code>23:11 victoria current$conda --version
conda 4.3.30
23:11 victoria current$source activate py36scikit
(py36scikit) 23:11 victoria current$which python
/home/.../opt/anaconda3-201611/envs/py36scikit/bin/python
(py36scikit) 23:11 victoria current$conda update scikit-learn
Fetching package metadata ...........
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /home/bojar/opt/anaconda3-201611/envs/py36scikit:
#
scikit-learn              0.21.1           py36hd81dba3_0
(py36scikit) 23:12 victoria current$python
Python 3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sklearn
>>> print (sklearn.__version__)
0.19.1
</code>```

Can someone please explain why the correct conda-installed python does not see the conda-installed scikit-learn 0.21.1 but some older version 0.19.1 from somewhere?

Update: the same issue even with a freshly installed conda 4.6.11-py37_0, a fresh conda environment which contains scikit-learn-0.21.1. The respective python from the environment still reports sklearn of 0.19.1.

答:
Works for me ...

It does very much sound like a collision with some other package.

Maybe finding out the exact path of the active sklearn module will help you:

```<code>import sklearn
print(sklearn.__file__)
</code>```

Body:
Sadly, I always keep fighting with python environments. The current struggle is that my most recent python installed by anaconda does not see the most recent scikit-learn installed by anaconda.

Details:

23:11 victoria current$conda --version
conda 4.3.30
23:11 victoria current$source activate py36scikit
(py36scikit) 23:11 victoria current$which python
/home/.../opt/anaconda3-201611/envs/py36scikit/bin/python
(py36scikit) 23:11 victoria current$conda update scikit-learn
Fetching package metadata ...........
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /home/bojar/opt/anaconda3-201611/envs/py36scikit:
#
scikit-learn              0.21.1           py36hd81dba3_0
(py36scikit) 23:12 victoria current$python
Python 3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sklearn
>>> print (sklearn.__version__)
0.19.1

Can someone please explain why the correct conda-installed python does not see the conda-installed scikit-learn 0.21.1 but some older version 0.19.1 from somewhere?

Update: the same issue even with a freshly installed conda 4.6.11-py37_0, a fresh conda environment which contains scikit-learn-0.21.1. The respective python from the environment still reports sklearn of 0.19.1.

Body:
Works for me ...

It does very much sound like a collision with some other package.

Maybe finding out the exact path of the active sklearn module will help you:

import sklearn
print(sklearn.__file__)


问:
What do you call a DLL that is placed on the same directory as the EXE?
I need a little help in terminology.

You can put an assembly in the GAC to "share" these assembly globally in the machine. What do you call if you put the assembly in the same directory where the executable is?

I have been calling it "side-by-side" because the EXE and the DLL is "side-by-side". I've done some reading and it seems that "side-by-side" stands for something else

EDIT: Are those DLLs called "Private assemblies"?

答:
Side-by-side refers to two versions of the same assembly (i.e. 1.0.0.0, 1.1.0.0) being installed in the GAC at the same time.

Whether in the GAC or in the same local directory as the main application EXE assembly, this DLL assembly would be known as a dependency of the main assembly.


问:
How can I generate a pdf from web URL with Symfony 4?
I try to generate a pdf from webURL with the snappy bundle:

```<code>class PagesController extends AbstractController
{
 /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request)
  {
    $snappy = $this->get("knp_snappy.pdf");
    $snappy->setOption("encoding","UTF-8");

    $filename = "mypdf";
    $webSiteURL = "http://www.stackoverflow.com";
    return new Response(
      $snappy->getOutput($webSiteURL),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
  }
</code>```

But when I try to open the pdf I get the error message:

Service "knp_snappy.pdf" not found: even though it exists in the app's
  container, the container inside "App\Controller\PagesController" is a
  smaller service locator that only knows about the "doctrine",
  "form.factory", "http_kernel", "parameter_bag", "request_stack",
  "router", "security.authorization_checker",
  "security.csrf.token_manager", "security.token_storage", "serializer",
  "session" and "twig" services. Try using dependency injection instead

This is my config/packages/knp_snappy.yaml file:

```<code>knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage
        options:    []
</code>```

One approach to solve this was, I tried to add use Knp\Component\Pager\PaginatorInterface; to my Controller, but then I get the error message:

Cannot determine controller argument for
  "App\Controller\PagesController::pdf()": the $paginator argument is
  type-hinted with the non-existent class or interface:
  "Knp\Component\Pager\PaginatorInterface".

Another approach to solve this was adding to my controller:

```<code>  public static function getSubscribedServices(): array
{
    $services = parent::getSubscribedServices();
    $services['fos_elastica.manager'] = RepositoryManagerInterface::class;
    $services['knp_paginator'] = PaginatorInterface::class;

    return $services;
}
</code>```

But then I get the error message:

The service "App\Controller\PagesController" has a dependency on a
  non-existent service "App\Controller\RepositoryManagerInterface".

答:
You can directly inject your dependencies into controller’s action like

```<code>use Knp\Snappy\Pdf;
class PagesController extends AbstractController
{
  /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request, Pdf $snappy)
  {
      $snappy->setOption("encoding","UTF-8");

      $filename = "mypdf";
      $webSiteURL = "http://www.stackoverflow.com";
      return new Response(
         $snappy->getOutput($webSiteURL),
      200,
      array(
         'Content-Type' => 'application/pdf',
         'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
   }
</code>```

Make sure service autowiring enabled in service.yml file
https://symfony.com/doc/current/service_container/autowiring.html#

Body:
I try to generate a pdf from webURL with the snappy bundle:

class PagesController extends AbstractController
{
 /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request)
  {
    $snappy = $this->get("knp_snappy.pdf");
    $snappy->setOption("encoding","UTF-8");

    $filename = "mypdf";
    $webSiteURL = "http://www.stackoverflow.com";
    return new Response(
      $snappy->getOutput($webSiteURL),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
  }

But when I try to open the pdf I get the error message:

Service "knp_snappy.pdf" not found: even though it exists in the app's
  container, the container inside "App\Controller\PagesController" is a
  smaller service locator that only knows about the "doctrine",
  "form.factory", "http_kernel", "parameter_bag", "request_stack",
  "router", "security.authorization_checker",
  "security.csrf.token_manager", "security.token_storage", "serializer",
  "session" and "twig" services. Try using dependency injection instead

This is my config/packages/knp_snappy.yaml file:

knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage
        options:    []

One approach to solve this was, I tried to add use Knp\Component\Pager\PaginatorInterface; to my Controller, but then I get the error message:

Cannot determine controller argument for
  "App\Controller\PagesController::pdf()": the $paginator argument is
  type-hinted with the non-existent class or interface:
  "Knp\Component\Pager\PaginatorInterface".

Another approach to solve this was adding to my controller:

  public static function getSubscribedServices(): array
{
    $services = parent::getSubscribedServices();
    $services['fos_elastica.manager'] = RepositoryManagerInterface::class;
    $services['knp_paginator'] = PaginatorInterface::class;

    return $services;
}

But then I get the error message:

The service "App\Controller\PagesController" has a dependency on a
  non-existent service "App\Controller\RepositoryManagerInterface".

Body:
You can directly inject your dependencies into controller’s action like

use Knp\Snappy\Pdf;
class PagesController extends AbstractController
{
  /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request, Pdf $snappy)
  {
      $snappy->setOption("encoding","UTF-8");

      $filename = "mypdf";
      $webSiteURL = "http://www.stackoverflow.com";
      return new Response(
         $snappy->getOutput($webSiteURL),
      200,
      array(
         'Content-Type' => 'application/pdf',
         'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
   }

Make sure service autowiring enabled in service.yml file
https://symfony.com/doc/current/service_container/autowiring.html#


问:
base64 decode and byte negotiate string
I have base64 encoded string sZCLmg== which is Note. What I am trying to do is to decode it with base64 and then use bytes negotiation to get string Note back.

```<code>import base64
encoded = 'sZCLmg==' #sZCLmg==  Note
data = base64.b64decode(encoded)
print data

mylist = []
mylist.append(data)
#print mylist[0][0]
bytes = mylist[0][0]
print (bytes ^ 0xFF)
</code>```

but I am getting error: ValueError: invalid literal for int() with base 10: '\xb1'
Any idea please what am I doing wrong to get original string Note?

答:
In Python2, iterating over the literal '\xb1\x90\x8b\x9a' produces strings, not bytes.

One solution would be to use a bytearray.

```<code>>>> ba = bytearray(data)
>>> ''.join(chr(x ^ 0xFF) for x in ba)
'Note'
</code>```

As @wovano points out in the comments, also it's possible to do this without using a bytearray, like this:

```<code>''.join(chr(ord(x) ^ 0xFF) for x in data)
</code>```

Title: base64 decode and byte negotiate string

Body:
I have base64 encoded string sZCLmg== which is Note. What I am trying to do is to decode it with base64 and then use bytes negotiation to get string Note back.

import base64
encoded = 'sZCLmg==' #sZCLmg==  Note
data = base64.b64decode(encoded)
print data

mylist = []
mylist.append(data)
#print mylist[0][0]
bytes = mylist[0][0]
print (bytes ^ 0xFF)

but I am getting error: ValueError: invalid literal for int() with base 10: '\xb1'
Any idea please what am I doing wrong to get original string Note?

Body:
In Python2, iterating over the literal '\xb1\x90\x8b\x9a' produces strings, not bytes.

One solution would be to use a bytearray.

>>> ba = bytearray(data)
>>> ''.join(chr(x ^ 0xFF) for x in ba)
'Note'

As @wovano points out in the comments, also it's possible to do this without using a bytearray, like this:

''.join(chr(ord(x) ^ 0xFF) for x in data)


问:
Errors in dynamic range in combobox
I have tried everything and looked trough forums but have not found a solution.

Tried all this versions that are commented out. Sometimes it would work but only if I have the "data" sheet open, but if I am on the Sheet1 it would show error and won't work.

```<code>Private Sub UserForm_Initialize()

    MultiPage1.Value = 0
    'Call ComboBox

     'Category = Worksheets("Sheet2").Range(Range("B1"), Range("B1").End(xlDown)).Address
     'ComboBox1.RowSource = Worksheets("data").Range(Range("A1"), Range("A1").End(xlDown)).Address
     'ComboBox2.RowSource = Sheet2.Range(Range("B1"), Range("B1").End(xlDown)).Address

     'Worksheets("data")

    ' Add array to combobox
    ComboBox1.List = Sheet2.Range("A1:A7").Value

    ' Set the first item in combobox
    'ComboBox1.ListIndex = 0
    'ComboBox2.ListIndex = 0

End Sub
</code>```

答:
Use something like this:

```<code>With Worksheets("data")
    ComboBox1.List = .Range(.Range("A1"), .Range("A1").End(xlDown)).Value
End With
</code>```

In your posted examples you have unqualified Range() references, which by default point to the ActiveSheet

Title: Errors in dynamic range in combobox

Body:
I have tried everything and looked trough forums but have not found a solution.

Tried all this versions that are commented out. Sometimes it would work but only if I have the "data" sheet open, but if I am on the Sheet1 it would show error and won't work.

Private Sub UserForm_Initialize()

    MultiPage1.Value = 0
    'Call ComboBox

     'Category = Worksheets("Sheet2").Range(Range("B1"), Range("B1").End(xlDown)).Address
     'ComboBox1.RowSource = Worksheets("data").Range(Range("A1"), Range("A1").End(xlDown)).Address
     'ComboBox2.RowSource = Sheet2.Range(Range("B1"), Range("B1").End(xlDown)).Address

     'Worksheets("data")

    ' Add array to combobox
    ComboBox1.List = Sheet2.Range("A1:A7").Value

    ' Set the first item in combobox
    'ComboBox1.ListIndex = 0
    'ComboBox2.ListIndex = 0

End Sub

Body:
Use something like this:

With Worksheets("data")
    ComboBox1.List = .Range(.Range("A1"), .Range("A1").End(xlDown)).Value
End With

In your posted examples you have unqualified Range() references, which by default point to the ActiveSheet


问:
I get the error message twice during validating a model attribute in rails
Kindly, I am trying to validate the length of a model attribute in rails 5, but when I check the validation in the console, I receive the validation message twice. for ex. this is the validation code in the model:

```<code>validates_length_of :title, minimum: 2, maximum: 100
</code>```

and when , I use the rails console, to create a new invalid record with nil title

```<code>message = Message.create(sender_id: 3)
</code>```

and when I try to get the error message using: message.errors.details, I get

```<code>{:title=>[{:error=>:too_short, :count=>2}, {:error=>:too_short, :count=>2}]}
</code>```

I noticed that issue during tests running using rspec. The test does not pass , rspec expects the error messages twice as displayed above.
any help please for what is causing this duplication in the error messages and how to avoid that.Thanks

答: I am sorry for that, I spent so many times solving that issue, and I found some silly mistake which helped getting that error messages duplicated. sorry again </p>

Body:
Kindly, I am trying to validate the length of a model attribute in rails 5, but when I check the validation in the console, I receive the validation message twice. for ex. this is the validation code in the model:

validates_length_of :title, minimum: 2, maximum: 100

and when , I use the rails console, to create a new invalid record with nil title

message = Message.create(sender_id: 3)

and when I try to get the error message using: message.errors.details, I get

{:title=>[{:error=>:too_short, :count=>2}, {:error=>:too_short, :count=>2}]}

I noticed that issue during tests running using rspec. The test does not pass , rspec expects the error messages twice as displayed above.
any help please for what is causing this duplication in the error messages and how to avoid that.Thanks


问:
Security for ASP.NET application
I am developing a .net based application which is for a financial institution and it has multiple roles so I am not using built in ROLE PROVIDER.

Now what i want is that when create user i just assign role and when user logs in with the assigned role he/she cannot open any form on which he/she has no rights.

How to come up with a role based security system for my application ? I would appreciate if someone can help me and guide me to come up with a strong and secure application.

Thanks

答:
Read the following article:

Introduction to Role-Based Security in .NET

Title: Security for ASP.NET application


问:
Ant design - How do i auto close select ("tags" or "multiple" mode) dropdown after each selection?
I'm using ant.design select component ("tags" or "multiple" mode) in a page, i want dropdown to be automatically closes after each selection. Now it remains open and i should click on other places in the page to close the dropdown list.

import { Select } from 'antd';

const { Option } = Select;

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select mode="multiple" placeholder="Select Countries" size="large" onChange={handleChange}>
    <Option value="country1">Country1</Option>
    <Option value="country2">Country2</Option>
    <Option value="country3">Country3</Option>
    <Option value="country4">Country4</Option>
    <Option value="country5">Country5</Option>
    <Option value="country6">Country6</Option>
</Select>,
  mountNode,
);
```

答:
From the docs:

```<code>import { Select } from 'antd';

const Option = Select.Option;

function handleChange( value ) {
  console.log( `selected ${value}` );
}

<Select defaultValue="lucy" style={ { width: 120 } } onChange={ handleChange }>
  <Option value="jack">Jack</Option>
  <Option value="lucy">Lucy</Option>
  <Option value="disabled" disabled>Disabled</Option>
  <Option value="Yiminghe">yiminghe</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } disabled>
  <Option value="lucy">Lucy</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } loading>
    <Option value="lucy">Lucy</Option>
</Select>
</code>```

Use it's own <Option>

More info: https://ant.design/components/select/

Body:
From the docs:

import { Select } from 'antd';

const Option = Select.Option;

function handleChange( value ) {
  console.log( `selected ${value}` );
}

<Select defaultValue="lucy" style={ { width: 120 } } onChange={ handleChange }>
  <Option value="jack">Jack</Option>
  <Option value="lucy">Lucy</Option>
  <Option value="disabled" disabled>Disabled</Option>
  <Option value="Yiminghe">yiminghe</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } disabled>
  <Option value="lucy">Lucy</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } loading>
    <Option value="lucy">Lucy</Option>
</Select>

Use it's own <Option>

More info: https://ant.design/components/select/


问:
jQuery doesn't load whole table
I have a website with a table where I would like to update data periodically.

I have a script:

```<code>   <script src="/js/jquery.min.js"></script>
   <script>
      $( document ).ready(function() {
       setTimeout( function results() {
         $('.results').load("results.php?RES=1");
         setTimeout(results, 120000);
       }, 0000);
    })
    </script>
</code>```

This runs when page is ready and then after every two minutes.

The response from results.php?RES=1 is following:

```<code>        <th colspan='7'>DS1</th>
<tr>

        <td>1</td>
        <td>02:02:48</td>
        <td>(1) Name</td>
        <td>TEAM</td>
        <td>ger</td>
        <td></td>
        <td></td>
                    </tr><tr>
        <td>2</td>
        <td>00:47:49</td>
        <td>(99) Name</td>
        <td>TEAM</td>
        <td>EST</td>
        <td></td>
        <td></td>
                    </tr>
</code>```

The output should be inserted into here:

```<code><div class="col col-md-5 px-5 pt-3" style="background-color:white;">
        <div class="row">
            <div class="col-12">
                <h1 class="py-3">RESULTS</h1>

<div class="table-responsive">
<table class="table table-sm table-striped" style="table-layout: fixed;">
  <thead>
  <tr>
    <th width="5%">Place</th>
    <th width="10%">Time</th>
    <th width="30%">Name</th>
    <th width="15%">Team</th>
    <th width="10%">Country</th>
    <th width="20%" colspan="2"></th>
  </tr>
  </thead>
  <tbody class="list results" id="results">
    ///***THE RESULTS SHOULD BE APPEAR HERE***///
                    </tbody>
</table>
</div>

            </div>
        </div>
    </div>
</code>```

Somehow only the last row of table appears. Why?

Thanks for helping :)

答: It started working by wrapping  element with

Title: jQuery doesn't load whole table

Body:
I have a website with a table where I would like to update data periodically.

I have a script:

This runs when page is ready and then after every two minutes.

The response from results.php?RES=1 is following:

        DS1

        1
        02:02:48
        (1) Name
        TEAM
        ger

        2
        00:47:49
        (99) Name
        TEAM
        EST

The output should be inserted into here:

RESULTS

    Place
    Time
    Name
    Team
    Country

    ///***THE RESULTS SHOULD BE APPEAR HERE***///

Somehow only the last row of table appears. Why?

Thanks for helping :)

Body: It started working by wrapping <th> element with <tr>


问:
how to incorporate ngif criteria
I am trying to only display data if they meet the cirteria of image.media_type === image. How do I add that inside this ngfor so only images are displayed?</p>

```<code><div *ngFor="let image of childPhotos">

    <div class="gallery openImageDialog" data-id={{image.url}} data-title={{image.title}}>
      <span id="myExplan" data-id={{image.explanation}}></span>
      <a href="#gardenImage" class="thumbnail" data-toggle="modal">
        <img class="img-responsive" src={{image.url}} alt={{image.title}}>
        <div class="hidden" data-title={{image.title}}></div>
      </a>
      <div class="desc">{{image.title}}</div>
    </div>

</div>
</code>```

答:
Certainly you can add it right after the ngFor loop with the div</p>

```<code><div *ngFor="let image of childPhotos">
    <div *ngIf="image.media_type === 'image'" class="gallery openImageDialog" data-id={{image.url}} data-title={{image.title}}>
      <span id="myExplan" data-id={{image.explanation}}></span>
      <a href="#gardenImage" class="thumbnail" data-toggle="modal">
        <img class="img-responsive" src={{image.url}} alt={{image.title}}>
        <div class="hidden" data-title={{image.title}}></div>
      </a>
      <div class="desc">{{image.title}}</div>
    </div>
</div>
</code>```

Title: how to incorporate ngif criteria

Body:
I am trying to only display data if they meet the cirteria of image.media_type === image. How do I add that inside this ngfor so only images are displayed?

{{image.title}}

Body:
Certainly you can add it right after the ngFor loop with the div

<div *ngFor="let image of childPhotos">
    <div *ngIf="image.media_type === 'image'" class="gallery openImageDialog" data-id={{image.url}} data-title={{image.title}}>
      <span id="myExplan" data-id={{image.explanation}}></span>
      <a href="#gardenImage" class="thumbnail" data-toggle="modal">
        <img class="img-responsive" src={{image.url}} alt={{image.title}}>
        <div class="hidden" data-title={{image.title}}></div>
      </a>
      <div class="desc">{{image.title}}</div>
    </div>
</div>


问:
How to retrieve 1 document from firebase/firestore collection based on date in dart/flutter?
Ofc, I know the basic way we retrieve a whole bunch of documents from a collection like so:

      stream: Firestore.instance
          .collection("collection_name")
          .orderBy("date", descending: true) // new entries first
          .snapshots(),
      builder: (context, snapshot) { ....
```

<p>This is fine when I'm displaying a whole bunch of data.</p>

<p>But I have situation where I need to do some calculations with the last added numbers, meaning I just need to get 1 document, so I what I do is sort data by date and limit by 1, then make the query for this one document like this</p>

<pre class="lang-sh prettyprint-override"><code>List<DocumentSnapshot> list;
    QuerySnapshot querySnapshots;
    if (await AuthHelper.checkIfUserIsLoggedIn()) {
      String userId = await AuthHelper.getUserID();
      querySnapshots = await Firestore.instance
          .collection("collection_name")
          .orderBy("date", descending: true) // new entries first, date is one the entries btw
          .limit(1)
          .getDocuments(); // Get Documents not as a stream
      list = querySnapshots.documents; // Make snapshots into a list
      return (list ?? null);
    } else {
      return null;
    }
</code>```

But is this the best way to do it ? When making this query aren't I getting the whole set of documents and discarding the rest ? Which means when this collections grows this is going get slower and slower ?

Is there a better way to retrieve the last added document ? So I can use it as list/array/map and not as stream ?

Thanks.

答: When you limit the query, you are only ever going to read that number of documents maximum.  It's not going to read the entire collection and discard the extras.

Body:
Ofc, I know the basic way we retrieve a whole bunch of documents from a collection like so:

      stream: Firestore.instance
          .collection("collection_name")
          .orderBy("date", descending: true) // new entries first
          .snapshots(),
      builder: (context, snapshot) { ....

This is fine when I'm displaying a whole bunch of data.

But I have situation where I need to do some calculations with the last added numbers, meaning I just need to get 1 document, so I what I do is sort data by date and limit by 1, then make the query for this one document like this

List<DocumentSnapshot> list;
    QuerySnapshot querySnapshots;
    if (await AuthHelper.checkIfUserIsLoggedIn()) {
      String userId = await AuthHelper.getUserID();
      querySnapshots = await Firestore.instance
          .collection("collection_name")
          .orderBy("date", descending: true) // new entries first, date is one the entries btw
          .limit(1)
          .getDocuments(); // Get Documents not as a stream
      list = querySnapshots.documents; // Make snapshots into a list
      return (list ?? null);
    } else {
      return null;
    }

But is this the best way to do it ? When making this query aren't I getting the whole set of documents and discarding the rest ? Which means when this collections grows this is going get slower and slower ?

Is there a better way to retrieve the last added document ? So I can use it as list/array/map and not as stream ?

Thanks.


问:
How to get http responses from multiple requests in the order they're recieved
In my application, there are roughly 15 threads that each send an http request to an api endpoint once every 15 seconds; meaning about 1 request a second. These threads should be running indefinitely and only need to be created once. I am unsure how to continuously receive the responses on the main thread so that they can be parsed and dealt with. In trying to research this problem I found several frameworks that look like they could help; ScheduledExecutorService, NIO, Grizzly, AHC. But, I'm paralyzed by the amount of options and am unsure of what to implement.

My main goal is, for each of the 15 requests, to have the request sent off on its own every 15 seconds and receive the response on the main thread as it comes in.

答: No special frameworks are required for such a simple task. Just create an instance of BlockingQueue (ArrayBlockingQueue looks like the best choice). Each network thread calls queue.put(response) and the main thread makes response=queue.take() in a loop.


问:
New nodejs app deployed on heroku app doesn't find my libs
I'm trying to deploy a node.js app on heroku (btw it is my first time that I do that).

The same module that works on dev doesn't on testing (as usuall I would like to say) because the directory is not found.

This is the impliceted piece of code:

```<code>const PersistanceManager = require( `@mainlib/PersistanceManager` );
</code>```

Where @mainlib is a variable into my package.json

```<code>    "@mainlib": "lib/"
</code>```

basically it is pointing to lib that is in the root directory.
I looked around but I found thousands of answer that didn't work for me.

答: We have this problem because we using a with backslash, that is good on Windows, instead of fowardslash that it is what heroku expects when you working on it.

Body:
I'm trying to deploy a node.js app on heroku (btw it is my first time that I do that).

The same module that works on dev doesn't on testing (as usuall I would like to say) because the directory is not found.

This is the impliceted piece of code:

const PersistanceManager = require( `@mainlib/PersistanceManager` );

Where @mainlib is a variable into my package.json

    "@mainlib": "lib/"

basically it is pointing to lib that is in the root directory.
I looked around but I found thousands of answer that didn't work for me.


问:
Add A City To An Existing Country In EF(Entity Framework)
Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

```<code>City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();
</code>```

What's wrong with this code?
I want to insert a city of for a country to database. "(vs2008sp1)"
The country already exist.

```<code>Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}
</code>```

definition is

```<code>City Table(Id int,FK_Country int,name nvarchar(50))
Country Table(Id int,name nvarchar(50))
</code>```

Id in City and Country table in Identity(Auto Increment)

Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

答:
I don't know what Country.CreateCountry(CountryId); does, but in any case you need to get the existing country from the database through the EF context.

That is, so that Entity Framework knows you want to use an existing country you need to "get" it through your dbContext and then assign it to the city. That way the Country entity will be "attached" and EF won't try to create a new one.

The reverse should work too: Get the country from the DB and add the City to the Country instead of the Country to the City.

Body:
Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();

What's wrong with this code?
I want to insert a city of for a country to database. "(vs2008sp1)"
The country already exist.

Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}

definition is

City Table(Id int,FK_Country int,name nvarchar(50))
Country Table(Id int,name nvarchar(50))

Id in City and Country table in Identity(Auto Increment)

Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.


问:
HTML5 video stops when CSS animation plays
I have a html video tag with autoplay:

```<code><container>
    <video src="./images/grid.mp4" preload autoplay loop muted></video>
</container>
</code>```

The autoplay actually works, but the video stops if the parent element has a CSS animation:

```<code>container {
    animation: RotateColor 7s ease infinite alternate-reverse;
}

@keyframes RotateColor {
    0% {
        transform: scale(1);
        filter: hue-rotate(0deg);
    }
    100% {
        transform: scale(1.02);
        filter: hue-rotate(130deg);
    }
}
</code>```

Is this intended behaviour? Can't I use CSS animations or filters on playing video?

The CSS animation DOES work when I use an animating GIF in the background, but I've read that an MP4 should have much better performance than a GIF.

Sideways related, playing this video with other html elements on top of it causes my laptop fans to spin like crazy, CPU goes to 90%... Is there a way to mitigate this? I am scaling a small video (640 * 480) up to 1440 * 900 in the background of the website. Is the scaling the problem?

答:
I tried with the same set of animations as posted by you and its working fine.

I think that the playsinline attribute (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-playsinline) may be required when resizing the video element and can help here if it's not working for you.

Body:
I have a html video tag with autoplay:

<container>
    <video src="./images/grid.mp4" preload autoplay loop muted></video>
</container>

The autoplay actually works, but the video stops if the parent element has a CSS animation:

container {
    animation: RotateColor 7s ease infinite alternate-reverse;
}

@keyframes RotateColor {
    0% {
        transform: scale(1);
        filter: hue-rotate(0deg);
    }
    100% {
        transform: scale(1.02);
        filter: hue-rotate(130deg);
    }
}

Is this intended behaviour? Can't I use CSS animations or filters on playing video?

The CSS animation DOES work when I use an animating GIF in the background, but I've read that an MP4 should have much better performance than a GIF.

Sideways related, playing this video with other html elements on top of it causes my laptop fans to spin like crazy, CPU goes to 90%... Is there a way to mitigate this? I am scaling a small video (640 * 480) up to 1440 * 900 in the background of the website. Is the scaling the problem?


问:
Equivalent Command for "members" in RHEL
I have requirement to check members of the group "wheel" periodically.

I see that 'members wheel' is expected to display the members of that group. However when i tried, it says command not found. I see no entries in the man page as well.

I am using RHEL - Linux Version 3.10 (Red Hat 4.8.5)

I know we can use awk and cat in combination to get these details from "/etc/group" file

But is there a straight forward or a better approach?

答:
This is an answered question from Linux admin.

In short the answer is:

I prefer to use the getent command ...

Since getent uses the same name service as the system, getent will show all information, including that gained from network information sources such as LDAP.

So for a group, you should use the following ...

```<code>getent group name_of_group
</code>```

where name_of_group is replaced with the group you want to look up.
Note that this only returns supplementary group memberships, it
doesn't include the users who have this group as their primary group.

There are a whole lot of other lookups that you can do ... passwd
being another useful one, which you'll need to list primary groups.

Body:
This is an answered question from Linux admin.

In short the answer is:

I prefer to use the getent command ...

Since getent uses the same name service as the system, getent will show all information, including that gained from network information sources such as LDAP.

So for a group, you should use the following ...

getent group name_of_group

where name_of_group is replaced with the group you want to look up.
Note that this only returns supplementary group memberships, it
doesn't include the users who have this group as their primary group.

There are a whole lot of other lookups that you can do ... passwd
being another useful one, which you'll need to list primary groups.


问:
Nested Panels / Toolbars in Sencha Touch
I'm trying to create a constant bottom toolbar, which controls a panel above it. Then the panel above it should have a toolbar of its own (at the top). I've attempted the below code, which almost works, but I can't see the html of the sub-page inner panels. I think it's because the panel isn't taking up the remaining height, but I don't know why.

Anyone have any ideas? Thanks!

```<code>Ext.setup({
    onReady: function() {

    // Sub-page sections
    var blah = {
        style: "background-color: #B22222; color:#FF0000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };
    var blah2 = {
        style: "background-color: #404040; color:#000000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };

    // Main portion of the page, which includes top toolbar and content
    var page1 = new Ext.TabPanel({
        dock: "bottom",
        layout: "card",
        items: [blah, blah2, blah],
        title: "one",
        flex: 1
    });

    // This is the outer panel with the bottom toolbar
    var wrapper = new Ext.Panel({
        fullscreen: true,
        items: page1,
        dockedItems: [
          {
            xtype: "toolbar",
            dock: "bottom",
            items: [
              {
                iconMask: true,
                iconCls: "download"
              },
              {
                iconMask: true,
                iconCls: "favorites"
              },
              {
                iconMask: true,
                iconCls: "search"
              },
              {
                iconMask: true,
                iconCls: "user"
              }
            ]
          }
        ]
      });
    }
});
</code>```

答:
take the

layout: "card",

out of the page1 TabPanel, and place it in the wrapper Panel instead

Body:
I'm trying to create a constant bottom toolbar, which controls a panel above it. Then the panel above it should have a toolbar of its own (at the top). I've attempted the below code, which almost works, but I can't see the html of the sub-page inner panels. I think it's because the panel isn't taking up the remaining height, but I don't know why.

Anyone have any ideas? Thanks!

Ext.setup({
    onReady: function() {

    // Sub-page sections
    var blah = {
        style: "background-color: #B22222; color:#FF0000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };
    var blah2 = {
        style: "background-color: #404040; color:#000000;",
        title: "one",
        html: "Why can't I see this html",
        layout:"fit",
        flex: 1
    };

    // Main portion of the page, which includes top toolbar and content
    var page1 = new Ext.TabPanel({
        dock: "bottom",
        layout: "card",
        items: [blah, blah2, blah],
        title: "one",
        flex: 1
    });

    // This is the outer panel with the bottom toolbar
    var wrapper = new Ext.Panel({
        fullscreen: true,
        items: page1,
        dockedItems: [
          {
            xtype: "toolbar",
            dock: "bottom",
            items: [
              {
                iconMask: true,
                iconCls: "download"
              },
              {
                iconMask: true,
                iconCls: "favorites"
              },
              {
                iconMask: true,
                iconCls: "search"
              },
              {
                iconMask: true,
                iconCls: "user"
              }
            ]
          }
        ]
      });
    }
});


问:
Why can't I create a multidimensional array of arrays?
My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.

In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].

Declaring string[][,] compiles with no problem but I can't initialize the variable:

```<code>string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors
</code>```

The following errors are generated for the second line:

```<code>CS1586  Array creation must have array size or array initializer
CS0178  Invalid rank specifier: expected ',' or ']' ModChess
CS0178  Invalid rank specifier: expected ',' or ']' ModChess
</code>```

I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.

答:
string[][,] multiArrayOfArrays; //No problemo

Here you just declare variable of specific type.

multiArrayOfArrays = new string[][8,8]; //Generates errors

And here you actually create new object of specific type. It generates errors because this is invalid syntax for multidimentional array initialization.

You need to specify size for first dimension [] and then initialize each element of that array with string[,].

Think of it as array of arrays:

string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[5][,];//create 5 elements of string[,] array
for (int i = 0; i < multiArrayOfArrays.Length; ++i)
{
    multiArrayOfArrays[i] = new string[8,8];//actually fill elements with string[8,8]
}
```

<p>or </p>

<pre class="lang-cs prettyprint-override"><code>string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][,]
{
    new string[8,8],
    new string[8,8],
    new string[8,8],
};
</code>```

Body:
My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.

In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].

Declaring string[][,] compiles with no problem but I can't initialize the variable:

string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors

The following errors are generated for the second line:

CS1586  Array creation must have array size or array initializer
CS0178  Invalid rank specifier: expected ',' or ']' ModChess
CS0178  Invalid rank specifier: expected ',' or ']' ModChess

I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.

Body:
string[][,] multiArrayOfArrays; //No problemo

Here you just declare variable of specific type.

multiArrayOfArrays = new string[][8,8]; //Generates errors

And here you actually create new object of specific type. It generates errors because this is invalid syntax for multidimentional array initialization.

You need to specify size for first dimension [] and then initialize each element of that array with string[,].

Think of it as array of arrays:

string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[5][,];//create 5 elements of string[,] array
for (int i = 0; i < multiArrayOfArrays.Length; ++i)
{
    multiArrayOfArrays[i] = new string[8,8];//actually fill elements with string[8,8]
}

or

string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][,]
{
    new string[8,8],
    new string[8,8],
    new string[8,8],
};


问:
Copy huge datasets between two Postgres servers
I want to copy huge datasets between two postgres servers. Specifically I want to:

copy some columns (not all) from two tables in source db server, to
a single table in destination db server.

rename those columns in destination table (as datasets are copies) as destination column name isn't same as origin column name (maybe I should say insert values in some_column_name in destination table).

I understand postgres_fdwcannot be used to achieve this task as it copies entire table to new one (not merging selected field to form a new table) and both origin and destination tables must be of matching column number.

My source db server is a remote I ssh, and the datasets to copy is about 5GB.

Any suggestion to achieve my task?

答:
Idea:

Have one server (the host) write into a staging table (example below).

When the host server writes to the staging table it sets the created_ts.

When the foreign server reads the data successfully, it sets the xchange_ts.

Using foreign data wrapper you may not need the xchange_err field but the idea of that is to report a failed import.

```<code>CREATE TABLE staging
( id          SERIAL PRIMARY KEY
, created_ts  TIMESTAMPTZ
, xchange_ts  TIMESTAMPTZ
, xchange_err TEXT DEFAULT NULL
, colA        type_datatype
, colB        type_datatype
);
</code>```

I actually haven't used the postgres_fdw but I imagine the foreign table would be defined something like this.

```<code>CREATE FOREIGN TABLE staging
( id          INTEGER PRIMARY KEY
, created_ts  TIMESTAMPTZ
, xchange_ts  TIMESTAMPTZ
, xchange_err TEXT DEFAULT NULL
, colA        type_datatype
, colB        type_datatype
)
SERVER <server_name>
OPTIONS (schema_name '<schema_name>', table_name 'staging');
</code>```

Body:
Idea:

Have one server (the host) write into a staging table (example below).

When the host server writes to the staging table it sets the created_ts.

When the foreign server reads the data successfully, it sets the xchange_ts.

Using foreign data wrapper you may not need the xchange_err field but the idea of that is to report a failed import.

CREATE TABLE staging
( id          SERIAL PRIMARY KEY
, created_ts  TIMESTAMPTZ
, xchange_ts  TIMESTAMPTZ
, xchange_err TEXT DEFAULT NULL
, colA        type_datatype
, colB        type_datatype
);

I actually haven't used the postgres_fdw but I imagine the foreign table would be defined something like this.

CREATE FOREIGN TABLE staging
( id          INTEGER PRIMARY KEY
, created_ts  TIMESTAMPTZ
, xchange_ts  TIMESTAMPTZ
, xchange_err TEXT DEFAULT NULL
, colA        type_datatype
, colB        type_datatype
)
SERVER <server_name>
OPTIONS (schema_name '<schema_name>', table_name 'staging');