问:
Can't load static files after cloning a Django project
I know this question has been asked a lot but I really can't figure out why my static files won't be loaded. I cloned a project from a friend(no idea if that has anything to do with it) and when try to link to the static files I keep getting the 404 error in the debug console on Chrome.

header in my HTML

```<code>{% load staticfiles %}
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!--http://ianlunn.github.io/Hover/-->
<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link href="{% static 'css/hover.css' %}" rel="stylesheet" media="all">
  <link href="css/hover.css" rel="stylesheet" media="all">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="{% static 'js/bootstrap.min.js' %}"></script>
  <link rel="stylesheet" href="{% static 'css/bootstrap-theme.css' %}">
  <link rel="stylesheet" href="{% static 'css/bootstrap-override.css' %}">
</head>

import os
import datetime

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DJANGO_DIR = os.path.dirname(BASE_DIR)
PROJECT_DIR = os.path.dirname(os.path.dirname(DJANGO_DIR))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ****

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "django.contrib.sites",

    #3rd Party APPS
    'rest_framework',
    'rest_framework_jwt',
    'cuser', #https://github.com/tmm/django-username-email
    "pinax.stripe",

    #Custom modules
    'api',

    #Own apps
    'apps.user',
    'apps.payment',
]

# Custom user model
AUTH_USER_MODEL = 'user.User'

# SITE_ID for the Sites framework
SITE_ID = 1

PINAX_STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "**")
PINAX_STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "**")

JWT_AUTH = {
    'JWT_ALLOW_REFRESH': True,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}

DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.signals.SignalsPanel',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'audit_log.middleware.UserLoggingMiddleware',
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(DJANGO_DIR, 'templates'), os.path.join(DJANGO_DIR, 'email_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',
                'django.template.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

REST_FRAMEWORK = {
    # 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

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

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = '/project/static/'

MEDIA_URL = 'django/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'django/')
</code>```

urls.py

```<code>urlpatterns = [
    url(r'^', include(auth_urls)),
    url(r'^', include(user_urls)),
    url(r'^', include(referral_urls)),
    url(r'^', include(payment_urls)),
    url(r'^', include(cabinet_urls)),
    # Admin
    url(r'^admin/', admin.site.urls),
    url(r'^api/feedback/', FeedbackView.as_view()),
]

if common.DEBUG:
    urlpatterns += static(common.MEDIA_URL, document_root=common.MEDIA_ROOT)
    urlpatterns += static(common.STATIC_URL, document_root=common.STATIC_ROOT)
</code>```

I think I've tried everything, I'm having no problem loading MEDIA_URL and MEDIA_URL

Here's a screenshot of my project structure

答:
Try this: STATIC_ROOT = os.path.join(BASE_DIR, '/project/static/')

The static files can be tricky and there are many reasons why they won't load. You say your media files are loading properly and its because you reference them like MEDIA_ROOT = os.path.join(BASE_DIR, 'django/'). If you would Print that Path (print MEDIA_ROOT) something like this would come in your console: "ThisPC/Documents/Github/django/media". This path leads directly to your Media Folder but when django is looking for the Static Root it won't find the folder since you only said "project/static" but it should be "ThisPC/Documents/Github/project/static" (or similar to this).

If you ask why your friend did that, its because you only upload the GitHub folder when you go in production and there the static path would be correct. The Media files won't work like this in production.

What Fazil Zaid pointed out in the comments is also important. In your urls.py file you have if common.DEBUG:, usually you would use if settings.DEBUG: (for Debug = True in the settings.py file) change that line or find out what common.py is and why he used it. It seems to be an extra settings file. I would nor recommend to use it if you are not familiar with the project.

Before you push that project to production you want to change the Secret Key and install White Noise for the static files. I hope that helps and will do the trick.

p.s. what exactly is this?
PINAX_STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "sk_test_7dTOnMGX55bNC2yQ4ihqsHuV")
PINAX_STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "pk_test_LutZeiAuAewyQhJuLLUJXdfi") And you also posted the secret key of the project? You know when its just some hobby Site so you can practice its all fun and games but when payments are involved you can get sued for posting things like this online. If a Users bank account details get hacked (and that quite easy with all the passwords you are providing) you have huge Problems. PLEASE remember to change all of these before pushing anything online. Happy Coding :)

Edit:
  Try this one:
      STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), '/project/static') or hardcoded STATIC_ROOT = users/elitebook/documents/github/project/static/

The Path should be correct. That is definitely your Problem or at least one of the major ones. Django does not know where to look for the static files. If it does not work copy the printed Media Path, edit it and then put the hardcoded path into your settings file. This should be the Path: STATIC_ROOT = users/elitebook/documents/github/project/static/ Not sure if a C:/ is infront of that part or not look at the Media root and try to copy the first part and edit the second so it points to static instead of Media. When Debug is True and your files still don't load than you have another Problem somewhere else.

Body:
I know this question has been asked a lot but I really can't figure out why my static files won't be loaded. I cloned a project from a friend(no idea if that has anything to do with it) and when try to link to the static files I keep getting the 404 error in the debug console on Chrome.

header in my HTML

{% load staticfiles %}
{% load static %}

<!DOCTYPE html>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link href="{% static 'css/hover.css' %}" rel="stylesheet" media="all">
  <link href="css/hover.css" rel="stylesheet" media="all">

  <link rel="stylesheet" href="{% static 'css/bootstrap-theme.css' %}">
  <link rel="stylesheet" href="{% static 'css/bootstrap-override.css' %}">

import os
import datetime

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DJANGO_DIR = os.path.dirname(BASE_DIR)
PROJECT_DIR = os.path.dirname(os.path.dirname(DJANGO_DIR))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ****

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "django.contrib.sites",

    #3rd Party APPS
    'rest_framework',
    'rest_framework_jwt',
    'cuser', #https://github.com/tmm/django-username-email
    "pinax.stripe",

    #Custom modules
    'api',

    #Own apps
    'apps.user',
    'apps.payment',
]

# Custom user model
AUTH_USER_MODEL = 'user.User'

# SITE_ID for the Sites framework
SITE_ID = 1

PINAX_STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "**")
PINAX_STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "**")

JWT_AUTH = {
    'JWT_ALLOW_REFRESH': True,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}

DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.signals.SignalsPanel',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'audit_log.middleware.UserLoggingMiddleware',
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(DJANGO_DIR, 'templates'), os.path.join(DJANGO_DIR, 'email_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',
                'django.template.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

REST_FRAMEWORK = {
    # 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

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

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = '/project/static/'

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

urls.py

urlpatterns = [
    url(r'^', include(auth_urls)),
    url(r'^', include(user_urls)),
    url(r'^', include(referral_urls)),
    url(r'^', include(payment_urls)),
    url(r'^', include(cabinet_urls)),
    # Admin
    url(r'^admin/', admin.site.urls),
    url(r'^api/feedback/', FeedbackView.as_view()),
]

if common.DEBUG:
    urlpatterns += static(common.MEDIA_URL, document_root=common.MEDIA_ROOT)
    urlpatterns += static(common.STATIC_URL, document_root=common.STATIC_ROOT)

I think I've tried everything, I'm having no problem loading MEDIA_URL and MEDIA_URL

Here's a screenshot of my project structure


来源: stackexchange

问:
reading entire text file using vba
I'm trying to read a text file using vba. I tried the below code

```<code>Open "C:\tester.txt" For Input As #1
Worksheets("UI").Range("H12").Value = Input$(LOF(1), 1)
Close #1
</code>```

When I run this I'm getting an error.

Run-time error '62'. Input past end of file.

The content of text file is:

Unable to open COM10. Make sure it is connected

    Plus other stuff

    And more stuff

    way more stuff

Thanks in advance for help.

答:
More Slightly modified for those who do not like VBA to have to make up explicit variables and then waste time transfer data to them.. Let With. do the job</p>

```<code>Function LoadFileStr$(FN$)

  With CreateObject("Scripting.FileSystemObject")

          LoadFileStr = .OpenTextFile(FN, 1).readall

        End With

End Function
</code>```

ContentLicense: CC BY-SA 3.0

Title: reading entire text file using vba

Body:
I'm trying to read a text file using vba. I tried the below code

Open "C:\tester.txt" For Input As #1
Worksheets("UI").Range("H12").Value = Input$(LOF(1), 1)
Close #1

When I run this I'm getting an error.

Run-time error '62'. Input past end of file.

The content of text file is:

Unable to open COM10. Make sure it is connected

    Plus other stuff

    And more stuff

    way more stuff

Thanks in advance for help.

Body:
More Slightly modified for those who do not like VBA to have to make up explicit variables and then waste time transfer data to them.. Let With. do the job

Function LoadFileStr$(FN$)

  With CreateObject("Scripting.FileSystemObject")

          LoadFileStr = .OpenTextFile(FN, 1).readall

        End With

End Function


问:
Upload a file to SharePoint through the built-in web services
What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?

Following the two initial answers...

We definitely need to use the Web Service layer as we will be making these calls from remote client applications.

The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.

There is additionally a web service to upload files, painful but works all the time.

Are you referring to the “Copy” service?
We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?

I have posted our code as a suggested answer.

答:
Another option is to use plain ol' HTTP PUT:

```<code>WebClient webclient = new WebClient();
webclient.Credentials = new NetworkCredential(_userName, _password, _domain);
webclient.UploadFile(remoteFileURL, "PUT", FilePath);
webclient.Dispose();
</code>```

Where remoteFileURL points to your SharePoint document library...

OwnerDisplayName: Andy McCluggage

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Andy McCluggage

Body:
Another option is to use plain ol' HTTP PUT:

WebClient webclient = new WebClient();
webclient.Credentials = new NetworkCredential(_userName, _password, _domain);
webclient.UploadFile(remoteFileURL, "PUT", FilePath);
webclient.Dispose();

Where remoteFileURL points to your SharePoint document library...

OwnerDisplayName: Jim Harte


问:
Deserialize JSON into C# dynamic object?
Is there a way to deserialize JSON content into a C# dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer.

答: The object you want DynamicJSONObject is included in the System.Web.Helpers.dll from the ASP.NET Web Pages package, which is part of WebMatrix.</p>

ContentLicense: CC BY-SA 4.0


问:
Clustering SURF features of an image dataset using k-means algorithm
I want to implement Bag of Visual Words in MATLAB.  First I read images from dataset directory and I detect SURF features and extract them using these two functions detectSURFFeatures and extractFeatures.

I store each feature into a cell array and finally I want to cluster them using the k-means algorithm but I can't fit this data into k-means function input. How can I insert SURF features into the k-means clustering algorithm in MATLAB?

Here is my sample code which reads image from files and extracts their SURF features.

```<code>clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    image=imread(fullFileName);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    features{k}= im_features;

end

[centers, assignments] = kmeans(double(features), 100);
</code>```

答:
kmeans expects a N x P matrix for the input data where N is the total number of examples and P is the total number of features.  What you are doing incorrectly is placing each feature matrix into a cell array.  What you have to do instead is to concatenate all of the features from all of the images into a single matrix.

The easiest way to do that would be to add the following code before your kmeans call:

```<code>features = vertcat(features{:});
</code>```

The function vertcat will vertically stack matrices together given a list of matrices that all share the same number of columns.  Doing features{:} extracts out a comma-separated list so that it is equivalent to doing:

```<code>features = vertcat(features{1}, features{2}, ...);
</code>```

The final effect is that this will vertically stack all of the SURF features from every single image together into a 2D matrix.  You are using the default version of SURF, so each feature should be of length 64, so you should have 64 columns.  The number of rows should be the total number of features detected over all images.

Therefore, to be absolutely clear:

```<code>clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    image=imread(fullFileName);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    features{k}= im_features;

end

% New code
features = vertcat(features{:});

% Resume old code
[centers, assignments] = kmeans(double(features), 100);
</code>```

Body:
I want to implement Bag of Visual Words in MATLAB.  First I read images from dataset directory and I detect SURF features and extract them using these two functions detectSURFFeatures and extractFeatures.

I store each feature into a cell array and finally I want to cluster them using the k-means algorithm but I can't fit this data into k-means function input. How can I insert SURF features into the k-means clustering algorithm in MATLAB?

Here is my sample code which reads image from files and extracts their SURF features.

clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    image=imread(fullFileName);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    features{k}= im_features;

end

[centers, assignments] = kmeans(double(features), 100);

Body:
kmeans expects a N x P matrix for the input data where N is the total number of examples and P is the total number of features.  What you are doing incorrectly is placing each feature matrix into a cell array.  What you have to do instead is to concatenate all of the features from all of the images into a single matrix.

The easiest way to do that would be to add the following code before your kmeans call:

features = vertcat(features{:});

The function vertcat will vertically stack matrices together given a list of matrices that all share the same number of columns.  Doing features{:} extracts out a comma-separated list so that it is equivalent to doing:

features = vertcat(features{1}, features{2}, ...);

The final effect is that this will vertically stack all of the SURF features from every single image together into a 2D matrix.  You are using the default version of SURF, so each feature should be of length 64, so you should have 64 columns.  The number of rows should be the total number of features detected over all images.

Therefore, to be absolutely clear:

clc;
clear;
close all;
folder = 'CarData/TrainImages/cars';
filePattern = fullfile(folder, '*.pgm');
f=dir(filePattern);
files={f.name};
for k=1:numel(files)
    fullFileName = fullfile(folder, files{k});
    image=imread(fullFileName);
    temp =  detectSURFFeatures(image);
    [im_features, temp] = extractFeatures(image, temp);
    features{k}= im_features;

end

% New code
features = vertcat(features{:});

% Resume old code
[centers, assignments] = kmeans(double(features), 100);


问:
requires_grad relation to leaf nodes
From the docs:

requires_grad – Boolean indicating whether the Variable has been
  created by a subgraph containing any Variable, that requires it.  Can
  be changed only on leaf Variables

What does it mean by leaf nodes here? Are leaf nodes only the input nodes?

If it can be only changed at the leaf nodes, how can I freeze layers then?

答:
Leaf nodes of a graph are those nodes (i.e. Variables) that were not computed directly from other nodes in the graph. For example:

```<code>import torch
from torch.autograd import Variable

A = Variable(torch.randn(10,10)) # this is a leaf node
B = 2 * A # this is not a leaf node
w = Variable(torch.randn(10,10)) # this is a leaf node
C = A.mm(w) # this is not a leaf node
</code>```

If a leaf node requires_grad, all subsequent nodes computed from it will automatically also require_grad. Else, you could not apply the chain rule to calculate the gradient of the leaf node which requires_grad. This is the reason why requires_grad can only be set for leaf nodes: For all others, it can be smartly inferred and is in fact determined by the settings of the leaf nodes used for computing these other variables.

Note that in a typical neural network, all parameters are leaf nodes. They are not computed from any other Variables in the network. Hence, freezing layers using requires_gradis simple. Here, is an example taken from the PyTorch docs:

```<code>model = torchvision.models.resnet18(pretrained=True)
for param in model.parameters():
    param.requires_grad = False

# Replace the last fully-connected layer
# Parameters of newly constructed modules have requires_grad=True by default
model.fc = nn.Linear(512, 100)

# Optimize only the classifier
optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)
</code>```

Even though, what you really do is freezing the entire gradient computation (which is what you should be doing as it avoids unnecessary computation). Technically, you could leave the requires_grad flag on, and only define your optimizer for a subset of the parameters that you would like to learn.

Title: requires_grad relation to leaf nodes

Body:
Leaf nodes of a graph are those nodes (i.e. Variables) that were not computed directly from other nodes in the graph. For example:

import torch
from torch.autograd import Variable

A = Variable(torch.randn(10,10)) # this is a leaf node
B = 2 * A # this is not a leaf node
w = Variable(torch.randn(10,10)) # this is a leaf node
C = A.mm(w) # this is not a leaf node

If a leaf node requires_grad, all subsequent nodes computed from it will automatically also require_grad. Else, you could not apply the chain rule to calculate the gradient of the leaf node which requires_grad. This is the reason why requires_grad can only be set for leaf nodes: For all others, it can be smartly inferred and is in fact determined by the settings of the leaf nodes used for computing these other variables.

Note that in a typical neural network, all parameters are leaf nodes. They are not computed from any other Variables in the network. Hence, freezing layers using requires_gradis simple. Here, is an example taken from the PyTorch docs:

model = torchvision.models.resnet18(pretrained=True)
for param in model.parameters():
    param.requires_grad = False

# Replace the last fully-connected layer
# Parameters of newly constructed modules have requires_grad=True by default
model.fc = nn.Linear(512, 100)

# Optimize only the classifier
optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9)

Even though, what you really do is freezing the entire gradient computation (which is what you should be doing as it avoids unnecessary computation). Technically, you could leave the requires_grad flag on, and only define your optimizer for a subset of the parameters that you would like to learn.


问:
Scroll to the very bottom of the page Python
Having issue with scrolling method. Here is my code, by looks like it works fine, but completely ignoring self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") line.

Is there any other method by chance?

Keep in mind, I cannot use any particular element like 'self.driver.find_element_by_id' at the end, because they keep changing all the time.

```<code>def ViewEventHistory(self):
    self.login()
    self.controlMenu('2')
    time.sleep(2)
    view_event = self.driver.find_element_by_id('com.eightdevelopment.eas.android:id/btn_event_history')
    view_event.click()
    time.sleep(10)
    self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)
</code>```

答:
As I understand, the problem here is that your are trying to scroll the window, but actually you need to scroll the pop-up that is opened by view_event.click().

You can use a snippet I wrote for one of my projects. It accepts an optional Selenium element and scrolls it. If it's not provided, the function scrolls the main window.

```<code>def _scroll(self, scroll_obj=None):
    if scroll_obj:
        self.driver.execute_script(
            'arguments[0].scrollTop = arguments[0].scrollHeight;', scroll_obj)
    else:
        self.driver.execute_script(
            'document.body.scrollTop = document.body.scrollHeight;')
</code>```

Body:
Having issue with scrolling method. Here is my code, by looks like it works fine, but completely ignoring self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") line.

Is there any other method by chance?

Keep in mind, I cannot use any particular element like 'self.driver.find_element_by_id' at the end, because they keep changing all the time.

def ViewEventHistory(self):
    self.login()
    self.controlMenu('2')
    time.sleep(2)
    view_event = self.driver.find_element_by_id('com.eightdevelopment.eas.android:id/btn_event_history')
    view_event.click()
    time.sleep(10)
    self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)

Body:
As I understand, the problem here is that your are trying to scroll the window, but actually you need to scroll the pop-up that is opened by view_event.click().

You can use a snippet I wrote for one of my projects. It accepts an optional Selenium element and scrolls it. If it's not provided, the function scrolls the main window.

def _scroll(self, scroll_obj=None):
    if scroll_obj:
        self.driver.execute_script(
            'arguments[0].scrollTop = arguments[0].scrollHeight;', scroll_obj)
    else:
        self.driver.execute_script(
            'document.body.scrollTop = document.body.scrollHeight;')


问:
Stripe implementation got error Cannot read property 'addEventListener' of null

I am trying to imeplement Stripe into my ASP.NET C#
I followed and integrate the Stripe Elements https://stripe.com/docs/elements

My code

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Payment2.aspx.cs" Inherits="Payment2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        /**
 * The CSS shown here will not be introduced in the Quickstart guide, but shows
 * how you can use CSS to style your Element's container.
 */
        .StripeElement {
            background-color: white;
            padding: 8px 12px;
            border-radius: 4px;
            border: 1px solid transparent;
            box-shadow: 0 1px 3px 0 #e6ebf1;
            -webkit-transition: box-shadow 150ms ease;
            transition: box-shadow 150ms ease;
        }

        .StripeElement--focus {
            box-shadow: 0 1px 3px 0 #cfd7df;
        }

        .StripeElement--invalid {
            border-color: #fa755a;
        }

        .StripeElement--webkit-autofill {
            background-color: #fefde5 !important;
        }
    </style>

    <script src="https://js.stripe.com/v3/"></script>
    <script type="text/javascript">
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <script src="https://js.stripe.com/v3/"></script>

            <form action="/Payment2.aspx" method="post" id="payment-form">
                <div class="form-row">
                    <label for="card-element">
                        Credit or debit card
                    </label>
                    <div id="card-element">
                        <!-- a Stripe Element will be inserted here. -->
                    </div>

                    <!-- Used to display form errors -->
                    <div id="card-errors" role="alert"></div>
                </div>

                <button>Submit Payment</button>
            </form>

        </div>
    </form>
    <script>

        // Create a Stripe client
        var stripe = Stripe('pk_test_2O7D78OBubjUApxMMbvbHLVr');

        // Create an instance of Elements
        var elements = stripe.elements();

        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
        var style = {
            base: {
                color: '#32325d',
                lineHeight: '24px',
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: 'antialiased',
                fontSize: '16px',
                '::placeholder': {
                    color: '#aab7c4'
                }
            },
            invalid: {
                color: '#fa755a',
                iconColor: '#fa755a'
            }
        };

        // Create an instance of the card Element
        var card = elements.create('card', { style: style });

        // Add an instance of the card Element into the `card-element` <div>
        card.mount('#card-element');

        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function (event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        // Handle form submission
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function (event) {
            event.preventDefault();

            stripe.createToken(card).then(function (result) {
                if (result.error) {
                    // Inform the user if there was an error
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    // Send the token to your server
                    stripeTokenHandler(result.token);
                }
            });
        });
    </script>
</body>
</html>
</code>```

Can someone tell me why I had error Uncaught TypeError: Cannot read property 'addEventListener' of null when I run the chrome console?
Error is from form.addEventListener('submit', function (event) {

答:
The problem is that you have a form within a form, which is invalid HTML:

```<code><form id="form1" runat="server">
  <div>
    <script src="https://js.stripe.com/v3/"></script>
    <form action="/Payment2.aspx" method="post" id="payment-form">
      <div class="form-row">
        <label for="card-element">
          Credit or debit card
        </label>
        <div id="card-element">
          <!-- a Stripe Element will be inserted here. -->
        </div>
        <!-- Used to display form errors -->
        <div id="card-errors" role="alert"></div>
      </div>
      <button>Submit Payment</button>
    </form>
  </div>
</form>
</code>```

You need to update your code to remove the outer form, as your addEventListener() is targeting the inner form:

```<code><div>
  <script src="https://js.stripe.com/v3/"></script>
  <form action="/Payment2.aspx" method="post" id="payment-form">
    <div class="form-row">
      <label for="card-element">
        Credit or debit card
      </label>
      <div id="card-element">
        <!-- a Stripe Element will be inserted here. -->
      </div>
      <!-- Used to display form errors -->
      <div id="card-errors" role="alert"></div>
    </div>
    <button>Submit Payment</button>
  </form>
</div>
</code>```

Not that it is possible to create a form within a form by utilising jQuery, though it's rather complex, and isn't needed in this case.

Hope this helps! :)

Body:
I am trying to imeplement Stripe into my ASP.NET C#
I followed and integrate the Stripe Elements https://stripe.com/docs/elements

My code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Payment2.aspx.cs" Inherits="Payment2" %>

<!DOCTYPE html>

    <title></title>

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

            <form action="/Payment2.aspx" method="post" id="payment-form">

                        Credit or debit card

                <button>Submit Payment</button>
            </form>

    </form>

Can someone tell me why I had error Uncaught TypeError: Cannot read property 'addEventListener' of null when I run the chrome console?
Error is from form.addEventListener('submit', function (event) {

Body:
The problem is that you have a form within a form, which is invalid HTML:

<form id="form1" runat="server">
  <div>
    <script src="https://js.stripe.com/v3/"></script>
    <form action="/Payment2.aspx" method="post" id="payment-form">
      <div class="form-row">
        <label for="card-element">
          Credit or debit card
        </label>
        <div id="card-element">
          <!-- a Stripe Element will be inserted here. -->
        </div>
        <!-- Used to display form errors -->
        <div id="card-errors" role="alert"></div>
      </div>
      <button>Submit Payment</button>
    </form>
  </div>
</form>

You need to update your code to remove the outer form, as your addEventListener() is targeting the inner form:

<div>
  <script src="https://js.stripe.com/v3/"></script>
  <form action="/Payment2.aspx" method="post" id="payment-form">
    <div class="form-row">
      <label for="card-element">
        Credit or debit card
      </label>
      <div id="card-element">
        <!-- a Stripe Element will be inserted here. -->
      </div>
      <!-- Used to display form errors -->
      <div id="card-errors" role="alert"></div>
    </div>
    <button>Submit Payment</button>
  </form>
</div>

Not that it is possible to create a form within a form by utilising jQuery, though it's rather complex, and isn't needed in this case.

Hope this helps! :)


问:
img with position absolute inside a div with position absolute
So I've got a main div element with position: relative.
Inside of it there's another div with position: absolute.
And inside that div I want to have  that will also have position absolute to it's parent element, but I can't get it to work.

Is there any workaround without having to nest that img inside another div? (I had problems with that due to the shape of my overlay and I will want to transform the image)

.1 {  position: relative;  }

.2 {  position: absolute;  }

.2 img {  position: absolute;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="1">
  <div class="2">
    <img src="foo.jpg">
  </div>
</div></code>```

答:
It works!

position: absolute, as far as I know, is relative to its first parent element that is not position: static, which is what every element is positioned by default.

.parent {
  position: relative;
}

.child {
  left: 100px;
  position: absolute;
}

img {
  left: 100px;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">
    <img src="https://via.placeholder.com/200x150">
  </div>
</div></code>```

Body:
It works!

position: absolute, as far as I know, is relative to its first parent element that is not position: static, which is what every element is positioned by default.

.parent {
  position: relative;
}

.child {
  left: 100px;
  position: absolute;
}

img {
  left: 100px;
  position: absolute;
}

<div class="parent">
  <div class="child">
    <img src="https://via.placeholder.com/200x150">
  </div>
</div>


问:
Android - Switching between Activities and Screens with same xml file
I'm building an app for educational purposes, with a lot of questions and challenges to the user to solve. But, it would be a HUGE amount of screens if I create a lot of questions and one xml file and activity for each one, as I want to have different kinds of questions, where the user should be able to write the code, select a block of code or select the correct answer about theory and stuff. Is there a way to use the same model of screen(xml file) for one specific kind of question? Like, using one model to all the screens and questions where the user should select the correct answer, and another model to another kind of question..

p.s: Yes, i'm kind newbie in Android

Thanks! :)

答:
I would recommend using FragmentStatePagerAdapter

You only needs one layout and every time a fragment looses focus, it is destroyed automatically.

It is the same as adapters. You just create the visible views and 2 more. In this case you will have the visible question and one on the left and one on the right.

Let me know if you need any help.


问:
await is a reserved word error in Expo XDE for React Native
Right to the point:

I'm using Expo XDE with react-native to build a cross-platform mobile app.

I want to save and retrieve a couple of variables using AsyncStorage ("localstorage" alternative in react-native).

After adding the pieces of code to store and retrieve,

Expo XDE is showing the following error when building the JavaScript bundle: "await is a reserved word"

According to the documentation (https://facebook.github.io/react-native/docs/asyncstorage.html), I got to use "await" when accessing AsyncStorage.

Any ideas? Is it a problem related to Expo XDE only?

Thanks!!

答:
To use await, your function including const username = await AsyncStorage.getItem(); needs to be async.

You can do like this :

```<code>async myfunction() {
  ...
  const username = await AsyncStorage.getItem();
  ...
}
</code>```

Body:
To use await, your function including const username = await AsyncStorage.getItem(); needs to be async.

You can do like this :

async myfunction() {
  ...
  const username = await AsyncStorage.getItem();
  ...
}


问:
Adding null conditional to function throw not defined
I´m new with Angular and JS and I have a funcion that load a simple select like this:

Angular Ctrl

```<code>function detalleRegistrosCtrl($scope, apiService, notificationService, $rootScope, $location, $stateParams, $http, $state) {
        Dropzone.autoDiscover = false;
        $scope.catalogoPadre = $stateParams.catalogopadre;

        cargarCatalogo();

    $scope.regresar = function () {
        $state.go("root.catalogosgenericos");
    }

    function errorCatalogo(res) {
        bootbox.alert("Error al cargar el catalogo" + res.data);
    }

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {

                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);
</code>```

Problem is when I try to add an if conditional into cargarCatalogo() function. When I do it as:

```<code>    if ($scope.catalogoPadre != null) {

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {
                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);
     }
</code>```

I´m getting into chrome console:

Error: cargarCatalogo is not defined

Can someone explain me what is wrong? I just add a conditional to a function.

答:
Instead of wrapping condition on the function declaration , add the condition when you call the cargarCatalogo() function. On your detalleRegistrosCtrl already calling that function

```<code>Dropzone.autoDiscover = false;
$scope.catalogoPadre = $stateParams.catalogopadre;
if ($scope.catalogoPadre != null) {
    cargarCatalogo();
}
</code>```

Body:
I´m new with Angular and JS and I have a funcion that load a simple select like this:

Angular Ctrl

function detalleRegistrosCtrl($scope, apiService, notificationService, $rootScope, $location, $stateParams, $http, $state) {
        Dropzone.autoDiscover = false;
        $scope.catalogoPadre = $stateParams.catalogopadre;

        cargarCatalogo();

    $scope.regresar = function () {
        $state.go("root.catalogosgenericos");
    }

    function errorCatalogo(res) {
        bootbox.alert("Error al cargar el catalogo" + res.data);
    }

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {

                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);

Problem is when I try to add an if conditional into cargarCatalogo() function. When I do it as:

    if ($scope.catalogoPadre != null) {

     function cargarCatalogo() {
         apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
            function (res) {
                $scope.Catalogos = res.data;
                $scope.selectedID = selected.ID;
            }, errorCatalogo);
     }

I´m getting into chrome console:

Error: cargarCatalogo is not defined

Can someone explain me what is wrong? I just add a conditional to a function.

Body:
Instead of wrapping condition on the function declaration , add the condition when you call the cargarCatalogo() function. On your detalleRegistrosCtrl already calling that function

Dropzone.autoDiscover = false;
$scope.catalogoPadre = $stateParams.catalogopadre;
if ($scope.catalogoPadre != null) {
    cargarCatalogo();
}


问:
Button to get me to an <div id= doesn't work
I just want that when I press Submit button to get me to the
 where the other code will be.

This is my work:

```<code><!DOCTYPE html>
</code>```

```<code><head>
    <title>MyWebsite</title>
</head>

<body>
    <div id="Start" align="center">
        <h1 style="color:red">My</style><span style="color:blue">Website</span></h1>
        <hr/>
        Name:<br/>
        <input type="text" name="username"><br/>
        Password:<br/>
        <input type="password" name="password"><br/><br/>
        <form action="Home">
            <input type="submit" name="continue" value="Continue">
        </form>
    </div>

    <div id="Home" align="center">
        <p>Hello world!</p>
    </div>
</body>
</code>```

答:
You need some PHP (or other server side language) between your form and the div below it. Otherwise you're just refreshing the page when you hit submit.

You could also use javascript/jQuery.

Try doing one or both of the above and then come back for help if you have trouble.

Body:
I just want that when I press Submit button to get me to the
 where the other code will be.

This is my work:

<!DOCTYPE html>

    <title>MyWebsite</title>

My</style>Website

        Name:

        <input type="text" name="username">

        Password:

        <input type="password" name="password">

        <form action="Home">
            <input type="submit" name="continue" value="Continue">
        </form>

Hello world!


问:
NewCard screen from DrawerNavigator item
I hope i'm able to explain this properly, and that there isn't already an answer out there. It seems there is still a few design decisions up in the air for apps that have a StackNavigator nested inside DrawerNavigator.

What I'm trying to achieve: I have a link to a "Settings" screen in my DrawerNavigator, similar to a lot of apps. I will use Google Play Music as an example for what I want. Clicking on "Settings" sends you to a new screen with only a "back" / "done" button. The Drawer Menu is not accessible.

Question: How can I add a link in the DrawerNavigator that links to a new card/modal view? I'm guessing it can be achieved my some nested navigator stack, but I haven't been able to get anything that works.

Sample code:

```<code>const DashboardNavigator = StackNavigator({
  Home: { screen: HomeScreen }
})

const SettingsNavigator = StackNavigator({
  Settings: {screen: SettingsScreen}

// I thought adding 'mode': 'modal would give me the functionality
// I'm looking for my it doesn't

}, { mode: 'modal', initialRoute: 'Settings' })

const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: DashboardNavigator
  },
  Settings: {
    screen: SettingsNavigator
  }
})
</code>```

There is a pull request to allow disabling the Drawer Menu on specific screens so i'm not really worried about that right now, but just navigating to a screen where navigation.goBack() takes me back to the last screen I was on (with the card slide animation).

答:
Was able to get it with this, although I still can access the Drawer menu... Hopefully they add the ability to disable the Drawer soon.</p>

```<code>const DrawerComponent = ({ navigation }) => {
  return (
    <View>
      <Button onPress={() => navigation.navigate("SettingsView")} title="settings" />
    </View>
  )
}

const DashboardNavigator = StackNavigator({
  Home: { screen: HomeScreen },
  SettingsView: { screen: SettingsScreen }
})

const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: DashboardNavigator
  }
}, { contentComponent: DrawerComponent })

const RootNavigator = StackNavigator({
  Root: {
    screen: DrawerNavigation
  }
})
</code>```

Body:
I hope i'm able to explain this properly, and that there isn't already an answer out there. It seems there is still a few design decisions up in the air for apps that have a StackNavigator nested inside DrawerNavigator.

What I'm trying to achieve: I have a link to a "Settings" screen in my DrawerNavigator, similar to a lot of apps. I will use Google Play Music as an example for what I want. Clicking on "Settings" sends you to a new screen with only a "back" / "done" button. The Drawer Menu is not accessible.

Question: How can I add a link in the DrawerNavigator that links to a new card/modal view? I'm guessing it can be achieved my some nested navigator stack, but I haven't been able to get anything that works.

Sample code:

const DashboardNavigator = StackNavigator({
  Home: { screen: HomeScreen }
})

const SettingsNavigator = StackNavigator({
  Settings: {screen: SettingsScreen}

// I thought adding 'mode': 'modal would give me the functionality
// I'm looking for my it doesn't

}, { mode: 'modal', initialRoute: 'Settings' })

const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: DashboardNavigator
  },
  Settings: {
    screen: SettingsNavigator
  }
})

There is a pull request to allow disabling the Drawer Menu on specific screens so i'm not really worried about that right now, but just navigating to a screen where navigation.goBack() takes me back to the last screen I was on (with the card slide animation).

Body:
Was able to get it with this, although I still can access the Drawer menu... Hopefully they add the ability to disable the Drawer soon.

const DrawerComponent = ({ navigation }) => {
  return (
    <View>
      <Button onPress={() => navigation.navigate("SettingsView")} title="settings" />
    </View>
  )
}

const DashboardNavigator = StackNavigator({
  Home: { screen: HomeScreen },
  SettingsView: { screen: SettingsScreen }
})

const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: DashboardNavigator
  }
}, { contentComponent: DrawerComponent })

const RootNavigator = StackNavigator({
  Root: {
    screen: DrawerNavigation
  }
})


问:
C/C++ function using float or double or int
I have seperate functions for reading from a text file (depending on whether its an int,  float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

```<code>float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}

double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}

int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}
</code>```

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.

答: ANSI C doesn't support function overloading, which is what you are trying to accomplish.  C++ does, however.  See the StackOverflow link here: Default values on arguments in C functions and function overloading in C</p>

Body:
I have seperate functions for reading from a text file (depending on whether its an int,  float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}

double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}

int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.


问:
Index numbers for row-wise duplicate entries using numpy/pandas in python
I have a numpy array/pandas data frame

```<code>[[0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [0 0 1 0],
 [0 0 1 0]]
</code>```

I need index number of row duplicates for this array. The results should be something like (0,2,4), (1,3), (5,6).

So far I have a work around, like I am running loops, one with unique values of the array rows against the actual array rows. That gives me results but not in the fashion I would want them to be.
This is the code I have made which gives me pairs but for a large array, this is very messy.

```<code>for i, row in enumerate(array):
    for j, row1 in enumerate(unique(array)):
        if tuple(row)==tuple(row1):
            pair.append(tuple([j,i]))
</code>```

my results looks like this:

```<code> [(0, 276),(1, 2931),(2, 3891),(3, 2165),(4, 1822),(5, 1241),
 (5, 2635),(5, 2644),(5, 2862),(5, 3296)]
</code>```

My array is very big, so this way I am manually choosing tuples based on the first value as the indicator for duplicates, then I choose the actual row number which is a duplicate. for Ex. - tuples having 5 as their first value mean row 1241 is duplicated at 2635, 2644, 2862 and 3296.

Can anyone suggest me a better way to work on this problem.
I have looked around here but nothing concrete I could get.

答:
I would convert arrays to strings and simply find the indices of unique strings in the original array.

Let's use your array:

```<code>a = [[0, 0, 0, 1],
     [1, 0, 0, 1],
     [0, 0, 0, 1],
     [1, 0, 0, 1],
     [0, 0, 0, 1],
     [0, 0, 1, 0],
     [0, 0, 1, 0]]

for unique in np.unique([str(el) for el in a]):
    print np.where(np.array([str(el) for el in a]) == str(unique))[0]
</code>```

This would output:

```<code>[0 2 4]
[5 6]
[1 3]
</code>```

As you wanted

Body:
I have a numpy array/pandas data frame

[[0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [0 0 1 0],
 [0 0 1 0]]

I need index number of row duplicates for this array. The results should be something like (0,2,4), (1,3), (5,6).

So far I have a work around, like I am running loops, one with unique values of the array rows against the actual array rows. That gives me results but not in the fashion I would want them to be.
This is the code I have made which gives me pairs but for a large array, this is very messy.

for i, row in enumerate(array):
    for j, row1 in enumerate(unique(array)):
        if tuple(row)==tuple(row1):
            pair.append(tuple([j,i]))

my results looks like this:

 [(0, 276),(1, 2931),(2, 3891),(3, 2165),(4, 1822),(5, 1241),
 (5, 2635),(5, 2644),(5, 2862),(5, 3296)]

My array is very big, so this way I am manually choosing tuples based on the first value as the indicator for duplicates, then I choose the actual row number which is a duplicate. for Ex. - tuples having 5 as their first value mean row 1241 is duplicated at 2635, 2644, 2862 and 3296.

Can anyone suggest me a better way to work on this problem.
I have looked around here but nothing concrete I could get.

Body:
I would convert arrays to strings and simply find the indices of unique strings in the original array.

Let's use your array:

a = [[0, 0, 0, 1],
     [1, 0, 0, 1],
     [0, 0, 0, 1],
     [1, 0, 0, 1],
     [0, 0, 0, 1],
     [0, 0, 1, 0],
     [0, 0, 1, 0]]

for unique in np.unique([str(el) for el in a]):
    print np.where(np.array([str(el) for el in a]) == str(unique))[0]

This would output:

[0 2 4]
[5 6]
[1 3]

As you wanted


问:
Angular 2 button click animation
I want to animate a scale-down-then-scale-back effect on every button clicks. Here are what I tried:

```<code><button (click)="clickMe()" [ngClass]="{'animated-button': animated}">Button</button>
</code>```

Here's my CSS:

```<code>@keyframes buttonClickAnimation {
  0% {transform: scale(0.8);}
  100% {transform: scale(1);}
}
.animated-button {
  animation: buttonClickAnimation 0.5s;
}
</code>```

Here's my component:

```<code>...
animated: boolean = false;

clickMe() {
  this.animated = true;
}
</code>```

This only works on the very first click, which makes sense because my animated variable never gets set back to false. However, if I set it back to false in clickMe(), the animation wouldn't have time to execute. Maybe this isn't even the right way to implement this. Please advise! Thank you.

答:
You can toggle a boolean (true/false) value by appending a !

```<code>animated: boolean = false;

clickMe() {
  this.animated = !this.animated;
}
</code>```

Title: Angular 2 button click animation

Body:
I want to animate a scale-down-then-scale-back effect on every button clicks. Here are what I tried:

<button (click)="clickMe()" [ngClass]="{'animated-button': animated}">Button</button>

Here's my CSS:

@keyframes buttonClickAnimation {
  0% {transform: scale(0.8);}
  100% {transform: scale(1);}
}
.animated-button {
  animation: buttonClickAnimation 0.5s;
}

Here's my component:

...
animated: boolean = false;

clickMe() {
  this.animated = true;
}

This only works on the very first click, which makes sense because my animated variable never gets set back to false. However, if I set it back to false in clickMe(), the animation wouldn't have time to execute. Maybe this isn't even the right way to implement this. Please advise! Thank you.

Body:
You can toggle a boolean (true/false) value by appending a !

animated: boolean = false;

clickMe() {
  this.animated = !this.animated;
}


问:
hide a div and show new one in initial position
So I have 2 div's side by side. What I want to do is hide/remove the left div and replace it with the right one which will move to the left and take the initial position of the right div.

I want this to be done when the about link is clicked.

HTML -

```<code><div class="nav">
            <div class="column c1">
                <a href="#">About</a>
            </div>

        </div>

        <div id="feed" class="feed" style="margin-top: 54px;">

            <div class="column c2">
                <p>
                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK. C-oC aims to contribute to the
                    necessary exaltation of talented artists within the various
                    ethnic minorities within the UK.
                </p>
                <p>
                    <a href="#">Find out more about Creatives of Colour..</a>
                </p>
            </div>

    <!-- Show on click -->

    <div class="feed-show" style="margin-top: 54px;">

            <div class="column c2">
                <p>
                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK. C-oC aims to contribute to the
                    necessary exaltation of talented artists within the various
                    ethnic minorities within the UK.
                </p>
                <p>
                    <a href="#">Find out more about Creatives of Colour..</a>
                </p>
            </div>

        </div>
</code>```

CSS -

```<code>    .c1 {
    max-width: 24%;
}

.column {
    position: relative;
    float:left;
    padding-right: 1%;
    width: 585px;
}

/* feed */
.feed {
    width: 96%;
    left: 2%;
    margin-top: 75px;
    padding-left: 2px;
}

.c2 {
    max-width: 49%;
}

.feed-item {
    position: relative;
    width: 100%;
    height: auto;
    padding-bottom: 25px;
    padding-top:2.5%;
}

.f-artist {
    padding-top: 1%;
}
</code>```

The idea is to give the site a one-page style.

Hopefully this can be achieved with CSS only, however jQuery suggestions are more then welcome.

Here is the codepen

Thanks!

答:
You should try jquery .hide() function for you to hide your desired division. Your css seems to be okay because division are float in left.</p>

```<code>$(document).ready(function){
    //about click
    $('.c1').on('click',function(){
        $('#feed').hide()

    })
}
</code>```

Body:
So I have 2 div's side by side. What I want to do is hide/remove the left div and replace it with the right one which will move to the left and take the initial position of the right div.

I want this to be done when the about link is clicked.

HTML -

                About

                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK. C-oC aims to contribute to the
                    necessary exaltation of talented artists within the various
                    ethnic minorities within the UK.

                    Find out more about Creatives of Colour..

                    Creatives of Colour (C-oC) is an independent directory
                    that provides you with up to date information on
                    current, and future work of creatives of colour
                    being showcased in the UK. C-oC aims to contribute to the
                    necessary exaltation of talented artists within the various
                    ethnic minorities within the UK.

                    Find out more about Creatives of Colour..

CSS -

    .c1 {
    max-width: 24%;
}

.column {
    position: relative;
    float:left;
    padding-right: 1%;
    width: 585px;
}

/* feed */
.feed {
    width: 96%;
    left: 2%;
    margin-top: 75px;
    padding-left: 2px;
}

.c2 {
    max-width: 49%;
}

.feed-item {
    position: relative;
    width: 100%;
    height: auto;
    padding-bottom: 25px;
    padding-top:2.5%;
}

.f-artist {
    padding-top: 1%;
}

The idea is to give the site a one-page style.

Hopefully this can be achieved with CSS only, however jQuery suggestions are more then welcome.

Here is the codepen

Thanks!

Body:
You should try jquery .hide() function for you to hide your desired division. Your css seems to be okay because division are float in left.

$(document).ready(function){
    //about click
    $('.c1').on('click',function(){
        $('#feed').hide()

    })
}


问:
java.xml XMLConstants.FEATURE_SECURE_PROCESSING cannot resolve or not is a field
I work with Eclipse, Spring MVC and Maven.The Java version is 1.6

I have the following method

```<code>public static DocumentBuilder getBuilder(ServletContext servletContext)
{
 DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
        factory.setValidating(true);

        DocumentBuilder builder = null;
        try {
            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            builder = factory.newDocumentBuilder();
</code>```

I have an error in the eclipse editor in the line:

```<code>factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
</code>```

The error is

```<code>FEATURE_SECURE_PROCESSING cannot be resolved or not is a field
</code>```

In the editor Eclipse I see:

Maven dependencies are:

Why don't I have the variable

```<code>XMLConstants.FEATURE_SECURE_PROCESSING ?
</code>```

答:
One of the libraries in your classpath contains an older version of javax.xml.XMLConstants.  You need to find and remove that library.  Try using Ctrl + Shift + T or select Navigate -> Open Type in Eclipse to find the offending jar file.

Also, you have at least two libraries, Xerces and Xalan, that aren't necessary and can be removed, as they're bundled with the JDK.

Body:
I work with Eclipse, Spring MVC and Maven.The Java version is 1.6

I have the following method

public static DocumentBuilder getBuilder(ServletContext servletContext)
{
 DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
        factory.setValidating(true);

        DocumentBuilder builder = null;
        try {
            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            builder = factory.newDocumentBuilder();

I have an error in the eclipse editor in the line:

factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,

The error is

FEATURE_SECURE_PROCESSING cannot be resolved or not is a field

In the editor Eclipse I see:

Maven dependencies are:

Why don't I have the variable

XMLConstants.FEATURE_SECURE_PROCESSING ?


问:
Sending a command using ssh with libssh2 lib
I try to use libssh2 to send a command over ssh, but cannot receive the expected response.

It connects well wwith my raspberry pi.

function to send a command:

```<code>char * s7c_hardware::sendCmd(char * cmd, bool out)
{
        if (!(channel = libssh2_channel_open_session(session))) return "-1";
        libssh2_channel_setenv(channel, "FOO", "bar");
        if (libssh2_channel_request_pty(channel, "vanilla")) return "-2";
        if (libssh2_channel_shell(channel)) return "-3";
        int rc;
        while ((rc = libssh2_channel_exec(channel, cmd)) ==
            LIBSSH2_ERROR_EAGAIN)
        {
            waitsocket(sock, session);
        }
        char * output = "";
        if (out)
        {
            do
            {
                char buffer[99999];
                rc = libssh2_channel_read(channel, buffer, sizeof(buffer));
                if (rc > 0)
                {
                    fprintf(stderr, "We read:\n");
                    for (int i = 0; i < rc; ++i)
                        fputc(buffer[i], stderr);
                    fprintf(stderr, "\n");
                }
                else {
                    if (rc != LIBSSH2_ERROR_EAGAIN)
                        fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
                }
            } while (rc > 0);
        }
        libssh2_channel_free(channel);
        channel = NULL;
        return output;
}
</code>```

Where cmd is the command and out is if wants output or not.

And if I try to send "uptime" and receive the up time, I receive this instead:

```<code>We read:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Jul  1 10:27:51 2017 from desktop-ca160hm.local

We read:
pi@rasp:~$
</code>```

答: I believe requesting a shell and requesting a single command's execution are mutually exclusive. If you want to run a command, get its output, and end the channel (not necessarily the session), you should run libssh2_channel_exec and not run libssh2_channel_shell.

Body:
I try to use libssh2 to send a command over ssh, but cannot receive the expected response.

It connects well wwith my raspberry pi.

function to send a command:

char * s7c_hardware::sendCmd(char * cmd, bool out)
{
        if (!(channel = libssh2_channel_open_session(session))) return "-1";
        libssh2_channel_setenv(channel, "FOO", "bar");
        if (libssh2_channel_request_pty(channel, "vanilla")) return "-2";
        if (libssh2_channel_shell(channel)) return "-3";
        int rc;
        while ((rc = libssh2_channel_exec(channel, cmd)) ==
            LIBSSH2_ERROR_EAGAIN)
        {
            waitsocket(sock, session);
        }
        char * output = "";
        if (out)
        {
            do
            {
                char buffer[99999];
                rc = libssh2_channel_read(channel, buffer, sizeof(buffer));
                if (rc > 0)
                {
                    fprintf(stderr, "We read:\n");
                    for (int i = 0; i < rc; ++i)
                        fputc(buffer[i], stderr);
                    fprintf(stderr, "\n");
                }
                else {
                    if (rc != LIBSSH2_ERROR_EAGAIN)
                        fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
                }
            } while (rc > 0);
        }
        libssh2_channel_free(channel);
        channel = NULL;
        return output;
}

Where cmd is the command and out is if wants output or not.

And if I try to send "uptime" and receive the up time, I receive this instead:

We read:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Jul  1 10:27:51 2017 from desktop-ca160hm.local

We read:
pi@rasp:~$


问:
Java Hmac-Sha1 hexdigest different to Nodejs
I've been trying to get a basic HMAC-SHA1 request signing method working.

The server uses NodeJS to verify the signature. To check what I should be getting I wrote the below script to run locally (which I have tested with cURL to ensure it is generating the correct signature).

```<code>const body = JSON.stringify(require('./json-events/test-event.json'));
const crypto = require('crypto');

const digest = crypto.createHmac('sha1', secretKey)
    .update(body, 'utf8')
    .digest('hex');

console.log(digest);
</code>```

Which prints out 70c244c06513c882bb8704c2d887a95a08d77f3a

The client's signing code is;

```<code>String xSignature = null;
final char[] hexArray = "0123456789abcdef".toCharArray();

try {
      SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA1");
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(key);

      byte[] digest = mac.doFinal(body.getBytes("UTF-8"));
      char[] hexChars = new char[digest.length * 2];

      for (int j = 0; j < digest.length; ++j) {
          int v = digest[j] & 0xFF;
          hexChars[j * 2] = hexArray[v >>> 4];
          hexChars[j * 2 + 1] = hexArray[v & 0x0F];
      }

      xSignature = new String(hexChars);
  } catch (Exception e) {
    System.out.println(e.getMessage());
}
</code>```

Which, when printing out xSignature it gives 5f855052675f135da151d6fa844a7678ede90afc.

To try and debug this, I used a quick python3 script to check which one isn't right.

```<code>import hashlib
import hmac
import json
from collections import OrderedDict

body = json.dumps(json.load(open("json-events/test-event.json"),
                object_pairs_hook=OrderedDict), indent=2).encode("utf-8")
sig = hmac.new(secret_key, msg=body, digestmod=hashlib.sha1).hexdigest()

print(sig)
</code>```

Returns 5f855052675f135da151d6fa844a7678ede90afc, which is the same as the Java method.

Everywhere I look though, it seems that the NodeJS code is 100% correct. So I'm guessing there is a common flaw in my Java and Python code.

Any insight would be much appreciated.

Here are some of the other webpages I've looked at;

Python HMAC-SHA1 vs Java HMAC-SHA1 different results

Converting HMAC-SHA1 from node.js to Java

Preparing a string for HMAC

NodeJS Crypto Hmac class documentation

UPDATE: Using a simpler string "asdfghjkl" instead of a complex JSON string, generates the same signature. So it seems like there are some invisible characters that are changing the digest when comparing the Java/Python to the NodeJS.

答:
I found out the resolution to the issue (and forgot to post the answer here). The signature is different when the order of the dictionary's key-value pairs differs. Such a simple oversight.

So;

```<code>{
    "key1": "Value1",
    "key2": "Value2"
}
</code>```

Will produce a different digest string to;

```<code>{
    "key2": "Value2",
    "key1": "Value1"
}
</code>```

So make sure your key-values are ordered exactly the same way when calculating the HMAC-SHA1 between two languages!

Body:
I've been trying to get a basic HMAC-SHA1 request signing method working.

The server uses NodeJS to verify the signature. To check what I should be getting I wrote the below script to run locally (which I have tested with cURL to ensure it is generating the correct signature).

const body = JSON.stringify(require('./json-events/test-event.json'));
const crypto = require('crypto');

const digest = crypto.createHmac('sha1', secretKey)
    .update(body, 'utf8')
    .digest('hex');

console.log(digest);

Which prints out 70c244c06513c882bb8704c2d887a95a08d77f3a

The client's signing code is;

String xSignature = null;
final char[] hexArray = "0123456789abcdef".toCharArray();

try {
      SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA1");
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(key);

      byte[] digest = mac.doFinal(body.getBytes("UTF-8"));
      char[] hexChars = new char[digest.length * 2];

      for (int j = 0; j < digest.length; ++j) {
          int v = digest[j] & 0xFF;
          hexChars[j * 2] = hexArray[v >>> 4];
          hexChars[j * 2 + 1] = hexArray[v & 0x0F];
      }

      xSignature = new String(hexChars);
  } catch (Exception e) {
    System.out.println(e.getMessage());
}

Which, when printing out xSignature it gives 5f855052675f135da151d6fa844a7678ede90afc.

To try and debug this, I used a quick python3 script to check which one isn't right.

import hashlib
import hmac
import json
from collections import OrderedDict

body = json.dumps(json.load(open("json-events/test-event.json"),
                object_pairs_hook=OrderedDict), indent=2).encode("utf-8")
sig = hmac.new(secret_key, msg=body, digestmod=hashlib.sha1).hexdigest()

print(sig)

Returns 5f855052675f135da151d6fa844a7678ede90afc, which is the same as the Java method.

Everywhere I look though, it seems that the NodeJS code is 100% correct. So I'm guessing there is a common flaw in my Java and Python code.

Any insight would be much appreciated.

Here are some of the other webpages I've looked at;

Python HMAC-SHA1 vs Java HMAC-SHA1 different results

Converting HMAC-SHA1 from node.js to Java

Preparing a string for HMAC

NodeJS Crypto Hmac class documentation

UPDATE: Using a simpler string "asdfghjkl" instead of a complex JSON string, generates the same signature. So it seems like there are some invisible characters that are changing the digest when comparing the Java/Python to the NodeJS.

Body:
I found out the resolution to the issue (and forgot to post the answer here). The signature is different when the order of the dictionary's key-value pairs differs. Such a simple oversight.

So;

{
    "key1": "Value1",
    "key2": "Value2"
}

Will produce a different digest string to;

{
    "key2": "Value2",
    "key1": "Value1"
}

So make sure your key-values are ordered exactly the same way when calculating the HMAC-SHA1 between two languages!


问:
Unsafe tuple calculus expressions
Consider a relation R1 (roll no,marks). Suppose the entries in R1 are (1,20) and (2,25) and let the domain of roll no and marks be all positive integers  .

Now a tuple calculus expression like
{ t | ~ (t belongs to R1) } is unsafe as we can have infinite number of tuples possible.
Suppose I restrict the domain of roll no and marks as positive integers between 1 to 50. Now will the above expression still remain unsafe? I think that it should not be unsafe as we have a finite domain.

答:
Finite vs infinite plays a certain role in whether a query is safe. But it isn't that a query is safe when no domain is infinite.

Safe queries are ones whose syntax guarantees domain-independence. A domain-independent query is one whose result can be calculated using relational algebra operators on base relations. The relational operators cannot (by design) calculate the relation of tuples that have the heading of a base relation but are not in it. For R that is { t | t NOT IN R }. I'd give an equivalent relational expression but there isn't one, which is the point. Another way to put this is that a domain-independent query returns the same result no matter what its domains. (Hence the name.) Infinite domains are used in examples because a domain-dependent query with an infinite domain will have an infinite number of rows in its result and it is expected that that infinite result makes it obvious that it cannot be calculated. Anyway these definitions of domain-independence just do not say that a query is domain-independent/safe when there is no infinite domain.

The relational algebra operators are limited to calculating sets of tuples expressible in calculus with every NOT following an AND and with all such AND NOTs and all ORs having operands with the same attributes. The former are calculated via MINUS and the latter are calculated via UNION. Calculating domain-dependent/unsafe query results for finite domains is straightforward. (After all, we know what tuples aren't in a relation.) But the extra relational operators needed have a computational complexity based on the product of the cardinalities of the domains of base relations instead of based on the much smaller number of tuples in base relations. The particular operators of the relational algebra are specifically chosen to avoid those queries/calculations.

(A convincing proof/explanation relies on deriving via valid reasoning rules from accepted assumptions and theorems. If you want to find the flaw in your reasoning, you need to give it per a reference that you accept and share.)

PS If you work out your example in detail with domains & data then you will find that even with finite domains it is difficult to find a relational algebra expression returning its value. Because there isn't one. (Using "relational algebra" in the same sense as domain-independence/safety does.)

Title: Unsafe tuple calculus expressions


问:
Issue creating database tables using Symfony console
I'm trying to create the database tables using Symfony command's using the following line :

```<code>php app/console doctrine:schema:create
</code>```

I obtain the following error :

```<code>[Doctrine\ORM\Mapping\MappingException]
No identifier/primary key specified for Entity "Cupon\CiudadBundle\Entity\Ciudad". Every Entity must have an identifier/primary key.
</code>```

And it's the above class :

namespace Cupon\TiendaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class Tienda
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;

   /** @ORM\ManyToOne(targetEntity="Cupon\CiudadBundle\Entity\Ciudad") */
   protected $ciudad;

   /**
   * Get id
   *
   * @return integer
   */
   public function getId()
   {
     return $this->id;
   }

   /**
    * Set ciudad
    *
    * @param \Cupon\CiudadBundle\Entity\Ciudad $ciudad
    * @return Tienda
    */
   public function setCiudad(\Cupon\CiudadBundle\Entity\Ciudad $ciudad = null)
   {
      $this->ciudad = $ciudad;
      return $this;
   }

   /**
   * Get ciudad
   *
   * @return \Cupon\CiudadBundle\Entity\Ciudad
   */
   public function getCiudad()
   {
      return $this->ciudad;
   }

   public function __toString()
   {
      return $this->getNombre();
   }

}
```

I don't understand whats really happen, because I put the ID for the class. Any help is appreciated.

答:
Just check if the Ciudad Entity has an id

You should include the following annotations for example:

```<code>namespace Cupon\TiendaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class Ciudad
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;
//..
</code>```

Body:
I'm trying to create the database tables using Symfony command's using the following line :

php app/console doctrine:schema:create

I obtain the following error :

[Doctrine\ORM\Mapping\MappingException]
No identifier/primary key specified for Entity "Cupon\CiudadBundle\Entity\Ciudad". Every Entity must have an identifier/primary key.

And it's the above class :

namespace Cupon\TiendaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class Tienda
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;

   /** @ORM\ManyToOne(targetEntity="Cupon\CiudadBundle\Entity\Ciudad") */
   protected $ciudad;

   /**
   * Get id
   *
   * @return integer
   */
   public function getId()
   {
     return $this->id;
   }

   /**
    * Set ciudad
    *
    * @param \Cupon\CiudadBundle\Entity\Ciudad $ciudad
    * @return Tienda
    */
   public function setCiudad(\Cupon\CiudadBundle\Entity\Ciudad $ciudad = null)
   {
      $this->ciudad = $ciudad;
      return $this;
   }

   /**
   * Get ciudad
   *
   * @return \Cupon\CiudadBundle\Entity\Ciudad
   */
   public function getCiudad()
   {
      return $this->ciudad;
   }

   public function __toString()
   {
      return $this->getNombre();
   }

}

I don't understand whats really happen, because I put the ID for the class. Any help is appreciated.

Body:
Just check if the Ciudad Entity has an id

You should include the following annotations for example:

namespace Cupon\TiendaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class Ciudad
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;
//..


问:
Array to String conversion
here's my code:

```<code>$menu .= $this->$item['type']($item);
</code>```

$item['type'] is a string - 'single' and it uses method single(). Yet the browser shows me this error:

```<code>Array to string conversion
</code>```

I have no idea why, since single returns a string, $item['type'] also is a string. I even tried checking this:

```<code>var_dump($this->$item['type']([]));
</code>```

and it still returns the same error. Do you know why?

答:
i believe this will work try it :</p>

```<code>$method = $item['type'];
var_dump($this->$method($item));
</code>```

Title: Array to String conversion

Body:
here's my code:

$menu .= $this->$item['type']($item);

$item['type'] is a string - 'single' and it uses method single(). Yet the browser shows me this error:

Array to string conversion

I have no idea why, since single returns a string, $item['type'] also is a string. I even tried checking this:

var_dump($this->$item['type']([]));

and it still returns the same error. Do you know why?

Body:
i believe this will work try it :

$method = $item['type'];
var_dump($this->$method($item));


问:
Get Properties of Generic Class That Is A Grouping
I have the following code which gets all the properties that are of type string which is then used to filter the source against.

```<code>public IQueryable<T> FilterSource(IQueryable<T> source, string filter)
{
    var properties = typeof(T).GetProperties().Where(x => x.PropertyType == typeof(string)).Select(x => x.Name);
}
</code>```

My problem is that the source happens to be an IGrouping, so when I call typeof(T).GetProperties() I only get access to the grouping keys. Whereas I need to get the properties in the objects inside the grouping.

What is the best way to achieve this?

答:
If you know that you will be passing an IGrouping, the following should work. However, this way requires that you pass the types of the key and grouped object.

```<code>    public static void FilterSource<TKey,TElement>(IQueryable<IGrouping<TKey, TElement>> source, string filter)
    {
        //TElement is the type inside the grouping
        var properties = typeof(TElement).GetProperties().Where(x => x.PropertyType == typeof(string)) .Select(x => x.Name);
    }
</code>```

Body:
I have the following code which gets all the properties that are of type string which is then used to filter the source against.

public IQueryable<T> FilterSource(IQueryable<T> source, string filter)
{
    var properties = typeof(T).GetProperties().Where(x => x.PropertyType == typeof(string)).Select(x => x.Name);
}

My problem is that the source happens to be an IGrouping, so when I call typeof(T).GetProperties() I only get access to the grouping keys. Whereas I need to get the properties in the objects inside the grouping.

What is the best way to achieve this?

Body:
If you know that you will be passing an IGrouping, the following should work. However, this way requires that you pass the types of the key and grouped object.

    public static void FilterSource<TKey,TElement>(IQueryable<IGrouping<TKey, TElement>> source, string filter)
    {
        //TElement is the type inside the grouping
        var properties = typeof(TElement).GetProperties().Where(x => x.PropertyType == typeof(string)) .Select(x => x.Name);
    }


问:
Display a value from "data" inside donut chart - AmCharts
I´m trying to display a dynamic value (from backend) inside the inner radius of a pie donut chart (typically a percentage value).
Can you help me?

thanks

答:
You can add a label into allLabels. The other option is to add the label after the chart initiated:

```<code>chart.addListener("init", function (e) {
    e.chart.addLabel(...);
});
</code>```

var chart = AmCharts.makeChart("chartdiv", {
    "type": "pie",
    "theme": "light",
    "innerRadius": "40%",
    "gradientRatio": [-0.4, -0.4, -0.4, -0.4, -0.4, -0.4, 0, 0.1, 0.2, 0.1, 0, -0.2, -0.5],
    "dataProvider": [{
        "country": "Lithuania",
        "litres": 501.9
    }, {
        "country": "Czech Republic",
        "litres": 301.9
    }, {
        "country": "Ireland",
        "litres": 201.1
    }, {
        "country": "Germany",
        "litres": 165.8
    }, {
        "country": "Australia",
        "litres": 139.9
    }, {
        "country": "Austria",
        "litres": 128.3
    }],
    "balloonText": "[[value]]",
    "valueField": "litres",
    "titleField": "country",
    "balloon": {
        "drop": true,
        "adjustBorderColor": false,
        "color": "#FFFFFF",
        "fontSize": 16
    },
  "allLabels": [{
    "y": "47%",
    "align": "center",
    "size": 20,
    "bold": true,
    "color": "#555",
    "text": "30%"
  }],
    "export": {
        "enabled": true
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#chartdiv {
 width  : 100%;
 height  : 500px;
 font-size : 11px;
}       </code>```

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

       ```

Body:
You can add a label into allLabels. The other option is to add the label after the chart initiated:

chart.addListener("init", function (e) {
    e.chart.addLabel(...);
});

var chart = AmCharts.makeChart("chartdiv", {
    "type": "pie",
    "theme": "light",
    "innerRadius": "40%",
    "gradientRatio": [-0.4, -0.4, -0.4, -0.4, -0.4, -0.4, 0, 0.1, 0.2, 0.1, 0, -0.2, -0.5],
    "dataProvider": [{
        "country": "Lithuania",
        "litres": 501.9
    }, {
        "country": "Czech Republic",
        "litres": 301.9
    }, {
        "country": "Ireland",
        "litres": 201.1
    }, {
        "country": "Germany",
        "litres": 165.8
    }, {
        "country": "Australia",
        "litres": 139.9
    }, {
        "country": "Austria",
        "litres": 128.3
    }],
    "balloonText": "[[value]]",
    "valueField": "litres",
    "titleField": "country",
    "balloon": {
        "drop": true,
        "adjustBorderColor": false,
        "color": "#FFFFFF",
        "fontSize": 16
    },
  "allLabels": [{
    "y": "47%",
    "align": "center",
    "size": 20,
    "bold": true,
    "color": "#555",
    "text": "30%"
  }],
    "export": {
        "enabled": true
    }
});

#chartdiv {
 width  : 100%;
 height  : 500px;
 font-size : 11px;
}

<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/pie.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
<div id="chartdiv"></div>


问:
Date operation with round giving wrong results (oracle sql on db.grussell.org)
I'm practicing SQL from the execises at db.grussell.org and excecise 10 from tutorial 5 (https://db.grussell.org/sql/interface.cgi?tn=Tutorial%205&qn=9) asks for how old are employees in months.

Here is the question

```<code>How old is each employee in months.
Format this as employee number against age in months.
Round to the nearest whole number of months.
</code>```

Here is my code (empno is the employee ID, dob is the date of birth as a date type on the employee table

```<code>select e.empno,
 round( months_between ( trunc(sysdate,'mm'),trunc(dob) ) )
  from employee e
</code>```

Here are my results

```<code>EMPLOYEE MONTHS_BETWEEN
1       882
2       845
3       674
4       647
5       705
6       756
7       832
8       714
9       714
10      670
11      658
12      700
13      902
14      853
15      748
16      658
17      683
18      673
19      702
20      640
21      622
22      927
23      751
24      810
25      758
26      689
27      779
28      732
29      586
30      633
31      744
32      695
</code>```

For the rows where the employee number is 5,10 and 16 the result is incorrect for some reason that I cannot understand, for all the others the result is correct.

I'm suspecting that I'm missing something on the round function or not adding or subtracting some date on the months_between parameters.

Could someone point me in the right direction on what would be wrong with those?
I can't really understand why some of the data is correct and some isn't...
There is a chance that the exercise is wrong but I would not be able to tell.

答:
The reason is because you are truncating sysdate.  So, as of this month (July 2017), you are measuring the age as of July 1st, instead of the current date.

Instead just do:

```<code>select e.empno,
       round(months_between(sysdate, e.dob)) as age_in_months
from employee e;
</code>```

Body:
I'm practicing SQL from the execises at db.grussell.org and excecise 10 from tutorial 5 (https://db.grussell.org/sql/interface.cgi?tn=Tutorial%205&qn=9) asks for how old are employees in months.

Here is the question

How old is each employee in months.
Format this as employee number against age in months.
Round to the nearest whole number of months.

Here is my code (empno is the employee ID, dob is the date of birth as a date type on the employee table

select e.empno,
 round( months_between ( trunc(sysdate,'mm'),trunc(dob) ) )
  from employee e

Here are my results

EMPLOYEE MONTHS_BETWEEN
1       882
2       845
3       674
4       647
5       705
6       756
7       832
8       714
9       714
10      670
11      658
12      700
13      902
14      853
15      748
16      658
17      683
18      673
19      702
20      640
21      622
22      927
23      751
24      810
25      758
26      689
27      779
28      732
29      586
30      633
31      744
32      695

For the rows where the employee number is 5,10 and 16 the result is incorrect for some reason that I cannot understand, for all the others the result is correct.

I'm suspecting that I'm missing something on the round function or not adding or subtracting some date on the months_between parameters.

Could someone point me in the right direction on what would be wrong with those?
I can't really understand why some of the data is correct and some isn't...
There is a chance that the exercise is wrong but I would not be able to tell.

Body:
The reason is because you are truncating sysdate.  So, as of this month (July 2017), you are measuring the age as of July 1st, instead of the current date.

Instead just do:

select e.empno,
       round(months_between(sysdate, e.dob)) as age_in_months
from employee e;


问:
variable is losing its value in c program
This is written in 'c' and compiled with gcc.  I'm not sure what else you need to know.

The smallest complete example I could put together is shown here.  The variable 'numatoms' loses its value when it gets to line 23 (after the scanf()).

I'm stumped. Maybe it has something to do with scanf() overwritting the space for numatoms?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/*
 *
 */
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];

do {
    printf("NO. OF ATOMS?");
    fflush(stdout);
    scanf("%d", &numatoms);
    printf("\r\n");
    for(;;){
        printf("value of numatoms is %u\r\n", numatoms);
        printf("RAY?");
        fflush(stdout);
        scanf("%u", &r);
        printf("value of numatoms is %u\r\n", numatoms);
        if(r < 1)
            break;
        else {
            printf("value of numatoms is %u\r\n", numatoms);
        }
    }
    printf("CARE TO TRY AGAIN?");
    fflush(stdout);
    scanf("%s", a);
    printf("\r\n");
} while (a[0] == 'y' || a[0] == 'Y');

return (EXIT_SUCCESS);
</code>```

}

答:
uint8_t is 8 bits long %u reads an unsigned int (probably 32 bits long).

You either need to make numatoms "bigger" (i.e. unsigned int) or read the correct size (see scanf can't scan into inttypes (uint8_t))

Body:
This is written in 'c' and compiled with gcc.  I'm not sure what else you need to know.

The smallest complete example I could put together is shown here.  The variable 'numatoms' loses its value when it gets to line 23 (after the scanf()).

I'm stumped. Maybe it has something to do with scanf() overwritting the space for numatoms?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/*
 *
 */
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];

do {
    printf("NO. OF ATOMS?");
    fflush(stdout);
    scanf("%d", &numatoms);
    printf("\r\n");
    for(;;){
        printf("value of numatoms is %u\r\n", numatoms);
        printf("RAY?");
        fflush(stdout);
        scanf("%u", &r);
        printf("value of numatoms is %u\r\n", numatoms);
        if(r < 1)
            break;
        else {
            printf("value of numatoms is %u\r\n", numatoms);
        }
    }
    printf("CARE TO TRY AGAIN?");
    fflush(stdout);
    scanf("%s", a);
    printf("\r\n");
} while (a[0] == 'y' || a[0] == 'Y');

return (EXIT_SUCCESS);

}


问:
Scoring predictions in sklearn (Python machine learning)
I'm going through the following IPython Notebook which analyzes the Iris dataset

At one point in the notebook the author builds the following model:

At this point, I became very confused. What is going on in the last line?
From what I learned, you should create a prediction based on the model and then compare that prediction to the y_test values.

I would have done the following:

```<code>predictions = decision_tree_classifier.predict(X_test)
from sklearn.metrics import classification_report
print classification_report(y_test, predictions)
</code>```

What is going on when the author generates a score based on the testing_inputs and the testing_classes?

答:
From the docs:

score(X, y, sample_weight=None)

Returns the mean accuracy on the given test data and labels.

And that's exactly what it does. It internally carries out prediction on X_test, generates y_pred and compares it to y_test to compute an accuracy score.

What you do is similar, but in two steps. You first predict and then compare to y_test. In addition, you are printing out the precision, recall and f1-score.

Body:
I'm going through the following IPython Notebook which analyzes the Iris dataset

At one point in the notebook the author builds the following model:

At this point, I became very confused. What is going on in the last line?
From what I learned, you should create a prediction based on the model and then compare that prediction to the y_test values.

I would have done the following:

predictions = decision_tree_classifier.predict(X_test)
from sklearn.metrics import classification_report
print classification_report(y_test, predictions)

What is going on when the author generates a score based on the testing_inputs and the testing_classes?