问:
Get anonymous users with Cloud Functions for Firebase
I am using Cloud Functions to manage the database and the auth in my project. I followed the example https://github.com/firebase/functions-samples/tree/master/delete-unused-accounts-cron to delete inactive users in my app. I want to get only the anonymous users that were inactive for some time. I don't know to make the query to the identity toolkit to filter only the correct ones. Does anybody help?

Thanks!

答: I think your best bet is to write the account auth provider(s) into your database at the time of login, then use that to further filter the set of accounts that should be deleted.  This way, you won't have to take the time to query each uid to find out what its providers are.</p>


来源: stackexchange

问:
Display css and javascript code as it does when files are saved in their format. But inside html file?
I use notepad++ and have got an index.html file that contains css and javascript.

Is there a way to display css and javascript code as it does when files are saved in their format; but in this case inside the html file?

Any editor, software, plugin for notepad++?

答:
I did not fully understand what you are asking but here is my answer:
To add a javascript file/library to your HTML:

To add javascript directly into your HTML code:
    Some script here...<\script>
To add a CSS file to your HTML:

To add CSS directly into your HTML code:
     Your CSS...

EDIT

So now I understand what you want but I don't know of any add ons. Personally when i started coding HTML and the other related languages I used Coffee Cup free HTML editor: https://www.coffeecup.com/
Now I code for more professional uses and i downloaded a very large editor called Microsoft Visual Studio 2017.

ContentLicense: CC BY-SA 3.0


问:
Pandas If/then else with multiple conditions
This is such a simple thing yet I'm spending hours trying to figure out, when I could easily do this in SQL or Tableau.

So imagine I have an ID column and a Item1 and Item2 column. In SQL, I'd write:

```<code>CASE
WHEN Item1 IS NULL AND Item2 IS NULL
THEN '0'
WHEN Item1 IS NOT NULL AND ITEM2 IS NOT NULL
THEN '2'
WHEN Item1 IS NULL AND Item2 is NOT NULL
THEN '1'
WHEN Item1 IS NOT NULL AND Item2 IS NULL
THEN '1'
END
</code>```

Any ideas how I can replicate this in pandas?  To clarify, this has to be a NEW column with values either being 0, 1 or 2.

答:
It sounds like you just want the count of non-null entries in each row. So something along the lines of

```<code>df[['Item 1', 'Item 2']].notnull().sum(axis=1)
</code>```

should work: you just compute whether each element is null and sum up by row. You may have to use something like np.isnan() instead of isnotnull() if you want to detect NaN numerical values instead.

You can then assign this result to a new column in the DataFrame in the usual way.

Body:
This is such a simple thing yet I'm spending hours trying to figure out, when I could easily do this in SQL or Tableau.

So imagine I have an ID column and a Item1 and Item2 column. In SQL, I'd write:

CASE
WHEN Item1 IS NULL AND Item2 IS NULL
THEN '0'
WHEN Item1 IS NOT NULL AND ITEM2 IS NOT NULL
THEN '2'
WHEN Item1 IS NULL AND Item2 is NOT NULL
THEN '1'
WHEN Item1 IS NOT NULL AND Item2 IS NULL
THEN '1'
END

Any ideas how I can replicate this in pandas?  To clarify, this has to be a NEW column with values either being 0, 1 or 2.

Body:
It sounds like you just want the count of non-null entries in each row. So something along the lines of

df[['Item 1', 'Item 2']].notnull().sum(axis=1)

should work: you just compute whether each element is null and sum up by row. You may have to use something like np.isnan() instead of isnotnull() if you want to detect NaN numerical values instead.

You can then assign this result to a new column in the DataFrame in the usual way.


问:
Is it possible to upload APNS Certificates to the azure notification hub programatically or via the CLI
We are investigating the azure notification hub, and while we have had success sending/receiving messages from it, we also require programatic configuration of the hub.

It seems that the only way possible to create the notification hub is via the azure cli with an azuredeploy.json ARM template like this one. However, I can't find any information about adding an APNS certificate to that.

Looking at the Automation Script generated from our hub, there is no evidence of the google firebase API key or the APNS certificate. Is this possible or do these need to be done through the azure portal at all times.

UPDATED: I have managed to create a notification hub namespace using the arm template with little issue, however I am getting a "bad request" (correlation id - 3faee649-7084-436d-8d7e-4a9c6f79cc4e) when trying to create the notification hub itself with the apns certificate.

this post is someone having a similar problem, however their key for the apns is a lot shorter than mine. I literally created a base64 string from the certificate file which is 5000+ characters wrong, I assume that is incorrect, but I can't figure out what value from apple is meant to go in here.

My template looks like this:

```<code>    {
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "Gcm.GoogleApiKey": {
      "type": "string",
      "metadata": {
        "description": "Google Cloud Messaging API Key"
      },
      "defaultValue": ""
    },
    "Apns.apnsCertificate": {
        "type": "string",
        "metadata": {
          "description": "A certificate (in base 64 format) provided by Apple on the iOS Provisioning Portal"
        }
      },
      "Apns.certificateKey": {
        "type": "string",
        "metadata": {
          "description": "The Certificate Key provided by the iOS Provisioning Portal when registering the application"
        },
        "defaultValue": ""
      },
      "Apns.endpoint": {
        "type": "string",
        "metadata": {
          "description": "The APNS endpoint to which our service connects. This is one of two values: gateway.sandbox.push.apple.com for the sandbox endpoint or gateway.push.apple.com, for the production endpoint. Any other value is invalid"
        },
        "defaultValue": "gateway.sandbox.push.apple.com"
      }
  },
  "variables": {
    "hubVersion": "[providers('Microsoft.NotificationHubs', 'namespaces').apiVersions[0]]",
    "notificationHubNamespace": "[concat('hubv2', uniqueString(resourceGroup().id))]",
    "notificationHubName": "notificationhub"
  },
  "resources": [
    {
      "name": "[variables('NotificationHubNamespace')]",
      "location": "[resourceGroup().location]",
      "type": "Microsoft.NotificationHubs/namespaces",
      "apiVersion": "2017-04-01",
      "comments": "Notification hub namespace",
      "properties": {
        "namespaceType": "NotificationHub"
      },
      "resources": [
        {
          "name": "[concat(variables('NotificationHubNamespace'),'/',variables('NotificationHubName'))]",
          "location": "[resourceGroup().location]",
          "type": "Microsoft.NotificationHubs/namespaces/notificationHubs",
          "apiVersion": "2017-04-01",
          "properties": {
            "GcmCredential": {
              "properties": {
                "googleApiKey": "[parameters('Gcm.GoogleApiKey')]",
                "gcmEndpoint": "https://android.googleapis.com/gcm/send"
              }
            },
            "apnsCredential": {
                "properties": {
                    "apnsCertificate" : "[parameters('Apns.apnsCertificate')]",
                    "certificateKey" : "[parameters('Apns.certificateKey')]",
                    "endpoint" : "[parameters('Apns.endpoint')]"
                }
            }
          },
          "dependsOn": [
            "[concat('Microsoft.NotificationHubs/namespaces/', variables('NotificationHubNamespace'))]"
          ]
        }
      ]
    }
  ],
  "outputs": {
  }
}
</code>```

答:
In the apnsCredentials property, the apsnCertificate is the base64 string from file and the certificatekey is your certificate password which needs to be a strong password. Are you following the same?

Also, is there an inner error message you see. If yes, what is it?

Thanks,
Amol

Body:
We are investigating the azure notification hub, and while we have had success sending/receiving messages from it, we also require programatic configuration of the hub.

It seems that the only way possible to create the notification hub is via the azure cli with an azuredeploy.json ARM template like this one. However, I can't find any information about adding an APNS certificate to that.

Looking at the Automation Script generated from our hub, there is no evidence of the google firebase API key or the APNS certificate. Is this possible or do these need to be done through the azure portal at all times.

UPDATED: I have managed to create a notification hub namespace using the arm template with little issue, however I am getting a "bad request" (correlation id - 3faee649-7084-436d-8d7e-4a9c6f79cc4e) when trying to create the notification hub itself with the apns certificate.

this post is someone having a similar problem, however their key for the apns is a lot shorter than mine. I literally created a base64 string from the certificate file which is 5000+ characters wrong, I assume that is incorrect, but I can't figure out what value from apple is meant to go in here.

My template looks like this:

    {
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "Gcm.GoogleApiKey": {
      "type": "string",
      "metadata": {
        "description": "Google Cloud Messaging API Key"
      },
      "defaultValue": ""
    },
    "Apns.apnsCertificate": {
        "type": "string",
        "metadata": {
          "description": "A certificate (in base 64 format) provided by Apple on the iOS Provisioning Portal"
        }
      },
      "Apns.certificateKey": {
        "type": "string",
        "metadata": {
          "description": "The Certificate Key provided by the iOS Provisioning Portal when registering the application"
        },
        "defaultValue": ""
      },
      "Apns.endpoint": {
        "type": "string",
        "metadata": {
          "description": "The APNS endpoint to which our service connects. This is one of two values: gateway.sandbox.push.apple.com for the sandbox endpoint or gateway.push.apple.com, for the production endpoint. Any other value is invalid"
        },
        "defaultValue": "gateway.sandbox.push.apple.com"
      }
  },
  "variables": {
    "hubVersion": "[providers('Microsoft.NotificationHubs', 'namespaces').apiVersions[0]]",
    "notificationHubNamespace": "[concat('hubv2', uniqueString(resourceGroup().id))]",
    "notificationHubName": "notificationhub"
  },
  "resources": [
    {
      "name": "[variables('NotificationHubNamespace')]",
      "location": "[resourceGroup().location]",
      "type": "Microsoft.NotificationHubs/namespaces",
      "apiVersion": "2017-04-01",
      "comments": "Notification hub namespace",
      "properties": {
        "namespaceType": "NotificationHub"
      },
      "resources": [
        {
          "name": "[concat(variables('NotificationHubNamespace'),'/',variables('NotificationHubName'))]",
          "location": "[resourceGroup().location]",
          "type": "Microsoft.NotificationHubs/namespaces/notificationHubs",
          "apiVersion": "2017-04-01",
          "properties": {
            "GcmCredential": {
              "properties": {
                "googleApiKey": "[parameters('Gcm.GoogleApiKey')]",
                "gcmEndpoint": "https://android.googleapis.com/gcm/send"
              }
            },
            "apnsCredential": {
                "properties": {
                    "apnsCertificate" : "[parameters('Apns.apnsCertificate')]",
                    "certificateKey" : "[parameters('Apns.certificateKey')]",
                    "endpoint" : "[parameters('Apns.endpoint')]"
                }
            }
          },
          "dependsOn": [
            "[concat('Microsoft.NotificationHubs/namespaces/', variables('NotificationHubNamespace'))]"
          ]
        }
      ]
    }
  ],
  "outputs": {
  }
}


问:
XML C# Parse - Complex
I have been on google for a while but am just stumped.  I need to parse xml of this nature.  I can't seem to skip to elements in the middle, e.g. Folder.  I have limited the xml as there were many 'Folder' elements.  Any guidance would be appreciated.  I was after the FolderID element's attribute ID.</p>

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14"
        MinorVersion="1"
        MajorBuildNumber="225"
        MinorBuildNumber="46"
        Version="Exchange2010_SP1"
        xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetFolderResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Folders>
            <t:Folder>
              <t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
              <t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
              <t:DisplayName>Top of Information Store</t:DisplayName>
              <t:TotalCount>0</t:TotalCount>
              <t:ChildFolderCount>15</t:ChildFolderCount>
              <t:EffectiveRights>
                <t:CreateAssociated>true</t:CreateAssociated>
                <t:CreateContents>true</t:CreateContents>
                <t:CreateHierarchy>true</t:CreateHierarchy>
                <t:Delete>true</t:Delete>
                <t:Modify>true</t:Modify>
                <t:Read>true</t:Read>
                <t:ViewPrivateItems>true</t:ViewPrivateItems>
              </t:EffectiveRights>
              <t:PermissionSet>
                <t:Permissions>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Default</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Anonymous</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                </t:Permissions>
              </t:PermissionSet>
              <t:UnreadCount>0</t:UnreadCount>
            </t:Folder>
          </m:Folders>
        </m:GetFolderResponseMessage>
      </m:ResponseMessages>
    </m:GetFolderResponse>
  </s:Body>
</s:Envelope>
</code>```

答:
LINQ to XML is the best .NET XML Parsing API.
See
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/xdocument-class-overview</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {

            var doc = XDocument.Load(@"c:\temp\foo.xml");
            var ns = (XNamespace)"http://schemas.microsoft.com/exchange/services/2006/types";

            var folders = doc.Descendants(ns + "Folder");

            foreach (var e in folders)
            {
                var folderId = e.Element(ns + "FolderId").Attribute("Id").Value;
                Console.WriteLine(folderId);
            }

            Console.WriteLine("Hit any key to exit.");
            Console.ReadKey();

        }
    }
}
</code>```

Title: XML C# Parse - Complex

Body:
I have been on google for a while but am just stumped.  I need to parse xml of this nature.  I can't seem to skip to elements in the middle, e.g. Folder.  I have limited the xml as there were many 'Folder' elements.  Any guidance would be appreciated.  I was after the FolderID element's attribute ID.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14"
        MinorVersion="1"
        MajorBuildNumber="225"
        MinorBuildNumber="46"
        Version="Exchange2010_SP1"
        xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetFolderResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Folders>
            <t:Folder>
              <t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
              <t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
              <t:DisplayName>Top of Information Store</t:DisplayName>
              <t:TotalCount>0</t:TotalCount>
              <t:ChildFolderCount>15</t:ChildFolderCount>
              <t:EffectiveRights>
                <t:CreateAssociated>true</t:CreateAssociated>
                <t:CreateContents>true</t:CreateContents>
                <t:CreateHierarchy>true</t:CreateHierarchy>
                <t:Delete>true</t:Delete>
                <t:Modify>true</t:Modify>
                <t:Read>true</t:Read>
                <t:ViewPrivateItems>true</t:ViewPrivateItems>
              </t:EffectiveRights>
              <t:PermissionSet>
                <t:Permissions>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Default</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Anonymous</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                </t:Permissions>
              </t:PermissionSet>
              <t:UnreadCount>0</t:UnreadCount>
            </t:Folder>
          </m:Folders>
        </m:GetFolderResponseMessage>
      </m:ResponseMessages>
    </m:GetFolderResponse>
  </s:Body>
</s:Envelope>

Body:
LINQ to XML is the best .NET XML Parsing API.
See
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/xdocument-class-overview

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {

            var doc = XDocument.Load(@"c:\temp\foo.xml");
            var ns = (XNamespace)"http://schemas.microsoft.com/exchange/services/2006/types";

            var folders = doc.Descendants(ns + "Folder");

            foreach (var e in folders)
            {
                var folderId = e.Element(ns + "FolderId").Attribute("Id").Value;
                Console.WriteLine(folderId);
            }

            Console.WriteLine("Hit any key to exit.");
            Console.ReadKey();

        }
    }
}


问:
Is there an nServiceBus sample for Pub/Sub with WCF?
It's a really common pattern and I'm finding it a nightmare to implement!

--

The WcfIntegration sample is almost what I'm looking for in that it receives messages via a WCF endpoint.  However, it receives messages back on itself.  I want a separate subscriber.

So what I'm trying to do is merge the WcfIntegration and pub/sub samples.

The real need is for a website to call a class library, which then calls the WCF endpoint of the publisher.

A subscriber then picks receives a message that the publisher publishes, and does whatever with it.

--

Rob

答:
I've finally got it to work here:-

http://code.google.com/p/nservicebus-wcf-pubsub/downloads/list

Anyone is welcome to improve the code.

ContentLicense: CC BY-SA 2.5


问:
Modelling data using dataframes
I am trying to train a dataset to predict whether an inputted text is from a science fiction novel or not. I am relatively new to python, so I don't know exactly what I am doing wrong.

Code:

```<code>#class17.py
"""
Created on Fri Nov 17 14:07:36 2017

@author: twaters

Read three science fiction novels
Predict a sentence or paragraph
see whether sentence/phrase/book is from a science fiction novel or not
"""

import nltk
import pandas as pd
import csv
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression

from sklearn import model_selection
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from nltk.corpus import stopwords

#nltk.download()

irobot = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/irobot.txt"
enders_game = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/endersgame.txt"
space_odyssey ="C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/spaceodyssey.txt"
to_kill_a_mockingbird = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/tokillamockingbird.txt"

sr = set(stopwords.words('english'))
freq = {}

def main():
    #read_novels()
    model_novels()

def read_novel(b, is_scifi):

    read_file = open(b)

    text = read_file.read()
    words = text.split()
    clean_tokens = words[:]
    filtered_list = []

    for word in clean_tokens:
        word = word.lower()
        if word not in sr:
            filtered_list.append(word)

    freq = nltk.FreqDist(clean_tokens)
    #print(filtered_list)
    for word in clean_tokens:
       count = freq.get(word,0)
       freq[word] = count + 1

    frequency_list = freq.keys()

    with open('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', 'w', encoding='utf-8') as csvfile:
        fieldnames = ['word','frequency','is_scifi']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator = '\n')
        writer.writeheader()

        for words in frequency_list:
            writer.writerow({'word': words,'frequency': freq[words],'is_scifi':is_scifi})

    print("List compiled.")

def read_novels():

    read_novel(enders_game, 0)
    read_novel(space_odyssey, 0)
    read_novel(irobot, 0)
    read_novel(to_kill_a_mockingbird, 1)

def model_novels():

    df = pd.read_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', 'rb', delimiter='\t', encoding='utf-8')
    print(df)

    #for index in range(2, df.shape[0], 100):
    df_subset = df.loc[1:]
    #print(df_subset)
    X = df_subset.loc[:, 'frequency':'is_scifi']
    Y = df_subset.loc[:, 'frequency':'is_scifi']
    testing_size = 0.2
    seed = 7
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

    selectedModel = LogisticRegression()
    selectedModel.fit(X_train, Y_train)
    predictions = selectedModel.predict(X_validation)

#%%
#print("Accuracy Score:\n", accuracy_score(Y_validation, predictions))
#print("Confusion Matrix:\n",confusion_matrix(predictions, Y_validation))
#print("Class report:\n", classification_report(Y_validation, predictions))
#df_test = pd.read_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', delimiter='\t')
#predictions_test = selectedModel.predict(df_test)
#test_frame = pd.DataFrame(predictions_test)
#test_frame.to_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data_result.txt', sep='\t')
</code>```

Error:
Traceback (most recent call last):

File "", line 1, in
    main()

File "C:/Users/user/Desktop/Assignments/SQL/Python/DA Project/class17.py", line 36, in main
    model_novels()

File "C:/Users/user/Desktop/Assignments/SQL/Python/DA Project/class17.py", line 95, in model_novels
    selectedModel.fit(X_train, Y_train)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\linear_model\logistic.py", line 1216, in fit
    order="C")

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 573, in check_X_y
    ensure_min_features, warn_on_dtype, estimator)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 453, in check_array
    _assert_all_finite(array)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 44, in _assert_all_finite
    " or a value too large for %r." % X.dtype)

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

If you need access to the files I am reading from, I can link them.

Thank you for your help!

答:
Here are the points in the stacktrace which you should pay attention to:

File "C:/Users/user/Desktop/Assignments/SQL/Python/DA Project/class17.py", line 95, in model_novels selectedModel.fit(X_train, Y_train)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 44, in _assert_all_finite " or a value too large for %r." % X.dtype)

That tells us there is a problem with formatting X so the logistic regression will accept it.

You should check X_train and X to see if they contain errant values.

This answer will give you some pointers on how to do that.

Python pandas: check if any value is NaN in DataFrame

Title: Modelling data using dataframes

Body:
I am trying to train a dataset to predict whether an inputted text is from a science fiction novel or not. I am relatively new to python, so I don't know exactly what I am doing wrong.

Code:

#class17.py
"""
Created on Fri Nov 17 14:07:36 2017

@author: twaters

Read three science fiction novels
Predict a sentence or paragraph
see whether sentence/phrase/book is from a science fiction novel or not
"""

import nltk
import pandas as pd
import csv
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression

from sklearn import model_selection
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from nltk.corpus import stopwords

#nltk.download()

irobot = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/irobot.txt"
enders_game = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/endersgame.txt"
space_odyssey ="C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/spaceodyssey.txt"
to_kill_a_mockingbird = "C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/tokillamockingbird.txt"

sr = set(stopwords.words('english'))
freq = {}

def main():
    #read_novels()
    model_novels()

def read_novel(b, is_scifi):

    read_file = open(b)

    text = read_file.read()
    words = text.split()
    clean_tokens = words[:]
    filtered_list = []

    for word in clean_tokens:
        word = word.lower()
        if word not in sr:
            filtered_list.append(word)

    freq = nltk.FreqDist(clean_tokens)
    #print(filtered_list)
    for word in clean_tokens:
       count = freq.get(word,0)
       freq[word] = count + 1

    frequency_list = freq.keys()

    with open('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', 'w', encoding='utf-8') as csvfile:
        fieldnames = ['word','frequency','is_scifi']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator = '\n')
        writer.writeheader()

        for words in frequency_list:
            writer.writerow({'word': words,'frequency': freq[words],'is_scifi':is_scifi})

    print("List compiled.")

def read_novels():

    read_novel(enders_game, 0)
    read_novel(space_odyssey, 0)
    read_novel(irobot, 0)
    read_novel(to_kill_a_mockingbird, 1)

def model_novels():

    df = pd.read_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', 'rb', delimiter='\t', encoding='utf-8')
    print(df)

    #for index in range(2, df.shape[0], 100):
    df_subset = df.loc[1:]
    #print(df_subset)
    X = df_subset.loc[:, 'frequency':'is_scifi']
    Y = df_subset.loc[:, 'frequency':'is_scifi']
    testing_size = 0.2
    seed = 7
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

    selectedModel = LogisticRegression()
    selectedModel.fit(X_train, Y_train)
    predictions = selectedModel.predict(X_validation)

#%%
#print("Accuracy Score:\n", accuracy_score(Y_validation, predictions))
#print("Confusion Matrix:\n",confusion_matrix(predictions, Y_validation))
#print("Class report:\n", classification_report(Y_validation, predictions))
#df_test = pd.read_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data.txt', delimiter='\t')
#predictions_test = selectedModel.predict(df_test)
#test_frame = pd.DataFrame(predictions_test)
#test_frame.to_csv('C:/Users/twaters/Desktop/Assignments/SQL/Python/DA Project/novels_data_result.txt', sep='\t')

Error:
Traceback (most recent call last):

File "", line 1, in
    main()

File "C:/Users/user/Desktop/Assignments/SQL/Python/DA Project/class17.py", line 36, in main
    model_novels()

File "C:/Users/user/Desktop/Assignments/SQL/Python/DA Project/class17.py", line 95, in model_novels
    selectedModel.fit(X_train, Y_train)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\linear_model\logistic.py", line 1216, in fit
    order="C")

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 573, in check_X_y
    ensure_min_features, warn_on_dtype, estimator)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 453, in check_array
    _assert_all_finite(array)

File "D:\Program Files (x86)\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 44, in _assert_all_finite
    " or a value too large for %r." % X.dtype)

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

If you need access to the files I am reading from, I can link them.

Thank you for your help!


问:
Spring Boot Security Authentication - 302 Redirects
I am trying to test my web api thats secured using the standard Spring Security API.  I have implemented my own User authentication service by implementing UserDetailService.  However whenever I login to my application the /login api keeps returning a 302 redirect.  I verified that my login page is working correctly by manually testing both good credentials and bad credentials and it did properly authenticate correctly to the homepage depending on whether the credentials were good, however it still returned a 302 for /login.  Im wondering why Spring/Thymeleaf is returning a 302 redirect when performing the /login request.  This is preventing my ability to test any of my guarded endpoints when locked down with spring security.

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
public JwtTokenFilter jwtTokenFilter() {
    return new JwtTokenFilter();
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .csrf()
            .disable()
            .cors()
            .and()
            .authorizeRequests().antMatchers("/profiles/**","/img/**","/resources","/v2/**","/users", "/login", "/error/**", "/keepalive", "/register").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/")
            .permitAll()
            .and()
            .logout();

    http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(asList("*"));
    configuration.setAllowedMethods(asList("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
</code>```

Login.html Page

```<code>   <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
>
<head>
    <title>Login</title>
    <div th:replace="fragments/header :: header-css"/>
</head>
<body class="white-bg">

<div th:replace="fragments/header :: header"/>

    <div class="middle-box text-center loginscreen">
        <div>
            <div>

                <h1 class="logo-name"></h1>

            </div>
        <h3>Welcome to </h3>

        <p>Login in. To see it in action.</p>
        <form th:action="@{/login}" method="post">
            <fieldset>
                <div th:if="${param.error}">
                    <div class="alert alert-danger">
                        Invalid username and password.
                    </div>
                </div>
                <div th:if="${param.logout}">
                    <div class="alert alert-info">
                        You have been logged out.
                    </div>
                </div>

                <div class="form-group">
                    <input type="text" name="username" id="username" class="form-control"
                           placeholder="UserName" required="true" autofocus="true"/>
                </div>
                <div class="form-group">
                    <input type="password" name="password" id="password" class="form-control"
                           placeholder="Password" required="true"/>
                </div>
                <input type="submit" class="btn btn-lg btn-primary btn-block" value="Sign In"/>

                <a href="#"><small>Forgot password?</small></a>
                <p class="text-muted text-center"><small>Do not have an account?</small></p>
                <a class="btn btn-sm btn-white btn-block" href="register.html">Create an account</a>
            </fieldset>
        </form>
        <p class="m-t"> <small>DigiProof Company © 2017</small> </p>
    </div>
</div>
</code>```

BaseController.java for routing

```<code>@Controller
public class BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String homeMain() {
        return "home";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }

    @GetMapping("/login")
    public String login(Principal principal) {
        if (principal!=null && ((Authentication)principal).isAuthenticated())
            return "redirect:/home";
        else
            return "login";
    }

    @RequestMapping(value="/registration", method = RequestMethod.GET)
    public ModelAndView registration(){
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) {
        ModelAndView modelAndView = new ModelAndView();
        User userByEmailExists = userService.findUserByEmail(user.getEmail());
        if (userByEmailExists != null) {
            bindingResult
                    .rejectValue("email", "error.user",
                            "There is already a user registered with the email provided");
        }
        if (bindingResult.hasErrors()) {
            modelAndView.setViewName("register");
        } else {
            userService.save(user);
            modelAndView.addObject("successMessage", "User has been registered successfully");
            modelAndView.addObject("user", new User());
            modelAndView.setViewName("register");
        }
        return modelAndView;
    }

    @GetMapping("/profile")
    public String profile() {
        return "profile";
    }

    @GetMapping("/activity")
    public String activity() {
        return "activity";
    }

    @GetMapping("/teams")
    public String teams() {
        return "teams";
    }

    @GetMapping("/404")
    public String error404() {
        return "/error/403";
    }

    @GetMapping("/403")
    public String error403() {
        return "/error/403";
    }

    @GetMapping("/500")
    public String error500() {
        return "/error/500";
    }

    @GetMapping("/error")
    public String error() {
        return "/error/500";
    }

}
</code>```

答:
spring security formLogin default intercept the "/login" request, i find that your login page url is "/login" which is conflict with this filter. you can define your login page url like this:

```<code>.formLogin()
        .loginPage("/page/login.html").permitAll()
</code>```

and change then controller mapping from login --> /page/login

Body:
I am trying to test my web api thats secured using the standard Spring Security API.  I have implemented my own User authentication service by implementing UserDetailService.  However whenever I login to my application the /login api keeps returning a 302 redirect.  I verified that my login page is working correctly by manually testing both good credentials and bad credentials and it did properly authenticate correctly to the homepage depending on whether the credentials were good, however it still returned a 302 for /login.  Im wondering why Spring/Thymeleaf is returning a 302 redirect when performing the /login request.  This is preventing my ability to test any of my guarded endpoints when locked down with spring security.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
public JwtTokenFilter jwtTokenFilter() {
    return new JwtTokenFilter();
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .csrf()
            .disable()
            .cors()
            .and()
            .authorizeRequests().antMatchers("/profiles/**","/img/**","/resources","/v2/**","/users", "/login", "/error/**", "/keepalive", "/register").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/")
            .permitAll()
            .and()
            .logout();

    http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(asList("*"));
    configuration.setAllowedMethods(asList("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}

Login.html Page

   <!DOCTYPE html>

    <title>Login</title>

Welcome to

Login in. To see it in action.

        <form th:action="@{/login}" method="post">
            <fieldset>

                        Invalid username and password.

                        You have been logged out.

                    <input type="text" name="username" id="username" class="form-control"
                           placeholder="UserName" required="true" autofocus="true"/>

                    <input type="password" name="password" id="password" class="form-control"
                           placeholder="Password" required="true"/>

                <input type="submit" class="btn btn-lg btn-primary btn-block" value="Sign In"/>

                Forgot password?

Do not have an account?

                Create an account
            </fieldset>
        </form>

 DigiProof Company © 2017

BaseController.java for routing

@Controller
public class BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String homeMain() {
        return "home";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }

    @GetMapping("/login")
    public String login(Principal principal) {
        if (principal!=null && ((Authentication)principal).isAuthenticated())
            return "redirect:/home";
        else
            return "login";
    }

    @RequestMapping(value="/registration", method = RequestMethod.GET)
    public ModelAndView registration(){
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) {
        ModelAndView modelAndView = new ModelAndView();
        User userByEmailExists = userService.findUserByEmail(user.getEmail());
        if (userByEmailExists != null) {
            bindingResult
                    .rejectValue("email", "error.user",
                            "There is already a user registered with the email provided");
        }
        if (bindingResult.hasErrors()) {
            modelAndView.setViewName("register");
        } else {
            userService.save(user);
            modelAndView.addObject("successMessage", "User has been registered successfully");
            modelAndView.addObject("user", new User());
            modelAndView.setViewName("register");
        }
        return modelAndView;
    }

    @GetMapping("/profile")
    public String profile() {
        return "profile";
    }

    @GetMapping("/activity")
    public String activity() {
        return "activity";
    }

    @GetMapping("/teams")
    public String teams() {
        return "teams";
    }

    @GetMapping("/404")
    public String error404() {
        return "/error/403";
    }

    @GetMapping("/403")
    public String error403() {
        return "/error/403";
    }

    @GetMapping("/500")
    public String error500() {
        return "/error/500";
    }

    @GetMapping("/error")
    public String error() {
        return "/error/500";
    }

}

Body:
spring security formLogin default intercept the "/login" request, i find that your login page url is "/login" which is conflict with this filter. you can define your login page url like this:

.formLogin()
        .loginPage("/page/login.html").permitAll()

and change then controller mapping from login --> /page/login


问:
Array of 12 elements- find count- practice
Could you guys please walk and help me with this practice question?
I'm unable to figure out how the answer is 5.</p>

```<code>int arr[12] = { 1,3,5,0,7,2,0,4,4,0,8,8 };
int count = 0;
for (int i = 0; i<11; i++) {
    if (arr[i] = arr[i + 1])
        count++;
    else
        count--;
}
cout << count << endl;
</code>```

答:
In your example you have :

```<code>if (arr[i] = arr[i + 1])
</code>```

which is the =, not ==. It is assigning not checking for equality. So in the example:

```<code>if (a = 3) {
</code>```

You will assign a to 3 and check if 3 is true, which it is. This leads to an easy look at why the answer is 5:

```<code>arr=>  { 1,3,5,0,7,2,0,4,4,0,8,8 };
count=>    1,2,1,2,3,2,3,4,3,4,5
</code>```

And if you are interested, look at the array after you have completed. It will look like this:

```<code>{3,5,0,7,2,0,4,4,0,8,8,8} // Everything has been moved down 1 (except for the final member)
</code>```

See a live example of this here.

Body:
Could you guys please walk and help me with this practice question?
I'm unable to figure out how the answer is 5.

int arr[12] = { 1,3,5,0,7,2,0,4,4,0,8,8 };
int count = 0;
for (int i = 0; i<11; i++) {
    if (arr[i] = arr[i + 1])
        count++;
    else
        count--;
}
cout << count << endl;

Body:
In your example you have :

if (arr[i] = arr[i + 1])

which is the =, not ==. It is assigning not checking for equality. So in the example:

if (a = 3) {

You will assign a to 3 and check if 3 is true, which it is. This leads to an easy look at why the answer is 5:

arr=>  { 1,3,5,0,7,2,0,4,4,0,8,8 };
count=>    1,2,1,2,3,2,3,4,3,4,5

And if you are interested, look at the array after you have completed. It will look like this:

{3,5,0,7,2,0,4,4,0,8,8,8} // Everything has been moved down 1 (except for the final member)

See a live example of this here.


问:
Why does git using ssh use git as a username

This is just a general question about how git functions. I couldn't find anything in the git manual related to this, maybe I'm not looking in the right place.

When you clone using an ssh link from a git server, the username it uses is git, not the username of the key you are trying to use. Why does git do this and how is git able to tell which keypair that it should use to authenticate the connection.

答:
When you clone using an ssh link from a git server, the username it uses is git, not the username of the key you are trying to use.

Correct.  The reason for this is that the service is tied to a user account, and you need to access the server as that user in order to invoke the service.  This is really a feature of SSH and not of Git--Git is just using SSH as a transport.
Also, SSH--and therefore Git--knows nothing about the user associated with the SSH key--just that it's been approved for accessing the account.  This is usually done through the authorized_keys file for the Git user, and tools like Gerrit or Gitolite manage that file as you add and remove users.  The authorized_keys file allows specifying a specific command to run when authenticated, and these tools use that feature to communicate the user--then the app determines the permissions from there.

Why does git do this and how is git able to tell which keypair that it should use to authenticate the connection.

There's a bit of a misconception here.  Some of this is not so much Git as it is SSH.  And tools like Git use SSH as the transport because it's done the hard work of authenticating, securing network activity, and has tools like ssh-agent to make authentication easier.  Why reinvent the wheel?

The keypair is actually determined one of two ways: you specify it in your ~/.ssh/config (this is what I do), or you let ssh walk through the available keys and figure it out.  The latter can lead to problems if the administrator has setup strict rules since any key that doesn't work will count as an authentication attempt.  Most people don't have more than one key, so it's generally not a problem.

You can see some of this negotiation happening by using ssh -v git@github.com, or whichever server you're going against:

```<code>OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /Users/jszakmeister/.ssh/config
debug1: /Users/jszakmeister/.ssh/config line 286: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Control socket "/tmp/git@github.com:22" does not exist
debug1: Connecting to github.com [192.30.255.113] port 22.
debug1: Connection established.
debug1: identity file /Users/jszakmeister/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/jszakmeister/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version libssh_0.7.0
debug1: no match: libssh_0.7.0
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ssh-rsa
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /Users/jszakmeister/.ssh/known_hosts:25
Warning: Permanently added the RSA host key for IP address '192.30.255.113' to the list of known hosts.
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/jszakmeister/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([192.30.255.113]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
PTY allocation request failed on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi jszakmeister! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Connection to github.com closed.
Transferred: sent 2988, received 1868 bytes, in 0.2 seconds
Bytes per second: sent 19242.2, received 12029.6
debug1: Exit status 1
</code>```

I'm not sure that entirely answers your question, but I hope it helps.

Update

SSH is an extremely capable tool that also has a lot of configuration options.  One thing you can do to make life a little easier is setup your config to apply the username and key file you want to use:

~/.ssh/config

```<code>Host gh
    User git
    Hostname github.com
    IdentityFile ~/.ssh/id_github
</code>```

You could use something like the above to allow git clone gh:foo/bar.git to essentially mean git clone git@github.com:foo/bar.git and use a different SSH key for authentication. I use this feature all the time, not just for  Git-related stuff.

Body:
When you clone using an ssh link from a git server, the username it uses is git, not the username of the key you are trying to use.

Correct.  The reason for this is that the service is tied to a user account, and you need to access the server as that user in order to invoke the service.  This is really a feature of SSH and not of Git--Git is just using SSH as a transport.
Also, SSH--and therefore Git--knows nothing about the user associated with the SSH key--just that it's been approved for accessing the account.  This is usually done through the authorized_keys file for the Git user, and tools like Gerrit or Gitolite manage that file as you add and remove users.  The authorized_keys file allows specifying a specific command to run when authenticated, and these tools use that feature to communicate the user--then the app determines the permissions from there.

Why does git do this and how is git able to tell which keypair that it should use to authenticate the connection.

There's a bit of a misconception here.  Some of this is not so much Git as it is SSH.  And tools like Git use SSH as the transport because it's done the hard work of authenticating, securing network activity, and has tools like ssh-agent to make authentication easier.  Why reinvent the wheel?

The keypair is actually determined one of two ways: you specify it in your ~/.ssh/config (this is what I do), or you let ssh walk through the available keys and figure it out.  The latter can lead to problems if the administrator has setup strict rules since any key that doesn't work will count as an authentication attempt.  Most people don't have more than one key, so it's generally not a problem.

You can see some of this negotiation happening by using ssh -v git@github.com, or whichever server you're going against:

OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /Users/jszakmeister/.ssh/config
debug1: /Users/jszakmeister/.ssh/config line 286: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Control socket "/tmp/git@github.com:22" does not exist
debug1: Connecting to github.com [192.30.255.113] port 22.
debug1: Connection established.
debug1: identity file /Users/jszakmeister/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/jszakmeister/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version libssh_0.7.0
debug1: no match: libssh_0.7.0
debug1: Authenticating to github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ssh-rsa
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /Users/jszakmeister/.ssh/known_hosts:25
Warning: Permanently added the RSA host key for IP address '192.30.255.113' to the list of known hosts.
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/jszakmeister/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([192.30.255.113]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
PTY allocation request failed on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi jszakmeister! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Connection to github.com closed.
Transferred: sent 2988, received 1868 bytes, in 0.2 seconds
Bytes per second: sent 19242.2, received 12029.6
debug1: Exit status 1

I'm not sure that entirely answers your question, but I hope it helps.

Update

SSH is an extremely capable tool that also has a lot of configuration options.  One thing you can do to make life a little easier is setup your config to apply the username and key file you want to use:

~/.ssh/config

Host gh
    User git
    Hostname github.com
    IdentityFile ~/.ssh/id_github

You could use something like the above to allow git clone gh:foo/bar.git to essentially mean git clone git@github.com:foo/bar.git and use a different SSH key for authentication. I use this feature all the time, not just for  Git-related stuff.

ContentLicense: CC BY-SA 4.0


问:
Why does this jQuery not affect elements outputted from PHP, only ones defined in HTML?
I'm trying to make a dynamic nav menu similar to this. The javascript is here and worked perfectly when I tested it with:

```<code><div id='nav'>
        <ul>
            <li class="navHeader">OOC</li>
            <li><a href='#'>Home</a></li>
            <li class='active'><a href='#'>Products</a>
                <ul>
                    <li><a href='#'>Product 1</a>
                        <ul>
                            <li><a href='#'>Sub Product</a></li>
                            <li><a href='#'>Sub Product</a></li>
                        </ul>
                    </li>

                    <li><a href='#'>Product 2</a>
                        <ul>
                            <li><a href='#'>Sub Product</a></li>
                            <li><a href='#'>Sub Product</a></li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</code>```

However, I tried to switch the content of the nav to this:

```<code><div id='nav'>
        <ul>
            <li class="navHeader">OOC</li>
            <?php echo getNav(); ?>
        </ul>
    </div>
</code>```

PHP:

```<code>function formatNav($navPg){
    $navLine = "<li><a href='?pg=".$navPg['url']."'>".$navPg['name']."</a></li>";
    if ($navPg['subPgs'] > 0) {
        $navLine .= "<ul>";
        foreach($navPg['subPgs'] as $subPg) {
            $navLine .= formatNav($subPg);
        }
        $navLine .= "</ul>";
    }
    return $navLine;
}

function getNav(){
        $navPgs = array(array(
                            'name'=>'profile',
                            'url'=>'profile',
                            'subPgs'=>array(
                                array(
                                    'name'=>'subaccounts',
                                    'url'=>'profile&cat=subs',
                                    'subPgs'=>''
                                ),
                                array(
                                    'name'=>'options',
                                    'url'=>'profile&cat=opts',
                                    'subPgs'=>''
                                )
                            )
                        )
                    );

    $finalNav = "";
    foreach($navPgs as $navPg){
        $finalNav .= formatNav($navPg);
    }
    return $finalNav;
}
</code>```

And none of the Javascript runs on it.

The JS doesn't add the class has-sub to the li elements that have submenus. Elements with has-sub added in the PHP display their CSS properly but don't perform the dropdown event. I debugged the list of
 elements found after cssmenu.find('li ul').parent().addClass('has-sub'); in the JS, and it doesn't include the PHP-generated ones.

I debugged the PHP output, and it's a perfect set of li and ul elements as if I'd formatted them by hand. The JS works fine by itself, the PHP works fine by itself, but when I try to combine them, the JS fails.

Somebody had the same problem here, but the answers aren't helpful. I can change my implementation to build the list elements dynamically in javascript based on a JSON list of qualities about it, but I want to know why I have to do that instead of echoing them out from PHP directly, especially if there's a more direct workaround.

Is the PHP running after $(document).ready fires somehow even though it runs server-side?

JS runs client-side, but valid DOM elements outputted from server-side scripts should be indistinguishable from ones created client-side. Right?

Why isn't this?

edit: Pictures of output from the PHP by itself. Nothing seems wrong with it.

答:
The function is not generating the same structure, which could be the issue.

I've tweaked your function to return the same structure, as your working one.

Give it a try.

```<code><?php
function formatNav($navPg){
    $navLine = "<li><a href='".$navPg['url']."'>".$navPg['name']."</a>";
    if (is_array($navPg['subPgs']) && count($navPg['subPgs']) > 0) {
        $navLine .= "<ul>";
        foreach($navPg['subPgs'] as $subPg) {
            $navLine .= formatNav($subPg);
        }
        $navLine .= "</ul>";
    } else {
        $navLine .= "</li>";
    }
    if (is_array($navPg['subPgs']) && count($navPg['subPgs']) > 0) {
        $navLine .= "</li>";
    }
    return $navLine;
}

function getNav(){
    $navPgs = array(
        array(
            'name'=>'Home',
            'url'=>'#',
            'subPgs'=>array()
        ),
        array(
            'name'=>'Products',
            'url'=>'#',
            'subPgs'=>array(
                array(
                    'name'=>'Product 1',
                    'url'=>'#',
                    'subPgs'=>array(
                        array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),
                    )
                ),
                array(
                    'name'=>'Product 2',
                    'url'=>'#',
                    'subPgs'=>array(
                        array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),
                    )
                )
            )
        )
    );

    $finalNav = "";
    foreach($navPgs as $navPg){
        $finalNav .= formatNav($navPg);
    }
    return $finalNav;
}
</code>```

https://3v4l.org/gjM0Y

```<code><div id='nav'>
   <ul>
      <li class="navHeader">OOC</li>
      <li><a href='#'>Home</a></li>
      <li>
         <a href='#'>Products</a>
         <ul>
            <li>
               <a href='#'>Product 1</a>
               <ul>
                  <li><a href='#'>Sub Product</a></li>
                  <li><a href='#'>Sub Product</a></li>
               </ul>
            </li>
            <li>
               <a href='#'>Product 2</a>
               <ul>
                  <li><a href='#'>Sub Product</a></li>
                  <li><a href='#'>Sub Product</a></li>
               </ul>
            </li>
         </ul>
      </li>
   </ul>
</div>
</code>```

Body:
I'm trying to make a dynamic nav menu similar to this. The javascript is here and worked perfectly when I tested it with:

OOC

Home

Products

Product 1

Sub Product

Sub Product

Product 2

Sub Product

Sub Product

However, I tried to switch the content of the nav to this:

OOC

            <?php echo getNav(); ?>

PHP:

function formatNav($navPg){
    $navLine = "
".$navPg['name']."
";
    if ($navPg['subPgs'] > 0) {
        $navLine .= "
";
        foreach($navPg['subPgs'] as $subPg) {
            $navLine .= formatNav($subPg);
        }
        $navLine .= "
";
    }
    return $navLine;
}

function getNav(){
        $navPgs = array(array(
                            'name'=>'profile',
                            'url'=>'profile',
                            'subPgs'=>array(
                                array(
                                    'name'=>'subaccounts',
                                    'url'=>'profile&cat=subs',
                                    'subPgs'=>''
                                ),
                                array(
                                    'name'=>'options',
                                    'url'=>'profile&cat=opts',
                                    'subPgs'=>''
                                )
                            )
                        )
                    );

    $finalNav = "";
    foreach($navPgs as $navPg){
        $finalNav .= formatNav($navPg);
    }
    return $finalNav;
}

And none of the Javascript runs on it.

The JS doesn't add the class has-sub to the li elements that have submenus. Elements with has-sub added in the PHP display their CSS properly but don't perform the dropdown event. I debugged the list of
 elements found after cssmenu.find('li ul').parent().addClass('has-sub'); in the JS, and it doesn't include the PHP-generated ones.

I debugged the PHP output, and it's a perfect set of li and ul elements as if I'd formatted them by hand. The JS works fine by itself, the PHP works fine by itself, but when I try to combine them, the JS fails.

Somebody had the same problem here, but the answers aren't helpful. I can change my implementation to build the list elements dynamically in javascript based on a JSON list of qualities about it, but I want to know why I have to do that instead of echoing them out from PHP directly, especially if there's a more direct workaround.

Is the PHP running after $(document).ready fires somehow even though it runs server-side?

JS runs client-side, but valid DOM elements outputted from server-side scripts should be indistinguishable from ones created client-side. Right?

Why isn't this?

edit: Pictures of output from the PHP by itself. Nothing seems wrong with it.

Body:
The function is not generating the same structure, which could be the issue.

I've tweaked your function to return the same structure, as your working one.

Give it a try.

<?php
function formatNav($navPg){
    $navLine = "<li><a href='".$navPg['url']."'>".$navPg['name']."</a>";
    if (is_array($navPg['subPgs']) && count($navPg['subPgs']) > 0) {
        $navLine .= "<ul>";
        foreach($navPg['subPgs'] as $subPg) {
            $navLine .= formatNav($subPg);
        }
        $navLine .= "</ul>";
    } else {
        $navLine .= "</li>";
    }
    if (is_array($navPg['subPgs']) && count($navPg['subPgs']) > 0) {
        $navLine .= "</li>";
    }
    return $navLine;
}

function getNav(){
    $navPgs = array(
        array(
            'name'=>'Home',
            'url'=>'#',
            'subPgs'=>array()
        ),
        array(
            'name'=>'Products',
            'url'=>'#',
            'subPgs'=>array(
                array(
                    'name'=>'Product 1',
                    'url'=>'#',
                    'subPgs'=>array(
                        array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),
                    )
                ),
                array(
                    'name'=>'Product 2',
                    'url'=>'#',
                    'subPgs'=>array(
                        array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),array(
                            'name'=>'Sub Product',
                            'url'=>'#',
                            'subPgs'=>array()
                        ),
                    )
                )
            )
        )
    );

    $finalNav = "";
    foreach($navPgs as $navPg){
        $finalNav .= formatNav($navPg);
    }
    return $finalNav;
}

https://3v4l.org/gjM0Y

<div id='nav'>
   <ul>
      <li class="navHeader">OOC</li>
      <li><a href='#'>Home</a></li>
      <li>
         <a href='#'>Products</a>
         <ul>
            <li>
               <a href='#'>Product 1</a>
               <ul>
                  <li><a href='#'>Sub Product</a></li>
                  <li><a href='#'>Sub Product</a></li>
               </ul>
            </li>
            <li>
               <a href='#'>Product 2</a>
               <ul>
                  <li><a href='#'>Sub Product</a></li>
                  <li><a href='#'>Sub Product</a></li>
               </ul>
            </li>
         </ul>
      </li>
   </ul>
</div>


问:
Is there a quick way to edit multiple yaml files at once?
I have about 30 yaml files used as configs but the properties in the files are still under development. So there will be times when new properties have to be added.

It would be tedious to add the same property to all the different files, is there a quick way/tool?

答:
There are a few ways, but my favorite would be to use :cdo/:cfdo. Simply :grep/:vimgrep your files then run a command with :cdo.

```<code>:vimgrep /pattern/ *.yaml
:cdo s/foo/bar/|w
</code>```

The command to :cdo doesn't need to be a substitution, you can use any ex command (See :h ex-cmd-index). For example use :normal to capitalize the first character of each match, :cdo norm ~.

See the following Vimcasts episode:

Project-wide find and replace Note: :cdo is available in Vim 8.

Search multiple files with :vimgrep

You can also may be able to use the argument list and :argdo.

```<code>:args *.yaml
:argdo s/foo/bar/|w
</code>```

Related Vimcasts espidodes:

Meet the arglist

Populating the arglist

Using :argdo to change multiple files

For more help see:

```<code>:h :cdo
:h :vimgrep
:h :s
:h quickfix
:h arglist
:h :argdo
:h :args
</code>```

Body:
There are a few ways, but my favorite would be to use :cdo/:cfdo. Simply :grep/:vimgrep your files then run a command with :cdo.

:vimgrep /pattern/ *.yaml
:cdo s/foo/bar/|w

The command to :cdo doesn't need to be a substitution, you can use any ex command (See :h ex-cmd-index). For example use :normal to capitalize the first character of each match, :cdo norm ~.

See the following Vimcasts episode:

Project-wide find and replace Note: :cdo is available in Vim 8.

Search multiple files with :vimgrep

You can also may be able to use the argument list and :argdo.

:args *.yaml
:argdo s/foo/bar/|w

Related Vimcasts espidodes:

Meet the arglist

Populating the arglist

Using :argdo to change multiple files

For more help see:

:h :cdo
:h :vimgrep
:h :s
:h quickfix
:h arglist
:h :argdo
:h :args


问:
Cannot start an LXD container when the subuid and subgid information for root are changed
New to LXD and running into a problem where I am trying to build a subuid and subgid map for the root user of my container so that when root writes to the directory /megalith, it will be the UID/GID of the host user (1000:1000) rather than uid/gid of 165536:65536.  I am trying to follow the instructions that are listed here:

http://insights.ubuntu.com/2016/12/08/mounting-your-home-directory-in-lxd/

But when I try to start the container, I receive the errors listed below.  If I return the root subuid and subgid entries back to root:165536:65536 though, everything starts to work properly, except that when I write to /megalith, the UID and GID are 165536:65536 obviously.

Is there anything else that I need to do to make the root subuid and subgid mappings work properly that may not be in the documentation or that I may be missing?

```<code>cliff@reventon /megalith $ id
uid=1000(cliff) gid=1000(cliff) groups=1000(cliff),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),130(sambashare),132(lxd)

cliff@reventon /megalith $ cat /etc/subuid
cliff:100000:65536
lxd:165536:65536
root:1000:1

cliff@reventon /megalith $ cat /etc/subgid
cliff:100000:65536
lxd:165536:65536
root:1000:1

cliff@reventon /megalith $ lxc init ubuntu-daily:z zestytest
Creating zestytest

cliff@reventon /megalith $ lxc config set zestytest raw.idmap 'both 1000 1000'

cliff@reventon /megalith $ lxc config device add zestytest megalith disk source=/megalith path=/megalith
Device megalith added to zestytest

cliff@reventon /megalith $ lxc start zestytest
error: Error calling 'lxd forkstart zestytest /var/lib/lxd/containers /var/log/lxd/zestytest/lxc.conf': err='exit status 1'
  lxc 20170112215311.265 ERROR lxc_start - start.c:lxc_spawn:1163 - Failed to set up id mapping.
  lxc 20170112215311.303 ERROR lxc_start - start.c:__lxc_start:1338 - Failed to spawn container "zestytest".
  lxc 20170112215311.855 ERROR lxc_conf - conf.c:run_buffer:347 - Script exited with status 1
  lxc 20170112215311.855 ERROR lxc_start - start.c:lxc_fini:546 - Failed to run lxc.hook.post-stop for container "zestytest".
  lxc 20170112215311.858 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.858 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/systemd//lxc/zestytest
  lxc 20170112215311.861 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.861 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/cpuset//lxc/zestytest
  lxc 20170112215311.864 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.864 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/hugetlb//lxc/zestytest
  lxc 20170112215311.867 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.867 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/cpu//lxc/zestytest
  lxc 20170112215311.869 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.869 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/pids//lxc/zestytest
  lxc 20170112215311.872 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.872 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/perf_event//lxc/zestytest
  lxc 20170112215311.875 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.875 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/freezer//lxc/zestytest
  lxc 20170112215311.878 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.878 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/memory//lxc/zestytest
  lxc 20170112215311.881 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.881 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/net_cls//lxc/zestytest
  lxc 20170112215311.884 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.884 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/devices//lxc/zestytest
  lxc 20170112215311.886 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.886 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/blkio//lxc/zestytest

Try `lxc info --show-log zestytest` for more info
</code>```

答:
Not quite sure if this addresses your question: https://github.com/lxc/lxc/issues/1622

The gist of that thread is that it's unsafe/non-sensical to map a host uid and/or host gid to the container root uid and/or gid.  If you want to do what you describe, you should map to the default container user or create a new container user and run your commands with that container user.  Then you can map the host uid/gid to that container uid/gid.

Body:
New to LXD and running into a problem where I am trying to build a subuid and subgid map for the root user of my container so that when root writes to the directory /megalith, it will be the UID/GID of the host user (1000:1000) rather than uid/gid of 165536:65536.  I am trying to follow the instructions that are listed here:

http://insights.ubuntu.com/2016/12/08/mounting-your-home-directory-in-lxd/

But when I try to start the container, I receive the errors listed below.  If I return the root subuid and subgid entries back to root:165536:65536 though, everything starts to work properly, except that when I write to /megalith, the UID and GID are 165536:65536 obviously.

Is there anything else that I need to do to make the root subuid and subgid mappings work properly that may not be in the documentation or that I may be missing?

cliff@reventon /megalith $ id
uid=1000(cliff) gid=1000(cliff) groups=1000(cliff),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),130(sambashare),132(lxd)

cliff@reventon /megalith $ cat /etc/subuid
cliff:100000:65536
lxd:165536:65536
root:1000:1

cliff@reventon /megalith $ cat /etc/subgid
cliff:100000:65536
lxd:165536:65536
root:1000:1

cliff@reventon /megalith $ lxc init ubuntu-daily:z zestytest
Creating zestytest

cliff@reventon /megalith $ lxc config set zestytest raw.idmap 'both 1000 1000'

cliff@reventon /megalith $ lxc config device add zestytest megalith disk source=/megalith path=/megalith
Device megalith added to zestytest

cliff@reventon /megalith $ lxc start zestytest
error: Error calling 'lxd forkstart zestytest /var/lib/lxd/containers /var/log/lxd/zestytest/lxc.conf': err='exit status 1'
  lxc 20170112215311.265 ERROR lxc_start - start.c:lxc_spawn:1163 - Failed to set up id mapping.
  lxc 20170112215311.303 ERROR lxc_start - start.c:__lxc_start:1338 - Failed to spawn container "zestytest".
  lxc 20170112215311.855 ERROR lxc_conf - conf.c:run_buffer:347 - Script exited with status 1
  lxc 20170112215311.855 ERROR lxc_start - start.c:lxc_fini:546 - Failed to run lxc.hook.post-stop for container "zestytest".
  lxc 20170112215311.858 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.858 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/systemd//lxc/zestytest
  lxc 20170112215311.861 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.861 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/cpuset//lxc/zestytest
  lxc 20170112215311.864 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.864 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/hugetlb//lxc/zestytest
  lxc 20170112215311.867 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.867 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/cpu//lxc/zestytest
  lxc 20170112215311.869 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.869 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/pids//lxc/zestytest
  lxc 20170112215311.872 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.872 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/perf_event//lxc/zestytest
  lxc 20170112215311.875 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.875 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/freezer//lxc/zestytest
  lxc 20170112215311.878 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.878 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/memory//lxc/zestytest
  lxc 20170112215311.881 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.881 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/net_cls//lxc/zestytest
  lxc 20170112215311.884 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.884 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/devices//lxc/zestytest
  lxc 20170112215311.886 ERROR lxc_conf - conf.c:userns_exec_1:4374 - Error setting up child mappings
  lxc 20170112215311.886 ERROR lxc_cgfsng - cgroups/cgfsng.c:recursive_destroy:1274 - Error destroying /sys/fs/cgroup/blkio//lxc/zestytest

Try `lxc info --show-log zestytest` for more info


问:
How to disable Pepper moving around the room
If the power batch is lifted, this means Pepper is probably charging and the motions around the room and the rotations around himself are disabled. Is there a way to forbid those motions and rotations while this power batch is closed?</p>

答:
For one time specifically in your application, you can use

ALTracker.setMode("Head") or

ALBasicAwareness.setTrackingMode("Head")

For a global settings (robot behavior even when not running an app), you can add the following preference:

domain: com.aldebaran.autonomouslife

key: DefaultBasicAwarenessTrackingMode

value: Head


问:
JavaScript code with If Statements
I have been working on a text based game for personal use to get better at JavaScript. With this game, the user answers the questions that is written (like a story/choice game). This is my code...

```<code><!DOCTYPE HTML>
<html>

<head>
<!--<script type="text/javascript" src="gamescript.js"></script>-->

<style>
body {
  font-family: Calibri, sans-serif;
}

#mspace {
  padding: 10px 20px;
  background: #ff0;
}

.hideThis {
  display: none;
}

button {
  margin: 10px;
}

</style>

<script>

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the" + choice1;
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below
document.getElementById("mspace")

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases
window.onload = function(){
    document.getElementById("fight").onclick = fightResponse;
    document.getElementById("run").onclick = runResponse;
}

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

window.onload = function writeMessage() {
  // write message into the yellow paragraph
  document.getElementById("mspace").innerHTML = msg;
}

</script>
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>

<!---- Boss ---->
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>

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

When the questions appear, although it does what I want it to, I wanted it so that when the user enters either "Door 1" or "Door 2" for the first question, the 2nd question to appear after it. In my code, it's like a list of questions with text box underneath. It doesn't look nice and I don't know how to change it.

For the "Final Boss" code, It doesn't seem to be working and i don't know why. I have checked the F12 developer tool and no errors are showing.

All the help is appreciated and thank you!

答:
You need to set visibility hidden and visible for the particular elements as necessary.
For your second problem, you should not create the writeMessage function on window.onload. Here is the updated code with some other formatting corrections.

document.getElementById("choice1").style.visibility = "hidden";
document.getElementById("question2").style.visibility = "hidden";
document.getElementById("question3").style.visibility = "hidden";

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered " + door;
        document.getElementById("choice1").style.visibility = "visible";
document.getElementById("question2").style.visibility = "visible";
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered " + door;
        document.getElementById("choice1").style.visibility = "visible";
document.getElementById("question2").style.visibility = "visible";
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the " + choice1;
        document.getElementById("question3").style.visibility = "visible";
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
        document.getElementById("question3").style.visibility = "visible";
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below
document.getElementById("mspace").innerHTML = msg;

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases
window.onload = function(){
    document.getElementById("fight").onclick = fightResponse;
    document.getElementById("run").onclick = runResponse;
}

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

function writeMessage() {
  document.getElementById("mspace").innerHTML = msg;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>

<head>

</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<div id="question2">
<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>
</div>

<!---- Boss ---->
<div id="question3">
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>
</div>

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

Title: JavaScript code with If Statements

Body:
I have been working on a text based game for personal use to get better at JavaScript. With this game, the user answers the questions that is written (like a story/choice game). This is my code...

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?

<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>

Fight the Monster!

  <button id="fight">Fight</button>
  <button id="run">Run</button>

When the questions appear, although it does what I want it to, I wanted it so that when the user enters either "Door 1" or "Door 2" for the first question, the 2nd question to appear after it. In my code, it's like a list of questions with text box underneath. It doesn't look nice and I don't know how to change it.

For the "Final Boss" code, It doesn't seem to be working and i don't know why. I have checked the F12 developer tool and no errors are showing.

All the help is appreciated and thank you!

Body:
You need to set visibility hidden and visible for the particular elements as necessary.
For your second problem, you should not create the writeMessage function on window.onload. Here is the updated code with some other formatting corrections.

document.getElementById("choice1").style.visibility = "hidden";
document.getElementById("question2").style.visibility = "hidden";
document.getElementById("question3").style.visibility = "hidden";

function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1" || door == "door 1"){
        document.getElementById("door").innerHTML = "You have entered " + door;
        document.getElementById("choice1").style.visibility = "visible";
document.getElementById("question2").style.visibility = "visible";
    }else if (door == "Door 2" || door == "door 2"){
        document.getElementById("door").innerHTML = "You have entered " + door;
        document.getElementById("choice1").style.visibility = "visible";
document.getElementById("question2").style.visibility = "visible";
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

function myFunction2(){
    var choice1 = document.getElementById("myInput2").value;
    if (choice1 == "enter passageway" || choice1 == "passageway"){
        document.getElementById("choice1").innerHTML = "You entered the " + choice1;
        document.getElementById("question3").style.visibility = "visible";
     }else if (choice1 == "continue searching"){
        document.getElementById("choice1").innerHTML = "You " + choice1;
        document.getElementById("question3").style.visibility = "visible";
    }else{
        document.getElementById("choice1").innerHTML = "You must choose an option!"
    }
}

// JS for BOSS level
// starting variable for the boss
var stamina = 10;

// starting message
var msg = "A huge, threatening monster wants to fight you! What do you do?";
// run a function that is below
document.getElementById("mspace").innerHTML = msg;

// click a button to execute a function
// NOTE: no parentheses after the function name in these cases
window.onload = function(){
    document.getElementById("fight").onclick = fightResponse;
    document.getElementById("run").onclick = runResponse;
}

function runResponse() {
  if (stamina > 8) {
    msg = "The monster swings his long arm and -- GAME OVER!";
    hideButtons();
  } else if (stamina > 3) {
    msg = "Well, that's one way to end a fight ...";
    hideButtons();
  } else {
    msg = "Keep fighting! The monster is almost dead!";
  }
  writeMessage();
}

function fightResponse() {
  if (stamina > 8) {
    msg = "The monster is strong! It resists your attack!";
  } else if (stamina > 5) {
    msg = "With a loud screech, the monster stands firm.";
  } else if (stamina > 3) {
    msg = "Your attack seems to be having an effect! The monster stumbles!";
  } else if (stamina > 0) {
    msg = "This monster is about to fall! It staggers and reels!";
  } else {
    msg = "With a final swing! The monster has been defeated! You have triumphed!";
    hideButtons();
  }
  // create new random number from 0 to 5
  var damage = Math.floor(Math.random() * 6);
  // subtract it from stamina
  stamina -= damage;
  writeMessage();
}

function hideButtons() {
  // changes the class on the div - see the CSS pane
  document.getElementById("game").className = "hideThis";
}

function writeMessage() {
  document.getElementById("mspace").innerHTML = msg;
}

<!DOCTYPE HTML>
<html>

<head>

</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<!---- Question 1 ---->
<p id ="choice1">Behind Door 1 is an empty room. Whilst searching the room for clues, you see a hidden passageway. Do you wish to enter the passageway or continue searching?</p>

<div id="question2">
<input id="myInput2" type="text">

<button onclick="myFunction2()">Enter</button>
</div>

<!---- Boss ---->
<div id="question3">
<h1>Fight the Monster!</h1>

<p id="mspace"></p>

<div id="game">

  <button id="fight">Fight</button>
  <button id="run">Run</button>

</div>
</div>

</body>
</html>