问:
Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'
I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element.

However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue :

```<code>'WSGIRequest' object has no attribute 'session'
</code>```

This is the entire Traceback :

```<code>Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/Authentification/Login/

Django Version: 2.0
Python Version: 3.6.2
Installed Applications:
['Institution',
 'django.conf.urls',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrapform',
 'django_countries',
 'chartit',
 'Configurations',
 'Home',
 'Authentication',
 'Identity',
 'rest_framework',
 'Fiscal',
 'bootstrap4']
Installed Middleware:
[]

Traceback:

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login
  26.                 login(request, user)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login
  130.     if SESSION_KEY in request.session:

Exception Type: AttributeError at /Authentification/Login/
Exception Value: 'WSGIRequest' object has no attribute 'session'
</code>```

In my Authentification app :

```<code># views.py file
#-*- coding: utf-8 -*-

from django.contrib.auth import authenticate, login, logout
from .forms import ConnexionForm
from django.shortcuts import render, reverse, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import LoggedUsers

from API_GED import Logger

import datetime
from django.views.decorators.csrf import csrf_exempt,csrf_protect

@csrf_exempt
def Login(request):
    error = False

    if request.method == "POST":
        form = ConnexionForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)  # Nous vérifions si les données sont correctes
            if user:  # Si l'objet renvoyé n'est pas None
                login(request, user)

                response = redirect('Homepage')

                return response

            else: # sinon une erreur sera affichée
                error = True

    else:
        form = ConnexionForm()

    return render(request, 'Authentication_Homepage.html', locals())

def Logout(request):

    logout(request)

    return redirect(reverse('Choice'))

def ConnectedUsers(request) :

    logged_users = LoggedUsers.objects.all()
    print (logged_users)

    logged_users_number = LoggedUsers.objects.all().count()

    context = {
        "logged_users":logged_users,
        "logged_users_number":logged_users_number,
    }

    return render(request, "Authentication_LoggedUsers.html", context)
</code>```

An my models.py file :

```<code>from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out

# class UserProfile(models.Model):
#     user   = models.OneToOneField(User)
#     avatar = models.ImageField(upload_to='/images/')

class LoggedUsers(models.Model):
    user = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE)

    def __str__(self):
        return '{}{}{}'.format(self.user.first_name + " ",  self.user.last_name  + " (", self.user.username + ")")

def login_user(sender, request, user, **kwargs):
        LoggedUsers(user=user).save()

def logout_user(sender, request, user, **kwargs):
        try:
            u = LoggedUsers.objects.get(user=user)
            u.delete()
        except LoggedUsers.DoesNotExist:
            pass

user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)
</code>```

In my settings.py file, I have MIDDLEWARE_CLASSES :

```<code>MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.gzip.GZipMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'DatasystemsCORE.middleware.OnlineNowMiddleware',
]
</code>```

Any idea ?

EDIT :

I wrote MIDDLEWARE like this :

```<code>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',
]
</code>```

It seems to work !

答: So the MIDDLEWARE_CLASSES changed to MIDDLEWARE https://docs.djangoproject.com/en/2.0/topics/http/middleware/#activating-middleware

Body:
I upgraded my Django version from 1.11.5 to 2.0 and I'm trying to solve different deprecated element.

However, even if my CSS/bootstrap style sheet doesn't work, I don't overcome to log into my Django software. I have this issue :

'WSGIRequest' object has no attribute 'session'

This is the entire Traceback :

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/Authentification/Login/

Django Version: 2.0
Python Version: 3.6.2
Installed Applications:
['Institution',
 'django.conf.urls',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrapform',
 'django_countries',
 'chartit',
 'Configurations',
 'Home',
 'Authentication',
 'Identity',
 'rest_framework',
 'Fiscal',
 'bootstrap4']
Installed Middleware:
[]

Traceback:

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/Users/valentinjungbluth/Desktop/Django/DatasystemsCORE/DatasystemsCore/DatasystemsCORE/Authentication/views.py" in Login
  26.                 login(request, user)

File "/Users/valentinjungbluth/Desktop/DatasystemsCORE3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py" in login
  130.     if SESSION_KEY in request.session:

Exception Type: AttributeError at /Authentification/Login/
Exception Value: 'WSGIRequest' object has no attribute 'session'

In my Authentification app :

# views.py file
#-*- coding: utf-8 -*-

from django.contrib.auth import authenticate, login, logout
from .forms import ConnexionForm
from django.shortcuts import render, reverse, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import LoggedUsers

from API_GED import Logger

import datetime
from django.views.decorators.csrf import csrf_exempt,csrf_protect

@csrf_exempt
def Login(request):
    error = False

    if request.method == "POST":
        form = ConnexionForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)  # Nous vérifions si les données sont correctes
            if user:  # Si l'objet renvoyé n'est pas None
                login(request, user)

                response = redirect('Homepage')

                return response

            else: # sinon une erreur sera affichée
                error = True

    else:
        form = ConnexionForm()

    return render(request, 'Authentication_Homepage.html', locals())

def Logout(request):

    logout(request)

    return redirect(reverse('Choice'))

def ConnectedUsers(request) :

    logged_users = LoggedUsers.objects.all()
    print (logged_users)

    logged_users_number = LoggedUsers.objects.all().count()

    context = {
        "logged_users":logged_users,
        "logged_users_number":logged_users_number,
    }

    return render(request, "Authentication_LoggedUsers.html", context)

An my models.py file :

from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out

# class UserProfile(models.Model):
#     user   = models.OneToOneField(User)
#     avatar = models.ImageField(upload_to='/images/')

class LoggedUsers(models.Model):
    user = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE)

    def __str__(self):
        return '{}{}{}'.format(self.user.first_name + " ",  self.user.last_name  + " (", self.user.username + ")")

def login_user(sender, request, user, **kwargs):
        LoggedUsers(user=user).save()

def logout_user(sender, request, user, **kwargs):
        try:
            u = LoggedUsers.objects.get(user=user)
            u.delete()
        except LoggedUsers.DoesNotExist:
            pass

user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)

In my settings.py file, I have MIDDLEWARE_CLASSES :

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.gzip.GZipMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'DatasystemsCORE.middleware.OnlineNowMiddleware',
]

Any idea ?

EDIT :

I wrote MIDDLEWARE like this :

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',
]

It seems to work !


来源: stackexchange

问:
How do I connect a row with one another and order them alphabetically?
Please see the image first.

{image: https://i.hizliresim.com/8NRGrV.png}

I want to connect the rows TR and EN, so like yatırım >> invesment and I want them to go together wherever I put them and after that I want to list them alphabetically, just like dictionary. Is it possible? Thank you.

答:
Select all items (click one item in list and ctrl+a) and make table (insert>table). Make sure that my table has headers option checked. Now you can sort them alphabetically and all of them are connected so they change together. For sort you can use dropdown in headers.

Bütün objeleri seç. Tablo oluştur (ekle>tablo) tik işaretli olsun şuan türkçesini hatırlayamadım. Sonra nerden sıralamak istiyosan o başlıktaki açılır butona bas sırala de. Zaten tablo olduğu için hepsi artık birbirine bağlı en ve tr otomatik takip eder.

ContentLicense: CC BY-SA 3.0


问:
rails_admin.git installation problem or more general problem
i want to install this https://github.com/sferik/rails_admin
so i pasting those  2 in the gemfile

```<code>gem 'devise' # Devise must be required before RailsAdmin

gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'
</code>```

however when i bundle install, the second one alone seems to give this problem:

```<code>Fetching git://github.com/sferik/rails_admin.git
sh: git: command not found
An error has occurred in git when running `git clone "git://github.com/sferik/rails_admin.git" "/Library/Ruby/Gems/1.8/cache/bundler/git/rails_admin-76c2c78f1892a43807d922e810aef4edcddc12b7" --bare --no-hardlinks`. Cannot complete bundling.
</code>```

Any ideas?

答: It doesn't appear as if you have git installed. Please follow the GitHub guide for installing it on your operating system.</p>

ContentLicense: CC BY-SA 2.5

Body:
i want to install this https://github.com/sferik/rails_admin
so i pasting those  2 in the gemfile

gem 'devise' # Devise must be required before RailsAdmin

gem 'rails_admin', :git => 'git://github.com/sferik/rails_admin.git'

however when i bundle install, the second one alone seems to give this problem:

Fetching git://github.com/sferik/rails_admin.git
sh: git: command not found
An error has occurred in git when running `git clone "git://github.com/sferik/rails_admin.git" "/Library/Ruby/Gems/1.8/cache/bundler/git/rails_admin-76c2c78f1892a43807d922e810aef4edcddc12b7" --bare --no-hardlinks`. Cannot complete bundling.

Any ideas?


问:
Arraylist - Separate a string and put it into an array
I want to separate a string and put it into an array.

Example:

```<code>id = 12,32,544,877,136,987

arraylist: [0]-->12
           [1]-->32
           [2]--544
           [3]-->877
           [4]-->136
           [5]-->987
</code>```

How to do that?

答:
If your id var is a String, you can use the Split method:</p>

```<code>id.Split(',')
</code>```

Body:
I want to separate a string and put it into an array.

Example:

id = 12,32,544,877,136,987

arraylist: [0]-->12
           [1]-->32
           [2]--544
           [3]-->877
           [4]-->136
           [5]-->987

How to do that?

Body:
If your id var is a String, you can use the Split method:

id.Split(',')


问:
How do I get one value from a duplicate name?
Situation: I have a list of classes in a list view. It's working fine. I am able to retrieve the classes in a list like this:

```<code>English
Math
French
</code>```

This is the database of classes:

Now, when clicking on a list item, I want to show the section of that class, so when I click on the English list item, an alert dialog should show with the section of that class. I am able to do that like this:

```<code>listclasses.setLongClickable(true);

listclasses.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final String selectedFromList = (String) listclasses.getItemAtPosition(position);
        final DatabaseReference retrieve = FirebaseDatabase.getInstance().getReference().child("Class");
        retriev.orderByChild("Classname").equalTo(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot data: dataSnapshot.getChildren()){

                    String key=data.getKey();

                    DatabaseReference referes=FirebaseDatabase.getInstance().getReference().child("Class");
                    referes.orderByKey().equalTo(key).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            for(DataSnapshot datas: dataSnapshot.getChildren()){

                            String section=datas.child("section").getValue().toString();

                            LayoutInflater li = LayoutInflater.from(StudentSearchActivity.this); //inflate converts xml to a view object to use in code
                            View promptsView = li.inflate(R.layout.info, null); //two parameters, the xml and the root(null means the layout is a child of viewgroup

                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                    StudentSearchActivity.this); /*alertdialog.builder class,creates a builder for alert dialog, parameter is context */

                            alertDialogBuilder.setView(promptsView);
                            final TextView sections = (TextView) promptsView.findViewById(R.id.sections);
                            sections.setText(section);
                            alertDialogBuilder.setCancelable(true); //true can be canceled with back key
                            alertDialogBuilder.setPositiveButton("Ok",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                            AlertDialog alertDialog = alertDialogBuilder.create(); //creates alert dialog from builder
                            alertDialog.show();
                        }}
</code>```

Problem: When I have the same class name example English but each one is in a section, I get the section of both on long click of an item. Example:

Step 1: long click on English item.

Step 2: alert dialog with section:503 appears.

Step 3: on back pressed or on ok pressed, another alert dialog with section:402 appears.

So both sections are appearing on long click of one class since it's the same name, but this is wrong. Only the section of that English class should appear, then when clicking on the other English class, also the section of this English class should appear only. Can this be solved in Firebase?

I'm using addListenerForSingleValueEvent and also in the database it is Classname as in the code.

答:
It looks like you hardcoded the listclasses's value and then using the value to query one of the Class which is why you might get multiple children. It's because there are two childs which contains the same value for the classname based on your screenshot.

You have to attach a listener to the Class node and then populate the listclasses based on the database's value, and then set the OnClickListener or OnLongItemClickListener to each one of them that shows an AlertDialog with their own section value.

Here's the solution

```<code>// to store the class's value
List<Class> classes = new ArrayList<>();

// to retrieve the list of class from the database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Class");
ref.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Class class = dataSnapshot.getValue(Class.class);
        classes.add(class);

        ... add 'class.getClassName()' to the listclasses adapter
    }
});

// add the OnItemLongClickListener
listclasses.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView <<?>parent, View view, int position, long id) {
        Class selectedClass = classes.get(position);

        ... show an AlertDialog with the value of 'selectedClass.getSection()'
    }
});
</code>```

Body:
Situation: I have a list of classes in a list view. It's working fine. I am able to retrieve the classes in a list like this:

English
Math
French

This is the database of classes:

Now, when clicking on a list item, I want to show the section of that class, so when I click on the English list item, an alert dialog should show with the section of that class. I am able to do that like this:

listclasses.setLongClickable(true);

listclasses.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final String selectedFromList = (String) listclasses.getItemAtPosition(position);
        final DatabaseReference retrieve = FirebaseDatabase.getInstance().getReference().child("Class");
        retriev.orderByChild("Classname").equalTo(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot data: dataSnapshot.getChildren()){

                    String key=data.getKey();

                    DatabaseReference referes=FirebaseDatabase.getInstance().getReference().child("Class");
                    referes.orderByKey().equalTo(key).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            for(DataSnapshot datas: dataSnapshot.getChildren()){

                            String section=datas.child("section").getValue().toString();

                            LayoutInflater li = LayoutInflater.from(StudentSearchActivity.this); //inflate converts xml to a view object to use in code
                            View promptsView = li.inflate(R.layout.info, null); //two parameters, the xml and the root(null means the layout is a child of viewgroup

                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                    StudentSearchActivity.this); /*alertdialog.builder class,creates a builder for alert dialog, parameter is context */

                            alertDialogBuilder.setView(promptsView);
                            final TextView sections = (TextView) promptsView.findViewById(R.id.sections);
                            sections.setText(section);
                            alertDialogBuilder.setCancelable(true); //true can be canceled with back key
                            alertDialogBuilder.setPositiveButton("Ok",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                            AlertDialog alertDialog = alertDialogBuilder.create(); //creates alert dialog from builder
                            alertDialog.show();
                        }}

Problem: When I have the same class name example English but each one is in a section, I get the section of both on long click of an item. Example:

Step 1: long click on English item.

Step 2: alert dialog with section:503 appears.

Step 3: on back pressed or on ok pressed, another alert dialog with section:402 appears.

So both sections are appearing on long click of one class since it's the same name, but this is wrong. Only the section of that English class should appear, then when clicking on the other English class, also the section of this English class should appear only. Can this be solved in Firebase?

I'm using addListenerForSingleValueEvent and also in the database it is Classname as in the code.

Body:
It looks like you hardcoded the listclasses's value and then using the value to query one of the Class which is why you might get multiple children. It's because there are two childs which contains the same value for the classname based on your screenshot.

You have to attach a listener to the Class node and then populate the listclasses based on the database's value, and then set the OnClickListener or OnLongItemClickListener to each one of them that shows an AlertDialog with their own section value.

Here's the solution

// to store the class's value
List<Class> classes = new ArrayList<>();

// to retrieve the list of class from the database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Class");
ref.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Class class = dataSnapshot.getValue(Class.class);
        classes.add(class);

        ... add 'class.getClassName()' to the listclasses adapter
    }
});

// add the OnItemLongClickListener
listclasses.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView <<?>parent, View view, int position, long id) {
        Class selectedClass = classes.get(position);

        ... show an AlertDialog with the value of 'selectedClass.getSection()'
    }
});


答:
MIDDLEWARE_CLASSES has been deprecated since Django 1.10 and was removed completely in version 2.0. That means you have no middleware at all.

You should use the MIDDLEWARE setting instead; note, that uses new-style middleware, you might need to upgrade your custom middleware class.

Title: Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'


问:
Python3.6.2 on Windows10 "ImportError: cannot import name 'Flask'"
I'm trying run Flask in Windows 10. But i see error:

```<code>(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn> C:\Users\r.tjutin\Envs\HelloWorls\Scripts\python.exe C:/Users/r.tjutin/PycharmProjects/untitled/learn/flask.py
Traceback (most recent call last):
File "C:/Users/r.tjutin/PycharmProjects/untitled/learn/flask.py", line 2, in <module>
    from flask import Flask
File "C:\Users\r.tjutin\PycharmProjects\untitled\learn\flask.py", line 2, in <module>
    from flask import Flask
ImportError: cannot import name 'Flask'
(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn> pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
click (6.7)
Flask (0.12.2)
itsdangerous (0.24)
Jinja2 (2.10)
MarkupSafe (1.0)
pip (9.0.1)
setuptools (38.2.4)
Werkzeug (0.12.2)
wheel (0.30.0)
(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn>
(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn> python.exe --version
Python 3.6.2
</code>```

Please, help me, i'am tired search. I have used virtualenv to create a workspace, I have used my workspace through activate.bat, i have used powershell instead cmd, nothing worked.

答: name script flask.py is not good. But module name flask is import your script. Please rename script flask.py -> flask1.py for example and run it.</p>

Body:
I'm trying run Flask in Windows 10. But i see error:

(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn> C:\Users\r.tjutin\Envs\HelloWorls\Scripts\python.exe C:/Users/r.tjutin/PycharmProjects/untitled/learn/flask.py
Traceback (most recent call last):
File "C:/Users/r.tjutin/PycharmProjects/untitled/learn/flask.py", line 2, in <module>
    from flask import Flask
File "C:\Users\r.tjutin\PycharmProjects\untitled\learn\flask.py", line 2, in <module>
    from flask import Flask
ImportError: cannot import name 'Flask'
(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn> pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
click (6.7)
Flask (0.12.2)
itsdangerous (0.24)
Jinja2 (2.10)
MarkupSafe (1.0)
pip (9.0.1)
setuptools (38.2.4)
Werkzeug (0.12.2)
wheel (0.30.0)
(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn>
(HelloWorls) PS C:\Users\r.tjutin\PycharmProjects\untitled\learn> python.exe --version
Python 3.6.2

Please, help me, i'am tired search. I have used virtualenv to create a workspace, I have used my workspace through activate.bat, i have used powershell instead cmd, nothing worked.


问:
In JMeter and BeanShell, how can I make a variable lowercase?
In JMeter's User Parameters, how can I make a variable lowercase?

Left column

```<code>my_lowercase_variable
</code>```

Right column

```<code>${__BeanShell('${my_variable}'.toLowerCase())}  //fails
</code>```

or

```<code>${__javaScript('${my_variable}'.toLowerCase())}  //fails
</code>```

Such that ${my_lowercase_variable} is lowercase of ${my_variable}. Tried with quote and without and escaping and such. No luck. Any tricks or tips welcome.

答:
Note to self.

It turns out to be a two liner in BeanShell Sampler rather than a __BeanShell command.  Not exactly in the examples unfortunately.

I added the BeanShell Sampler under the Thread Group, then made a variable.  No parameters in the form were required only the two liner script below. As long as I don't change the variable I can copy the data to another variable, change that instead, and then make a Value reference to that wherever needed.

First define a variable in some User Parameters or such
ie:

```<code>Name: my_initial_reference
Value: ITS IN CAPS
</code>```

Add a Bean Sampler under the User Preferences or definition list (just next, it's not a child process)

Put in:

```<code>String blah = "${my_initial_reference}"; //
vars.put("blah", blah.toLowerCase());  //${blah} = "its in caps" now available
</code>```

Now under that with Name/Value pairs I can map ${blah} as the value to whatever process name requires it.

Note that the Debug response will still show the initial value in caps but you'll also see blah=its in caps which is what I wanted to use.

Body:
In JMeter's User Parameters, how can I make a variable lowercase?

Left column

my_lowercase_variable

Right column

${__BeanShell('${my_variable}'.toLowerCase())}  //fails

or

${__javaScript('${my_variable}'.toLowerCase())}  //fails

Such that ${my_lowercase_variable} is lowercase of ${my_variable}. Tried with quote and without and escaping and such. No luck. Any tricks or tips welcome.

Body:
Note to self.

It turns out to be a two liner in BeanShell Sampler rather than a __BeanShell command.  Not exactly in the examples unfortunately.

I added the BeanShell Sampler under the Thread Group, then made a variable.  No parameters in the form were required only the two liner script below. As long as I don't change the variable I can copy the data to another variable, change that instead, and then make a Value reference to that wherever needed.

First define a variable in some User Parameters or such
ie:

Name: my_initial_reference
Value: ITS IN CAPS

Add a Bean Sampler under the User Preferences or definition list (just next, it's not a child process)

Put in:

String blah = "${my_initial_reference}"; //
vars.put("blah", blah.toLowerCase());  //${blah} = "its in caps" now available

Now under that with Name/Value pairs I can map ${blah} as the value to whatever process name requires it.

Note that the Debug response will still show the initial value in caps but you'll also see blah=its in caps which is what I wanted to use.


问:
Android: NullPointerException on NetworkInfo.isConnected() with Firebase
Sometimes, on different mobiles (Android 7) there is this crash:

```<code>Fatal Exception: java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.google.firebase.iid.zzae@3c68978
       at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1178)
       at android.os.Handler.handleCallback(Handler.java:751)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6321)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.net.NetworkInfo.isConnected()' on a null object reference
       at com.google.firebase.iid.zzad.zzchr(Unknown Source)
       at com.google.firebase.iid.zzae.onReceive(Unknown Source)
       at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1163)
       at android.os.Handler.handleCallback(Handler.java:751)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6321)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

Have you seen this error before? I don't know how to correct this bug...

Thank you very much guys!

答:
```<code>final boolean zzchr() {
    ConnectivityManager var1;
    return (var1 = (ConnectivityManager)this.getContext().getSystemService("connectivity")) != null && var1.getActiveNetworkInfo() != null && var1.getActiveNetworkInfo().isConnected();
}
</code>```

This is the code for zzchr. There is already a null check added for getActiveNetworkInfo but you are still getting NPE.

You can check on other possibilities of NPE here. Hope it helps.

Body:
Sometimes, on different mobiles (Android 7) there is this crash:

Fatal Exception: java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.google.firebase.iid.zzae@3c68978
       at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1178)
       at android.os.Handler.handleCallback(Handler.java:751)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6321)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.net.NetworkInfo.isConnected()' on a null object reference
       at com.google.firebase.iid.zzad.zzchr(Unknown Source)
       at com.google.firebase.iid.zzae.onReceive(Unknown Source)
       at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1163)
       at android.os.Handler.handleCallback(Handler.java:751)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6321)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Have you seen this error before? I don't know how to correct this bug...

Thank you very much guys!

Body:
final boolean zzchr() {
    ConnectivityManager var1;
    return (var1 = (ConnectivityManager)this.getContext().getSystemService("connectivity")) != null && var1.getActiveNetworkInfo() != null && var1.getActiveNetworkInfo().isConnected();
}

This is the code for zzchr. There is already a null check added for getActiveNetworkInfo but you are still getting NPE.

You can check on other possibilities of NPE here. Hope it helps.


问:
ImportError no module named tests

I would like perform this import:

```<code>from tests.db.connection_tests import ConnectionTests
</code>```

where tests contains a module named db.

I am getting ImportError: No module named 'tests.db'.

The structure of tests is:

```<code>tests
    |
    db
        |
        connection_tests.py
    |
    moduleA
</code>```

The problem seems to be that Python already has a module called tests. The only option that came to my mind was to rename the tests module.

答: Try setting PYTHONPATH env variable to the path upto your tests folder.

Title: ImportError no module named tests

Body:
I would like perform this import:

from tests.db.connection_tests import ConnectionTests

where tests contains a module named db.

I am getting ImportError: No module named 'tests.db'.

The structure of tests is:

tests
    |
    db
        |
        connection_tests.py
    |
    moduleA

The problem seems to be that Python already has a module called tests. The only option that came to my mind was to rename the tests module.


问:
EF Core: How to add the relationship to shadow property?
I have two classes:

```<code>public class DbLibrary
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<DbDepartment> Departments { get; set; } = new List<DbDepartment>();
}

public class DbDepartment
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
</code>```

In this model I need DbDepartment hasn't the property contained the link to DbLibrary. But I need the cascade delete on the database side. For this purpose I add the shadow property to DbDepartment. It is the foreign key. How to relate the primary key DbLibrary class with the shadow property?

This is my attempt:

```<code>protected override void OnModelCreating(ModelBuilder builder)
{
    // Create the shadow property
    var id = builder.Entity<DbDepartment>().Property<Guid>("LibraryId");

    // Create the relationship for cascade delete
    builder.Entity<DbLibrary>().HasMany(n => n.Departments)
        .WithOne(m => id /* it is wrong */).OnDelete(DeleteBehavior.Cascade);
}
</code>```

答:
Shadow properties represent a primitive properties (FK in your case) and cannot be used to create navigation property.

In order to configure the relationship end without navigation property, you use the corresponding Has / With parameterless overload. Whether the FK is shadow or regular property doesn't matter. It matters when you configure the associated FK using HasForeignKey method, which means that for shadow properties you have to use the overload with string property name rather than lambda expression.

Here is the desired fluent configuration:

```<code>builder.Entity<DbLibrary>()
    .HasMany(e => e.Departments)
    .WithOne()
    .HasForeignKey("LibraryId")
    .OnDelete(DeleteBehavior.Cascade);
</code>```

Body:
I have two classes:

public class DbLibrary
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<DbDepartment> Departments { get; set; } = new List<DbDepartment>();
}

public class DbDepartment
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

In this model I need DbDepartment hasn't the property contained the link to DbLibrary. But I need the cascade delete on the database side. For this purpose I add the shadow property to DbDepartment. It is the foreign key. How to relate the primary key DbLibrary class with the shadow property?

This is my attempt:

protected override void OnModelCreating(ModelBuilder builder)
{
    // Create the shadow property
    var id = builder.Entity<DbDepartment>().Property<Guid>("LibraryId");

    // Create the relationship for cascade delete
    builder.Entity<DbLibrary>().HasMany(n => n.Departments)
        .WithOne(m => id /* it is wrong */).OnDelete(DeleteBehavior.Cascade);
}

Body:
Shadow properties represent a primitive properties (FK in your case) and cannot be used to create navigation property.

In order to configure the relationship end without navigation property, you use the corresponding Has / With parameterless overload. Whether the FK is shadow or regular property doesn't matter. It matters when you configure the associated FK using HasForeignKey method, which means that for shadow properties you have to use the overload with string property name rather than lambda expression.

Here is the desired fluent configuration:

builder.Entity<DbLibrary>()
    .HasMany(e => e.Departments)
    .WithOne()
    .HasForeignKey("LibraryId")
    .OnDelete(DeleteBehavior.Cascade);


问:
How to access functions from other files?
This throws error as: 'login is not defined'.</p>

```<code>//<Common.js>
var Common = function(){
this.login = function(uname,password){
    //All your code that you want to call from the test spec
    element(by.id('txtUserName')).sendKeys(login);
    element(by.id('txtPassword')).sendKeys(password);
    element(by.xpath('//input[@id="btnLogin"]')).click();

};
};

module.exports = new Common();

//<Test.js>
var newPage = require('./Common.js');

describe('The application', function() {

  it('should let you log into the application', function() {
         newPage.login('abcd', '1234');
 });
});

Failures:
1) The application should let you log into the application
  Message:
    Failed: login is not defined
  Stack:
    ReferenceError: login is not defined
</code>```

答:
Update 'login' to 'uname' in below line</p>

```<code>element(by.id('txtUserName')).sendKeys(uname);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This throws error as: 'login is not defined'.

//<Common.js>
var Common = function(){
this.login = function(uname,password){
    //All your code that you want to call from the test spec
    element(by.id('txtUserName')).sendKeys(login);
    element(by.id('txtPassword')).sendKeys(password);
    element(by.xpath('//input[@id="btnLogin"]')).click();

};
};

module.exports = new Common();

//<Test.js>
var newPage = require('./Common.js');

describe('The application', function() {

  it('should let you log into the application', function() {
         newPage.login('abcd', '1234');
 });
});

Failures:
1) The application should let you log into the application
  Message:
    Failed: login is not defined
  Stack:
    ReferenceError: login is not defined

Body:
Update 'login' to 'uname' in below line

element(by.id('txtUserName')).sendKeys(uname);


答:
Try:</p>

```<code>string[] arraylist = id.Split(',');
</code>```

Title: Arraylist - Separate a string and put it into an array

Body:
Try:

string[] arraylist = id.Split(',');


问:
Eclipse Hibernate Library downloads
Netbeans does comes with a set of library already to use, i havent found that feature on eclipse i manually have to downloads the library in order to have them and even have to configure on my enviroment??

Thanks,

答:
Yeah, but it's no big deal.

Just download Hibernate itself and if you want to, hibernate tools for eclipse. I personally really like HQL editor from mentioned tools. Then use hibernate as simply, as adding it to your project's classpath.

Title: Eclipse Hibernate Library downloads


问:
Regular Expression to match a list of strings and ignore a list of strings
I am looking for a regular expression that meets the below requirement

Ignore all the strings that starts with zzTest

Match all the strings that contains the word rest and not started with zzTest

Input Strings:

```<code>zzTest.docs:service1
zzTest.rest:service2
Regression.rest:service1
Regression.docs.service2
</code>```

Expected output:

```<code>Regression.rest:service1
</code>```

Tried with the regular expression \s*(?!\w*(zzTest)\w*)\w*(rest)\w*\s*
Its works when there is no dot(.) in the input String

Any help appreciated

答:
You may use

```<code>s.matches("(?!zzTest).*rest.*")
</code>```

The pattern will work as follows:

^ - start of string (implicit in matches)

(?!zzTest) - not starting with zzTest

.*rest.* - any 0+ chars other than line break chars, as many as possible, up to the last rest in the line, and then the rest of the line.

$ - (implicit in matches()): end of string.

To match the whole string, add (?s) at the start of the pattern.

To extend it, use alternations:

```<code>s.matches("(?!zzTest|yyTest|etc).*(?:rest|more here).*")
</code>```

To add whole word matching support, use \b around the words:

```<code>s.matches("(?!\\b(?:zzTest|yyTest|etc)\\b).*\\b(?:rest|more here)\\b.*")
</code>```

Body:
I am looking for a regular expression that meets the below requirement

Ignore all the strings that starts with zzTest

Match all the strings that contains the word rest and not started with zzTest

Input Strings:

zzTest.docs:service1
zzTest.rest:service2
Regression.rest:service1
Regression.docs.service2

Expected output:

Regression.rest:service1

Tried with the regular expression \s*(?!\w*(zzTest)\w*)\w*(rest)\w*\s*
Its works when there is no dot(.) in the input String

Any help appreciated

Body:
You may use

s.matches("(?!zzTest).*rest.*")

The pattern will work as follows:

^ - start of string (implicit in matches)

(?!zzTest) - not starting with zzTest

.*rest.* - any 0+ chars other than line break chars, as many as possible, up to the last rest in the line, and then the rest of the line.

$ - (implicit in matches()): end of string.

To match the whole string, add (?s) at the start of the pattern.

To extend it, use alternations:

s.matches("(?!zzTest|yyTest|etc).*(?:rest|more here).*")

To add whole word matching support, use \b around the words:

s.matches("(?!\\b(?:zzTest|yyTest|etc)\\b).*\\b(?:rest|more here)\\b.*")


问:
What fast loss convergence indicates on a CNN?
I'm training two CNNs (AlexNet e GoogLeNet) in two differents DL libraries (Caffe e Tensorflow). The networks was implemented by dev teams of each libraries (here and here)

I reduced the original Imagenet dataset to 1024 images of 1 category -- but setted 1000 categories to classify on the networks.

So I trained the CNNs, varying processing unit (CPU/GPU) and batches sizes, and I observed that the losses converges fastly to near zero (in mostly times before 1 epoch be completed), like in this graph (Alexnet on Tensorflow):

In portuguese, 'Épocas' is epochs and 'Perda' is loss. The number in the keys are refering for batch sizes.

The weight decays and initial learning rate are the same as used on models that I downloaded, I only changed the dataset and the batch sizes.

Why my networks are converging this way, and not like this way?

答:
The loss function is less noisy than usual and does not oscillate for a few reasons.

The main one is because you have only 1 category, so (to simplify a bit) the network is easily improving at each step, just by improving the score for that category on all your inputs.

Take a look at the (beautiful !) image below: if you have several classes, a good step for one sample is often a bad one for another sample (because they have different categories), which is why the loss goes up locally sometimes. A network update made on a sample of category 1 is a bad step for all samples of cat 2, and conversely, but the sum of the two types of updates goes in the right direction (they compensate their bad parts, only the useful part of the steps remain). If you have 1 class, you'll go straight and fast to "always predict category 1", whereas with 2 or more categories, you'll zigzag and converge slowly to "always predict correctly".

There are a few other effects, like the fact that your dataset is relatively small (so it's easier to learn), that you don't test that often, and maybe you have some smoothing (is your loss computed on the whole dataset or on a batch ? Usually it's on a batch, which participates in the usual loss function graph).

The difference between your curves is also normal, but still characteristic of the fact that you have only 1 class actually present in the dataset. First notice that the CPU and the GPU have the same behavior, because they do exactly he same thing, just at a different speed. When your batch size is >1, the updates in the network that are done are the average of all the updates that you would have done with the samples alone (again simplifying a bit). So usually you'd get smarter updates (more likely togo in the direction of "Always predict correctly"), so you'd need less updates to reach good performances. There is a tradeoff between this faster convergence and the fact that bigger batches use more data for each update, so it's hard to say beforehand which curve should converge faster. It's widely considered that you should use minibatch of size > 1 (but not too big either). Now when you have only 1 class actually present in the dataset, all updates are roughly in the same direction "Always predict 1", so the minibatch average is basically the same, but consumed more data to get roughly the same update. Since you still need the same number of these updates, you'll converge after the same number of steps, so you'll consume more data for the same result.


问:
My current MySQL join is not working
I have the following tables:

Users

```<code>id | name
-----------------
 1 | Johny Bravo
</code>```

Orders

```<code>id | users_id | number
----------------------
 1 |    1    | 111111
 2 |    1    | 222222
 3 |    1    | 333333
 4 |    1    | 444444
</code>```

Example

```<code>id | text | number
------------------
 1 | test | 111111
 2 | test | 111111
 3 | test | 222222
 4 | test | 222222
 5 | test | 333333
 6 | test | 333333
</code>```

Desired Outcome

```<code>id: 1
name: Johny Brawo
count(orders): 4
count(example): 6
</code>```

My current query, which doesn't work

```<code>SELECT users.id, users.name, count(orders.id), count(example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id
</code>```

My current result

```<code>id: 1
name: Johny Brawo
count(orders): 8
count(example): 8
</code>```

Any help would be greatly appreciated.

答:
try count(distinct orders.id), count(distinct example.id)

I've not done any MySQL really, but this works in other Databases...

Title: My current MySQL join is not working

Body:
I have the following tables:

Users

id | name
-----------------
 1 | Johny Bravo

Orders

id | users_id | number
----------------------
 1 |    1    | 111111
 2 |    1    | 222222
 3 |    1    | 333333
 4 |    1    | 444444

Example

id | text | number
------------------
 1 | test | 111111
 2 | test | 111111
 3 | test | 222222
 4 | test | 222222
 5 | test | 333333
 6 | test | 333333

Desired Outcome

id: 1
name: Johny Brawo
count(orders): 4
count(example): 6

My current query, which doesn't work

SELECT users.id, users.name, count(orders.id), count(example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id

My current result

id: 1
name: Johny Brawo
count(orders): 8
count(example): 8

Any help would be greatly appreciated.


问:
Programmatically displaying HTML element titles
Is there a javascript way to display or hide element title (defined as an html attribute), as if the mouse was hovering above said dom element, without actually involving the mouse?

Thanks in advance.

答:
You can make a tooltip layout (div with border) yourself, and show it when you want with jQuery. You can select a link element with a title like this:</p>

```<code>a[title] {}
</code>```

Body:
You can make a tooltip layout (div with border) yourself, and show it when you want with jQuery. You can select a link element with a title like this:

a[title] {}


问:
How to seamlessly rename a minion?
I am considering to move to salt (currently using ansible) to manage a set of standalone IoT devices (Raspberry Pi in practical terms).

The devices would be installed with a generic image, to which I would add on top the installation of salt (client side) as well as a configuration file pointing to salt-master, which is going to serve state files to be consumed by the minions.

The state files include an HTTP query for a name, which is then applied to the device (as its hostname). The obvious problem is that at that stage the minion has already registered with salt-master under the previous (generic) name.

How to handle such a situation? Specifically: how to propagate the new hostname to salt-master? (just changing the hostname and rebooting did not help, I assume the hostname is bundled, on the server, with the ID of the minion).

The more general question would be whether salt is the right product for such a situatiuon (where setting the state of the minion changes its name, among others)

答:
Your Minion ID is based on the hostname during the installation. When you change the hostname after you installed the salt-minion, the Minion ID will not change.

The Minion ID is specified in /etc/salt/minion_id. When you change the Minion ID:

The Minion will identify itself with the new ID to the Master and stops listening to the old ID.

The Master will detect the new Minion ID as a new Minion and it shows a new key in Unaccepted Keys.

After accepting the key on the Master you will be able to use the Minion with the new key only. The old key is still accepted on the Master but doesn't work anymore.

I can come up with two solutions for your situation:

Use salt-ssh to provision your minions. The Master will connect to your Raspberry PI using SSH. It will setup the correct hostname, install and configure salt-minion. After this is finished, your minion will connect to the master with the correct ID. But this requires the Master to know when and where a minion is available...

You mentioned the state where the hostname is set. Change the Minion ID and restart the minion service in the same state. This will change the Minion ID but you need to accept the new key afterwards. Note that the minion will never report a state as successfully finished when you restart the salt-minion service in it.

Title: How to seamlessly rename a minion?


问:
show error message when the course is already register in php
i want this code to show me a error message when student already register a course     </p>

```<code> $reds = mysqli_query($db,"SELECT count(*) FROM `course` " );
    $row = mysqli_fetch_row($reds);
    $num = $row[0];

echo $num>0 ; die();
   var_dump($num) ;die();
    if ($num>0){
   // echo "record already exits";
}

else {

    $sd = "INSERT INTO `users_course`(users_id,course_id) VALUES ( ' {$_SESSION['users_id']}', '$course_id')";
    $r = mysqli_query($db, $sd);
        if ($r) {

        $m = ' register';
        header('location: registercourse.php'); //redirect to index page after inserting
</code>```

答:
Do like below:-

```<code><?php
    session_start(); //start session to use session variable
    $user_id = $_SESSION['users_id'];
    $reds = mysqli_query($db,"SELECT * FROM `users_course` WHERE users_id = $user_id AND course_id= $course_id " );

    if (mysqli_num_rows($reds)>0){
        echo "record already exits";exit;
}else {
    $sd = "INSERT INTO `users_course`(users_id,course_id) VALUES ( $user_id, $course_id)";
    $r = mysqli_query($db, $sd);
    if ($r) {
        $m = ' register';
        header('location: registercourse.php'); //redirect to index page after inserting
    }else{
        echo "error:-".mysqli_error($db);
    }
}
</code>```

Note:- May be above code worked for you currently, but it is wide open for SQL Injection, so try to read prepared statements and use them.

mysqli.prepare

So check this for an example:-

```<code><?php
    session_start(); //start session to use session variable
    $user_id = $_SESSION['users_id'];
    $stmt = mysqli_prepare($db, "SELECT * FROM `users_course` WHERE users_id = ? AND course_id= ?");
    mysqli_stmt_bind_param($stmt, 'ii', $user_id, $course_id);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    if(mysqli_stmt_num_rows($stmt)>0){
        /* close statement */
        mysqli_stmt_close($stmt);
        echo "record already exits";exit;
    }else{
        $stmt = mysqli_prepare($db,"INSERT INTO `users_course`(users_id,course_id) VALUES (?, ?)";
        mysqli_stmt_bind_param($stmt, 'ii', $user_id, $course_id);
        if ( mysqli_stmt_execute($stmt)) {
            $m = ' register';
            header('location: registercourse.php'); //redirect to index page after inserting
        }else{
            echo "error:-".mysqli_error($db);
        }
    }

/* close connection */
mysqli_close($db);
?>
</code>```

Body:
i want this code to show me a error message when student already register a course

 $reds = mysqli_query($db,"SELECT count(*) FROM `course` " );
    $row = mysqli_fetch_row($reds);
    $num = $row[0];

echo $num>0 ; die();
   var_dump($num) ;die();
    if ($num>0){
   // echo "record already exits";
}

else {

    $sd = "INSERT INTO `users_course`(users_id,course_id) VALUES ( ' {$_SESSION['users_id']}', '$course_id')";
    $r = mysqli_query($db, $sd);
        if ($r) {

        $m = ' register';
        header('location: registercourse.php'); //redirect to index page after inserting

Body:
Do like below:-

<?php
    session_start(); //start session to use session variable
    $user_id = $_SESSION['users_id'];
    $reds = mysqli_query($db,"SELECT * FROM `users_course` WHERE users_id = $user_id AND course_id= $course_id " );

    if (mysqli_num_rows($reds)>0){
        echo "record already exits";exit;
}else {
    $sd = "INSERT INTO `users_course`(users_id,course_id) VALUES ( $user_id, $course_id)";
    $r = mysqli_query($db, $sd);
    if ($r) {
        $m = ' register';
        header('location: registercourse.php'); //redirect to index page after inserting
    }else{
        echo "error:-".mysqli_error($db);
    }
}

Note:- May be above code worked for you currently, but it is wide open for SQL Injection, so try to read prepared statements and use them.

mysqli.prepare

So check this for an example:-

<?php
    session_start(); //start session to use session variable
    $user_id = $_SESSION['users_id'];
    $stmt = mysqli_prepare($db, "SELECT * FROM `users_course` WHERE users_id = ? AND course_id= ?");
    mysqli_stmt_bind_param($stmt, 'ii', $user_id, $course_id);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    if(mysqli_stmt_num_rows($stmt)>0){
        /* close statement */
        mysqli_stmt_close($stmt);
        echo "record already exits";exit;
    }else{
        $stmt = mysqli_prepare($db,"INSERT INTO `users_course`(users_id,course_id) VALUES (?, ?)";
        mysqli_stmt_bind_param($stmt, 'ii', $user_id, $course_id);
        if ( mysqli_stmt_execute($stmt)) {
            $m = ' register';
            header('location: registercourse.php'); //redirect to index page after inserting
        }else{
            echo "error:-".mysqli_error($db);
        }
    }

/* close connection */
mysqli_close($db);
?>


问:
C++11 linker error VS17
```<code>#include <iostream>
#include <fstream>
#include <type_traits>
#include <Windows.h>

#include "abase.h"

using namespace std;
class Storage {
    string _path;

public:
    Storage(string path);
    ~Storage() = default;
    template <typename T >
        bool writeFile(string fileName,
            typename enable_if<is_base_of<ABase, T>::value, T >::type* data);
}
</code>```

Definition...

```<code> #include "storage.h"

Storage::Storage(string path)
{
    this->_path = path;
}
template <typename T >
        bool Storage::writeFile(string fileName,
            typename enable_if<is_base_of<ABase, T>::value, T >::type* data){
       return true;
}
</code>```

Im still getting error by Linker:

LNK2019    unresolved external symbol "public: bool __thiscall
  Storage::writeFile(class std::basic_string,class std::allocator >,class AFile*)"
  (??$writeFile@VAFile@@@Storage@@QAE_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVAFile@@@Z)
  referenced in function _main

Why am i getting it if code is looking right. Its generic definition of method in a class and Im trying to constrain class type passing to the method.
And the AFile is inherited from ABase.

ABase is abstract class.

Simple usage in main:

```<code>Storage* s = new Storage("C:\\aPath...");
AFile* afile = new AFile();
s->writeFile<AFile>("a.txt", afile);
</code>```

答:
To solve your linking error you can explicitly instantiate[1] your template member function in the Storage.cpp like this:

```<code>template
bool Storage::writeFile<AFile>(string fileName,
    enable_if<is_base_of<ABase, AFile>::value, AFile>::type* data);
</code>```

so the compiler creates the function and the linker can find.

It's better to move the definitions in the header file - Why can templates only be implemented in the header file?.

Title: C++11 linker error VS17

Body:
#include <iostream>
#include <fstream>
#include <type_traits>
#include <Windows.h>

#include "abase.h"

using namespace std;
class Storage {
    string _path;

public:
    Storage(string path);
    ~Storage() = default;
    template <typename T >
        bool writeFile(string fileName,
            typename enable_if<is_base_of<ABase, T>::value, T >::type* data);
}

Definition...

 #include "storage.h"

Storage::Storage(string path)
{
    this->_path = path;
}
template <typename T >
        bool Storage::writeFile(string fileName,
            typename enable_if<is_base_of<ABase, T>::value, T >::type* data){
       return true;
}

Im still getting error by Linker:

LNK2019    unresolved external symbol "public: bool __thiscall
  Storage::writeFile(class std::basic_string,class std::allocator >,class AFile*)"
  (??$writeFile@VAFile@@@Storage@@QAE_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVAFile@@@Z)
  referenced in function _main

Why am i getting it if code is looking right. Its generic definition of method in a class and Im trying to constrain class type passing to the method.
And the AFile is inherited from ABase.

ABase is abstract class.

Simple usage in main:

Storage* s = new Storage("C:\\aPath...");
AFile* afile = new AFile();
s->writeFile<AFile>("a.txt", afile);

Body:
To solve your linking error you can explicitly instantiate[1] your template member function in the Storage.cpp like this:

template
bool Storage::writeFile<AFile>(string fileName,
    enable_if<is_base_of<ABase, AFile>::value, AFile>::type* data);

so the compiler creates the function and the linker can find.

It's better to move the definitions in the header file - Why can templates only be implemented in the header file?.


问:
Perl LWP Post form-data with my boundary
I want to post data with content type multipart/form-data:

```<code>use strict;
use warnings;

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->post (
    'http://127.0.0.1:12555',
    'Content-Type' => 'form-data',
    Content => {
        'data1' => rand,
        'data2' => rand,
    }
);
</code>```

And i tested the submitted data:

```<code>use strict;
use warnings;
use IO::Socket::INET;
use Socket qw ( inet_aton );

my $sock_listen = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '12555',
    Proto => 'tcp',
    Listen => 3,
    Reuse => 1,
);
$sock_listen->autoflush ();

my $sock;
while ( $sock = $sock_listen->accept ( ) )
{
    my $data = '';
    $sock->recv ( $data, 4096 );
    print $data . "\n";
}
</code>```

Test #1 result:

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 162
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.876556396484375
--xYzZY
Content-Disposition: form-data; name="data1"

0.62921142578125
--xYzZY--
</code>```

Test #2 result:

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 163
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.896942138671875
--xYzZY
Content-Disposition: form-data; name="data1"

0.041656494140625
--xYzZY--
</code>```

I added a data:

```<code>        'data3' => '--xYzZY'
</code>```

and got:

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 221
Content-Type: multipart/form-data; boundary=Tegj

--Tegj
Content-Disposition: form-data; name="data2"

0.34613037109375
--Tegj
Content-Disposition: form-data; name="data3"

--xYzZY
--Tegj
Content-Disposition: form-data; name="data1"

0.678955078125
--Tegj--
</code>```

The question is how i can set the boundary manually to 32 chars string like browser's ----WebKitFormBoundary[...] using LWP?

Or can just use IO::Socket?

答:
The sole purpose of the boundary is to separate the message parts and the only requirement on it is that it doesn't appear anywhere in the message.   I don't see a good reason to attempt to set it to be "the same" as anything else.  Besides, no tool guarantees that it will always use the same one.

More importantly, setting it to a fixed string (without regard for the message) is dangerous: how does anyone know that such a string may not be in a message?

Finally, I don't think it is possible to do so, precisely because the boundary must be checked to ensure that it indeed isn't in the message; so no tool should provide a way to set it to a predefined string.

Have a look at HTTP::Request::Common's source. See how the sub boundary() badly mangles the string to return, and how much work goes into the boundary elsewhere. Then CHECK_BOUNDARY: block changes it further if it isn't good enough. This is clearly not meant to be set outside.

The post method of LWP::UserAgent exists as a shortcut for this module's one.

Note that simbabque found a way to set the boundary, which then also undergoes the checks.

Body:
I want to post data with content type multipart/form-data:

use strict;
use warnings;

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->post (
    'http://127.0.0.1:12555',
    'Content-Type' => 'form-data',
    Content => {
        'data1' => rand,
        'data2' => rand,
    }
);

And i tested the submitted data:

use strict;
use warnings;
use IO::Socket::INET;
use Socket qw ( inet_aton );

my $sock_listen = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '12555',
    Proto => 'tcp',
    Listen => 3,
    Reuse => 1,
);
$sock_listen->autoflush ();

my $sock;
while ( $sock = $sock_listen->accept ( ) )
{
    my $data = '';
    $sock->recv ( $data, 4096 );
    print $data . "\n";
}

Test #1 result:

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 162
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.876556396484375
--xYzZY
Content-Disposition: form-data; name="data1"

0.62921142578125
--xYzZY--

Test #2 result:

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 163
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.896942138671875
--xYzZY
Content-Disposition: form-data; name="data1"

0.041656494140625
--xYzZY--

I added a data:

        'data3' => '--xYzZY'

and got:

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 221
Content-Type: multipart/form-data; boundary=Tegj

--Tegj
Content-Disposition: form-data; name="data2"

0.34613037109375
--Tegj
Content-Disposition: form-data; name="data3"

--xYzZY
--Tegj
Content-Disposition: form-data; name="data1"

0.678955078125
--Tegj--

The question is how i can set the boundary manually to 32 chars string like browser's ----WebKitFormBoundary[...] using LWP?

Or can just use IO::Socket?


问:
Rewrite under exists
Say I have the following relation:

```<code>Inductive my_relation: nat -> Prop :=
constr n: my_relation n.
</code>```

and I want to prove the following:

```<code>Lemma example:
  (forall n, my_relation n -> my_relation (S n)) -> (exists n, my_relation n) -> exists n, my_relation (S n).
Proof.
  intros.
</code>```

After introducing, I have the following environment:

```<code>1 subgoal
H : forall n : nat, my_relation n -> my_relation (S n)
H0 : exists n : nat, my_relation n
______________________________________(1/1)
exists n : nat, my_relation (S n)
</code>```

My question is: is there a possibility to rewrite H under the exists quantifier ? If not, is there a strategy to solve this kind of problem (this particular one is not really relevant, but problems where you have to prove an exists using another exists, and where, informally, you can « deduce » a way to rewrite the exists in the hypothesis into the exists in the goal) ?

For instance, if I try rewrite H in H0. I have, an error (Error: Cannot find a relation to rewrite.).

答:
The standard way to manipulate an existential quantification in an hypothesis is to get a witness of the property using inversion or, better and simpler, destruct.

You can give a name to the variable using one of the following syntaxes:

```<code>destruct H0 as (n, H0).
destruct H0 as [n H0].
destruct H0 as (n & H0).
</code>```

Note that you can also destruct an hypothesis using intro-patterns.

```<code>intros H (n & H0).
</code>```

And you can even directly apply H in H0.

```<code>intros H (n & H0%H). exists n. assumption.
</code>```

Software Foundations explains this in a clear way.

Title: Rewrite under exists

Body:
Say I have the following relation:

Inductive my_relation: nat -> Prop :=
constr n: my_relation n.

and I want to prove the following:

Lemma example:
  (forall n, my_relation n -> my_relation (S n)) -> (exists n, my_relation n) -> exists n, my_relation (S n).
Proof.
  intros.

After introducing, I have the following environment:

1 subgoal
H : forall n : nat, my_relation n -> my_relation (S n)
H0 : exists n : nat, my_relation n
______________________________________(1/1)
exists n : nat, my_relation (S n)

My question is: is there a possibility to rewrite H under the exists quantifier ? If not, is there a strategy to solve this kind of problem (this particular one is not really relevant, but problems where you have to prove an exists using another exists, and where, informally, you can « deduce » a way to rewrite the exists in the hypothesis into the exists in the goal) ?

For instance, if I try rewrite H in H0. I have, an error (Error: Cannot find a relation to rewrite.).

Body:
The standard way to manipulate an existential quantification in an hypothesis is to get a witness of the property using inversion or, better and simpler, destruct.

You can give a name to the variable using one of the following syntaxes:

destruct H0 as (n, H0).
destruct H0 as [n H0].
destruct H0 as (n & H0).

Note that you can also destruct an hypothesis using intro-patterns.

intros H (n & H0).

And you can even directly apply H in H0.

intros H (n & H0%H). exists n. assumption.

Software Foundations explains this in a clear way.


问:
How does mean image subtraction work?
To preface, I am new to the field of ML/CV, and am currently in the process of training a custom conv net using Caffe.

I am interested in mean image subtraction to achieve basic data normalization on my training images. However, I am confused as to how mean subtraction works and exactly what benefits it has.

I know that a "mean image" can be calculated from the training set, which is then subtracted from the training, validation, and testing sets to make the network less sensitive to differing background and lightening conditions.

Does this involve calculating the mean of all pixels in each image, and averaging these? Or, is the value from each pixel coordinate averaged across all images in the set (i.e. average values of pixels at location (1,1) for all images)? This may require that all images are the same size...

Also, for colored images (3-channels), is the value for each channel individually averaged?

Any clarity would be appreciated.

答:
In deep learning, there are in fact different practices as to how to subtract the mean image.

Subtract mean image

The first way is to subtract mean image as @lejlot described. But there is an issue if your dataset images are not the same size. You need to make sure all dataset images are in the same size before using this method (e.g., resize original image and crop patch of same size from original image). It is used in original ResNet paper, see reference here.

Subtract the per-channel mean

The second way is to subtract per-channel mean from the original image, which is more popular. In this way, you do not need to resize or crop the original image. You can just calculate the per-channel mean from the training set. This is used widely in deep learning, e.g, Caffe: here and here. Keras: here. PyTorch: here. (PyTorch also divide the per-channel value by standard deviation.)

Title: How does mean image subtraction work?


问:
tfs 2015 (vNext ) build - Git version task failed
I am unable to run GitVersion Task , after I updated the version to v4.0.0-beta.12  followed the  guidelines and updated the Gitversion task

any help is appreciated. what did i miss here ?

gitversion Task:

output looks like this:

答:
Take a look at this thread:  Nuget Packager - how to specify GitVersion variables

This won't work on TFS2015 on prem as mentioned by
  @chrisrpatterson due to limitation in the agent. There was a note
  in the GitVersion documentation about this, which was removed since
  this is implemented now in VSO, but might be a good idea to add it
  back for the On-Prem case.

Not sure if it works well with new released build agent, try to update it.
As a workaround environment variables can be used in custom scripts. You could try to directly call GitVersion.exe command. Detail steps about how to handle this please refer this tutorial: Integrating GitVersion and Gitflow in your vNext Build


问:
Angular 5 and atmosphere.js
I need to use atmosphere.js in my angular 5 project.

I've done these steps:

```<code>npm install --save @types/atmosphere.js
npm install --save atmosphere.js
</code>```

and I've created a service:

```<code>import { Injectable } from '@angular/core';
import * as Rx from 'rxjs';
import * as Atmosphere from 'atmosphere.js';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class  WebsocketService {
  public eventsSubject: Rx.Subject<any> = new Rx.Subject<any>();
  private url:string = "http://localhost:4200/ws/register";

  private socket: Atmosphere.Atmosphere;
  private subSocket: any;
  private request: Atmosphere.Request;

  public dataStream: Subject<any> = new Subject<any>();

  constructor() {

     ...

     try {
        this.subSocket = this.socket.subscribe(this.request);
     } catch (e) {
        console.log("Error: " + e);
     }
  }
</code>```

but the socket is always undefined.

where is my error?

thanks

答:
You should actually instantiate your socket in someway, my guess is using new:

```<code>private socket: Atmosphere.Atmosphere = new Atmosphere.Atmosphere();
</code>```

The first part is just a type definition you give to the TypeScript compiler. The property will stay undefined until you actually assign something to it.

Although looking over their api, this does not seem to be the right way. Try this:

```<code>export class  WebsocketService {
  // ...
  private socket: typeof Atmosphere = Atmosphere;
  private subSocket: Subscription;
  private request: Atmosphere.Request = new atmosphere.AtmosphereRequest();

  constructor() {
     try {
        this.subSocket = this.socket.subscribe(this.request);
     } catch (e) {
        console.log("Error: " + e);
     }
  }
}
</code>```

Title: Angular 5 and atmosphere.js

Body:
I need to use atmosphere.js in my angular 5 project.

I've done these steps:

npm install --save @types/atmosphere.js
npm install --save atmosphere.js

and I've created a service:

import { Injectable } from '@angular/core';
import * as Rx from 'rxjs';
import * as Atmosphere from 'atmosphere.js';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class  WebsocketService {
  public eventsSubject: Rx.Subject<any> = new Rx.Subject<any>();
  private url:string = "http://localhost:4200/ws/register";

  private socket: Atmosphere.Atmosphere;
  private subSocket: any;
  private request: Atmosphere.Request;

  public dataStream: Subject<any> = new Subject<any>();

  constructor() {

     ...

     try {
        this.subSocket = this.socket.subscribe(this.request);
     } catch (e) {
        console.log("Error: " + e);
     }
  }

but the socket is always undefined.

where is my error?

thanks

Body:
You should actually instantiate your socket in someway, my guess is using new:

private socket: Atmosphere.Atmosphere = new Atmosphere.Atmosphere();

The first part is just a type definition you give to the TypeScript compiler. The property will stay undefined until you actually assign something to it.

Although looking over their api, this does not seem to be the right way. Try this:

export class  WebsocketService {
  // ...
  private socket: typeof Atmosphere = Atmosphere;
  private subSocket: Subscription;
  private request: Atmosphere.Request = new atmosphere.AtmosphereRequest();

  constructor() {
     try {
        this.subSocket = this.socket.subscribe(this.request);
     } catch (e) {
        console.log("Error: " + e);
     }
  }
}


问:
How to remove the trailing dynamic zeros for the given numbers in MS-SQL server
Given value in database table is 23.045000,45.6090, 23.900 .
  Output should be displayed as 23.045, 45.609, 23.9

答:
Cast the value as Float. like this</p>

```<code>select cast(23.045000 as float)-->23.045
select cast(45.6090 as float)-->45.609
select cast(23.900 as float)-->23.9
</code>```

Body:
Cast the value as Float. like this

select cast(23.045000 as float)-->23.045
select cast(45.6090 as float)-->45.609
select cast(23.900 as float)-->23.9


问:
Send/Receive Data to server in C#
In my programe I have a need for requesting data from server and upon collecting the response, use the returned data for further processing.

I am using "system.net.webrequest" class for the same. I have few questions on this:

after I receive the data (data is of 0.5MB size in minimum) I have to process this entire data to derive some result. I was thinking to store the returned data in a "txt" file and then read the data from that file and process.

Is this a better idea? If not, can you please suggest.

I am making post request to several servers (>10 servers) and using data from them. I observed that for some reason if the server is not reachable then my programe stops throwing an exception

Server Not Reachable

A first chance exception of type 'System.Net.WebException' occurred in System.dll

How can I solve this problem? Any idea?

Appreaciate your help.

Thanks,
Rahul

答:
Saving the data to a file is only necessary if you don't want to, or cannot, process it as you receive it or if you want to keep that data around after processing for debugging purposes. I typically avoid creating files like this if I can as it adds to the maintenance overhead.

To continue processing data from other servers in case of an exception on one, you will need to use a Try/Catch block as follows (pseudo):

```<code>foreach (var server in serverList)
{
    try
    {
        ... fetch data and process ...
    }
    catch (Exception ex)
    {
        // handle exception (log, requeue, etc)
    }
}
</code>```

Title: Send/Receive Data to server in C#

Body:
Saving the data to a file is only necessary if you don't want to, or cannot, process it as you receive it or if you want to keep that data around after processing for debugging purposes. I typically avoid creating files like this if I can as it adds to the maintenance overhead.

To continue processing data from other servers in case of an exception on one, you will need to use a Try/Catch block as follows (pseudo):

foreach (var server in serverList)
{
    try
    {
        ... fetch data and process ...
    }
    catch (Exception ex)
    {
        // handle exception (log, requeue, etc)
    }
}


问:
Return filename if filenames contain same keyword and are of roughly the same file size
Spent a decent amount of time on this question already, and I feel that it should be relatively straight-forward, but I want to accomplish this in a computationally efficient and Pythonic manner.

I have created two lists: one containing the keyword associated with each filename, and another containing the file size of those respective files rounded to the nearest 25 bytes. I am attempting to identify duplicate files in a fairly rudimentary manner, and there may be some very small differences in the files themselves (in terms of text), but in general a simple file size comparison should do the trick.

My approach thus far is to iterate through the filenames, keywords and file sizes and return filenames with keywords and sizes that are repeated more than once. Note that my current implementation below does not require that the sizes that are repeated are necessarily associated with that specific keyword (but this is what I want: file duplicates should have roughly the same file size and definitely the same keyword). I think I am just overthinking this, but would utilizing a dictionary here be of use?

Some sample filenames include:

```<code>United States vs Mexico on 4142017.txt w/ file size of 5282 bytes
Mexico vs Uruguay on 3272016.txt w/ file size of 5684 bytes
Spain vs France on 4222017.txt w/ file size of 4883 bytes
United States vs Mexico on 4152017.txt w/ file size of 5276 bytes
</code>```

Here is what I have thus far (I realize this does not work as is):

```<code>import os, re

path = 'Enter path here'; os.chdir(path)
folders = os.listdir(path)

for folder in folders[:3]:

    files = os.listdir(path + '\\' + folder); os.chdir(path + '\\' + folder)

    names = [re.findall(r'vs (.*) on', f)[0] for f in files]
    sizes = [os.stat(f).st_size for f in files]
    sizes = [int(25*round(float(s)/25)) for s in sizes]

    duplicates = [f for f, i, j in zip(files, names, sizes) if names.count(i)>1 and sizes.count(j)>1]

    print(duplicates)
</code>```

The desired output would be a list like follows:

```<code>['United States vs Mexico on 4142017.txt','United States vs Mexico on 4152017.txt']
</code>```

答:
I think the canonical way to do this sort of thing is with defaultdict, forming a dictionary with keys being a tuple of keyword and size, and values being the list of matching file name.

Mock-up example:

```<code>from collections import defaultdict

# input data as a list or sequence of tuples (keyword, size, filename):
entries = [('foo',3,'foo a'), ('bar',6,'bar b'), ('foo',3,'foo c')]

d = defaultdict(list)
for (k,v,f) in entries:
    d[(k,v)].append(f)

print [dupe for dupes in d.values() if len(dupes)>1 for dupe in dupes]
</code>```

The file names corresponding to entries with more duplicated keyword–size pairs are then those entries in the dictionary with length greater than 1.

To iterate through the duplicates instead of explicitly creating the list, one could use itertools.chain.from_iterable.

This is not the most memory-efficient approach — by checking the dictionary as it is built, one can avoid storing all the matching filenames — but it has the benefit of simplicity

Body:
Spent a decent amount of time on this question already, and I feel that it should be relatively straight-forward, but I want to accomplish this in a computationally efficient and Pythonic manner.

I have created two lists: one containing the keyword associated with each filename, and another containing the file size of those respective files rounded to the nearest 25 bytes. I am attempting to identify duplicate files in a fairly rudimentary manner, and there may be some very small differences in the files themselves (in terms of text), but in general a simple file size comparison should do the trick.

My approach thus far is to iterate through the filenames, keywords and file sizes and return filenames with keywords and sizes that are repeated more than once. Note that my current implementation below does not require that the sizes that are repeated are necessarily associated with that specific keyword (but this is what I want: file duplicates should have roughly the same file size and definitely the same keyword). I think I am just overthinking this, but would utilizing a dictionary here be of use?

Some sample filenames include:

United States vs Mexico on 4142017.txt w/ file size of 5282 bytes
Mexico vs Uruguay on 3272016.txt w/ file size of 5684 bytes
Spain vs France on 4222017.txt w/ file size of 4883 bytes
United States vs Mexico on 4152017.txt w/ file size of 5276 bytes

Here is what I have thus far (I realize this does not work as is):

import os, re

path = 'Enter path here'; os.chdir(path)
folders = os.listdir(path)

for folder in folders[:3]:

    files = os.listdir(path + '\\' + folder); os.chdir(path + '\\' + folder)

    names = [re.findall(r'vs (.*) on', f)[0] for f in files]
    sizes = [os.stat(f).st_size for f in files]
    sizes = [int(25*round(float(s)/25)) for s in sizes]

    duplicates = [f for f, i, j in zip(files, names, sizes) if names.count(i)>1 and sizes.count(j)>1]

    print(duplicates)

The desired output would be a list like follows:

['United States vs Mexico on 4142017.txt','United States vs Mexico on 4152017.txt']

Body:
I think the canonical way to do this sort of thing is with defaultdict, forming a dictionary with keys being a tuple of keyword and size, and values being the list of matching file name.

Mock-up example:

from collections import defaultdict

# input data as a list or sequence of tuples (keyword, size, filename):
entries = [('foo',3,'foo a'), ('bar',6,'bar b'), ('foo',3,'foo c')]

d = defaultdict(list)
for (k,v,f) in entries:
    d[(k,v)].append(f)

print [dupe for dupes in d.values() if len(dupes)>1 for dupe in dupes]

The file names corresponding to entries with more duplicated keyword–size pairs are then those entries in the dictionary with length greater than 1.

To iterate through the duplicates instead of explicitly creating the list, one could use itertools.chain.from_iterable.

This is not the most memory-efficient approach — by checking the dictionary as it is built, one can avoid storing all the matching filenames — but it has the benefit of simplicity


问:
how to show default selected option in select box
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

```<code>[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]
</code>```

and HTML code like this..

```<code><select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>
</code>```

Any response which is related to this will help me alot.
Thanks to you inAdvance

答:
I have not tested your code, but something like this should work:</p>

```<code><select formControlName="controlFordropdwn">
    <option *ngIf="type.value == type.selected">{{type.value}}</option> <!--I added this line -->
    <option *ngFor="let type of dropdown" [value]="type.value" [selected]='type.value == type.selected'>
        {{type.value}}
    </option>
</select>
</code>```

Body:
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]

and HTML code like this..

<select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>

Any response which is related to this will help me alot.
Thanks to you inAdvance

Body:
I have not tested your code, but something like this should work:

<select formControlName="controlFordropdwn">
    <option *ngIf="type.value == type.selected">{{type.value}}</option> <!--I added this line -->
    <option *ngFor="let type of dropdown" [value]="type.value" [selected]='type.value == type.selected'>
        {{type.value}}
    </option>
</select>


问:
How can I get pycharm to NOT auto-insert a closing docstring?
I hate anything in any IDE that inserts anything that I haven't explicitly told it to. Accordingly, I've turned off all of the auto-complete and auto-insert I can find, but I cannot find out how to kill this for docstrings. I type """ and press Space and it puts this in, instead:

```<code>"""
"""
</code>```

How can I turn this behaviour off?

答:
Also try:

```<code>Settings : Editor : General : Smart Keys
</code>```

Uncheck:

```<code>Add quotes for attribute value on typing '=' and attribute completion
</code>```

You might want to turn off this as well:

```<code>Auto-close tag on typing '</'
</code>```

Body:
I hate anything in any IDE that inserts anything that I haven't explicitly told it to. Accordingly, I've turned off all of the auto-complete and auto-insert I can find, but I cannot find out how to kill this for docstrings. I type """ and press Space and it puts this in, instead:

"""
"""

How can I turn this behaviour off?

Body:
Also try:

Settings : Editor : General : Smart Keys

Uncheck:

Add quotes for attribute value on typing '=' and attribute completion

You might want to turn off this as well:

Auto-close tag on typing '</'


问:
Laravel passport gives 401 Unauthenticated error
I'm using Laravel passport for API authentication, it works perfectly when I use it with one DB, but gives 401 when using multiple databases,

What I'm doing:

I have a multi-tenant DB, master DB have users, roles and all OAuth tables.

When I create a user with admin role it will create new DB with admin name, it will create sub DB with users, roles and all OAuth table. oauth_clients of sub DB will copy Password Grant Token and Personal Access Token from master DB and insert in sub DB, and also insert client_id in oauth_personal_access_clients.

I'm doing all the procedures which passport:install command does. (If I'm not missing something).

When I login with credentials from master DB it works perfectly, the real problem starts when I login with credentials from sub-database, I can get sub DB from a param client_code which I input with email,password while login.

It allows me login from sub DB but I get 401 Unauthenticated  error, get Access token while login and I pass Authentication Header with Bearer on every request after login from Angular front.

Don't know what I'm missing here.

DBConnection Middleware

DBConnection middleware  sets connection on every request after login,

```<code>public function handle($request, Closure $next)
    {
        if ( $request->method() != 'OPTIONS' ) {
            $this->access_code = $request->header('access-code');
            if ( $this->access_code != '' && $this->access_code != 'sa'  ) {
                app('App\Http\Controllers\Controller')->setDB(AppHelper::DB_PREFIX.$this->access_code);
            } else {
                app('App\Http\Controllers\Controller')->setDB(AppHelper::DB_DEFAULT);
            }
        }
        return $next($request);
    }
</code>```

DBConnection sets default DB in database.php dynamically, for that, I'm calling setDB method created on Controller.php

setDB Controller.php

```<code>public function setDB($database='') {
      $config = app()->make('config');
      $connections = $config->get('database.connections');
      $default_connection = $connections[$config->get('database.default')];
      $new_connection = $default_connection;
      $new_connection['database'] = $database;
      $config->set('database.connections.'.$database, $new_connection);
      $config->set('database.default', $database);
  }
</code>```

Is it possible to use passport with 2 different DB for same code?

Laravel 5.4
Passport 4.0
Angular 4.4 in front-end

答:
To answer your question: Yes you can!

In our middleware we do some like this:

```<code>config([
  'database.connections.tenant.schema' => $tenant
]);

DB::connection('tenant')->statement("SET search_path = $tenant");
</code>```

It really sounds to me that your search_path is not set up in properly. This would explain why you get a 401. Because Laravel Passport is searching in the wrong database in which it can't find the right token in your users table.

From PostgreSQL docs (https://www.postgresql.org/docs/9.1/static/runtime-config-client.html):

search_path (string)

This variable specifies the order in which schemas are searched when an object (table, data type, function, etc.) is referenced by a simple name with no schema specified. When there are objects of identical names in different schemas, the one found first in the search path is used. An object that is not in any of the schemas in the search path can only be referenced by specifying its containing schema with a qualified (dotted) name.

Body:
I'm using Laravel passport for API authentication, it works perfectly when I use it with one DB, but gives 401 when using multiple databases,

What I'm doing:

I have a multi-tenant DB, master DB have users, roles and all OAuth tables.

When I create a user with admin role it will create new DB with admin name, it will create sub DB with users, roles and all OAuth table. oauth_clients of sub DB will copy Password Grant Token and Personal Access Token from master DB and insert in sub DB, and also insert client_id in oauth_personal_access_clients.

I'm doing all the procedures which passport:install command does. (If I'm not missing something).

When I login with credentials from master DB it works perfectly, the real problem starts when I login with credentials from sub-database, I can get sub DB from a param client_code which I input with email,password while login.

It allows me login from sub DB but I get 401 Unauthenticated  error, get Access token while login and I pass Authentication Header with Bearer on every request after login from Angular front.

Don't know what I'm missing here.

DBConnection Middleware

DBConnection middleware  sets connection on every request after login,

public function handle($request, Closure $next)
    {
        if ( $request->method() != 'OPTIONS' ) {
            $this->access_code = $request->header('access-code');
            if ( $this->access_code != '' && $this->access_code != 'sa'  ) {
                app('App\Http\Controllers\Controller')->setDB(AppHelper::DB_PREFIX.$this->access_code);
            } else {
                app('App\Http\Controllers\Controller')->setDB(AppHelper::DB_DEFAULT);
            }
        }
        return $next($request);
    }

DBConnection sets default DB in database.php dynamically, for that, I'm calling setDB method created on Controller.php

setDB Controller.php

public function setDB($database='') {
      $config = app()->make('config');
      $connections = $config->get('database.connections');
      $default_connection = $connections[$config->get('database.default')];
      $new_connection = $default_connection;
      $new_connection['database'] = $database;
      $config->set('database.connections.'.$database, $new_connection);
      $config->set('database.default', $database);
  }

Is it possible to use passport with 2 different DB for same code?

Laravel 5.4
Passport 4.0
Angular 4.4 in front-end

Body:
To answer your question: Yes you can!

In our middleware we do some like this:

config([
  'database.connections.tenant.schema' => $tenant
]);

DB::connection('tenant')->statement("SET search_path = $tenant");

It really sounds to me that your search_path is not set up in properly. This would explain why you get a 401. Because Laravel Passport is searching in the wrong database in which it can't find the right token in your users table.

From PostgreSQL docs (https://www.postgresql.org/docs/9.1/static/runtime-config-client.html):

search_path (string)

This variable specifies the order in which schemas are searched when an object (table, data type, function, etc.) is referenced by a simple name with no schema specified. When there are objects of identical names in different schemas, the one found first in the search path is used. An object that is not in any of the schemas in the search path can only be referenced by specifying its containing schema with a qualified (dotted) name.