问:
Django 'AsgiRequest' object has no attribute 'content_type'
I am working on developing a django app named app, which is a part of a django project, but i am getting some problems when try to login admin.

```<code>import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'something'

DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'connections',
    'custom_user',
    'chat',
    'channels',
]

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

ROOT_URLCONF = 'testpoject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'traego.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'testproject',
        'USER': 'admin_testproject',
        'PASSWORD': 'passw123',
        'HOST': 'localhost',
        'PORT': '',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, "static")

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static-temp')]

STATIC_URL = '/static/'

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/home'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

AUTH_USER_MODEL = 'custom_user.EmailUser'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        "ROUTING": "chat.routing.channel_routing",
    },
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO'
        },
        'chat': {
            'handlers': ['console'],
            'propagate': False,
            'level': 'DEBUG',
        },
    },
}
</code>```

The error occurs when I try to login a super user create in shell by localhost:8000/admin/login/, it show error:

```<code>Internal Server Error: /admin/login/
</code>```

then show the traceback

```<code>[2017/04/01 23:58:36] HTTP GET /admin/ 302 [0.03, 127.0.0.1:45030]
[2017/04/01 23:58:36] HTTP GET /admin/login/ 200 [0.04, 127.0.0.1:45030]
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,380 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 84, in technical_500_response
    html = reporter.get_traceback_html()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 328, in get_traceback_html
    c = Context(self.get_traceback_data(), use_l10n=False)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 304, in get_traceback_data
    'filtered_POST': self.filter.get_post_parameters(self.request),
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 167, in get_post_parameters
    return request.POST
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,388 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
</code>```

This is my requirements.txt:

```<code>appdirs==1.4.2
Django==1.10.5
django-custom-user==0.7
packaging==16.8
psycopg2==2.6.2
pyparsing==2.1.10
six==1.10.0
Pillow==4.0.0
asgi-redis==0.8.3
asgiref==0.9
autobahn==0.12.1
channels==0.9.3
daphne==0.9.1
haikunator==1.0.1
msgpack-python==0.4.7
redis==2.10.5
six==1.10.0
Twisted==15.5.0
txaio==2.2.1
wheel==0.24.0
zope.interface==4.1.3
</code>```

Is there a good way to solve the problem?
The rarest thing is that until yesterday it worked correctly and today I did not make any changes and it does not work

答: AsgiRequest is from channels package. So either upgrade it to latest version or install a version of django that is supported by channels version you are using. So please try upgrading channels to latest version with pip install channels -U to fix this issue.

Body:
I am working on developing a django app named app, which is a part of a django project, but i am getting some problems when try to login admin.

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'something'

DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'connections',
    'custom_user',
    'chat',
    'channels',
]

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

ROOT_URLCONF = 'testpoject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'traego.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'testproject',
        'USER': 'admin_testproject',
        'PASSWORD': 'passw123',
        'HOST': 'localhost',
        'PORT': '',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, "static")

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static-temp')]

STATIC_URL = '/static/'

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/home'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

AUTH_USER_MODEL = 'custom_user.EmailUser'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        "ROUTING": "chat.routing.channel_routing",
    },
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO'
        },
        'chat': {
            'handlers': ['console'],
            'propagate': False,
            'level': 'DEBUG',
        },
    },
}

The error occurs when I try to login a super user create in shell by localhost:8000/admin/login/, it show error:

Internal Server Error: /admin/login/

then show the traceback

[2017/04/01 23:58:36] HTTP GET /admin/ 302 [0.03, 127.0.0.1:45030]
[2017/04/01 23:58:36] HTTP GET /admin/login/ 200 [0.04, 127.0.0.1:45030]
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,380 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 84, in technical_500_response
    html = reporter.get_traceback_html()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 328, in get_traceback_html
    c = Context(self.get_traceback_data(), use_l10n=False)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 304, in get_traceback_data
    'filtered_POST': self.filter.get_post_parameters(self.request),
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 167, in get_post_parameters
    return request.POST
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,388 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'

This is my requirements.txt:

appdirs==1.4.2
Django==1.10.5
django-custom-user==0.7
packaging==16.8
psycopg2==2.6.2
pyparsing==2.1.10
six==1.10.0
Pillow==4.0.0
asgi-redis==0.8.3
asgiref==0.9
autobahn==0.12.1
channels==0.9.3
daphne==0.9.1
haikunator==1.0.1
msgpack-python==0.4.7
redis==2.10.5
six==1.10.0
Twisted==15.5.0
txaio==2.2.1
wheel==0.24.0
zope.interface==4.1.3

Is there a good way to solve the problem?
The rarest thing is that until yesterday it worked correctly and today I did not make any changes and it does not work


来源: stackexchange

问:
IBM MobileFirst Platform 7.1 doesn't create android project from the hybrid app
I have an IBM MobileFirst Platform running on my eclipse and I have created a hello app with adding android environment to it. However, when I build the android environment, it just creates the native folder without creating the android project separately that I need to use to run using Android Studio. Is something wrong with my setup?

Jave Version:

```<code>Listening for transport dt_socket at address: 10777
Launching worklight (WebSphere Application Server 8.5.5.5/wlp-1.0.8.cl50520150305-2202) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_121-b13 (en_US)
</code>```

IBM MobileFirst Platform Version:

```<code>7.1.0.00.20170301-1645
</code>```

Hello app project:

答:
Check if all the Android plugins are installed enter image description here

I have seen the same issue but issue got resolved after
   1. All above android plugins are installed
   2. Oracle JDK8 made as default JDK for starting Android Plugin
   3. I have tried this using Eclipse version Kepler and Mars.

ContentLicense: CC BY-SA 3.0

Body:
I have an IBM MobileFirst Platform running on my eclipse and I have created a hello app with adding android environment to it. However, when I build the android environment, it just creates the native folder without creating the android project separately that I need to use to run using Android Studio. Is something wrong with my setup?

Jave Version:

Listening for transport dt_socket at address: 10777
Launching worklight (WebSphere Application Server 8.5.5.5/wlp-1.0.8.cl50520150305-2202) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_121-b13 (en_US)

IBM MobileFirst Platform Version:

7.1.0.00.20170301-1645

Hello app project:


问:
Composer: Strange behavior
I am farly new to composer. however I have been using it without any issues until now. My issues is that every time i run either composer update or install all files under my vendor folder gets into my  untracked list in git. I also have a .gitignore to prevent the "vendor" from being tracked, but apparently is not doing what is suppose to do. My .gitignore file is below.

```<code># phpunit itself is not needed
phpunit.phar
# local phpunit config
/phpunit.xml

# ignore sub directory for dev installed apps and extensions
/apps
/extensions

#custom
runtime/
web/

/vendor

!vendor/dixonsatit/
!vendor/dixonsatit/yii2-agency-theme/dist/img/
!vendor/dixonsatit/yii2-agency-theme/dist/css/
</code>```

Any tips will be helpful.

答:
First commit your current changes, then run following commands on top folder:

```<code>git rm -r --cached .
git add .
git commit -m "fixed untracked files"
</code>```

Ref link 1
Ref link 2

Title: Composer: Strange behavior

Body:
I am farly new to composer. however I have been using it without any issues until now. My issues is that every time i run either composer update or install all files under my vendor folder gets into my  untracked list in git. I also have a .gitignore to prevent the "vendor" from being tracked, but apparently is not doing what is suppose to do. My .gitignore file is below.

# phpunit itself is not needed
phpunit.phar
# local phpunit config
/phpunit.xml

# ignore sub directory for dev installed apps and extensions
/apps
/extensions

#custom
runtime/
web/

/vendor

!vendor/dixonsatit/
!vendor/dixonsatit/yii2-agency-theme/dist/img/
!vendor/dixonsatit/yii2-agency-theme/dist/css/

Any tips will be helpful.

Body:
First commit your current changes, then run following commands on top folder:

git rm -r --cached .
git add .
git commit -m "fixed untracked files"

Ref link 1
Ref link 2


问:
Rendering a section of a non-smooth QImage using QSGImageNode
I'm trying to render individual tiles from a tileset. For example, I want to display the grey tile in the tileset below:

In the real use case, these would be e.g. water, grass, etc. tiles in a game. There are some requirements for rendering these tiles:

They are 32x32 pixels and will be rendered fullscreen, so performance is important.

They should not be smoothed when scaled.

None of the built-in Qt Quick types meet these requirements (rendering a section of an image that's not smoothed), as far as I can tell. I've tried QQuickPaintedItem with various QPainter render hints (such as SmoothPixmapTransform set to false) without success; the image is "blurry" when upscaled. AnimatedSprite supports rendering sections of an image, but has no API to disable smoothing.

My idea was to implement a custom QQuickItem using the scene graph API.

main.cpp:

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QQuickWindow>
#include <QSGImageNode>

static QImage image;
static const int tileSize = 32;
static const int tilesetSize = 8;

class Tile : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(int index READ index WRITE setIndex NOTIFY indexChanged)

public:
    Tile() :
        mIndex(-1) {
        setWidth(tileSize);
        setHeight(tileSize);

        setFlag(QQuickItem::ItemHasContents);
    }

    QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
    {
        if (!oldNode) {
            oldNode = window()->createImageNode();
        }

        if (mIndex == -1)
            return oldNode;

        if (image.isNull()) {
            image = QImage("C:/tileset.png");
            if (image.isNull())
                return oldNode;
        }

        QSGTexture *texture = window()->createTextureFromImage(image);
        qDebug() << "textureSize:" << texture->textureSize();
        if (!texture)
            return oldNode;

        QSGImageNode *imageNode = static_cast<QSGImageNode*>(oldNode);
//        imageNode->setOwnsTexture(true);
        imageNode->setTexture(texture);
        qDebug() << "source rect:" << (mIndex % tileSize) * tileSize << (mIndex / tileSize) * tileSize << tileSize << tileSize;
        imageNode->setSourceRect((mIndex % tileSize) * tileSize, (mIndex / tileSize) * tileSize, tileSize, tileSize);

        return oldNode;

    }

    int index() const {
        return mIndex;
    }

    void setIndex(int index) {
        if (index == mIndex)
            return;

        mIndex = index;
        emit indexChanged();
    }

signals:
    void indexChanged();

private:
    int mIndex;
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<Tile>("App", 1, 0, "Tile");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

#include "main.moc"
</code>```

main.qml:

```<code>import QtQuick 2.9
import QtQuick.Controls 2.2

import App 1.0

ApplicationWindow {
    id: window
    width: 800
    height: 800
    visible: true

    Slider {
        id: slider
        from: 1
        to: 10
    }

    Tile {
        scale: slider.value
        index: 1
        anchors.centerIn: parent

        Rectangle {
            anchors.fill: parent
            color: "transparent"
            border.color: "darkorange"
        }
    }
}
</code>```

The output from this application looks fine, but nothing is rendered within the rectangle:

```<code>textureSize: QSize(256, 256)
source rect: 32 0 32 32
</code>```

Judging from the minimal docs, my implementation (in terms of how I create nodes) seems OK. Where am I going wrong?

答:
It does seem like you can have it both easier and more efficient.

Instead of implementing a custom QQuickItem you can just use a trivial ShaderEffect. You can pass an offset and control the sampling.

Additionally, you would only need one single black and white plus, and you can have the color dynamic by passing it as a parameter to the shader.

Lastly, doing an atlas yourself is likely redundant, as the scenegraph will likely put small textures in atlases anyway. And of course, there is the advantage of not having to write a single line of C++, while still getting an efficient and flexible solution.

Body:
I'm trying to render individual tiles from a tileset. For example, I want to display the grey tile in the tileset below:

In the real use case, these would be e.g. water, grass, etc. tiles in a game. There are some requirements for rendering these tiles:

They are 32x32 pixels and will be rendered fullscreen, so performance is important.

They should not be smoothed when scaled.

None of the built-in Qt Quick types meet these requirements (rendering a section of an image that's not smoothed), as far as I can tell. I've tried QQuickPaintedItem with various QPainter render hints (such as SmoothPixmapTransform set to false) without success; the image is "blurry" when upscaled. AnimatedSprite supports rendering sections of an image, but has no API to disable smoothing.

My idea was to implement a custom QQuickItem using the scene graph API.

main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QQuickWindow>
#include <QSGImageNode>

static QImage image;
static const int tileSize = 32;
static const int tilesetSize = 8;

class Tile : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(int index READ index WRITE setIndex NOTIFY indexChanged)

public:
    Tile() :
        mIndex(-1) {
        setWidth(tileSize);
        setHeight(tileSize);

        setFlag(QQuickItem::ItemHasContents);
    }

    QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
    {
        if (!oldNode) {
            oldNode = window()->createImageNode();
        }

        if (mIndex == -1)
            return oldNode;

        if (image.isNull()) {
            image = QImage("C:/tileset.png");
            if (image.isNull())
                return oldNode;
        }

        QSGTexture *texture = window()->createTextureFromImage(image);
        qDebug() << "textureSize:" << texture->textureSize();
        if (!texture)
            return oldNode;

        QSGImageNode *imageNode = static_cast<QSGImageNode*>(oldNode);
//        imageNode->setOwnsTexture(true);
        imageNode->setTexture(texture);
        qDebug() << "source rect:" << (mIndex % tileSize) * tileSize << (mIndex / tileSize) * tileSize << tileSize << tileSize;
        imageNode->setSourceRect((mIndex % tileSize) * tileSize, (mIndex / tileSize) * tileSize, tileSize, tileSize);

        return oldNode;

    }

    int index() const {
        return mIndex;
    }

    void setIndex(int index) {
        if (index == mIndex)
            return;

        mIndex = index;
        emit indexChanged();
    }

signals:
    void indexChanged();

private:
    int mIndex;
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<Tile>("App", 1, 0, "Tile");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

#include "main.moc"

main.qml:

import QtQuick 2.9
import QtQuick.Controls 2.2

import App 1.0

ApplicationWindow {
    id: window
    width: 800
    height: 800
    visible: true

    Slider {
        id: slider
        from: 1
        to: 10
    }

    Tile {
        scale: slider.value
        index: 1
        anchors.centerIn: parent

        Rectangle {
            anchors.fill: parent
            color: "transparent"
            border.color: "darkorange"
        }
    }
}

The output from this application looks fine, but nothing is rendered within the rectangle:

textureSize: QSize(256, 256)
source rect: 32 0 32 32

Judging from the minimal docs, my implementation (in terms of how I create nodes) seems OK. Where am I going wrong?


问:
Android - How to detect when user click recent app?
I want to develop a custom launcher android for Samsung Tablet where user can only exit the launcher with a passcode input.

Currently I face problem in recent app button. If user click recent app button, and then click the recent app, then click backpressed, device will go to TouchWiz launcher even I already set my launcher as a default launcher. Also, I disable the notification bar so user can't access it. However, when it go to TouchWiz via backpressed at recent app, the notification also disable, it should be able when in TouchWiz launcher.

My proposed solution is to detect when user click recent app and forbid any action that can cause the changes of current view.

答: I can't detect the recent app clicked. So I use onPause() to detect if my app is on foreground or background. If is in onPause() then my app is on background, if so, I do startActivity(myLauncher) so other app won't launched.


问:
How to check day cycle or night cycle based on time?
Hi I have a list of times but i want to check whether the time is day cycle or night cycle based on the list of times.

Example Night Cycle limit 00:00 to 12:00

Example Day Cycle limit 12:00 to 00:00

try{

```<code>            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
            Date date_from = formatter.parse("00:00");
            Date date_to = formatter.parse("12:00");
            Date dateNow = formatter.parse("07:30");
            if (date_from.before(dateNow)) {
                check = "nightCycle";
            } else if (dateNow.before(date_to)) {
                check = "nightCycle";
            } else if (dateNow.after(date_from)) {
                check = "nightCycle";
            } else {
                check = "DayCycle";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

答:
You need to use different conditions depending on the interval crossing midnight or not. Draw a little diagram, this helps to get the conditions right.</p>

```<code>if (date_from.before(date_to)) { // they are on the same day
    if (dateNow.after(date_from) && dateNow.before(date_to)) {
        check = "nightCycle";
    } else {
        check = "dayCycle";
    }
 } else { // interval crossing midnight
    if (dateNow.before(date_to) || dateNow.after(date_from)) {
        check = "nightCycle";
    } else {
        check = "dayCycle";
    }
 }
</code>```

Body:
Hi I have a list of times but i want to check whether the time is day cycle or night cycle based on the list of times.

Example Night Cycle limit 00:00 to 12:00

Example Day Cycle limit 12:00 to 00:00

try{

            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
            Date date_from = formatter.parse("00:00");
            Date date_to = formatter.parse("12:00");
            Date dateNow = formatter.parse("07:30");
            if (date_from.before(dateNow)) {
                check = "nightCycle";
            } else if (dateNow.before(date_to)) {
                check = "nightCycle";
            } else if (dateNow.after(date_from)) {
                check = "nightCycle";
            } else {
                check = "DayCycle";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Body:
You need to use different conditions depending on the interval crossing midnight or not. Draw a little diagram, this helps to get the conditions right.

if (date_from.before(date_to)) { // they are on the same day
    if (dateNow.after(date_from) && dateNow.before(date_to)) {
        check = "nightCycle";
    } else {
        check = "dayCycle";
    }
 } else { // interval crossing midnight
    if (dateNow.before(date_to) || dateNow.after(date_from)) {
        check = "nightCycle";
    } else {
        check = "dayCycle";
    }
 }


问:
Create DOM hierarchically
I have a list of keys and values and I intend to create an xml based on this information.

My list return:

```<code>1 person
2 information
3 name
3 surname
2 address
3 street
3 country
</code>```

And I want to generate an xml:

```<code><xml>
    <person>
        <information>
            <name></name>
            <surname></surname>
        </information>
        <address>
            <street></street>
            <country></country>
        </address>
    </person>
</xml>
</code>```

I have a list of elements, while traversing these elements would create the xml document hierarchically. I already have this code:

```<code>var elements = document.getElementsByClassName('elements');
var xml = document.createElement('xml');

for (var i = 0; i < elements.length; i++) {
    var key = elements[i].getAttribute('data-key');
    var value = elements[i].getAttribute('data-value');

    console.log(key +' -> '+ value);

    // HERE: create new elements appendChild "var xml"
}
</code>```

答:
Very similar to Forty3's answer but a tad more concise and uses and XML document, not an HTML document.

Note that if document is an HTML document, then document.createElement changes the tagname to lower case, whereas if it's an XML document, the tag case is preserved. Also, in an HTML document it's reliant on support for custom and unknown tagnames, which might not be available, so better to use an XML document.

I've made up a data source, it seems it comes from the document so hopefully it reasonably approximate what you're using. I've put some minimal validation on the level, there should be more validation of the input to ensure it meets some standardised format.

function buildDoc() {

  // Create an XML document to use to create the elements
   var doc = document.implementation.createDocument(null, null, null);

  var data = document.getElementsByClassName('elements');
  var root = doc.createElement('xml');
  var parent = root;
  var level = 0;
  var node, tagname;

  for (var i=0, iLen=data.length; i<iLen; i++) {
    dataNode = data[i];
    node = doc.createElement(dataNode.dataset.value);
    nodeLevel = dataNode.dataset.key;

    // Can only add nodes at level 1 or higher
    if (nodeLevel <= 0) {
      console.log('Level ' + nodeLevel + ' is invalid. Can only create nodes at level 1 or higher');
      return;
    }

    // If node at same level, is sibling of current parent
    // If node at lower level, go back levels and parents to same level
    // Append node, then make node the parent
    if (nodeLevel <= level) {
      while (nodeLevel < level) {
        parent = parent.parentNode;
        --level;
      }
      parent = parent.parentNode.appendChild(node);

    // If node at higher level, is child of current parent
    // Next node might higher again, so set parent to node
    } else if (nodeLevel > level){
      parent = parent.appendChild(node);
      level = nodeLevel;
    }
  }
  // Return the root
  return root;
}

window.onload = function() {
  console.log(buildDoc().outerHTML);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span class="elements" data-key="1" data-value="Person">1 person</span><br>
  <span class="elements" data-key="2" data-value="information">2 information</span><br>
  <span class="elements" data-key="3" data-value="name">3 name</span><br>
  <span class="elements" data-key="3" data-value="surname">3 surname</span><br>
  <span class="elements" data-key="2" data-value="address">2 address</span><br>
  <span class="elements" data-key="3" data-value="street">3 street</span><br>
  <span class="elements" data-key="3" data-value="country">3 country</span><br>
  <span class="elements" data-key="2" data-value="address">2 address</span><br>
  <span class="elements" data-key="3" data-value="street">3 street</span><br>
  <span class="elements" data-key="3" data-value="country">3 country</span><br>
</div></code>```

PS. This probably won't run in IE 10 or lower due to lack of support for data-* attributes.

Title: Create DOM hierarchically

Body:
I have a list of keys and values and I intend to create an xml based on this information.

My list return:

1 person
2 information
3 name
3 surname
2 address
3 street
3 country

And I want to generate an xml:

<xml>
    <person>
        <information>
            <name></name>
            <surname></surname>
        </information>
        <address>
            <street></street>
            <country></country>
        </address>
    </person>
</xml>

I have a list of elements, while traversing these elements would create the xml document hierarchically. I already have this code:

var elements = document.getElementsByClassName('elements');
var xml = document.createElement('xml');

for (var i = 0; i < elements.length; i++) {
    var key = elements[i].getAttribute('data-key');
    var value = elements[i].getAttribute('data-value');

    console.log(key +' -> '+ value);

    // HERE: create new elements appendChild "var xml"
}

Body:
Very similar to Forty3's answer but a tad more concise and uses and XML document, not an HTML document.

Note that if document is an HTML document, then document.createElement changes the tagname to lower case, whereas if it's an XML document, the tag case is preserved. Also, in an HTML document it's reliant on support for custom and unknown tagnames, which might not be available, so better to use an XML document.

I've made up a data source, it seems it comes from the document so hopefully it reasonably approximate what you're using. I've put some minimal validation on the level, there should be more validation of the input to ensure it meets some standardised format.

function buildDoc() {

  // Create an XML document to use to create the elements
   var doc = document.implementation.createDocument(null, null, null);

  var data = document.getElementsByClassName('elements');
  var root = doc.createElement('xml');
  var parent = root;
  var level = 0;
  var node, tagname;

  for (var i=0, iLen=data.length; i<iLen; i++) {
    dataNode = data[i];
    node = doc.createElement(dataNode.dataset.value);
    nodeLevel = dataNode.dataset.key;

    // Can only add nodes at level 1 or higher
    if (nodeLevel <= 0) {
      console.log('Level ' + nodeLevel + ' is invalid. Can only create nodes at level 1 or higher');
      return;
    }

    // If node at same level, is sibling of current parent
    // If node at lower level, go back levels and parents to same level
    // Append node, then make node the parent
    if (nodeLevel <= level) {
      while (nodeLevel < level) {
        parent = parent.parentNode;
        --level;
      }
      parent = parent.parentNode.appendChild(node);

    // If node at higher level, is child of current parent
    // Next node might higher again, so set parent to node
    } else if (nodeLevel > level){
      parent = parent.appendChild(node);
      level = nodeLevel;
    }
  }
  // Return the root
  return root;
}

window.onload = function() {
  console.log(buildDoc().outerHTML);
};

<div>
  <span class="elements" data-key="1" data-value="Person">1 person</span><br>
  <span class="elements" data-key="2" data-value="information">2 information</span><br>
  <span class="elements" data-key="3" data-value="name">3 name</span><br>
  <span class="elements" data-key="3" data-value="surname">3 surname</span><br>
  <span class="elements" data-key="2" data-value="address">2 address</span><br>
  <span class="elements" data-key="3" data-value="street">3 street</span><br>
  <span class="elements" data-key="3" data-value="country">3 country</span><br>
  <span class="elements" data-key="2" data-value="address">2 address</span><br>
  <span class="elements" data-key="3" data-value="street">3 street</span><br>
  <span class="elements" data-key="3" data-value="country">3 country</span><br>
</div>

PS. This probably won't run in IE 10 or lower due to lack of support for data-* attributes.


问:
Align a child class vertically to parent class
I am developing a webpage in which a user can show the larger image or preview of every thumbnails by hovering it.

I am using this Jquery code to show and center the larger image on the screen responsively.

```<code>var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

      $(self).children('.popup-preview').css("position", "fixed");
      $(self).children('.popup-preview').css("top", ($(window).height() / 2) - ($(self).children('.popup-preview').outerHeight() / 2));
      $(self).children('.popup-preview').css("left", ($(window).width() / 2) - ($(self).children('.popup-preview').outerWidth() / 2));

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);
</code>```

How can I align the larger image vertically the same with the parent class?

Here is my working sample code.

Update: Example is when the thumbnail is on the top or bottom of the screen and was hovered. The larger image should display vertically center of the screen.

答:
var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popup-preview {
  background: black;
  position: absolute;
  z-index: 1;
  top: 0;
  display: none;
}

.col-md-6 {
  float: left;
}

.theme-preview {
  position: relative;
}</code>```

THEME 1-1

           Preview

THEME 1-1

           Preview

THEME 1-1

           Preview

THEME 1-1

           Preview

```

Body:
I am developing a webpage in which a user can show the larger image or preview of every thumbnails by hovering it.

I am using this Jquery code to show and center the larger image on the screen responsively.

var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

      $(self).children('.popup-preview').css("position", "fixed");
      $(self).children('.popup-preview').css("top", ($(window).height() / 2) - ($(self).children('.popup-preview').outerHeight() / 2));
      $(self).children('.popup-preview').css("left", ($(window).width() / 2) - ($(self).children('.popup-preview').outerWidth() / 2));

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);

How can I align the larger image vertically the same with the parent class?

Here is my working sample code.

Update: Example is when the thumbnail is on the top or bottom of the screen and was hovered. The larger image should display vertically center of the screen.

Body:
var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);

.popup-preview {
  background: black;
  position: absolute;
  z-index: 1;
  top: 0;
  display: none;
}

.col-md-6 {
  float: left;
}

.theme-preview {
  position: relative;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-6.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-6.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>

  </div>
  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-4.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-4.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-3.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-3.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-5.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-5.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Android Studio Manifest Start and End Tags
I just recently started programming, and encountered a problem. My code seems fine, but Android Studio matches different start tags with end tags. This is my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="330" android:versionName="3.3 beta" package="com.example.furmanthelegend.nocrastinationapp">
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
<uses-permission android:name="android.permission.GET_TASKS" android:maxSdkVersion="24" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.sensor.stepcounter" android:required="false" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<application android:theme="null" android:label="NoCrastination" android:icon="res/drawable-mdpi-v4/ic_launcher.png" android:name="de.dfki.nocrastination.utils.NoCrastinationApplication" android:allowBackup="true">
    <activity android:label="NoCrastination" android:name="de.dfki.nocrastination.ui.activities.MainActivity" android:excludeFromRecents="true">
        <intent-filler>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filler>
    </activity>
    <activity android:label="Add New Condition" android:name="de.dfki.nocrastination.ui.activities.AddConditionsActivity" android:excludeFromRecents="true" />
    <activity android:label="Condition" android:name="de.dfki.nocrastination.ui.activities.ConditionDetailActivity" android:excludeFromRecents="true" />
    <activity android:label="App Information" android:name="de.dfki.nocrastination.ui.activities.appinformationActivity" android:excludeFromRecents="true" />
    <activity android:label="Recently Used Apps" android:name="de.dfki.nocrastination.ui.activities.previousappsActivity" android:excludeFromRecents="true" />
    <activity android:label="Credits" android:name="de.dfki.nocrastination.ui.activities.creditsActivity" android:excludeFromRecents="true" />
    <activity android:label="Settings" android:name="de.dfki.nocrastination.ui.activities.settingsactivity" android:excludeFromRecents="true" />
    <activity android:name="org.wordpress.passcodelock.PasscodeUnlockActivity" android:windowSoftInputMode="stateHidden" />
    <activity android:name="org.wordpress.passcodelock.PasscodeManagePasswordActivity" android:windowSoftInputMode="stateHidden" />
    <service android:name="de.dfki.nocrastination.logging.BackgroundService" android:enabled="true" android:exported="false" />
    <reciever android:name="de.dfki.nocrastination.logging.BootCompleteReceiver" android:enabled="true" android:exported="false" />
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </reciever>
    <provider android:label="NoCrastination" android:name="de.dfki.nocrastination.data.NoCrastinationProvider" android:exported="false" android:authorities="de.dfki.appdetox" />
    <service android:label="NoCrastination Laws" android:icon="res/drawable-xhdpi-v4/dcw_ic_extension.png" android:name="de.dfki.nocrastination.dashclockextension.nocrastinationExtension" android:permission="com.google.android.appa.dashclock.premission.READ_EXTENSION_DATA">
       <intent-filler>
           <action android:name="com.google.android.apps.dashclock.Extension" />
       </intent-filler>
        <meta-data android:name="protocolVersion" android:value="1" />
        <meta-data android:name="description" android:value="Shows current amount of active conditions and condition breaks" />
    </service>
    <service android:label="NoCrastination" android:name="de.dfki.nocrastination.logging.AppUsageAccesibilityService" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" android:enabled="true" >
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>
        <meta-data android:name="android.accessibilityservice" android:resource="res/xml/accessibility_service_config.xml" />
    </service>
    <meta-data android:name="com.crashlytics.ApiKey" android:value="c5cac52287e9abe392fe06e567285ee4aa9ed0bb" />
    <receiver android:label="NoCrastination's device admin" android:name="de.dfki.nocrastination.ui.activities.DeviceAdminSample" android:permission="android.permission.BING_DEVICE_ADMIN" android:description="Prevent stop forcefully">
            <meta-data android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <intent-filler>
                    <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filler>
    </receiver>
  </application>
<manifest>
</code>```

I am not great at programming, so any tips would be extremely appreciated and helpful. The main problem is that android studio matches  and other cases like that.

答:
you use inline close tag and outline also just remove the (/) from the reciever tag, to be:

```<code><reciever android:name="de.dfki.nocrastination.logging.BootCompleteReceiver" android:enabled="true" android:exported="false"> ==> removed "/"
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</reciever>
</code>```

And add "/" to the last line  to be

Body:
I just recently started programming, and encountered a problem. My code seems fine, but Android Studio matches different start tags with end tags. This is my code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="330" android:versionName="3.3 beta" package="com.example.furmanthelegend.nocrastinationapp">
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
<uses-permission android:name="android.permission.GET_TASKS" android:maxSdkVersion="24" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.sensor.stepcounter" android:required="false" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<application android:theme="null" android:label="NoCrastination" android:icon="res/drawable-mdpi-v4/ic_launcher.png" android:name="de.dfki.nocrastination.utils.NoCrastinationApplication" android:allowBackup="true">
    <activity android:label="NoCrastination" android:name="de.dfki.nocrastination.ui.activities.MainActivity" android:excludeFromRecents="true">
        <intent-filler>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filler>
    </activity>
    <activity android:label="Add New Condition" android:name="de.dfki.nocrastination.ui.activities.AddConditionsActivity" android:excludeFromRecents="true" />
    <activity android:label="Condition" android:name="de.dfki.nocrastination.ui.activities.ConditionDetailActivity" android:excludeFromRecents="true" />
    <activity android:label="App Information" android:name="de.dfki.nocrastination.ui.activities.appinformationActivity" android:excludeFromRecents="true" />
    <activity android:label="Recently Used Apps" android:name="de.dfki.nocrastination.ui.activities.previousappsActivity" android:excludeFromRecents="true" />
    <activity android:label="Credits" android:name="de.dfki.nocrastination.ui.activities.creditsActivity" android:excludeFromRecents="true" />
    <activity android:label="Settings" android:name="de.dfki.nocrastination.ui.activities.settingsactivity" android:excludeFromRecents="true" />
    <activity android:name="org.wordpress.passcodelock.PasscodeUnlockActivity" android:windowSoftInputMode="stateHidden" />
    <activity android:name="org.wordpress.passcodelock.PasscodeManagePasswordActivity" android:windowSoftInputMode="stateHidden" />
    <service android:name="de.dfki.nocrastination.logging.BackgroundService" android:enabled="true" android:exported="false" />
    <reciever android:name="de.dfki.nocrastination.logging.BootCompleteReceiver" android:enabled="true" android:exported="false" />
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </reciever>
    <provider android:label="NoCrastination" android:name="de.dfki.nocrastination.data.NoCrastinationProvider" android:exported="false" android:authorities="de.dfki.appdetox" />
    <service android:label="NoCrastination Laws" android:icon="res/drawable-xhdpi-v4/dcw_ic_extension.png" android:name="de.dfki.nocrastination.dashclockextension.nocrastinationExtension" android:permission="com.google.android.appa.dashclock.premission.READ_EXTENSION_DATA">
       <intent-filler>
           <action android:name="com.google.android.apps.dashclock.Extension" />
       </intent-filler>
        <meta-data android:name="protocolVersion" android:value="1" />
        <meta-data android:name="description" android:value="Shows current amount of active conditions and condition breaks" />
    </service>
    <service android:label="NoCrastination" android:name="de.dfki.nocrastination.logging.AppUsageAccesibilityService" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" android:enabled="true" >
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>
        <meta-data android:name="android.accessibilityservice" android:resource="res/xml/accessibility_service_config.xml" />
    </service>
    <meta-data android:name="com.crashlytics.ApiKey" android:value="c5cac52287e9abe392fe06e567285ee4aa9ed0bb" />
    <receiver android:label="NoCrastination's device admin" android:name="de.dfki.nocrastination.ui.activities.DeviceAdminSample" android:permission="android.permission.BING_DEVICE_ADMIN" android:description="Prevent stop forcefully">
            <meta-data android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <intent-filler>
                    <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filler>
    </receiver>
  </application>
<manifest>

I am not great at programming, so any tips would be extremely appreciated and helpful. The main problem is that android studio matches  and other cases like that.

Body:
you use inline close tag and outline also just remove the (/) from the reciever tag, to be:

<reciever android:name="de.dfki.nocrastination.logging.BootCompleteReceiver" android:enabled="true" android:exported="false"> ==> removed "/"
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</reciever>

And add "/" to the last line  to be


问:
How could I implement a serial communication protocol in a object-oriented form?
I’m working on with an embedded device that is connected to PC using RS232.

I need to do a software to communicate with this embedded device.

I program in Delphi. I never used to use object-oriented in the past. But I'm trying to change this.

I am not able to think in an object oriented manner to solve this problem.

I have this protocol:

```<code><STX><STX><COMMAND>[<DATA><DATA>...]<CHKSUM><ETX>
</code>```

where:

```<code><STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).
</code>```

The software computer will send a command via serial, and the device will answer, using the same protocol.

For example:

```<code>Reset command
PC sends     : <STX><STX><0x09><0x00><CHKSUM><ETX>
Device answer: <STX><STX><0x09><0x00><CHKSUM><ETX>

Get Version
PC sends     : <STX><STX><0x00><0x02><CHKSUM><ETX>
Device answer: <STX><STX><0x00><0x00><VER_L><VER_H><CHKSUM><ETX>
</code>```

I have to send a file stream to the device.

I'd like to obtain suggestions and/or examples of the best way to implement this in an object oriented manner. I'd like to be able to do unit-test too.

Thanks

答:
You should look at other serial send/receive communication models, such as HTTP.  In .NET, the HTTPWebRequest object is where you gather together all the pieces of info to be sent across the wire - including command (HTTP METHOD: GET, PUT, POST, etc) and byte stream.  The HTTPWebRequest object (and the HTTP stack) internally deals with the "paperwork" of calculating checksums of the data, chunking large data into smaller packets, etc.  All your code has to do is construct the request object, set the command, assign a stream of data to the request object's property, and send.

Another reason why you should look at existing communication object models like .NET HTTP is that serial comms are generally asynchronous from the perspective of your host CPU.  A lot of CPU time can pass by while transmitting the characters of the request on the serial port, and while waiting for the response.  Use an async model for your request/response so that you don't block the calling thread and potentially freeze your UI.

To continue the .NET HTTP example, HTTPWebRequest has a GetResponse method which sends the request and will block the calling thread until a response is received.  HTTPWebRequest also has a BeginGetResponse()/EndGetResponse() pair so that you can send the request and provide a callback to be executed when the response arrives at some later time.

Even if your immediate design is ok with a thread-blocking synchronous call model, you should at least investigate asynchronous coding patterns and consider implementing your object as such.  You can always call an asynchronous method in a thread-blocking synchronous way, but it's much more difficult to call a synchronous method in an asynchronous way.  Invest a little time now to give yourself more options down the road.

ContentLicense: CC BY-SA 2.5

Body:
I’m working on with an embedded device that is connected to PC using RS232.

I need to do a software to communicate with this embedded device.

I program in Delphi. I never used to use object-oriented in the past. But I'm trying to change this.

I am not able to think in an object oriented manner to solve this problem.

I have this protocol:

<STX><STX><COMMAND>[<DATA><DATA>...]<CHKSUM><ETX>

where:

<STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).

The software computer will send a command via serial, and the device will answer, using the same protocol.

For example:

Reset command
PC sends     : <STX><STX><0x09><0x00><CHKSUM><ETX>
Device answer: <STX><STX><0x09><0x00><CHKSUM><ETX>

Get Version
PC sends     : <STX><STX><0x00><0x02><CHKSUM><ETX>
Device answer: <STX><STX><0x00><0x00><VER_L><VER_H><CHKSUM><ETX>

I have to send a file stream to the device.

I'd like to obtain suggestions and/or examples of the best way to implement this in an object oriented manner. I'd like to be able to do unit-test too.

Thanks


问:
Rsync photos from internal to external hard drive
I have ~18gb worth of photos/videos on my internal that I'm trying to move to my external via Rsync.  I initially tried:

```<code>sudo rsync -avh --progress --delete /Non-system files/Photo.photoslibrary/
/#2/Text_photos/
</code>```

But no dice, "No such file" error. I thought that maybe .photoslibrary had to be in a folder so I moved it to "photos" folder in Non-system files and subsequently tried:

```<code>sudo rsync -avh --progress --delete /Non-system files/photos/
Photo.photoslibrary/ /#2/Text_photos/
</code>```

I'm still getting the same error of:

```<code>rsync: link_stat "/Non-system" failed: No such file or directory (2)
rsync: link_stat "/Users/jcb_carrillo/files/photos/Photos" failed: No such file
or directory (2)
</code>```

So two things I've noticed but don't know why it's reacting the way it is.
1. It's not reading the space in my partition "Non-system files" it only reads "Non-system".

And 2. Once the first error of "No such file or directory" happens it for some reason moves to "/Users/jcb_carrillo/files/photos/Photos" which is in an entirely other partition that as you can see in my command, was never specified to go there.

I think there's something wrong with my syntax. Any idea?

答:
Looks like you might need to escape the blank space for the directory name "Non-system file"</p>

```<code>sudo rsync -avh --progress --delete /Non-system\ files/Photo.photoslibrary/
/#2/Text_photos/
</code>```

Body:
I have ~18gb worth of photos/videos on my internal that I'm trying to move to my external via Rsync.  I initially tried:

sudo rsync -avh --progress --delete /Non-system files/Photo.photoslibrary/
/#2/Text_photos/

But no dice, "No such file" error. I thought that maybe .photoslibrary had to be in a folder so I moved it to "photos" folder in Non-system files and subsequently tried:

sudo rsync -avh --progress --delete /Non-system files/photos/
Photo.photoslibrary/ /#2/Text_photos/

I'm still getting the same error of:

rsync: link_stat "/Non-system" failed: No such file or directory (2)
rsync: link_stat "/Users/jcb_carrillo/files/photos/Photos" failed: No such file
or directory (2)

So two things I've noticed but don't know why it's reacting the way it is.
1. It's not reading the space in my partition "Non-system files" it only reads "Non-system".

And 2. Once the first error of "No such file or directory" happens it for some reason moves to "/Users/jcb_carrillo/files/photos/Photos" which is in an entirely other partition that as you can see in my command, was never specified to go there.

I think there's something wrong with my syntax. Any idea?

Body:
Looks like you might need to escape the blank space for the directory name "Non-system file"

sudo rsync -avh --progress --delete /Non-system\ files/Photo.photoslibrary/
/#2/Text_photos/


问:
QT/C++: Getting LASTINPUTINFO to work
Hi I am learning C++ through QT and I'm on the part where I'm trying to get LASTINPUTINFO to work. Below is the code I have made to see how it works but it seems to be only returning a single value and doesn't ever change whenever I make any inputs.

Care to explain what I'm doing wrong? And maybe provide a working example so I could get a grasp.

I'm trying to run it on Windows 10 Pro 64-bit.

```<code>#include <QtCore/QCoreApplication>
#include <QDebug>
#include <Windows.h>
#include <unistd.h>

using namespace std;

test()
{
    LASTINPUTINFO lastii;
    lastii.cbSize = sizeof(LASTINPUTINFO);

    return lastii.dwTime;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    while (true) {
        qDebug() << test();
        sleep(1);
    }

    return a.exec();
}
</code>```

Example output here.

```<code>138899896
138899896
138899896
138899896
138899896
138899896
138899896
</code>```

Fixed code for reference. Thanks to Anders.

```<code>#include <QtCore/QCoreApplication>
#include <QDebug>
#include <Windows.h>
#include <unistd.h>
#include <iostream>

using namespace std;

test()
{
    LASTINPUTINFO lastii;
    lastii.cbSize = sizeof(LASTINPUTINFO);
    GetLastInputInfo(&lastii);

    return (GetTickCount() - lastii.dwTime) / 1000;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    while (true) {
        cout<<test()<<"\n";
        sleep(1);
    }

    return a.exec();
}
</code>```

答:
LASTINPUTINFO is not a class, it is a simple C struct. You actually have to call a function to fill it:

```<code>DWORD test() {
  LASTINPUTINFO lastii;
  lastii.cbSize = sizeof(LASTINPUTINFO);
  GetLastInputInfo(&lastii);
  return lastii.dwTime;
}
</code>```

Title: QT/C++: Getting LASTINPUTINFO to work

Body:
Hi I am learning C++ through QT and I'm on the part where I'm trying to get LASTINPUTINFO to work. Below is the code I have made to see how it works but it seems to be only returning a single value and doesn't ever change whenever I make any inputs.

Care to explain what I'm doing wrong? And maybe provide a working example so I could get a grasp.

I'm trying to run it on Windows 10 Pro 64-bit.

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <Windows.h>
#include <unistd.h>

using namespace std;

test()
{
    LASTINPUTINFO lastii;
    lastii.cbSize = sizeof(LASTINPUTINFO);

    return lastii.dwTime;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    while (true) {
        qDebug() << test();
        sleep(1);
    }

    return a.exec();
}

Example output here.

138899896
138899896
138899896
138899896
138899896
138899896
138899896

Fixed code for reference. Thanks to Anders.

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <Windows.h>
#include <unistd.h>
#include <iostream>

using namespace std;

test()
{
    LASTINPUTINFO lastii;
    lastii.cbSize = sizeof(LASTINPUTINFO);
    GetLastInputInfo(&lastii);

    return (GetTickCount() - lastii.dwTime) / 1000;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    while (true) {
        cout<<test()<<"\n";
        sleep(1);
    }

    return a.exec();
}

Body:
LASTINPUTINFO is not a class, it is a simple C struct. You actually have to call a function to fill it:

DWORD test() {
  LASTINPUTINFO lastii;
  lastii.cbSize = sizeof(LASTINPUTINFO);
  GetLastInputInfo(&lastii);
  return lastii.dwTime;
}


问:
How can I add newline("\n") on Dialog.alert(textfromxml)?
this '\n' doesnt work. Also I tried with LabelField and TextField. Result is same.:(
my code:))

```<code> Dialog.alert(errorString);
</code>```

and my xml line.

1) Check your camera's ip address and port number.'\n'2) Try Again

答:
This should work:</p>

```<code>String errorString =
    "1) Check your camera's ip address and port number.\n2) Try Again";

Dialog.alert(errorString);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
this '\n' doesnt work. Also I tried with LabelField and TextField. Result is same.:(
my code:))

 Dialog.alert(errorString);

and my xml line.

1) Check your camera's ip address and port number.'\n'2) Try Again

Body:
This should work:

String errorString =
    "1) Check your camera's ip address and port number.\n2) Try Again";

Dialog.alert(errorString);


问:
Can you make a def method that makes more def methods for Python
I've been playing around with tkinter a little and I found that you have to make a def method to use buttons. So I wanted to make 13 buttons because I wanna make a calculator but I really didn't want to make 13 def methods that do very similar things. I tried doing a nested def method (I've never really done that before) but, from what I've tried, it won't work. Am I just doing it wrong or is it just impossible. If it is impossible, is there any other way to mass produce def methods besides a lot of copy and a lot of paste? Here's the code:</p>

```<code>from tkinter import *
window=Tk()

window.geometry("500x500")
print("Restarting")
user=""
def oneb():
    global user
    print("1",end="")
    user+="1"
def twob():
    global user
    user+="2"
    print("2",end="")
def threeb():
    global user
    user+="3"
    print("3",end="")
def fourb():
    global user
    user+="4"
    print("4",end="")
def fiveb():
    global user
    user+="5"
    print("5",end="")
def sixb():
    global user
    user+="6"
    print("6",end="")
def sevenb():
    global user
    user+="7"
    print("7",end="")
def eightb():
    global user
    user+="8"
    print("8",end="")
def nineb():
    global user
    user+="9"
    print("9",end="")
def zerob():
    global user
    user+="0"
    print("0",end="")
def plusb():
    global user
    user+="+"
    print("+",end="")
def minusb():
    global user
    print("-",end = "")
def equalb():
    global user
    if "+" in user:
        user=user.partition("+")
        symbol="+"
    elif "-" in user:
        user=user.partition("-")
        symbol="-"
    else:
        print("=",user)
    num1=user[0]
    num2=user[2]
    num1=int(num1)
    num2=int(num2)
    if symbol=="+":
        answer=num1+num2
    else:
        answer=num1-num2
    answer=str(answer)
    print("="+answer)

heightb=5
widthb=10

#I know here I probably should've just made a def method.
one=Button(window, text="1",command=oneb,height=heightb,width=widthb)
one.grid(row=1,column=1)

two=Button(window, text="2",command=twob,height=heightb,width=widthb)
two.grid(row=1,column=2)

three=Button(window, text="3",command=threeb,height=heightb,width=widthb)
three.grid(row=1,column=3)

four=Button(window, text="4",command=fourb,height=heightb,width=widthb)
four.grid(row=2,column=1)

five=Button(window, text="5",command=fiveb,height=heightb,width=widthb)
five.grid(row=2,column=2)

six=Button(window, text="6",command=sixb,height=heightb,width=widthb)
six.grid(row=2,column=3)

seven=Button(window, text="7",command=sevenb,height=heightb,width=widthb)
seven.grid(row=3,column=1)

eight=Button(window, text="8",command=eightb,height=heightb,width=widthb)
eight.grid(row=3,column=2)

nine=Button(window, text="9",command=nineb,height=heightb,width=widthb)
nine.grid(row=3,column=3)

zero=Button(window, text="0",command=zerob,height=heightb,width=widthb)
zero.grid(row=4,column=2)

plus=Button(window, text="+", command=plusb,height=heightb, width=widthb)
plus.grid(row=2,column=4)

minus=Button(window,text="-", command=minusb,height=heightb, width=widthb)
minus.grid(row=1,column=4)

equal=Button(window,text="=", command=equalb,height=heightb, width=widthb)
equal.grid(row=3,column=4)

mainloop()
#button location var.grid(row=x,column=x)
</code>```

答:
You can make a function that returns a function.

For example,

```<code>def build_button(number):
    def button():
        global user
        user += str(number)
        print(number, end="")
    return button

oneb = build_button(1)
twob = build_button(2)
# ...
</code>```

This should be functionally identical to the [number]b functions you have above.

Body:
I've been playing around with tkinter a little and I found that you have to make a def method to use buttons. So I wanted to make 13 buttons because I wanna make a calculator but I really didn't want to make 13 def methods that do very similar things. I tried doing a nested def method (I've never really done that before) but, from what I've tried, it won't work. Am I just doing it wrong or is it just impossible. If it is impossible, is there any other way to mass produce def methods besides a lot of copy and a lot of paste? Here's the code:

from tkinter import *
window=Tk()

window.geometry("500x500")
print("Restarting")
user=""
def oneb():
    global user
    print("1",end="")
    user+="1"
def twob():
    global user
    user+="2"
    print("2",end="")
def threeb():
    global user
    user+="3"
    print("3",end="")
def fourb():
    global user
    user+="4"
    print("4",end="")
def fiveb():
    global user
    user+="5"
    print("5",end="")
def sixb():
    global user
    user+="6"
    print("6",end="")
def sevenb():
    global user
    user+="7"
    print("7",end="")
def eightb():
    global user
    user+="8"
    print("8",end="")
def nineb():
    global user
    user+="9"
    print("9",end="")
def zerob():
    global user
    user+="0"
    print("0",end="")
def plusb():
    global user
    user+="+"
    print("+",end="")
def minusb():
    global user
    print("-",end = "")
def equalb():
    global user
    if "+" in user:
        user=user.partition("+")
        symbol="+"
    elif "-" in user:
        user=user.partition("-")
        symbol="-"
    else:
        print("=",user)
    num1=user[0]
    num2=user[2]
    num1=int(num1)
    num2=int(num2)
    if symbol=="+":
        answer=num1+num2
    else:
        answer=num1-num2
    answer=str(answer)
    print("="+answer)

heightb=5
widthb=10

#I know here I probably should've just made a def method.
one=Button(window, text="1",command=oneb,height=heightb,width=widthb)
one.grid(row=1,column=1)

two=Button(window, text="2",command=twob,height=heightb,width=widthb)
two.grid(row=1,column=2)

three=Button(window, text="3",command=threeb,height=heightb,width=widthb)
three.grid(row=1,column=3)

four=Button(window, text="4",command=fourb,height=heightb,width=widthb)
four.grid(row=2,column=1)

five=Button(window, text="5",command=fiveb,height=heightb,width=widthb)
five.grid(row=2,column=2)

six=Button(window, text="6",command=sixb,height=heightb,width=widthb)
six.grid(row=2,column=3)

seven=Button(window, text="7",command=sevenb,height=heightb,width=widthb)
seven.grid(row=3,column=1)

eight=Button(window, text="8",command=eightb,height=heightb,width=widthb)
eight.grid(row=3,column=2)

nine=Button(window, text="9",command=nineb,height=heightb,width=widthb)
nine.grid(row=3,column=3)

zero=Button(window, text="0",command=zerob,height=heightb,width=widthb)
zero.grid(row=4,column=2)

plus=Button(window, text="+", command=plusb,height=heightb, width=widthb)
plus.grid(row=2,column=4)

minus=Button(window,text="-", command=minusb,height=heightb, width=widthb)
minus.grid(row=1,column=4)

equal=Button(window,text="=", command=equalb,height=heightb, width=widthb)
equal.grid(row=3,column=4)

mainloop()
#button location var.grid(row=x,column=x)

Body:
You can make a function that returns a function.

For example,

def build_button(number):
    def button():
        global user
        user += str(number)
        print(number, end="")
    return button

oneb = build_button(1)
twob = build_button(2)
# ...

This should be functionally identical to the [number]b functions you have above.


问:
why there are two classes for handling request in Struts 1.3 , ActionServlet and RequestProcessor
Why in struts 1.3 we have two separated classes for handling request :

-- ActionServlet which intercept the request and calls RequestProcessors process method for further processing

  --RequestProcessor read XML file, find the appropriate Handler and handles request

My question is why this are two different classes?
I tried to search on the net and books but did not got any answer.

Can any one have any idea? please let me know

答:
The RequestProcessor Class is the actual place where the request processing takes place in a Struts controller environment.

When the request object first reaches the actionservlet class then it invokes the process method of the underlying RequestProcessor Class.

This process method then looks into the struts-config.xml file and tries to locate the name of the action that has come with the request.Once it identifies the action in the xml file it continues the rest of the steps needed for request processing.


问:
Simultaneous sessions of Rstudio
Is it possible to somehow open several RStudios at the same time? I have Rstudio open, and when I try to open another one, nothing happens. What is the proper way to work on several projects simultaneously in RStudio?

答: On a Windows machine you can "scroll click" on the icon and it will open a new session. You could probably also right click and choose something, not on a PC right now so cant tell for sure. </p>

Title: Simultaneous sessions of Rstudio


问:
symfony Notice: Undefined index: username
this code to fetch all user names from my database and print it on a web page but i get this error from this line

```<code>echo $row['username'];
</code>```

what's the wrong ?

```<code><?php

namespace test\stuffBundle\Controller;

use tuto\testBundle\Entity\Users;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Session\Session;
use Ratchet\WebSocket\WsServerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {

        $conn = $this->get('database_connection');

        while ($row = $conn->fetchAll('SELECT username FROM user')) {
            echo $row['username'];
        }
        return $this->render('teststuffBundle:Default:index.html.twig');
    }
}
</code>```

my entity user file

```<code><?php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
     /**
     *@var integer
     *
     * @ORM\Column(name="MatchP",type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $MatchP;
    public function getMatchP()
    {
        return $this->MatchP;
    }

    public function setMatchP($MatchP)
    {
        $this->MatchP = $MatchP;
    }

    public function __construct()
    {
        parent::__construct();
    }
}
</code>```

my print_r($row); output

```<code>Array ( [0] => Array ( [username] => shar ) [1] => Array ( [username] => koko ) ) Array ( [0] => Array ( [username] => shar ) [1]
</code>```

=> Array ( [username] => koko ) )

答:
I suspect it's a result set and you need to try like this:

```<code>$row = $conn->fetchAll('SELECT username FROM user');

foreach( $row as $user){
    echo $user['username'];
}
</code>```

Can you try and see if that works. I'm not certain it will work though.

Body:
this code to fetch all user names from my database and print it on a web page but i get this error from this line

echo $row['username'];

what's the wrong ?

<?php

namespace test\stuffBundle\Controller;

use tuto\testBundle\Entity\Users;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Session\Session;
use Ratchet\WebSocket\WsServerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {

        $conn = $this->get('database_connection');

        while ($row = $conn->fetchAll('SELECT username FROM user')) {
            echo $row['username'];
        }
        return $this->render('teststuffBundle:Default:index.html.twig');
    }
}

my entity user file

<?php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
     /**
     *@var integer
     *
     * @ORM\Column(name="MatchP",type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $MatchP;
    public function getMatchP()
    {
        return $this->MatchP;
    }

    public function setMatchP($MatchP)
    {
        $this->MatchP = $MatchP;
    }

    public function __construct()
    {
        parent::__construct();
    }
}

my print_r($row); output

Array ( [0] => Array ( [username] => shar ) [1] => Array ( [username] => koko ) ) Array ( [0] => Array ( [username] => shar ) [1]

=> Array ( [username] => koko ) )

Body:
I suspect it's a result set and you need to try like this:

$row = $conn->fetchAll('SELECT username FROM user');

foreach( $row as $user){
    echo $user['username'];
}

Can you try and see if that works. I'm not certain it will work though.


问:
How to receive and use a json in ajax sended from php?
I want to receive json from php to ajax and want to access the different field values in json.</p>

答:
On the PHP side, use json_encode() to convert your data to JSON, and write it out, then exit. Best send a content type header first, to make sure the receiving end recognizes it as JSON:

```<code><?php
$response_data = whatever_function();
$response = json_encode($response_data);
header("Content-type: text/json");
echo $response;
exit;
</code>```

On the client, your best bet is to use an existing AJAX framework, such as the AJAX functionality built into jQuery. Suppose your script is at http://example.com/ajax.php, and the client page is at http://example.com/ajaxclient.html, a suitable piece of jQuery would go something like:

```<code>$.getJSON('ajax.php', { /* GET data goes here */ }, function(data) {
    /* data contains the values you sent in your PHP script */
});
</code>```

Body:
On the PHP side, use json_encode() to convert your data to JSON, and write it out, then exit. Best send a content type header first, to make sure the receiving end recognizes it as JSON:

<?php
$response_data = whatever_function();
$response = json_encode($response_data);
header("Content-type: text/json");
echo $response;
exit;

On the client, your best bet is to use an existing AJAX framework, such as the AJAX functionality built into jQuery. Suppose your script is at http://example.com/ajax.php, and the client page is at http://example.com/ajaxclient.html, a suitable piece of jQuery would go something like:

$.getJSON('ajax.php', { /* GET data goes here */ }, function(data) {
    /* data contains the values you sent in your PHP script */
});


问:
JMETER Beanshell ( java.lang.String ) not found in class
I am developing a Jmeter beanshell script to work with Selenium. I decided to use the beanshell sampler so i can use java and selenium commands not accessible in the WDS interface.

My code work fine except for some String inputs. Here is a sample (torn down to barebones):

```<code>import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
</code>```

and i get this error

```<code>2017/03/31 13:43:21 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval   Sourced file: inline evaluation of: ``import org.openqa.selenium.chrome.ChromeOptions; debug();  ChromeOptions options . . . '' : Error in method invocation: Method addArguments( java.lang.String ) not found in class'org.openqa.selenium.chrome.ChromeOptions'  2017/03/31 13:43:21 WARN  - jmeter.protocol.java.sampler.BeanShellSampler: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.openqa.selenium.chrome.ChromeOptions; debug();  ChromeOptions options . . . '' : Error in method invocation: Method addArguments( java.lang.String ) not found in class'org.openqa.selenium.chrome.ChromeOptions'  201
</code>```

I see this similar in some other commands like sendkeys.

Why is this command not taking my String? I can run the full script and the browser opens file so i know selenium is setup with jmeter. It is just certain commands that use Strings that do this.

Thanks
J

答:
Depending on your Selenium client libraries version you may not have this method taking single String as a parameter. Create a new Beanshell Sampler with the following line:

```<code>log.info(javap(org.openqa.selenium.chrome.ChromeOptions));
</code>```

And look into JMeter console: you will see javap command printing out all the available methods for the ChromeOptions class, for instance for my installation (I have WebDriver Sampler plugin) it outputs the following:

Class class org.openqa.selenium.chrome.ChromeOptions extends class java.lang.Object

public boolean org.openqa.selenium.chrome.ChromeOptions.equals(java.lang.Object)

public int org.openqa.selenium.chrome.ChromeOptions.hashCode()

public void org.openqa.selenium.chrome.ChromeOptions.addArguments(java.lang.String[])

public void org.openqa.selenium.chrome.ChromeOptions.addArguments(java.util.List)

If you use the same Selenium libraries version (2.52.0) as I do you should change this line:

```<code>options.addArguments("start-maximized");
</code>```

to this one:

```<code>options.addArguments(new String[] {"start-maximized"});
</code>```

And your script should start working as expected.

See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on Beanshell scripting in JMeter tests.

Body:
I am developing a Jmeter beanshell script to work with Selenium. I decided to use the beanshell sampler so i can use java and selenium commands not accessible in the WDS interface.

My code work fine except for some String inputs. Here is a sample (torn down to barebones):

import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");

and i get this error

2017/03/31 13:43:21 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval   Sourced file: inline evaluation of: ``import org.openqa.selenium.chrome.ChromeOptions; debug();  ChromeOptions options . . . '' : Error in method invocation: Method addArguments( java.lang.String ) not found in class'org.openqa.selenium.chrome.ChromeOptions'  2017/03/31 13:43:21 WARN  - jmeter.protocol.java.sampler.BeanShellSampler: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.openqa.selenium.chrome.ChromeOptions; debug();  ChromeOptions options . . . '' : Error in method invocation: Method addArguments( java.lang.String ) not found in class'org.openqa.selenium.chrome.ChromeOptions'  201

I see this similar in some other commands like sendkeys.

Why is this command not taking my String? I can run the full script and the browser opens file so i know selenium is setup with jmeter. It is just certain commands that use Strings that do this.

Thanks
J

Body:
Depending on your Selenium client libraries version you may not have this method taking single String as a parameter. Create a new Beanshell Sampler with the following line:

log.info(javap(org.openqa.selenium.chrome.ChromeOptions));

And look into JMeter console: you will see javap command printing out all the available methods for the ChromeOptions class, for instance for my installation (I have WebDriver Sampler plugin) it outputs the following:

Class class org.openqa.selenium.chrome.ChromeOptions extends class java.lang.Object

public boolean org.openqa.selenium.chrome.ChromeOptions.equals(java.lang.Object)

public int org.openqa.selenium.chrome.ChromeOptions.hashCode()

public void org.openqa.selenium.chrome.ChromeOptions.addArguments(java.lang.String[])

public void org.openqa.selenium.chrome.ChromeOptions.addArguments(java.util.List)

If you use the same Selenium libraries version (2.52.0) as I do you should change this line:

options.addArguments("start-maximized");

to this one:

options.addArguments(new String[] {"start-maximized"});

And your script should start working as expected.

See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on Beanshell scripting in JMeter tests.


问:
What are the different build-in filters available in Angular.js?
What are the different build-in filters available in Angular.js can anyone explain me with example.

答:
here is the list of Angular built-in filters, with proper explanation.
https://docs.angularjs.org/api/ng/filter</p>