问:
OAuth 2.0 Works for Google Sheets but not for Google Calendar API
I am using the Google API for reading/writing Google Sheets and the Google Drive API.
I recently got assigned a project where it is necessary to send out Calendar invites. The Website is a JSF Page hosted on an Apache Tomcat 8.5. For other APIs, I am using a Service Account.
I now tried to authorize the Calendar Service same way but it fails. First line is the succesful authorize for the sheets service, its failing on the calendar service:

GoogleConnection: Absolut Path: H:/ownCloud/Wabco/Workspace/WabcoDiagram/WebContent/resources/webserviceaccount.json
  GoogleConnection: Absolut Path: H:/ownCloud/Wabco/Workspace/WabcoDiagram/WebContent/resources/webserviceaccount.json
  Exception in thread "main" java.lang.NoSuchMethodError: com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient$Builder.setBatchPath(Ljava/lang/String;)Lcom/google/api/client/googleapis/services/AbstractGoogleClient$Builder;
      at com.google.api.services.calendar.Calendar$Builder.setBatchPath(Calendar.java:6758)
      at com.google.api.services.calendar.Calendar$Builder.(Calendar.java:6737)
      at de.promolitor.wabcodiagramviewer.audit.AuditGoogleCalendar.getCalendarServiceLocal(AuditGoogleCalendar.java:112)
      at de.promolitor.wabcodiagramviewer.audit.AuditGoogleCalendar.initializeCalendarServiceLocal(AuditGoogleCalendar.java:150)
      at de.promolitor.wabcodiagramviewer.audit.AuditGoogleCalendar.main(AuditGoogleCalendar.java:156)

My Questions:
Can I login with a Service account into the Google Calendar API, or what are the changes I have to do, or is there another error in my code somewhere?

Can I send out Calendar Invites from a Web Service Service account and make another user the Admin / Creator of the event, so he can change the event if necessary? Does this require "domain-wide authority"?
I am working for a company that uses GSuit.

Example Code. The local functions are for local testing.

```<code>package de.promolitor.wabcodiagramviewer.audit;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.plus.Plus;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;

public class AuditGoogleCalendar {
    /** Application name. */
    private static final String APPLICATION_NAME = "Wabco Audit";

    /** Global instance of the {@link FileDataStoreFactory}. */
    // private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    private static GoogleCredential credential;

    /** Global instance of the HTTP transport. */
    private static HttpTransport httpTransport;

    private static Plus plus;

    private static Sheets service;
    private static Drive driveService;
    private static Calendar calendarService;

    /**
     * Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials at
     * ~/.credentials/sheets.googleapis.com-java-quickstart
     */
    private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS, DriveScopes.DRIVE,
            GmailScopes.MAIL_GOOGLE_COM, CalendarScopes.CALENDAR);

    static {
        try {
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    public static GoogleCredential authorize() throws IOException, GeneralSecurityException {
        String relativeWebPath = "/resources/" + "webserviceaccount.json";
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
        System.out.println("GoogleConnection: Absolut Path: " + absoluteDiskPath);

        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(absoluteDiskPath))
                .createScoped(SCOPES);
        return credential;
    }

    public static GoogleCredential authorizeLocal() throws IOException, GeneralSecurityException {
        String absoluteDiskPath = "H:/ownCloud/Wabco/Workspace/WabcoDiagram/WebContent/resources/webserviceaccount.json";
        System.out.println("GoogleConnection: Absolut Path: " + absoluteDiskPath);

        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(absoluteDiskPath))
                .createScoped(SCOPES);
        return credential;

    }

    public static Calendar getCalendarService() throws IOException, GeneralSecurityException {
        Credential credential = authorize();
        return new Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static Calendar getCalendarServiceLocal() throws IOException, GeneralSecurityException {
        Credential credential = authorizeLocal();
        return new Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
        credential = authorize();
        return new Sheets.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static Sheets getSheetsServiceLocal() throws IOException, GeneralSecurityException {
        credential = authorizeLocal();
        return new Sheets.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static Drive getDriveService() throws IOException, GeneralSecurityException {
        GoogleCredential credential = authorize();
        return new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static void initializeSheetService() throws IOException, GeneralSecurityException {
        service = getSheetsService();
    }

    public static void initializeSheetServiceLocal() throws IOException, GeneralSecurityException {
        service = getSheetsServiceLocal();
    }

    public static void initializeDriveService() throws IOException, GeneralSecurityException {
        driveService = getDriveService();
    }

    public static void initializeCalendarService() throws IOException, GeneralSecurityException {
        calendarService = getCalendarService();
    }

    public static void initializeCalendarServiceLocal() throws IOException, GeneralSecurityException {
        calendarService = getCalendarServiceLocal();
    }

    public static void main(String[] args) {
        try {
            initializeSheetServiceLocal();
            initializeCalendarServiceLocal();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
</code>```

答:
My Questions: Can I login with a Service account into the Google Calendar API, or what are the changes I have to do, or is there another error in my code somewhere?

Yes you can use a service account with Google Calendar.  Your code looks ok to me you should simply have to add the calendar scope which you have done and enable the google calendar api for the service account in Google developer console.

Can I send out Calendar Invites from a Web Service Service account and make another user the Admin / Creator of the event, so he can change the event if necessary? Does this require "domain-wide authority"? I am working for a company that uses GSuit.

Yes you can with a service account. You are going to have to have the Gsuit admin grant the service account access to the calendar then it will be able to create events and invite people. Yes it will require "domain-wide authority"? Once you have inserted the event you should be able to patch the event and set someone else as organizer. check this  its been a while since i have done this cant remember more then that sorry.

Body:
I am using the Google API for reading/writing Google Sheets and the Google Drive API.
I recently got assigned a project where it is necessary to send out Calendar invites. The Website is a JSF Page hosted on an Apache Tomcat 8.5. For other APIs, I am using a Service Account.
I now tried to authorize the Calendar Service same way but it fails. First line is the succesful authorize for the sheets service, its failing on the calendar service:

GoogleConnection: Absolut Path: H:/ownCloud/Wabco/Workspace/WabcoDiagram/WebContent/resources/webserviceaccount.json
  GoogleConnection: Absolut Path: H:/ownCloud/Wabco/Workspace/WabcoDiagram/WebContent/resources/webserviceaccount.json
  Exception in thread "main" java.lang.NoSuchMethodError: com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient$Builder.setBatchPath(Ljava/lang/String;)Lcom/google/api/client/googleapis/services/AbstractGoogleClient$Builder;
      at com.google.api.services.calendar.Calendar$Builder.setBatchPath(Calendar.java:6758)
      at com.google.api.services.calendar.Calendar$Builder.(Calendar.java:6737)
      at de.promolitor.wabcodiagramviewer.audit.AuditGoogleCalendar.getCalendarServiceLocal(AuditGoogleCalendar.java:112)
      at de.promolitor.wabcodiagramviewer.audit.AuditGoogleCalendar.initializeCalendarServiceLocal(AuditGoogleCalendar.java:150)
      at de.promolitor.wabcodiagramviewer.audit.AuditGoogleCalendar.main(AuditGoogleCalendar.java:156)

My Questions:
Can I login with a Service account into the Google Calendar API, or what are the changes I have to do, or is there another error in my code somewhere?

Can I send out Calendar Invites from a Web Service Service account and make another user the Admin / Creator of the event, so he can change the event if necessary? Does this require "domain-wide authority"?
I am working for a company that uses GSuit.

Example Code. The local functions are for local testing.

package de.promolitor.wabcodiagramviewer.audit;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.plus.Plus;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;

public class AuditGoogleCalendar {
    /** Application name. */
    private static final String APPLICATION_NAME = "Wabco Audit";

    /** Global instance of the {@link FileDataStoreFactory}. */
    // private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    private static GoogleCredential credential;

    /** Global instance of the HTTP transport. */
    private static HttpTransport httpTransport;

    private static Plus plus;

    private static Sheets service;
    private static Drive driveService;
    private static Calendar calendarService;

    /**
     * Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials at
     * ~/.credentials/sheets.googleapis.com-java-quickstart
     */
    private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS, DriveScopes.DRIVE,
            GmailScopes.MAIL_GOOGLE_COM, CalendarScopes.CALENDAR);

    static {
        try {
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    public static GoogleCredential authorize() throws IOException, GeneralSecurityException {
        String relativeWebPath = "/resources/" + "webserviceaccount.json";
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
        System.out.println("GoogleConnection: Absolut Path: " + absoluteDiskPath);

        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(absoluteDiskPath))
                .createScoped(SCOPES);
        return credential;
    }

    public static GoogleCredential authorizeLocal() throws IOException, GeneralSecurityException {
        String absoluteDiskPath = "H:/ownCloud/Wabco/Workspace/WabcoDiagram/WebContent/resources/webserviceaccount.json";
        System.out.println("GoogleConnection: Absolut Path: " + absoluteDiskPath);

        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(absoluteDiskPath))
                .createScoped(SCOPES);
        return credential;

    }

    public static Calendar getCalendarService() throws IOException, GeneralSecurityException {
        Credential credential = authorize();
        return new Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static Calendar getCalendarServiceLocal() throws IOException, GeneralSecurityException {
        Credential credential = authorizeLocal();
        return new Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
        credential = authorize();
        return new Sheets.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static Sheets getSheetsServiceLocal() throws IOException, GeneralSecurityException {
        credential = authorizeLocal();
        return new Sheets.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static Drive getDriveService() throws IOException, GeneralSecurityException {
        GoogleCredential credential = authorize();
        return new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }

    public static void initializeSheetService() throws IOException, GeneralSecurityException {
        service = getSheetsService();
    }

    public static void initializeSheetServiceLocal() throws IOException, GeneralSecurityException {
        service = getSheetsServiceLocal();
    }

    public static void initializeDriveService() throws IOException, GeneralSecurityException {
        driveService = getDriveService();
    }

    public static void initializeCalendarService() throws IOException, GeneralSecurityException {
        calendarService = getCalendarService();
    }

    public static void initializeCalendarServiceLocal() throws IOException, GeneralSecurityException {
        calendarService = getCalendarServiceLocal();
    }

    public static void main(String[] args) {
        try {
            initializeSheetServiceLocal();
            initializeCalendarServiceLocal();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


来源: stackexchange

问:
Not able to fetch the IP address in Node JS from the client side in the AWS server
I am using Node js and I want to fetch the IP address of the client device in AWS server.
I have two instances of AWS server So the code is working fine with one instance but when I upload this to another instance it is giving me wrong IP as "ffff:127.0.0.0".
Do I need to do anything extra?

I am using following code:

```<code>var ipAddress = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress
</code>```

答:
```<code>const clientIp = request.headers['x-forwarded-for'] || request.connection.remoteAddress
</code>```

<p>This works for me on my AWS ec2 instance. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am using Node js and I want to fetch the IP address of the client device in AWS server.
I have two instances of AWS server So the code is working fine with one instance but when I upload this to another instance it is giving me wrong IP as "ffff:127.0.0.0".
Do I need to do anything extra?

I am using following code:

var ipAddress = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress

Body:
const clientIp = request.headers['x-forwarded-for'] || request.connection.remoteAddress

This works for me on my AWS ec2 instance.


问:
Unselected UITabBar color?
I have an UITabBar with 5 items. I want to change the unselected color of all items. The items aren't declared in the UIViewController classes (i built them and linked the views in the Storyboard).

Is there an code like this : [[UITabBar appearance] set***UN***SelectedImageTintColor:[UIColor whiteColor]]; ?

答:
Swift 4 version (Without implicitly unwrapping Optionals) :

UIImage+Overlay.swift

```<code>import UIKit

extension UIImage {
    func with(color: UIColor) -> UIImage? {
        guard let cgImage = self.cgImage else {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        if let context = UIGraphicsGetCurrentContext() {
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            context.setBlendMode(.normal)
            let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            context.clip(to: imageRect, mask: cgImage)
            color.setFill()
            context.fill(imageRect)
            if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
                UIGraphicsEndImageContext();
                return newImage
            }
        }
        return nil;
    }
}
</code>```

CustomTabBarController.swift

```<code>class CustomTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            self.tabBar.unselectedItemTintColor = UIColor.init(white: 1, alpha: 0.5)
        } else {
            // Fallback on earlier versions
            if let items = self.tabBar.items {
                let unselectedColor = UIColor.init(white: 1, alpha: 0.5)
                let selectedColor = UIColor.white
                // Unselected state colors
                for item in items {
                    if let selectedImage = item.selectedImage?.with(color: unselectedColor)?.withRenderingMode(.alwaysOriginal) {
                        item.image = selectedImage
                    }
                }
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : unselectedColor], for: .normal)

                // Selected state colors
                tabBar.tintColor = selectedColor
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : selectedColor], for: .selected)
            }
        }

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "overpass-light", size: 12)!, NSAttributedStringKey.foregroundColor: UIColor.white], for: UIControlState.normal)
    }
}
</code>```

Title: Unselected UITabBar color?

Body:
Swift 4 version (Without implicitly unwrapping Optionals) :

UIImage+Overlay.swift

import UIKit

extension UIImage {
    func with(color: UIColor) -> UIImage? {
        guard let cgImage = self.cgImage else {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        if let context = UIGraphicsGetCurrentContext() {
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            context.setBlendMode(.normal)
            let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            context.clip(to: imageRect, mask: cgImage)
            color.setFill()
            context.fill(imageRect)
            if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
                UIGraphicsEndImageContext();
                return newImage
            }
        }
        return nil;
    }
}

CustomTabBarController.swift

class CustomTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            self.tabBar.unselectedItemTintColor = UIColor.init(white: 1, alpha: 0.5)
        } else {
            // Fallback on earlier versions
            if let items = self.tabBar.items {
                let unselectedColor = UIColor.init(white: 1, alpha: 0.5)
                let selectedColor = UIColor.white
                // Unselected state colors
                for item in items {
                    if let selectedImage = item.selectedImage?.with(color: unselectedColor)?.withRenderingMode(.alwaysOriginal) {
                        item.image = selectedImage
                    }
                }
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : unselectedColor], for: .normal)

                // Selected state colors
                tabBar.tintColor = selectedColor
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : selectedColor], for: .selected)
            }
        }

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "overpass-light", size: 12)!, NSAttributedStringKey.foregroundColor: UIColor.white], for: UIControlState.normal)
    }
}


问:
Possible solution for bitbucket pipeline docker-run limitation
My integration tests are highly dependent of a elastic search, given that to build my integration tests on bitbucket pipeline I would have to execute the docker-run command to be able to spin up my elastic-search instance during my integration tests.

But as probably some of you know, there's a limitation on the bitbucket pipeline

See the Docker command line reference for information on how to use
  these commands. Other commands, such as docker run, are currently
  forbidden for security reasons on our shared build infrastructure.

So given that I don't know how can I spin-up my escluster with all configurations that I need inside, painless scripts, mappings, ports exposed to be available for my integrations tests.

Does someone have any idea how could i achieve this?

答:
Ok I managed to get it working, I was struggling to run elastic search, due this error https://github.com/docker-library/elasticsearch/issues/111

This was fixed by applying the config discovery-type: single-node. Since I'm using this for integration tests I don't need to run ES in production mode. The thing is bitbucket-pipeline was not showing error logs for this error, so I was completely blind and I had to try many things till find out. Since I can't build and run my own image on pipelines, I uploaded an image with my own configuration (including single-node config) and scripts and to docker hub.

This is how my yaml looked like in the end:

```<code>image: maven:3.3.9
    pipelines:
      default:
        - step:
            caches:
              - maven
            script:
              - docker version
              - mvn clean package verify -Dmaven.docker.plugin.skip=true -s settings.xml
            services:
              - elasticsearch

    definitions:
      services:
        elasticsearch:
          image: elastic-search-bitbucket-pipeline
    options:
      docker: true
</code>```

Body:
Ok I managed to get it working, I was struggling to run elastic search, due this error https://github.com/docker-library/elasticsearch/issues/111

This was fixed by applying the config discovery-type: single-node. Since I'm using this for integration tests I don't need to run ES in production mode. The thing is bitbucket-pipeline was not showing error logs for this error, so I was completely blind and I had to try many things till find out. Since I can't build and run my own image on pipelines, I uploaded an image with my own configuration (including single-node config) and scripts and to docker hub.

This is how my yaml looked like in the end:

image: maven:3.3.9
    pipelines:
      default:
        - step:
            caches:
              - maven
            script:
              - docker version
              - mvn clean package verify -Dmaven.docker.plugin.skip=true -s settings.xml
            services:
              - elasticsearch

    definitions:
      services:
        elasticsearch:
          image: elastic-search-bitbucket-pipeline
    options:
      docker: true

ContentLicense: CC BY-SA 4.0


问:
TFS Build Solution failure: UnauthorizedAccess Microsoft.PowerShell.Commands.ImportModuleCommand
I'm attempting to set up our first build agent for TFS 2017 On-Premise. I've taken a 2012 R2 server, installed the agent and Visual Studio 2017. The agent appears in TFS with the correct capabilities. I've taken one of the default templates for building ASP.net projects and made the minimum changes possible to it. On the first run, I can see the first few steps of getting sources and updating NuGet packages complete successfully. However the build solution step fails, and I'm struggling to understand what the issue may be.

The build log shows the following:

```<code>2017-11-15T13:16:10.3583612Z ##[section]Starting: Build solution
2017-11-15T13:16:10.3583612Z ==============================================================================
2017-11-15T13:16:10.3583612Z Task         : Visual Studio Build
2017-11-15T13:16:10.3583612Z Description  : Build with MSBuild and set the Visual Studio version property
2017-11-15T13:16:10.3583612Z Version      : 1.119.0
2017-11-15T13:16:10.3583612Z Author       : Microsoft Corporation
2017-11-15T13:16:10.3583612Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613727)
2017-11-15T13:16:10.3583612Z ==============================================================================
2017-11-15T13:16:10.8588602Z Import-Module : AuthorizationManager check failed.
2017-11-15T13:16:10.8588602Z At line:1 char:453
2017-11-15T13:16:10.8588602Z + . ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variab ...
2017-11-15T13:16:10.8588602Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-11-15T13:16:10.8588602Z     + CategoryInfo          : SecurityError: (:) [Import-Module], PSSecurityException
2017-11-15T13:16:10.8588602Z     + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand
2017-11-15T13:16:10.9677474Z Invoke-VstsTaskScript : The term 'Invoke-VstsTaskScript' is not recognized as the name of a cmdlet, function, script
2017-11-15T13:16:10.9677474Z file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
2017-11-15T13:16:10.9677474Z and try again.
2017-11-15T13:16:10.9677474Z At line:1 char:786
2017-11-15T13:16:10.9677474Z + ... tlyContinue' ; Invoke-VstsTaskScript -ScriptBlock ([scriptblock]::Create('. ''\\ ...
2017-11-15T13:16:10.9677474Z +                    ~~~~~~~~~~~~~~~~~~~~~
2017-11-15T13:16:10.9677474Z     + CategoryInfo          : ObjectNotFound: (Invoke-VstsTaskScript:String) [], CommandNotFoundException
2017-11-15T13:16:10.9677474Z     + FullyQualifiedErrorId : CommandNotFoundException
2017-11-15T13:16:10.9677474Z
2017-11-15T13:16:10.9989971Z ##[error]Exit code 1 returned from process: file name 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', arguments '-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variable:PSHOME'' } else { Import-Module -Name ([System.IO.Path]::Combine($PSHOME, ''Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1'')) ; Import-Module -Name ([System.IO.Path]::Combine($PSHOME, ''Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1'')) }')) 2>&1 | ForEach-Object { Write-Verbose $_.Exception.Message -Verbose } ; Import-Module -Name '\\hidden-unc-path\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\VstsTaskSdk\VstsTaskSdk.psd1' -ArgumentList @{ NonInteractive = $true } -ErrorAction Stop ; $VerbosePreference = 'SilentlyContinue' ; $DebugPreference = 'SilentlyContinue' ; Invoke-VstsTaskScript -ScriptBlock ([scriptblock]::Create('. ''\\hidden-unc-path\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\VSBuild.ps1'''))"'.
2017-11-15T13:16:10.9989971Z ##[section]Finishing: Build solution
</code>```

答:
Looks like your PowerShell execution mode is set to require signed scripts to execute. The agent requires local unsigned scripts to run:

From an admin PowerShell  console, run:

```<code>Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
     - scope LocalMachine
</code>```

Then restart the agent.

Body:
I'm attempting to set up our first build agent for TFS 2017 On-Premise. I've taken a 2012 R2 server, installed the agent and Visual Studio 2017. The agent appears in TFS with the correct capabilities. I've taken one of the default templates for building ASP.net projects and made the minimum changes possible to it. On the first run, I can see the first few steps of getting sources and updating NuGet packages complete successfully. However the build solution step fails, and I'm struggling to understand what the issue may be.

The build log shows the following:

2017-11-15T13:16:10.3583612Z ##[section]Starting: Build solution
2017-11-15T13:16:10.3583612Z ==============================================================================
2017-11-15T13:16:10.3583612Z Task         : Visual Studio Build
2017-11-15T13:16:10.3583612Z Description  : Build with MSBuild and set the Visual Studio version property
2017-11-15T13:16:10.3583612Z Version      : 1.119.0
2017-11-15T13:16:10.3583612Z Author       : Microsoft Corporation
2017-11-15T13:16:10.3583612Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613727)
2017-11-15T13:16:10.3583612Z ==============================================================================
2017-11-15T13:16:10.8588602Z Import-Module : AuthorizationManager check failed.
2017-11-15T13:16:10.8588602Z At line:1 char:453
2017-11-15T13:16:10.8588602Z + . ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variab ...
2017-11-15T13:16:10.8588602Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-11-15T13:16:10.8588602Z     + CategoryInfo          : SecurityError: (:) [Import-Module], PSSecurityException
2017-11-15T13:16:10.8588602Z     + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand
2017-11-15T13:16:10.9677474Z Invoke-VstsTaskScript : The term 'Invoke-VstsTaskScript' is not recognized as the name of a cmdlet, function, script
2017-11-15T13:16:10.9677474Z file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
2017-11-15T13:16:10.9677474Z and try again.
2017-11-15T13:16:10.9677474Z At line:1 char:786
2017-11-15T13:16:10.9677474Z + ... tlyContinue' ; Invoke-VstsTaskScript -ScriptBlock ([scriptblock]::Create('. ''\\ ...
2017-11-15T13:16:10.9677474Z +                    ~~~~~~~~~~~~~~~~~~~~~
2017-11-15T13:16:10.9677474Z     + CategoryInfo          : ObjectNotFound: (Invoke-VstsTaskScript:String) [], CommandNotFoundException
2017-11-15T13:16:10.9677474Z     + FullyQualifiedErrorId : CommandNotFoundException
2017-11-15T13:16:10.9677474Z
2017-11-15T13:16:10.9989971Z ##[error]Exit code 1 returned from process: file name 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', arguments '-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variable:PSHOME'' } else { Import-Module -Name ([System.IO.Path]::Combine($PSHOME, ''Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1'')) ; Import-Module -Name ([System.IO.Path]::Combine($PSHOME, ''Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1'')) }')) 2>&1 | ForEach-Object { Write-Verbose $_.Exception.Message -Verbose } ; Import-Module -Name '\\hidden-unc-path\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\VstsTaskSdk\VstsTaskSdk.psd1' -ArgumentList @{ NonInteractive = $true } -ErrorAction Stop ; $VerbosePreference = 'SilentlyContinue' ; $DebugPreference = 'SilentlyContinue' ; Invoke-VstsTaskScript -ScriptBlock ([scriptblock]::Create('. ''\\hidden-unc-path\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\VSBuild.ps1'''))"'.
2017-11-15T13:16:10.9989971Z ##[section]Finishing: Build solution

Body:
Looks like your PowerShell execution mode is set to require signed scripts to execute. The agent requires local unsigned scripts to run:

From an admin PowerShell  console, run:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
     - scope LocalMachine

Then restart the agent.


问:
List of Guids not Model Binding Asp.Net Core
i'm sending an array of Guids to an ASP.NET Core Web app using aurelia-fetch-client, however on the server side the model binder doesn't pick it up and the list of notificationIds is null. However when i make the request through Swagger, or CURL it binds just fine.

I changed the signature of my controller method to accept a list of strings just in case there was something wrong with the GUID formatting, but same issue.

JS

```<code>var body = {notificationIds :  this.notifications.map(x => x.notificationId) };
    console.log("Dismissing All notifications");

    await this.httpClient.fetch('http://localhost:5000/api/notifications/clear',
        {
            method: 'POST',
            body: json(body),
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Requested-With': 'Fetch'
            },
            mode: 'cors'
        }).then(response => {
            if(response.status == 204){
               //Success! Remove Notifications from VM
            }
            else{

                console.log(response.status)
            }
        })
</code>```

Controller Method

```<code>// POST: api/Notifications
        [HttpPost]
        [Route("clear")]
        [ProducesResponseType((int)HttpStatusCode.NoContent)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> Post([FromBody]List<string> notificationIds)
        {
            if (notificationIds.IsNullOrEmpty())
            {
                return BadRequest("No notifications requested to be cleared");
            }

            var name = User.Claims.ElementAt(1);

            await _notificationRepository.Acknowledge(notificationIds, name.Value);

            return NoContent();
}
</code>```

Interesting thing is that Chrome (V62) shows nothing posted.

But Fiddler does

答:
The problem here is that you're not sending a list of GUIDs you are sending an object with a property that contains a list of GUIDs.  Either create and use a view model (as described by peinearydevelopment) or accept a dynamic parameter that refers to the json object.

```<code>public async Task<IActionResult> Post([FromBody] dynamic json)
{
    var notificationIds = json.notifcationIds;
    ...
</code>```

Body:
i'm sending an array of Guids to an ASP.NET Core Web app using aurelia-fetch-client, however on the server side the model binder doesn't pick it up and the list of notificationIds is null. However when i make the request through Swagger, or CURL it binds just fine.

I changed the signature of my controller method to accept a list of strings just in case there was something wrong with the GUID formatting, but same issue.

JS

var body = {notificationIds :  this.notifications.map(x => x.notificationId) };
    console.log("Dismissing All notifications");

    await this.httpClient.fetch('http://localhost:5000/api/notifications/clear',
        {
            method: 'POST',
            body: json(body),
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Requested-With': 'Fetch'
            },
            mode: 'cors'
        }).then(response => {
            if(response.status == 204){
               //Success! Remove Notifications from VM
            }
            else{

                console.log(response.status)
            }
        })

Controller Method

// POST: api/Notifications
        [HttpPost]
        [Route("clear")]
        [ProducesResponseType((int)HttpStatusCode.NoContent)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> Post([FromBody]List<string> notificationIds)
        {
            if (notificationIds.IsNullOrEmpty())
            {
                return BadRequest("No notifications requested to be cleared");
            }

            var name = User.Claims.ElementAt(1);

            await _notificationRepository.Acknowledge(notificationIds, name.Value);

            return NoContent();
}

Interesting thing is that Chrome (V62) shows nothing posted.

But Fiddler does

Body:
The problem here is that you're not sending a list of GUIDs you are sending an object with a property that contains a list of GUIDs.  Either create and use a view model (as described by peinearydevelopment) or accept a dynamic parameter that refers to the json object.

public async Task<IActionResult> Post([FromBody] dynamic json)
{
    var notificationIds = json.notifcationIds;
    ...


问:
Submit select option and current page url parameter
I have webpage like: index.php/voting/?name=someName which has form with select options:

```<code> <form id="voting-form" method="GET" action="index.php/vote/">
    <select name="company" id="company">
        <option value="company1">company 1</option>
        <option value="company2">company 2</option>
        <option value="company3">company 3</option>
    </select>

    <input type="submit" value="Submit">
</form>
</code>```

I need to submit this form with select value and url name parameter from current page. For example user chose company1: index.php/vote/?company=company1&name=someName

I tried to modify form action like this:

```<code> var url_string = window.location.href
 var url = new URL(url_string);
 var name = url.searchParams.get("name");
 document.getElementById('voting-form').action = "index.php/vote/?name=" + name +"&";
</code>```

But when I submit button, I am redirected to index.php/vote/?company=company1. so name param is missing

答:
You can add to form input with type hidden to add this to url params

```<code><input type="hidden" name="name" value"someName" id="nameInput">
</code>```

To set value of input you can use your JS with a bit modification

```<code>var url = new URL(window.location.href),
    name = url.searchParams.get("name");

document.getElementById('nameInput').value = name;
</code>```

or PHP like in @Globus example

Body:
I have webpage like: index.php/voting/?name=someName which has form with select options:

 <form id="voting-form" method="GET" action="index.php/vote/">
    <select name="company" id="company">
        <option value="company1">company 1</option>
        <option value="company2">company 2</option>
        <option value="company3">company 3</option>
    </select>

    <input type="submit" value="Submit">
</form>

I need to submit this form with select value and url name parameter from current page. For example user chose company1: index.php/vote/?company=company1&name=someName

I tried to modify form action like this:

 var url_string = window.location.href
 var url = new URL(url_string);
 var name = url.searchParams.get("name");
 document.getElementById('voting-form').action = "index.php/vote/?name=" + name +"&";

But when I submit button, I am redirected to index.php/vote/?company=company1. so name param is missing

Body:
You can add to form input with type hidden to add this to url params

<input type="hidden" name="name" value"someName" id="nameInput">

To set value of input you can use your JS with a bit modification

var url = new URL(window.location.href),
    name = url.searchParams.get("name");

document.getElementById('nameInput').value = name;

or PHP like in @Globus example


问:
Summing the same number of cells in one row which are populated in another
I'm wanting to automatically count and sum the same number of cells in one row based on those which are populated in another. What is the formula?

For example, I have a pre-populated budget for a company for each month for 12 months. Each month I want to compare the cumulative actuals against the budget.
I have 3 months (3 cells) worth of actuals which can be summed. What formula would I use to make a comparison and only sum the equivalent 3 cells in the budget row? And how do I then ensure that when there are only 4 months of data in one row, the corresponding 4 months in another are compared, and so on?

答:
You can use SUMIF function to sum one range if the other is populated, e.g

=SUMIF(D4:O4,"<>",D3:O3)

"<>" means "not blank" so this sums D3:O3 only when the corresponding cell in D4:O4 is not blank


问:
Vim syntax: Spell checking between certain regions
I'm trying to create a syntax file for this language called Sugar Cube 2.  You can find more about it here: http://www.motoslave.net/sugarcube/2/docs/macros.html

Generally, I don't want to spell check between the macros (e.g., <<if $myVariable>>).  But, you can make your own macros, and I happen to have made one that works like this:

```<code><<myDescription "This is a string that should be in english">>
</code>```

As you can see, "english" should be capitalized, so it would be useful to have spell checking in that case.

I already know about vim's syntax.  It's keyword, match, region, @NoSpell, etc.  But I'm really struggling to put these concepts together to achieve what I want:  Spell checking between a specific macro, but not all macros.  Here's my idea, and it leverages the concepts described in syn-priority:

```<code>syn match macroDelimiter "\v(<<|>>)"
" there's much more keywords than this
syn keyword macroKeywords contained if elseif else myDescription
syn region mostMacros matchgroup=macroKeywords start="<<" end=">>" contains=@NoSpell
syn region myMacro matchgroup=macroKeywords start="<<myDescription" end=">>"
</code>```

I mean... I tried that and it works.  One thing I don't like is how myDescription is highlighted just like the angled brackets.  I also don't like how the word myDescription itself is spell checked, but I can live with that one.  Is there a way to fix these issues?

This will fix the above issues:

```<code>set spell spelllang=en_us
syn match macroDelimiter "\v(<<|>>)"
" there's much more keywords than this
syn keyword macroKeywords contained if elseif else myDescription
syn region macroString start=+"+ end=+"+ skip=+\\"+
syn region mostMacros matchgroup=macroDelimiter start="<<" end=">>" contains=@NoSpell,macroString
"Notice how this is commented out
"syn region myMacro matchgroup=macroDelimiter start="<<myDescription" end=">>"

hi link macroKeywords Keyword
hi link macroDelimiter Constant
</code>```

But it adds a major problem: There are other macros with Strings.  The <<link>> and <<goto>> macros have Strings, too.  But I don't want to spell check the strings there.

答:
To get rid of the matchgroup highlighting for myDescription, but still enforce the match, end the start of the group via \ze:

```<code>syn region myMacro matchgroup=macroKeywords start="<<\zemyDescription" end=">>" contains=@Spell
</code>```

This will enable spelling for myDescription itself. To avoid that, you have to turn the syntax for it from keyword to match, in order to add contains=@NoSpell to it:

```<code>syn match myDescription "myDescription" contains=@NoSpell
syn region myMacro matchgroup=macroKeywords start="<<\zemyDescription" end=">>" contains=@Spell,myDescription
</code>```

Body:
I'm trying to create a syntax file for this language called Sugar Cube 2.  You can find more about it here: http://www.motoslave.net/sugarcube/2/docs/macros.html

Generally, I don't want to spell check between the macros (e.g., <<if $myVariable>>).  But, you can make your own macros, and I happen to have made one that works like this:

<<myDescription "This is a string that should be in english">>

As you can see, "english" should be capitalized, so it would be useful to have spell checking in that case.

I already know about vim's syntax.  It's keyword, match, region, @NoSpell, etc.  But I'm really struggling to put these concepts together to achieve what I want:  Spell checking between a specific macro, but not all macros.  Here's my idea, and it leverages the concepts described in syn-priority:

syn match macroDelimiter "\v(<<|>>)"
" there's much more keywords than this
syn keyword macroKeywords contained if elseif else myDescription
syn region mostMacros matchgroup=macroKeywords start="<<" end=">>" contains=@NoSpell
syn region myMacro matchgroup=macroKeywords start="<<myDescription" end=">>"

I mean... I tried that and it works.  One thing I don't like is how myDescription is highlighted just like the angled brackets.  I also don't like how the word myDescription itself is spell checked, but I can live with that one.  Is there a way to fix these issues?

This will fix the above issues:

set spell spelllang=en_us
syn match macroDelimiter "\v(<<|>>)"
" there's much more keywords than this
syn keyword macroKeywords contained if elseif else myDescription
syn region macroString start=+"+ end=+"+ skip=+\\"+
syn region mostMacros matchgroup=macroDelimiter start="<<" end=">>" contains=@NoSpell,macroString
"Notice how this is commented out
"syn region myMacro matchgroup=macroDelimiter start="<<myDescription" end=">>"

hi link macroKeywords Keyword
hi link macroDelimiter Constant

But it adds a major problem: There are other macros with Strings.  The <<link>> and <<goto>> macros have Strings, too.  But I don't want to spell check the strings there.

Body:
To get rid of the matchgroup highlighting for myDescription, but still enforce the match, end the start of the group via \ze:

syn region myMacro matchgroup=macroKeywords start="<<\zemyDescription" end=">>" contains=@Spell

This will enable spelling for myDescription itself. To avoid that, you have to turn the syntax for it from keyword to match, in order to add contains=@NoSpell to it:

syn match myDescription "myDescription" contains=@NoSpell
syn region myMacro matchgroup=macroKeywords start="<<\zemyDescription" end=">>" contains=@Spell,myDescription


问:
Angular universal: flickering and styles
I'm using angular cli 1.5, angular 5.0 and angular universal.

When using server side rendering, I'm noticing some flicker when the client takes over.

I've already specified { initialNavigation: 'enabled' } when importing routing module.

When could it come from? Also, I tried removing all styles from the server bundle, but it does not help... Is it really needed btw?

答:
The solution for me was to use the TransferState API, which prevented  flickering

https://angular.io/api/platform-browser/TransferState

Thanks @wassertim


问:
Update and set row where id is equal to an id in another table
I am trying to set 2 columns in a row, where the paymentid of that row is the same as the foreign key in another table to that row.

```<code>UPDATE
    SomeDB.dbo.[Payment]
SET
    TransactionId = {0},
    PaymentAccepted = 1
WHERE
</code>```

I have an OrderId, and that Order has a PaymentId foreign key to the Payment table.

答:
The following code will work for you ...</p>

```<code>Update SomeDB.dbo.[Payment]
SET TransactionId = {0}, PaymentAccepted = 1
FROM SomeDB.dbo.[Payment] A
INNER JOIN SomeDB.dbo.[SomeTable] B on A.ForeignID = B.ID
WHERE B.SomeColumn = {1}
</code>```

Body:
I am trying to set 2 columns in a row, where the paymentid of that row is the same as the foreign key in another table to that row.

UPDATE
    SomeDB.dbo.[Payment]
SET
    TransactionId = {0},
    PaymentAccepted = 1
WHERE

I have an OrderId, and that Order has a PaymentId foreign key to the Payment table.

Body:
The following code will work for you ...

Update SomeDB.dbo.[Payment]
SET TransactionId = {0}, PaymentAccepted = 1
FROM SomeDB.dbo.[Payment] A
INNER JOIN SomeDB.dbo.[SomeTable] B on A.ForeignID = B.ID
WHERE B.SomeColumn = {1}


问:
How to work out the complexity of an algorithm?
I have two questions for algorithm analysis, and would like to know how to determine the complexity of the following two:

First:

```<code>For(int i=2; i<n; i=i*i*i)
{
  //something O(1)
}
</code>```

Second:

```<code>n/1 + n/2 + n/3 +...+ n/n
</code>```

答:
For the first Algorithm:

Suppose that the initial value of i is 2 (rather than 1 that would lead to an infinite loop as @tschaefemedia remarked).

At the 1st iteration, i==2

At the second iteration, i==2*2*2 == 2ˆ3

At the third iteration, i== (2ˆ3 * 2ˆ3 * 2ˆ3) == 2ˆ(3*3)

At the fourth iteration, i== 2ˆ(3*3) * 2ˆ(3*3) * 2ˆ(3*3) == 2ˆ(3*3*3)

...

At iteration k+1, i== 2ˆ(3*3*3*...*3) == 2ˆ(3ˆk)

Suppose for simplicity that at iteration k-1, i becomes equal to n and the loop stops. Then:

n == 2ˆ(3ˆk)

log2(n) == 3^k

log3(log2(n)) == k

So, the complexity is O(log3(log2(n)))

As for the second question, I suppose that you are giving the complexity formula. So,

n/1 + n/2 + n/3 + ... + n/n = n (1+ 1/2 + 1/3 + ... + 1/n)

This is Harmonic series and it is O(log(n))

So, the overall complexity is O(n*log(n))

Body:
I have two questions for algorithm analysis, and would like to know how to determine the complexity of the following two:

First:

For(int i=2; i<n; i=i*i*i)
{
  //something O(1)
}

Second:

n/1 + n/2 + n/3 +...+ n/n


问:
Try-Catch-Finally Block
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

```<code>import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}
</code>```

Any Help Please

答:
Remove the throws clause from your connect() method. It already catches the IOException. If you declare your method as throwing a checked exception it must be caught upon calling.

Update: since Socket#close() can itself throw an exception, you need to decide what do you want to do about it. Exception handling is hard because people tend to only think about the happiest path a program can take.

If you don't want to catch the exception explicitly in the main() method, you have only one choice: wrap the call to s.close() (and every other method that can throw a checked exception) into its' own try-catch block and remove the throws clause:

```<code>    public void connect() {
        Socket s = new Socket();
        try {
            s.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
</code>```

But you should probably think—"what should I do when it fails?"—each time you're dealing with code that might throw.

Title: Try-Catch-Finally Block

Body:
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}

Any Help Please

Body:
Remove the throws clause from your connect() method. It already catches the IOException. If you declare your method as throwing a checked exception it must be caught upon calling.

Update: since Socket#close() can itself throw an exception, you need to decide what do you want to do about it. Exception handling is hard because people tend to only think about the happiest path a program can take.

If you don't want to catch the exception explicitly in the main() method, you have only one choice: wrap the call to s.close() (and every other method that can throw a checked exception) into its' own try-catch block and remove the throws clause:

    public void connect() {
        Socket s = new Socket();
        try {
            s.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

But you should probably think—"what should I do when it fails?"—each time you're dealing with code that might throw.


问:
How to use a library in multiple files in Nodejs
I want to use Winston for logging in my nodejs express project. In my main file( server.js ) I have the following code :

```<code>const winston = require('winston');
winston.level = process.env.LOG_LEVEL
winston.log('info', 'Hello log files!')
</code>```

I want to use this library in other files as well, so do I have to add these 2 lines to every file I want to use it or is there a better way to do it.

答:
The preferred way of doing this is adding your custom logger to the winston object:

var winston = require('winston');

// add a new logger to the winston object
winston.loggers.add('logger1', {
  console: {
    level: 'silly',
    colorize: true,
    label: 'Console One'
  },
  file: {
    filename: '/path/to/your/logfile.log'
    level: process.env.LOG_LEVEL
  }
}```
</div>
</div>
</p>

<p>After setting up your logger as described in the snippet above you can just "get" the logger in any other file in your application:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var winston = require('winston');

// get your preconfigured logger
var myLogger = winston.loggers.get('logger1');

// start logging!
myLogger.error('FooError');
myLogger.log('warn', 'Exiting application');</code>```

This is also the way, which is described in the winston documentation: Winston Docs

Body:
I want to use Winston for logging in my nodejs express project. In my main file( server.js ) I have the following code :

const winston = require('winston');
winston.level = process.env.LOG_LEVEL
winston.log('info', 'Hello log files!')

I want to use this library in other files as well, so do I have to add these 2 lines to every file I want to use it or is there a better way to do it.

Body:
The preferred way of doing this is adding your custom logger to the winston object:

var winston = require('winston');

// add a new logger to the winston object
winston.loggers.add('logger1', {
  console: {
    level: 'silly',
    colorize: true,
    label: 'Console One'
  },
  file: {
    filename: '/path/to/your/logfile.log'
    level: process.env.LOG_LEVEL
  }
}

After setting up your logger as described in the snippet above you can just "get" the logger in any other file in your application:

var winston = require('winston');

// get your preconfigured logger
var myLogger = winston.loggers.get('logger1');

// start logging!
myLogger.error('FooError');
myLogger.log('warn', 'Exiting application');

This is also the way, which is described in the winston documentation: Winston Docs


答: Either catch the thrown IOException or throw it and let JVM handle the same.

Title: Try-Catch-Finally Block


问:
Sync Outlook 2007 tasks with gmail tasks
Is there anyway, that tasks that are in Gmail can be synchronised with Outlook 2007.
Cheers
John</p>

答: Unfortunately not. Here is a thread of over 500 people wishing for the same thing. :-)</p>

ContentLicense: CC BY-SA 2.5


问:
How to get the profile name associated to the login username in Win10 C#?
So, currently I get the login credential (username) with this line:

```<code>Environment.UserName
</code>```

But what I want is to get the name which appears in Settings -> Accounts -> Your Info (Windows 10). Basically it's the name of the profile from the windows associated to that user that is logged in.
Any thoughts please?

答:
Maybe you could use DisplayName?

```<code>System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
</code>```

More information can be seen here.

Body:
So, currently I get the login credential (username) with this line:

Environment.UserName

But what I want is to get the name which appears in Settings -> Accounts -> Your Info (Windows 10). Basically it's the name of the profile from the windows associated to that user that is logged in.
Any thoughts please?

Body:
Maybe you could use DisplayName?

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

More information can be seen here.


问:
WebAPI call using volley
I'm trying to get access tokens from the server using a volley String request. I have tried making a JsonObjectRequest also. Both are below.

```<code>public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
    {

        //String url = prefixURL + "this/request/suffix";
        String url = "https://lw.xxx.co.uk/connect/token";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.e("Response", response);
                    }
                },

                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.e("Error.Response", error.networkResponse.toString());
                    }
                }
        ) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded");
                //..add other headers
                return params;
            }

            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("scope", "openid email phone profile offline_access roles");
                params.put("resource", "window.location.origin");
                params.put("grant_type", "password");
                params.put("username", "support@xxx.com");
                params.put("password", "tempPxxx");

                return params;
            }

        };

        requestQueue.add(request);
</code>```

.

```<code>public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
    {

        //String url = prefixURL + "this/request/suffix";
        String url = "https://lw.xxx.co.uk/connect/token";

Map<String, Object> jsonParams = new HashMap<>();

        jsonParams.put("scope", "openid email phone profile offline_access roles");
        jsonParams.put("resource", "window.location.origin");
        jsonParams.put("grant_type", "password");
        jsonParams.put("username", "support@xxx.com");
        jsonParams.put("password", "tempPxxx");

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response)
                    {
                        Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
                        if(null != response.toString())
                            listener.getResult(response);
                    }
                },

                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        if (null != error.networkResponse)
                        {

                            Log.e(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);

                            listener.getResult(null);
                        }
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                       // Map<String,String> params =  super.getHeaders();
                       // if(params==null)params = new HashMap<>();
                        Map<String,String> params = new HashMap<>();
                        params.put("Content-Type","application/x-www-form-urlencoded");
                        //..add other headers
                        return params;
                    }
        };

        requestQueue.add(request);
</code>```

.

I get the following response from the server:

```<code>E/Volley: [31388] BasicNetwork.performRequest: Unexpected response code 400 for https://lw.xxx.co.uk/connect/token
</code>```

.

My colleague who has written the server-side code has asked how to convert the following Angular code (his code that works with the API),  to Android.

Can anyone help with this?

```<code>getLoginEndpoint(userName: string, password: string): Observable<Response> {

        let header = new Headers();
        header.append("Content-Type", "application/x-www-form-urlencoded");

        let searchParams = new URLSearchParams();
        searchParams.append('username', userName);
        searchParams.append('password', password);
        searchParams.append('grant_type', 'password');
        searchParams.append('scope', 'openid email phone profile offline_access roles');
        searchParams.append('resource', window.location.origin);

        let requestBody = searchParams.toString();

        return this.http.post(this.loginUrl, requestBody, { headers: header });
    }
</code>```

答:
The problem was a couple of things.

I replaced "params.put("resource", "window.location.origin"); " with "params.put("resource", "https://lw.xxx.co.uk");"

Also, I found out that Volley ignore the getHeaders override, so I commented that method out and used the following to set the headers.

```<code>@Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

public void getAuthenticationTokens(Object param1, final String userName, final String password, final CustomListener<JSONObject> listener)
    {
        String url = "https://lw.xxx.co.uk/connect/token";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.e("Response", response);

                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.e("Error.Response", error.networkResponse.toString());
                    }
                }
        ) {

           /* @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded");
                //..add other headers
                return params;
            }*/
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("scope", "openid email phone profile offline_access roles");
                params.put("resource", "https://lw.xxx.co.uk");
                params.put("grant_type", "password");
                params.put("username", userName);
                params.put("password", password);
                return params;
            }

            @Override
            protected VolleyError parseNetworkError(VolleyError response) {
                try {

                    String json = new String(response.networkResponse.data, HttpHeaderParser.parseCharset(response.networkResponse.headers));
                    Log.e(TAG, "reponse error = " + json);
                }catch (Exception e){}
                return super.parseNetworkError(response);
            }
        };
        requestQueue.add(request);

    }//end of getAuthenticationTokens
</code>```

Title: WebAPI call using volley

Body:
I'm trying to get access tokens from the server using a volley String request. I have tried making a JsonObjectRequest also. Both are below.

public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
    {

        //String url = prefixURL + "this/request/suffix";
        String url = "https://lw.xxx.co.uk/connect/token";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.e("Response", response);
                    }
                },

                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.e("Error.Response", error.networkResponse.toString());
                    }
                }
        ) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded");
                //..add other headers
                return params;
            }

            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("scope", "openid email phone profile offline_access roles");
                params.put("resource", "window.location.origin");
                params.put("grant_type", "password");
                params.put("username", "support@xxx.com");
                params.put("password", "tempPxxx");

                return params;
            }

        };

        requestQueue.add(request);

.

public void getAuthenticationTokens(Object param1, final CustomListener<String> listener)
    {

        //String url = prefixURL + "this/request/suffix";
        String url = "https://lw.xxx.co.uk/connect/token";

Map<String, Object> jsonParams = new HashMap<>();

        jsonParams.put("scope", "openid email phone profile offline_access roles");
        jsonParams.put("resource", "window.location.origin");
        jsonParams.put("grant_type", "password");
        jsonParams.put("username", "support@xxx.com");
        jsonParams.put("password", "tempPxxx");

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response)
                    {
                        Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
                        if(null != response.toString())
                            listener.getResult(response);
                    }
                },

                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        if (null != error.networkResponse)
                        {

                            Log.e(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);

                            listener.getResult(null);
                        }
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                       // Map<String,String> params =  super.getHeaders();
                       // if(params==null)params = new HashMap<>();
                        Map<String,String> params = new HashMap<>();
                        params.put("Content-Type","application/x-www-form-urlencoded");
                        //..add other headers
                        return params;
                    }
        };

        requestQueue.add(request);

.

I get the following response from the server:

E/Volley: [31388] BasicNetwork.performRequest: Unexpected response code 400 for https://lw.xxx.co.uk/connect/token

.

My colleague who has written the server-side code has asked how to convert the following Angular code (his code that works with the API),  to Android.

Can anyone help with this?

getLoginEndpoint(userName: string, password: string): Observable<Response> {

        let header = new Headers();
        header.append("Content-Type", "application/x-www-form-urlencoded");

        let searchParams = new URLSearchParams();
        searchParams.append('username', userName);
        searchParams.append('password', password);
        searchParams.append('grant_type', 'password');
        searchParams.append('scope', 'openid email phone profile offline_access roles');
        searchParams.append('resource', window.location.origin);

        let requestBody = searchParams.toString();

        return this.http.post(this.loginUrl, requestBody, { headers: header });
    }

Body:
The problem was a couple of things.

I replaced "params.put("resource", "window.location.origin"); " with "params.put("resource", "https://lw.xxx.co.uk");"

Also, I found out that Volley ignore the getHeaders override, so I commented that method out and used the following to set the headers.

@Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

public void getAuthenticationTokens(Object param1, final String userName, final String password, final CustomListener<JSONObject> listener)
    {
        String url = "https://lw.xxx.co.uk/connect/token";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.e("Response", response);

                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.e("Error.Response", error.networkResponse.toString());
                    }
                }
        ) {

           /* @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded");
                //..add other headers
                return params;
            }*/
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String> ();
                params.put("scope", "openid email phone profile offline_access roles");
                params.put("resource", "https://lw.xxx.co.uk");
                params.put("grant_type", "password");
                params.put("username", userName);
                params.put("password", password);
                return params;
            }

            @Override
            protected VolleyError parseNetworkError(VolleyError response) {
                try {

                    String json = new String(response.networkResponse.data, HttpHeaderParser.parseCharset(response.networkResponse.headers));
                    Log.e(TAG, "reponse error = " + json);
                }catch (Exception e){}
                return super.parseNetworkError(response);
            }
        };
        requestQueue.add(request);

    }//end of getAuthenticationTokens


问:
Removing an item for a list without reducing the total number
Here we go again. So what I am trying to do is, let's say I have a list like this:

```<code>List = ['one','two','three']
</code>```

And they are all assigned to numbers 0,1,2 for example:

```<code>'one': 0, 'two': 1, 'three': 2
</code>```

What I want to do now is I want to remove an item from my list... let's say two

```<code>List.remove('two')
</code>```

But if I do this, 'three' goes into the place of two and the total amount decreases by one. Is there a way I can remove two, but still keep the total amount of objects in a list, with the ones being removed just being replaced with 'None' or something similar?

答:
You can iterate over the dictionary and replace the value that you want to remove:

```<code>s = {'one': 0, 'two': 1, 'three': 2}
target = "two"
new_s = {a if a != target else None:b for a, b in s.items()}
</code>```

Output:

```<code>{'one': 0, 'three': 2, None: 1}
</code>```

This way, the count value for "two" is retained, but the key substituted with None

Body:
Here we go again. So what I am trying to do is, let's say I have a list like this:

List = ['one','two','three']

And they are all assigned to numbers 0,1,2 for example:

'one': 0, 'two': 1, 'three': 2

What I want to do now is I want to remove an item from my list... let's say two

List.remove('two')

But if I do this, 'three' goes into the place of two and the total amount decreases by one. Is there a way I can remove two, but still keep the total amount of objects in a list, with the ones being removed just being replaced with 'None' or something similar?

Body:
You can iterate over the dictionary and replace the value that you want to remove:

s = {'one': 0, 'two': 1, 'three': 2}
target = "two"
new_s = {a if a != target else None:b for a, b in s.items()}

Output:

{'one': 0, 'three': 2, None: 1}

This way, the count value for "two" is retained, but the key substituted with None


问:
C initializer element is not constant
I'm getting a "error: initializer element is not constant"
with this code:

```<code>typedef struct {
    const int x;
    const int y;
} my_struct;

const int a = 8;
const int b = 12;

my_struct test = { a, b };
</code>```

Any idea of what's going on and how to fix it ?

答:
In C, using a const modifier does not produce a compile-time constant value.

Then, as per the rules of initialization, C11, chapter §6.7.9

All the expressions in an initializer for an object that has static or thread storage duration
  shall be constant expressions or string literals.

you'll be needing a constant-expression (compile time constat).

You may use a #define MACRO instead to get the result you want. Something like (warning: Code not tested)

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

typedef struct {
    const int x;
    const int y;
} my_struct;

//const int a = 8;
//const int b = 12;

#define a 8                  //use preprocessor MACROs
#define b 12                 //use preprocessor MACROs

my_struct test = { a, b };

int main(void)
{
    printf("Hello, world!\n");
    return 0;
}
</code>```

Title: C initializer element is not constant

Body:
I'm getting a "error: initializer element is not constant"
with this code:

typedef struct {
    const int x;
    const int y;
} my_struct;

const int a = 8;
const int b = 12;

my_struct test = { a, b };

Any idea of what's going on and how to fix it ?

Body:
In C, using a const modifier does not produce a compile-time constant value.

Then, as per the rules of initialization, C11, chapter §6.7.9

All the expressions in an initializer for an object that has static or thread storage duration
  shall be constant expressions or string literals.

you'll be needing a constant-expression (compile time constat).

You may use a #define MACRO instead to get the result you want. Something like (warning: Code not tested)

#include  <stdio.h>

typedef struct {
    const int x;
    const int y;
} my_struct;

//const int a = 8;
//const int b = 12;

#define a 8                  //use preprocessor MACROs
#define b 12                 //use preprocessor MACROs

my_struct test = { a, b };

int main(void)
{
    printf("Hello, world!\n");
    return 0;
}


答:
The form post doesn't care about your javascript, and does what it pleases.
You should create a hidden field in your form where you store the name in your GET parameter, so that the form submission also adds this parameter to the URL.

Change your code to:

```<code> <form id="voting-form" method="GET" action="index.php/vote/">
    <select name="company" id="company">
        <option value="company1">company 1</option>
        <option value="company2">company 2</option>
        <option value="company3">company 3</option>
    </select>

    <input name="name" value=<?=$_GET['name']?> type="hidden" />

    <input type="submit" value="Submit">
</form>
</code>```

Title: Submit select option and current page url parameter

Body:
I have webpage like: index.php/voting/?name=someName which has form with select options:

 <form id="voting-form" method="GET" action="index.php/vote/">
    <select name="company" id="company">
        <option value="company1">company 1</option>
        <option value="company2">company 2</option>
        <option value="company3">company 3</option>
    </select>

    <input type="submit" value="Submit">
</form>

I need to submit this form with select value and url name parameter from current page. For example user chose company1: index.php/vote/?company=company1&name=someName

I tried to modify form action like this:

 var url_string = window.location.href
 var url = new URL(url_string);
 var name = url.searchParams.get("name");
 document.getElementById('voting-form').action = "index.php/vote/?name=" + name +"&";

But when I submit button, I am redirected to index.php/vote/?company=company1. so name param is missing

Body:
The form post doesn't care about your javascript, and does what it pleases.
You should create a hidden field in your form where you store the name in your GET parameter, so that the form submission also adds this parameter to the URL.

Change your code to:

 <form id="voting-form" method="GET" action="index.php/vote/">
    <select name="company" id="company">
        <option value="company1">company 1</option>
        <option value="company2">company 2</option>
        <option value="company3">company 3</option>
    </select>

    <input name="name" value=<?=$_GET['name']?> type="hidden" />

    <input type="submit" value="Submit">
</form>


问:
Check multiple files if of the same
I have a paths_list,assuming they are of the same.

```<code>In [96]: len(paths_list)
Out[96]: 191
In [97]: paths_list
Out[97]:
['~/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.CloudPhotosConfiguration/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.PressAndHold/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.iCal.CalendarNC/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.languageassetd/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.photos.VideoConversionService/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.iCal/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.share.Video.upload-Youku/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.QuickTimePlayerX/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.PassKit.PaymentAuthorizationUIExtension/Data/Desktop/Dev/sample.py',
 ...]
</code>```

Tried to check them with a set

```<code>In [99]: { os.stat(i) for i in paths_list}
Out[99]: {os.stat_result(st_mode=33188, st_ino=8593437981, st_dev=16777220,
st_nlink=1, st_uid=501, st_gid=20, st_size=554, st_atime=1510741689,
st_mtime=1510453338, st_ctime=1510741688)}
</code>```

The returned set contains only one item to conclude that they are some files.

I learn that os.path.samefile checking two paths each time.
How to check the paths_list with os.path.samefile or other elegant methods?

答:
I am ok with your method, os.path.samefile() check st_ino and st_dev of both files, essentially same with your method, but if your really want to use samefile(), try this:

```<code>all(os.path.samefile(paths_list[i], paths_list[i+1])
    for i in range(len(paths_list)-1))
</code>```

by making sure every neighbor pair of the file in your file list return True with samefile() call, you could say they are all of the same file.

Title: Check multiple files if of the same

Body:
I have a paths_list,assuming they are of the same.

In [96]: len(paths_list)
Out[96]: 191
In [97]: paths_list
Out[97]:
['~/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.CloudPhotosConfiguration/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.PressAndHold/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.iCal.CalendarNC/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.languageassetd/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.photos.VideoConversionService/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.iCal/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.share.Video.upload-Youku/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.QuickTimePlayerX/Data/Desktop/Dev/sample.py',
 '~/Library/Containers/com.apple.PassKit.PaymentAuthorizationUIExtension/Data/Desktop/Dev/sample.py',
 ...]

Tried to check them with a set

In [99]: { os.stat(i) for i in paths_list}
Out[99]: {os.stat_result(st_mode=33188, st_ino=8593437981, st_dev=16777220,
st_nlink=1, st_uid=501, st_gid=20, st_size=554, st_atime=1510741689,
st_mtime=1510453338, st_ctime=1510741688)}

The returned set contains only one item to conclude that they are some files.

I learn that os.path.samefile checking two paths each time.
How to check the paths_list with os.path.samefile or other elegant methods?

Body:
I am ok with your method, os.path.samefile() check st_ino and st_dev of both files, essentially same with your method, but if your really want to use samefile(), try this:

all(os.path.samefile(paths_list[i], paths_list[i+1])
    for i in range(len(paths_list)-1))

by making sure every neighbor pair of the file in your file list return True with samefile() call, you could say they are all of the same file.


问:
Is there a simple algorithm that can determine if X is prime?
I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it.

I know I can just divide x by 2, 3, 4, 5, ..., square root of X and if I get to the square root, I can (safely) assume that the number is prime. Unfortunately this solution seems quite klunky.

I've looked into better algorithms on how to determine if a number is prime, but get confused fast.

Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?

Thanks much!

答:
I am working thru the Project Euler problems as well and in fact just finished #3 (by id) which is the search for the highest prime factor of a composite number (the number in the ? is 600851475143).

I looked at all of the info on primes (the sieve techniques already mentioned here), and on integer factorization on wikipedia and came up with a brute force trial division algorithm that I decided would do.

So as I am doing the euler problems to learn ruby I was looking into coding my algorithm and stumbled across the mathn library which has a Prime class and an Integer class with a prime_division method.  how cool is that.  i was able to get the correct answer to the problem with this ruby snippet:

```<code>require "mathn.rb"
puts 600851475143.prime_division.last.first
</code>```

this snippet outputs the correct answer to the console.  of course i ended up doing a ton of reading and learning before i stumbled upon this little beauty, i just thought i would share it with everyone...

OwnerDisplayName: Pulsehead

LastEditorDisplayName: Lance Roberts

Body:
I am working thru the Project Euler problems as well and in fact just finished #3 (by id) which is the search for the highest prime factor of a composite number (the number in the ? is 600851475143).

I looked at all of the info on primes (the sieve techniques already mentioned here), and on integer factorization on wikipedia and came up with a brute force trial division algorithm that I decided would do.

So as I am doing the euler problems to learn ruby I was looking into coding my algorithm and stumbled across the mathn library which has a Prime class and an Integer class with a prime_division method.  how cool is that.  i was able to get the correct answer to the problem with this ruby snippet:

require "mathn.rb"
puts 600851475143.prime_division.last.first

this snippet outputs the correct answer to the console.  of course i ended up doing a ton of reading and learning before i stumbled upon this little beauty, i just thought i would share it with everyone...

OwnerDisplayName: lil mudd


问:
How to implement an artificial neural network in Delphi?
I want to have an artificial neural network:

42 input neurons

168 hidden neurons

7 output neurons

This network is to play the game of "Connect Four". At the end of each game, the network gets feedback (game result / win?).

Learning should be done with Temporal Difference Learning.

My questions:

What values should be in my reward array?

And finally: How can I apply it to my game now?

Thank you so much in advance!

答: If you're interested in using a third party library (free for non-commercial products,  I've been very happy with some tools from this company http://www.mitov.com/html/intelligencelab.html  (although I've never used their intelligence lab, just video tools.)</p>


问:
Add a dot after a number in R
I have the following list c(1.23,1,0.9) which Shows in the console[1] 1.23 1 0.9  , I would like to transform it to:
[1] 1.23,1.,.9 .
As you can see the first numebr remains the same but 1 become 1. and 0.9 become .9.

Is there is an elegant way to have this Format ?

Regards

答:
Here is a method with sprintf and gsub:

```<code>gsub("0", "", sprintf("%.2f", x))
[1] "1.23" "1."   ".9"
</code>```

To add the commas you could place this in a paste function.

```<code>paste(gsub("0", "", sprintf("%.2f", x)), collapse=",")
[1] "1.23,1.,.9"
</code>```

Title: Add a dot after a number in R

Body:
Here is a method with sprintf and gsub:

gsub("0", "", sprintf("%.2f", x))
[1] "1.23" "1."   ".9"

To add the commas you could place this in a paste function.

paste(gsub("0", "", sprintf("%.2f", x)), collapse=",")
[1] "1.23,1.,.9"


问:
What is the equivalent of this syntax in Java?
Just a quick question about how to convert a certain line of code between c++ and Java. I've been learning about Neural Networks and I've been starting to write my own in the language I have the most experience with, Java. It's been pretty straightforward to translate the code from C++ to Java so far, however there's one little issue I've ran into. I'm puzzled by how to translate this specific line of code into a Java equivalent, and I can't find anything specific to this issue through searching.

The original code is:

```<code>Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};
</code>```

and my code is:

```<code>public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor
</code>```

My question is, how do I convert:

```<code>SNeuron(int NumInputs);
</code>```

into its Java equivalent? From what i've read, Structs don't seem to be a feature Java uses, so i'm just struggling a bit to understand what exactly that line of code actually does in the context it's used.

答:
In C++, SNeuron(int NumInputs); is the declaration of a constructor taking an int, and this is contained within the class declaration.

You don't do that in Java - effectively all constructors, and all functions for that matter, are inlined in the class declaration. In other words

```<code>SNeuron(int NumInputs); // within the class declaration
SNeuron::SNeuron(int NumInputs) : m_NumInputs(NumInputs){} // In a translation unit
</code>```

maps to

```<code>SNeuron(int NumInputs) {
   m_NumInputs = NumInputs;
}
</code>```

but note that using m_ for Java fields is idiosyncratic.

Body:
Just a quick question about how to convert a certain line of code between c++ and Java. I've been learning about Neural Networks and I've been starting to write my own in the language I have the most experience with, Java. It's been pretty straightforward to translate the code from C++ to Java so far, however there's one little issue I've ran into. I'm puzzled by how to translate this specific line of code into a Java equivalent, and I can't find anything specific to this issue through searching.

The original code is:

Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};

and my code is:

public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor

My question is, how do I convert:

SNeuron(int NumInputs);

into its Java equivalent? From what i've read, Structs don't seem to be a feature Java uses, so i'm just struggling a bit to understand what exactly that line of code actually does in the context it's used.

Body:
In C++, SNeuron(int NumInputs); is the declaration of a constructor taking an int, and this is contained within the class declaration.

You don't do that in Java - effectively all constructors, and all functions for that matter, are inlined in the class declaration. In other words

SNeuron(int NumInputs); // within the class declaration
SNeuron::SNeuron(int NumInputs) : m_NumInputs(NumInputs){} // In a translation unit

maps to

SNeuron(int NumInputs) {
   m_NumInputs = NumInputs;
}

but note that using m_ for Java fields is idiosyncratic.


问:
How to import multiple csv files in local DB?
I have a requirement of importing multiple files from a folder into a local DB table. column structures are same. Row count varies from 25 k to 200 k in each file.

which tool can be used to do it faster? like Sql server, oracle or Mysql

答:
I think this could help, at least for MySQL:</p>

```<code>LOAD DATA LOCAL INFILE '<filename>' INTO TABLE <table_name> FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' (<columns>);
</code>```

Body:
I think this could help, at least for MySQL:

LOAD DATA LOCAL INFILE '<filename>' INTO TABLE <table_name> FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' (<columns>);


问:
tvOS: pressesEnded is called intermittently
I am creating a subclass of a UIButton, the reason why I'm trying to intercept the touch is because I cant seem to find another way to receive 'press up' or 'press ended' events for the standard UIButton in tvOS. If I could find a way to do that then I wouldn't need to bother with the solution below.

pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) doesn't seem to be getting called every time I release the 'select' button on the Apple TV Remote.

pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) is being called every time without any issues. I've attached my code below. Any ideas what could be causing this issue?

```<code>class EVLPTZButton: UIButton
{
  var command: PTZCommand!
  var delegate: EVLPTZButtonCommandDelegate?

  override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?)
  {
    super.pressesBegan(presses, with: event)

    delegate?.ptzButton(pressesBeganFor: self, with: command)
  }

  override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?)
  {
    super.pressesEnded(presses, with: event)

    delegate?.ptzButton(pressesEndedFor: self)
  }
}
</code>```

答:
After some more testing it seems that when the 'select' button is released tvOS calls either pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) OR pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?).

I found this solution by jumping to the definition of pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) and finding this comment:

Your responder will receive either pressesEnded:withEvent or
  pressesCancelled:withEvent: for each press it is handling (those
  presses it received in pressesBegan:withEvent:).

Body:
I am creating a subclass of a UIButton, the reason why I'm trying to intercept the touch is because I cant seem to find another way to receive 'press up' or 'press ended' events for the standard UIButton in tvOS. If I could find a way to do that then I wouldn't need to bother with the solution below.

pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) doesn't seem to be getting called every time I release the 'select' button on the Apple TV Remote.

pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) is being called every time without any issues. I've attached my code below. Any ideas what could be causing this issue?

class EVLPTZButton: UIButton
{
  var command: PTZCommand!
  var delegate: EVLPTZButtonCommandDelegate?

  override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?)
  {
    super.pressesBegan(presses, with: event)

    delegate?.ptzButton(pressesBeganFor: self, with: command)
  }

  override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?)
  {
    super.pressesEnded(presses, with: event)

    delegate?.ptzButton(pressesEndedFor: self)
  }
}