问:
How to run war file on machine of client from another country without having error related to clock/ signature?
I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

```<code>Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)
</code>```

I came to this link and I think I am having almost same type of error :

StorageException for azure blob with java

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

Here is the code : (See the code in else loop from first method. It's blob related code.)

```<code>@Override
    public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
        if (jsonInput.containsKey("accountName")) {
            CloudFileClient fileClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            try {
                // fileClient =
                // FileClientProvider.getFileClientReference(jsonOutput);
                fileClient = storageAccount.createCloudFileClient();
                String directoryName = jsonInput.get("directoryStructure").toString();

                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                System.out.println(directoryNameArray.length);

                CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (share.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
                for (int i = 0; i < directoryNameArray.length; i++) {
                    String directoryToCreate = directoryNameArray[i];
                    CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

                    String directoryNameToListFiles = directory.getName();
                    if (i == directoryNameArray.length - 1) {
                        for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
                            boolean isDirectory;
                            if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
                                System.out.println("Directory Exists Here");
                            } else {
                                System.out.println("Name with files :" + fileItem.getUri().toString());
                                String downloadLocation = "/home/zcon/AzureDownloadedFiles";
                                String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
                                for (int j = 0; j < fileName.length; j++) {
                                    if (j == fileName.length - 1) {
                                        String fileNameWithExtension = fileName[j];
                                        File f = new File(downloadLocation + "/" + fileNameWithExtension);
                                        String DownloadTo = f.toString();
                                        f.createNewFile();
                                        CloudFile cloudFile = directory
                                                .getFileReference(fileNameWithExtension.replaceAll("%20", " "));
                                        System.out.println("fileName===========" + fileNameWithExtension);
                                        String tokenKey = testFileSAS(share, cloudFile);
                                        cloudFile.downloadToFile(DownloadTo);
                                        fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
                                        f.delete();
                                    }
                                }
                            }
                        }
                    }
                    rootDir = directory;
                }
                ArrayList fileNamesList = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameReturn = fileName[j];
                            String[] fileNameReturnArray = fileNameReturn.split("\\.");
                            fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("status", "successful");
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        } else {

            CloudBlobClient blobClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            ArrayList fileNamesList = new ArrayList<>();
            ArrayList blobItemList = new ArrayList<>();

            try {
                blobClient = storageAccount.createCloudBlobClient();
                String directoryName = jsonInput.get("directoryStructure").toString();
                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (container.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                // CloudBlockBlob blob =
                // container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
                CloudBlobDirectory directoryOfFile = container
                        .getDirectoryReference(jsonInput.get("directoryStructure").toString());
                for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
                    // System.out.println(blobItem.getUri());
                    // fileList.add(blobItem.getUri());
                    blobItemList.add(blobItem);

                }

                for(int  q= 0; q<blobItemList.size(); q++){
                    if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
                    {
                        blobItemList.remove(q);
                    }
                }
                System.out.println(blobItemList);
                for (int l = 0; l < blobItemList.size(); l++) {
                    CloudBlob blob = (CloudBlob) blobItemList.get(l);
                    if (blob.getUri().toString().contains("Temp.txt")) {
                        System.out.println("Temp file was skipped");
                    } else {
                        String tokenKey = testBlobSaS(blob, container);
                        fileList.add(blob.getUri().toString() + "?" + tokenKey);
                    }
                }
                System.out.println("size of blobItemList is=============" + blobItemList.size());

                for (int k = 0; k < fileList.size(); k++) {
                    String fileItem = fileList.get(k).toString();
                    String fileName[] = fileItem.split("\\s*/\\s*");

                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameWithExtension = fileName[j];
                            String[] parts = fileNameWithExtension.split("\\?");
                            System.out.println("fileName===========" + fileNameWithExtension);
                            fileNamesList.add(parts[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("status", "successful");
                System.out.println(fileList);
                return jsonOutput;
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        }

    }
</code>```

Method to create BlobSAS :

```<code>@Test
    // @Category(SlowTests.class)
    public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
            IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
        SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        container.uploadPermissions(perms);
        // Thread.sleep(30000);
        String sas = blob.generateSharedAccessSignature(sp, null);

        CloudBlockBlob sasBlob = new CloudBlockBlob(
                new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
        sasBlob.download(new ByteArrayOutputStream());

        // do not give the client and check that the new blob's client has the
        // correct perms
        CloudBlob blobFromUri = new CloudBlockBlob(
                PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromUri.getServiceClient().getCredentials().getClass().toString());

        // create credentials from sas
        StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
                blob.generateSharedAccessSignature(null, "readperm"));
        CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

        CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
                .getBlockBlobReference(blob.getName());
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromClient.getServiceClient().getCredentials().getClass().toString());
        assertEquals(bClient, blobFromClient.getServiceClient());
        return sas;

    }
</code>```

Method to create shared access blob policy :

```<code>private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;

    }
</code>```

What changes I should make here?

答:
Per my experience, the issue was caused by the incorrect code in the method private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy to get the UTC time via Calendar .

As reference, Here is my sample code to get UTC time using Calendar.

```<code>Calendar cal = Calendar.getInstance() ;
// Get the time zone offset
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// Get the daylight-saving time offset
int dstOffset = cal.get(Calendar.DST_OFFSET);
// Reduce these offsets above from local time to get UTC time
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
System.out.println(cal.getTime());
</code>```

Then, to add the expire time seconds to get the final date time.

Body:
I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)

I came to this link and I think I am having almost same type of error :

StorageException for azure blob with java

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

Here is the code : (See the code in else loop from first method. It's blob related code.)

@Override
    public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
        if (jsonInput.containsKey("accountName")) {
            CloudFileClient fileClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            try {
                // fileClient =
                // FileClientProvider.getFileClientReference(jsonOutput);
                fileClient = storageAccount.createCloudFileClient();
                String directoryName = jsonInput.get("directoryStructure").toString();

                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                System.out.println(directoryNameArray.length);

                CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (share.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
                for (int i = 0; i < directoryNameArray.length; i++) {
                    String directoryToCreate = directoryNameArray[i];
                    CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

                    String directoryNameToListFiles = directory.getName();
                    if (i == directoryNameArray.length - 1) {
                        for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
                            boolean isDirectory;
                            if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
                                System.out.println("Directory Exists Here");
                            } else {
                                System.out.println("Name with files :" + fileItem.getUri().toString());
                                String downloadLocation = "/home/zcon/AzureDownloadedFiles";
                                String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
                                for (int j = 0; j < fileName.length; j++) {
                                    if (j == fileName.length - 1) {
                                        String fileNameWithExtension = fileName[j];
                                        File f = new File(downloadLocation + "/" + fileNameWithExtension);
                                        String DownloadTo = f.toString();
                                        f.createNewFile();
                                        CloudFile cloudFile = directory
                                                .getFileReference(fileNameWithExtension.replaceAll("%20", " "));
                                        System.out.println("fileName===========" + fileNameWithExtension);
                                        String tokenKey = testFileSAS(share, cloudFile);
                                        cloudFile.downloadToFile(DownloadTo);
                                        fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
                                        f.delete();
                                    }
                                }
                            }
                        }
                    }
                    rootDir = directory;
                }
                ArrayList fileNamesList = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameReturn = fileName[j];
                            String[] fileNameReturnArray = fileNameReturn.split("\\.");
                            fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("status", "successful");
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        } else {

            CloudBlobClient blobClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            ArrayList fileNamesList = new ArrayList<>();
            ArrayList blobItemList = new ArrayList<>();

            try {
                blobClient = storageAccount.createCloudBlobClient();
                String directoryName = jsonInput.get("directoryStructure").toString();
                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (container.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                // CloudBlockBlob blob =
                // container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
                CloudBlobDirectory directoryOfFile = container
                        .getDirectoryReference(jsonInput.get("directoryStructure").toString());
                for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
                    // System.out.println(blobItem.getUri());
                    // fileList.add(blobItem.getUri());
                    blobItemList.add(blobItem);

                }

                for(int  q= 0; q<blobItemList.size(); q++){
                    if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
                    {
                        blobItemList.remove(q);
                    }
                }
                System.out.println(blobItemList);
                for (int l = 0; l < blobItemList.size(); l++) {
                    CloudBlob blob = (CloudBlob) blobItemList.get(l);
                    if (blob.getUri().toString().contains("Temp.txt")) {
                        System.out.println("Temp file was skipped");
                    } else {
                        String tokenKey = testBlobSaS(blob, container);
                        fileList.add(blob.getUri().toString() + "?" + tokenKey);
                    }
                }
                System.out.println("size of blobItemList is=============" + blobItemList.size());

                for (int k = 0; k < fileList.size(); k++) {
                    String fileItem = fileList.get(k).toString();
                    String fileName[] = fileItem.split("\\s*/\\s*");

                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameWithExtension = fileName[j];
                            String[] parts = fileNameWithExtension.split("\\?");
                            System.out.println("fileName===========" + fileNameWithExtension);
                            fileNamesList.add(parts[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("status", "successful");
                System.out.println(fileList);
                return jsonOutput;
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        }

    }

Method to create BlobSAS :

@Test
    // @Category(SlowTests.class)
    public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
            IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
        SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        container.uploadPermissions(perms);
        // Thread.sleep(30000);
        String sas = blob.generateSharedAccessSignature(sp, null);

        CloudBlockBlob sasBlob = new CloudBlockBlob(
                new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
        sasBlob.download(new ByteArrayOutputStream());

        // do not give the client and check that the new blob's client has the
        // correct perms
        CloudBlob blobFromUri = new CloudBlockBlob(
                PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromUri.getServiceClient().getCredentials().getClass().toString());

        // create credentials from sas
        StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
                blob.generateSharedAccessSignature(null, "readperm"));
        CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

        CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
                .getBlockBlobReference(blob.getName());
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromClient.getServiceClient().getCredentials().getClass().toString());
        assertEquals(bClient, blobFromClient.getServiceClient());
        return sas;

    }

Method to create shared access blob policy :

private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;

    }

What changes I should make here?

Body:
Per my experience, the issue was caused by the incorrect code in the method private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy to get the UTC time via Calendar .

As reference, Here is my sample code to get UTC time using Calendar.

Calendar cal = Calendar.getInstance() ;
// Get the time zone offset
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// Get the daylight-saving time offset
int dstOffset = cal.get(Calendar.DST_OFFSET);
// Reduce these offsets above from local time to get UTC time
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
System.out.println(cal.getTime());

Then, to add the expire time seconds to get the final date time.


来源: stackexchange

问:
How To Asynchronously Read/Write A Named Pipe In C#
I have a Windows form which hosts a custom User Control. This User Control fires up a seperate process (a .exe) which creates and initializes a NamedPipeServerStream. Once the process initializes the NamedPipeServerStream, the User Control connects to it as a NamedPipeClientStream.

This all works fine.

On the Windows form I then have a button called "Check For Updates". When this button is pressed, the NamedPipeClientStream sends a message to the server, to which the server responds which a MessageBox saying "I've been told to check for updates". So I can tell this client > server communication is working fine.

Here's the problem. The server is then supposed to send a message BACK to the client telling it that it's now checking for updates (So the User Control can update its status after verying its command was received by the server). But whenever this happens, everything locks up.

Now I am going to assume that this is because I am attempting to both read AND write to the Named Pipe at the same time?

Below are some code snippets from both the Server and the Client. (Both these snippets run in seperate threads in their respective processes so as to not block the UI)

GUpdater (The Named Pipe Server):

```<code>private void WaitForClientCommands()
{
    // Wait for a connection from a Named Pipe Client (The GUpControl)
    pipeStream.WaitForConnection();
    pipeConnected = true;

    // Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
    pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
    pipeStreamReader = new StreamReader(pipeStream);

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if(isWritingToPipe) continue;

        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        switch(message)
        {
            case "CheckForUpdates":
                //MessageBox.Show("Told to check for updates");
                SendMessageToClient("Checking For Updates, Woot!");
                break;
            case "DownloadUpdate":
                MessageBox.Show("Told to download update");
                break;
            case "ApplyUpdate":
                MessageBox.Show("Told to apply update");
                break;
        }
    }
}
</code>```

GUpControl (The Named Pipe Client):

```<code>private void WaitForServerCommands()
{
    if(!pipeConnected) return;

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if (isWritingToPipe) continue;

        // Attempt to read a line from the pipe
        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        MessageBox.Show("I got a message from the server!!\r\n" + message);
    }
}
</code>```

The following snippet is the method that is responsible for writing to the Client/Server from each component. (The only difference is in the name, i.e. SendMessageToClient and SendMessageToServer)

```<code>private void SendMessageToServer(string message)
{
    if(pipeConnected)
    {
        isWritingToPipe = true;
        pipeStreamWriter.WriteLine(message);
        isWritingToPipe = false;
    }
}
</code>```

The isWritingToPipe variable is a simple bool that is true when the respective process is attempting to write to the Named Pipe. This was my initial attempt at solving the problem.

Any help is much appreciated!

答:
The solution to this problem turned out to be a matter of rethinking the design of the software.

Instead of having a UserControl that talks to a seperate application each step of the Update process, the UserControl handles it all itself and then finally when it needs to apply the update (which involves overwriting application files, hence the need for a seperate process in the first place) it simply uses Process.Start("...") along with some command line arguements to call a seperate process to finish the job.

A much simpler solution than trying to do Inter-Process Communication for this task.

Still, it would have been nice to find out why my Bi-Directional communication wasn't working.

ContentLicense: CC BY-SA 2.5

Body:
I have a Windows form which hosts a custom User Control. This User Control fires up a seperate process (a .exe) which creates and initializes a NamedPipeServerStream. Once the process initializes the NamedPipeServerStream, the User Control connects to it as a NamedPipeClientStream.

This all works fine.

On the Windows form I then have a button called "Check For Updates". When this button is pressed, the NamedPipeClientStream sends a message to the server, to which the server responds which a MessageBox saying "I've been told to check for updates". So I can tell this client > server communication is working fine.

Here's the problem. The server is then supposed to send a message BACK to the client telling it that it's now checking for updates (So the User Control can update its status after verying its command was received by the server). But whenever this happens, everything locks up.

Now I am going to assume that this is because I am attempting to both read AND write to the Named Pipe at the same time?

Below are some code snippets from both the Server and the Client. (Both these snippets run in seperate threads in their respective processes so as to not block the UI)

GUpdater (The Named Pipe Server):

private void WaitForClientCommands()
{
    // Wait for a connection from a Named Pipe Client (The GUpControl)
    pipeStream.WaitForConnection();
    pipeConnected = true;

    // Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
    pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
    pipeStreamReader = new StreamReader(pipeStream);

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if(isWritingToPipe) continue;

        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        switch(message)
        {
            case "CheckForUpdates":
                //MessageBox.Show("Told to check for updates");
                SendMessageToClient("Checking For Updates, Woot!");
                break;
            case "DownloadUpdate":
                MessageBox.Show("Told to download update");
                break;
            case "ApplyUpdate":
                MessageBox.Show("Told to apply update");
                break;
        }
    }
}

GUpControl (The Named Pipe Client):

private void WaitForServerCommands()
{
    if(!pipeConnected) return;

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if (isWritingToPipe) continue;

        // Attempt to read a line from the pipe
        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        MessageBox.Show("I got a message from the server!!\r\n" + message);
    }
}

The following snippet is the method that is responsible for writing to the Client/Server from each component. (The only difference is in the name, i.e. SendMessageToClient and SendMessageToServer)

private void SendMessageToServer(string message)
{
    if(pipeConnected)
    {
        isWritingToPipe = true;
        pipeStreamWriter.WriteLine(message);
        isWritingToPipe = false;
    }
}

The isWritingToPipe variable is a simple bool that is true when the respective process is attempting to write to the Named Pipe. This was my initial attempt at solving the problem.

Any help is much appreciated!


问:
How to turn on the Security boot for MS Win10
I need to turn on this mode for test of my new drivers.

My operations:

In bios I set a support of UEFI

Enable the option Security boot.

Reboot PC

Load msinfo32 and see

BIOS is in UEFI

Security boot is in off. Why?????

My OS is MS Win 10 x64 1703,
Videocard is Gigabyte Geforce GTX 650, the utility GPU-Z shows that card supports UEFI.

Ideas?

答: Need to set  Platform Key in the BIOS. Thanks Alex for help.</p>

ContentLicense: CC BY-SA 3.0


问:
Avoid Parent model class creation in Django
I have the following data models:

```<code>class PaymentGateway(models.Model):
    GATEWAYS = Choices(
        ('stripe', _('Stripe')),
        ('paybox', _('PayBox')),
        ('generic', _('Generic')),
    )

    tenant = models.ForeignKey(Tenant,
related_name="payment_gateways")
    name = models.CharField(
        max_length=50,
        verbose_name=_('Name'),
        choices=GATEWAYS,
        default=GATEWAYS.generic
    )

class StripeGateway(PaymentGateway):
    stripe_public_key = models.CharField(max_length=255)
    stripe_key = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Stripe Gateway'

    def __init__(self, *args, **kwargs):
        super(StripeGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.stripe

    def __unicode__(self):
        return "Stripe data for %(school_name)s" % {"school_name": self.school.name}

class EtransactionGateway(PaymentGateway):
    pbx_site = models.IntegerField()
    pbx_rang = models.IntegerField()
    pbx_identifiant = models.IntegerField()
    pbx_devise = models.IntegerField()
    pbx_secret = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Etransaction Gateway'

    def __init__(self, *args, **kwargs):
        super(EtransactionGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.paybox

    def __unicode__(self):
        return "E-transaction data for %(school_name)s" % {"school_name": self.school.name}
</code>```

This is fine, but when I create an instance of either StripeGateway or EtransactionGateway, I can see another instace of PaymentGateway is created.

I've tried creating the PaymentGateway abstract as suggested [here](https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name-aEDIT: I've tried, based on comments, to add abstract to parent class and then I runnd-related-query-name) but when I do this and run the migration (I already run a first migration with the current scenario) then I get an error saying something like id field in eTransactionGateway conflicts with the one from paymentGateway (sorry I can't find the trace now).

For now this is ok, but I'd really like to not have instances of PaymentGateway or at least, have the backref payment_gateways return the children classes, because right now something like this:

```<code>tenant = Tenant.objects.get(name='tenant_1')
gws = tenant.payment_gateways.all()
</code>```

Return the parent instances, that have no value for me.

Any suggestions?

EDIT: I've tried, based on comments, to add abstract to parent class and then I run

So classes look like these now:

```<code>class PaymentGateway(models.Model):
    GATEWAYS = Choices(
        ('stripe', _('Stripe')),
        ('paybox', _('PayBox')),
        ('generic', _('Generic')),
    )

    tenant = models.ForeignKey(Tenant, related_name = "%(app_label)s_%(class)s_related")

    name = models.CharField(
        max_length=50,
        verbose_name=_('Name'),
        choices=GATEWAYS,
        default=GATEWAYS.generic
    )

    class Meta:
        abstract = True

class StripeGateway(PaymentGateway):
    stripe_public_key = models.CharField(max_length=255)
    stripe_key = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Stripe Gateway'

    def __init__(self, *args, **kwargs):
        super(StripeGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.stripe

    def __unicode__(self):
        return "Stripe data for %(school_name)s" % {"school_name": self.school.name}

class EtransactionGateway(PaymentGateway):
    pbx_site = models.IntegerField()
    pbx_rang = models.IntegerField()
    pbx_identifiant = models.IntegerField()
    pbx_devise = models.IntegerField()
    pbx_secret = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Etransaction Gateway'

    def __init__(self, *args, **kwargs):
        super(EtransactionGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.paybox

    def __unicode__(self):
        return "E-transaction data for %(school_name)s" % {"school_name": self.school.name}
</code>```

I've reset db first

```<code>python manage.py reset_db
</code>```

And then

```<code>python manage.py makemigrations
</code>```

And getting this messages like this:

```<code>You are trying to add a non-nullable field 'id' to etransactiongateway without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:

You are trying to add a non-nullable field 'tenant' to stripegateway without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
</code>```

1) Provide a one-off default now (will be set on all existing rows)
   2) Quit, and let me add a default in models.py

I select 1, since I don't even have the id field in my children classes (this is managed internally by Django), for second message I use id of a tenant I already know exists in db with id 1

Get this output afterwards:

```<code>Migrations for 'payment':
0010_auto_20170704_2305.py:
  - RemovEDIT: I've tried, based on comments, to add abstract to parent class and then I rune field tenat from paymentgateway
  - Remove field paymentgateway_ptr from etransactiongateway
  - Remove field paymentgateway_ptr from stripegateway
  - Add field id to etransactiongateway
  - Add field name to etransactiongateway
  - Add field tenant to etransactiongateway
  - Add field id to stripegateway
  - Add field name to stripegateway
  - Add field tenant to stripegateway
  - Delete model PaymentGateway
</code>```

This migration looks weird to me, but anyway, let's try migrate, this is the output:

```<code>  Applying payment.0010_auto_20170704_2305...Traceback (most recent call last):
  File "manage.py", line 25, in <module>
execute_from_command_line(sys.argv)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.state_forwards(self.app_label, project_state)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 51, in state_forwards
state.reload_model(app_label, self.model_name_lower)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 148, in reload_model
self.apps.render_multiple(states_to_be_rendered)
 File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 296, in render_multiple
model.render(self)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 585, in render
body,EDIT: I've tried, based on comments, to add abstract to parent class and then I run
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/models/base.py", line 223, in __new__
'base class %r' % (field.name, name, base.__name__)
django.core.exceptions.FieldError: Local field u'id' in class 'EtransactionGateway' clashes with field of similar name from base class 'PaymentGateway'
</code>```

答:
If you don't want to create a table for the parent model in the db, you could add abstract=True in the model's metaclass.

```<code>class PaymentGateway(models.Model):
    ...
    class Meta:
        abstract = True
</code>```

Source: Django abstract base classes

Body:
I have the following data models:

class PaymentGateway(models.Model):
    GATEWAYS = Choices(
        ('stripe', _('Stripe')),
        ('paybox', _('PayBox')),
        ('generic', _('Generic')),
    )

    tenant = models.ForeignKey(Tenant,
related_name="payment_gateways")
    name = models.CharField(
        max_length=50,
        verbose_name=_('Name'),
        choices=GATEWAYS,
        default=GATEWAYS.generic
    )

class StripeGateway(PaymentGateway):
    stripe_public_key = models.CharField(max_length=255)
    stripe_key = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Stripe Gateway'

    def __init__(self, *args, **kwargs):
        super(StripeGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.stripe

    def __unicode__(self):
        return "Stripe data for %(school_name)s" % {"school_name": self.school.name}

class EtransactionGateway(PaymentGateway):
    pbx_site = models.IntegerField()
    pbx_rang = models.IntegerField()
    pbx_identifiant = models.IntegerField()
    pbx_devise = models.IntegerField()
    pbx_secret = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Etransaction Gateway'

    def __init__(self, *args, **kwargs):
        super(EtransactionGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.paybox

    def __unicode__(self):
        return "E-transaction data for %(school_name)s" % {"school_name": self.school.name}

This is fine, but when I create an instance of either StripeGateway or EtransactionGateway, I can see another instace of PaymentGateway is created.

I've tried creating the PaymentGateway abstract as suggested [here](https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name-aEDIT: I've tried, based on comments, to add abstract to parent class and then I runnd-related-query-name) but when I do this and run the migration (I already run a first migration with the current scenario) then I get an error saying something like id field in eTransactionGateway conflicts with the one from paymentGateway (sorry I can't find the trace now).

For now this is ok, but I'd really like to not have instances of PaymentGateway or at least, have the backref payment_gateways return the children classes, because right now something like this:

tenant = Tenant.objects.get(name='tenant_1')
gws = tenant.payment_gateways.all()

Return the parent instances, that have no value for me.

Any suggestions?

EDIT: I've tried, based on comments, to add abstract to parent class and then I run

So classes look like these now:

class PaymentGateway(models.Model):
    GATEWAYS = Choices(
        ('stripe', _('Stripe')),
        ('paybox', _('PayBox')),
        ('generic', _('Generic')),
    )

    tenant = models.ForeignKey(Tenant, related_name = "%(app_label)s_%(class)s_related")

    name = models.CharField(
        max_length=50,
        verbose_name=_('Name'),
        choices=GATEWAYS,
        default=GATEWAYS.generic
    )

    class Meta:
        abstract = True

class StripeGateway(PaymentGateway):
    stripe_public_key = models.CharField(max_length=255)
    stripe_key = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Stripe Gateway'

    def __init__(self, *args, **kwargs):
        super(StripeGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.stripe

    def __unicode__(self):
        return "Stripe data for %(school_name)s" % {"school_name": self.school.name}

class EtransactionGateway(PaymentGateway):
    pbx_site = models.IntegerField()
    pbx_rang = models.IntegerField()
    pbx_identifiant = models.IntegerField()
    pbx_devise = models.IntegerField()
    pbx_secret = models.CharField(max_length=255)

    class Meta:
        verbose_name = u'Etransaction Gateway'

    def __init__(self, *args, **kwargs):
        super(EtransactionGateway, self).__init__(*args, **kwargs)
        self.name = PaymentGateway.GATEWAYS.paybox

    def __unicode__(self):
        return "E-transaction data for %(school_name)s" % {"school_name": self.school.name}

I've reset db first

python manage.py reset_db

And then

python manage.py makemigrations

And getting this messages like this:

You are trying to add a non-nullable field 'id' to etransactiongateway without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:

You are trying to add a non-nullable field 'tenant' to stripegateway without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:

1) Provide a one-off default now (will be set on all existing rows)
   2) Quit, and let me add a default in models.py

I select 1, since I don't even have the id field in my children classes (this is managed internally by Django), for second message I use id of a tenant I already know exists in db with id 1

Get this output afterwards:

Migrations for 'payment':
0010_auto_20170704_2305.py:
  - RemovEDIT: I've tried, based on comments, to add abstract to parent class and then I rune field tenat from paymentgateway
  - Remove field paymentgateway_ptr from etransactiongateway
  - Remove field paymentgateway_ptr from stripegateway
  - Add field id to etransactiongateway
  - Add field name to etransactiongateway
  - Add field tenant to etransactiongateway
  - Add field id to stripegateway
  - Add field name to stripegateway
  - Add field tenant to stripegateway
  - Delete model PaymentGateway

This migration looks weird to me, but anyway, let's try migrate, this is the output:

  Applying payment.0010_auto_20170704_2305...Traceback (most recent call last):
  File "manage.py", line 25, in <module>
execute_from_command_line(sys.argv)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.state_forwards(self.app_label, project_state)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 51, in state_forwards
state.reload_model(app_label, self.model_name_lower)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 148, in reload_model
self.apps.render_multiple(states_to_be_rendered)
 File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 296, in render_multiple
model.render(self)
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 585, in render
body,EDIT: I've tried, based on comments, to add abstract to parent class and then I run
  File "/home/acme/python_envs/acme/local/lib/python2.7/site-packages/django/db/models/base.py", line 223, in __new__
'base class %r' % (field.name, name, base.__name__)
django.core.exceptions.FieldError: Local field u'id' in class 'EtransactionGateway' clashes with field of similar name from base class 'PaymentGateway'

Body:
If you don't want to create a table for the parent model in the db, you could add abstract=True in the model's metaclass.

class PaymentGateway(models.Model):
    ...
    class Meta:
        abstract = True

Source: Django abstract base classes


问:
Variables in property files in spring boot
Can I use a propertie inside a application.properties?

sample:

```<code>myLevel=ERROR

logging.level.org.springframework=$myLevel
logging.level.org.apache.catalina=$myLevel
</code>```

tks

答:
You might use property placeholders:

The values in application.properties are filtered through the existing Environment when they are used so you can refer back to previously defined values (e.g. from System properties).

For your case:

```<code>myLevel=ERROR

logging.level.org.springframework=${myLevel}
logging.level.org.apache.catalina=${myLevel}
</code>```

See also:

Spring Boot - Placeholders in properties

Body:
Can I use a propertie inside a application.properties?

sample:

myLevel=ERROR

logging.level.org.springframework=$myLevel
logging.level.org.apache.catalina=$myLevel

tks

Body:
You might use property placeholders:

The values in application.properties are filtered through the existing Environment when they are used so you can refer back to previously defined values (e.g. from System properties).

For your case:

myLevel=ERROR

logging.level.org.springframework=${myLevel}
logging.level.org.apache.catalina=${myLevel}

See also:

Spring Boot - Placeholders in properties


问:
Android getting error in sqlite database class
I am getting this java runtime exception and i have checked my query as well. All seem to b right. i am just not understanding where i am going wrong
I have checked it and dint find anything wrong. Please help me
    This is my logcat

```<code> 07-05 10:59:38.204 12209-12209/com.example.user.easytodolist E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.user.easytodolist, PID: 12209
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.easytodolist/com.example.user.easytodolist.MainActivity}: android.database.sqlite.SQLiteException: near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);
                                                                                #################################################################
                                                                                Error Code : 1 (SQLITE_ERROR)
                                                                                Caused By : SQL(query) error or missing database.
                                                                                (near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);)
                                                                                #################################################################
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: android.database.sqlite.SQLiteException: near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);
                                                                                #################################################################
                                                                                Error Code : 1 (SQLITE_ERROR)
                                                                                Caused By : SQL(query) error or missing database.
                                                                                (near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);)
                                                                                #################################################################
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1000)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:565)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1838)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1769)
                                                                                at com.example.user.easytodolist.db.TaskHelper.onCreate(TaskHelper.java:17)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
                                                                                at com.example.user.easytodolist.MainActivity.updateUI(MainActivity.java:84)
                                                                                at com.example.user.easytodolist.MainActivity.onCreate(MainActivity.java:38)
                                                                                at android.app.Activity.performCreate(Activity.java:6904)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                                                                                ... 9 more
</code>```

This is my MainActivity.

```<code>import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.DialogPreference;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.user.easytodolist.db.Task;
import com.example.user.easytodolist.db.TaskHelper;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TaskHelper mHelper;
    private ListView mTaskListView;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHelper = new TaskHelper(this);
        mTaskListView = (ListView) findViewById(R.id.list_todo);
        updateUI();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
            switch(item.getItemId()){
                case R.id.action_add_task:
                    final EditText taskEditTask = new EditText(this);
                    AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("New Task")
                    .setMessage("Add a New Task")
                    .setView(taskEditTask)
                    .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String task = String.valueOf(taskEditTask.getText());
                            SQLiteDatabase db = mHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                           values.put(com.example.user.easytodolist.db.Task.TaskEntry.COL_TASK_TITLE,task);
                           db.insertWithOnConflict(Task.TaskEntry.TABLE,null,values,SQLiteDatabase.CONFLICT_REPLACE);
                            db.close();
                            updateUI();
                        }
                    })
                            .setNegativeButton("Cancel", null)
                            .create();
                    dialog.show();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);

            }
    }

    private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();
                SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor = db.query(Task.TaskEntry.TABLE,
                new String[]{Task.TaskEntry._ID, Task.TaskEntry.COL_TASK_TITLE} ,null,null,null,null,null);
        while (cursor.moveToNext()){
            int index = cursor.getColumnIndex(Task.TaskEntry.COL_TASK_TITLE);
            taskList.add(cursor.getString(index));
        }

        if(mAdapter == null){
            mAdapter = new ArrayAdapter<String>(this, R.layout.item_todo,R.id.task_title,taskList);
            mTaskListView.setAdapter(mAdapter);
        } else{
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }

        cursor.close();
        db.close();
    }

    public void deleteTask(View view){
        View parent = (View) view.getParent();
        TextView taskTextView  = (TextView) parent.findViewById(R.id.task_title);
        String task = String.valueOf(taskTextView.getText());
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.delete(Task.TaskEntry.TABLE, Task.TaskEntry.COL_TASK_TITLE + "= ?", new String[] {task});
        db.close();
        updateUI();

    }
}
</code>```

My TaskHelperclass

```<code>package com.example.user.easytodolist.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class TaskHelper extends SQLiteOpenHelper {
    public TaskHelper(Context context) {
        super(context,Task.DB_NAME,null,Task.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + Task.TaskEntry.TABLE + " ( " +
                                              Task.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                                              Task.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + Task.TaskEntry.TABLE);
        onCreate(db);
    }
}
</code>```

And Task Class

```<code>package com.example.user.easytodolist.db;

import android.provider.BaseColumns;

public class Task {

    public static final String DB_NAME = "com.example.user.easytodolist.db";
    public static final int DB_VERSION = 1;

    public class TaskEntry implements BaseColumns{
        public static final String TABLE= "tasks";
        public static final String COL_TASK_TITLE = "title";
    }
}
</code>```

答:
```<code>CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);
</code>```

This query should be

```<code>CREATE TABLE tasks(id INTEGER PRIMARY KEY, title TEXT NOT NULL);
</code>```

You missed the spaces

Body:
I am getting this java runtime exception and i have checked my query as well. All seem to b right. i am just not understanding where i am going wrong
I have checked it and dint find anything wrong. Please help me
    This is my logcat

 07-05 10:59:38.204 12209-12209/com.example.user.easytodolist E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.user.easytodolist, PID: 12209
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.easytodolist/com.example.user.easytodolist.MainActivity}: android.database.sqlite.SQLiteException: near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);
                                                                                #################################################################
                                                                                Error Code : 1 (SQLITE_ERROR)
                                                                                Caused By : SQL(query) error or missing database.
                                                                                (near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);)
                                                                                #################################################################
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: android.database.sqlite.SQLiteException: near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);
                                                                                #################################################################
                                                                                Error Code : 1 (SQLITE_ERROR)
                                                                                Caused By : SQL(query) error or missing database.
                                                                                (near "TABLEtasks": syntax error (code 1): , while compiling: CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);)
                                                                                #################################################################
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1000)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:565)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1838)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1769)
                                                                                at com.example.user.easytodolist.db.TaskHelper.onCreate(TaskHelper.java:17)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
                                                                                at com.example.user.easytodolist.MainActivity.updateUI(MainActivity.java:84)
                                                                                at com.example.user.easytodolist.MainActivity.onCreate(MainActivity.java:38)
                                                                                at android.app.Activity.performCreate(Activity.java:6904)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                                                                                ... 9 more

This is my MainActivity.

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.DialogPreference;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.user.easytodolist.db.Task;
import com.example.user.easytodolist.db.TaskHelper;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TaskHelper mHelper;
    private ListView mTaskListView;
    private ArrayAdapter<String> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHelper = new TaskHelper(this);
        mTaskListView = (ListView) findViewById(R.id.list_todo);
        updateUI();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
            switch(item.getItemId()){
                case R.id.action_add_task:
                    final EditText taskEditTask = new EditText(this);
                    AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle("New Task")
                    .setMessage("Add a New Task")
                    .setView(taskEditTask)
                    .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String task = String.valueOf(taskEditTask.getText());
                            SQLiteDatabase db = mHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                           values.put(com.example.user.easytodolist.db.Task.TaskEntry.COL_TASK_TITLE,task);
                           db.insertWithOnConflict(Task.TaskEntry.TABLE,null,values,SQLiteDatabase.CONFLICT_REPLACE);
                            db.close();
                            updateUI();
                        }
                    })
                            .setNegativeButton("Cancel", null)
                            .create();
                    dialog.show();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);

            }
    }

    private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();
                SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor = db.query(Task.TaskEntry.TABLE,
                new String[]{Task.TaskEntry._ID, Task.TaskEntry.COL_TASK_TITLE} ,null,null,null,null,null);
        while (cursor.moveToNext()){
            int index = cursor.getColumnIndex(Task.TaskEntry.COL_TASK_TITLE);
            taskList.add(cursor.getString(index));
        }

        if(mAdapter == null){
            mAdapter = new ArrayAdapter<String>(this, R.layout.item_todo,R.id.task_title,taskList);
            mTaskListView.setAdapter(mAdapter);
        } else{
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }

        cursor.close();
        db.close();
    }

    public void deleteTask(View view){
        View parent = (View) view.getParent();
        TextView taskTextView  = (TextView) parent.findViewById(R.id.task_title);
        String task = String.valueOf(taskTextView.getText());
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.delete(Task.TaskEntry.TABLE, Task.TaskEntry.COL_TASK_TITLE + "= ?", new String[] {task});
        db.close();
        updateUI();

    }
}

My TaskHelperclass

package com.example.user.easytodolist.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class TaskHelper extends SQLiteOpenHelper {
    public TaskHelper(Context context) {
        super(context,Task.DB_NAME,null,Task.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + Task.TaskEntry.TABLE + " ( " +
                                              Task.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                                              Task.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + Task.TaskEntry.TABLE);
        onCreate(db);
    }
}

And Task Class

package com.example.user.easytodolist.db;

import android.provider.BaseColumns;

public class Task {

    public static final String DB_NAME = "com.example.user.easytodolist.db";
    public static final int DB_VERSION = 1;

    public class TaskEntry implements BaseColumns{
        public static final String TABLE= "tasks";
        public static final String COL_TASK_TITLE = "title";
    }
}

Body:
CREATE TABLEtasks(_idINTEGER PRIMARY KEY AUTOINCREMENT, titleTEXT NOT NULL);

This query should be

CREATE TABLE tasks(id INTEGER PRIMARY KEY, title TEXT NOT NULL);

You missed the spaces


问:
why these code work but dont add record to my database
```<code>SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO projetablosu(basvuru_no)VALUES(@basvuru_no)";
cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
cmd.ExecuteNonQuery();
</code>```

答:
Well, if it doesn't add the record to the database you can hardly say it works, can you?

You are missing the @ in the parameter. Instead of

```<code>cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
</code>```

use

```<code>cmd.Parameters.Add("@basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
</code>```

You should also read Can we stop using AddWithValue() already?

Also, as Artem wrote in his comment, you should dispose your disposable objects. The proper way to do it is with the using statement:

```<code>using (var conn = new SqlConnection(@"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True"))
{
    using (var cmd = new SqlCommand("INSERT INTO projetablosu(basvuru_no)VALUES(@basvuru_no)", conn))
    {
        cmd.Parameters.Add("@basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
        cmd.ExecuteNonQuery();
    }
}
</code>```

Also note that you can use the constructors to pass all the properties you have set manually in your code, making the code shorter and more readable.

Body:
Well, if it doesn't add the record to the database you can hardly say it works, can you?

You are missing the @ in the parameter. Instead of

cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);

use

cmd.Parameters.Add("@basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;

You should also read Can we stop using AddWithValue() already?

Also, as Artem wrote in his comment, you should dispose your disposable objects. The proper way to do it is with the using statement:

using (var conn = new SqlConnection(@"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True"))
{
    using (var cmd = new SqlCommand("INSERT INTO projetablosu(basvuru_no)VALUES(@basvuru_no)", conn))
    {
        cmd.Parameters.Add("@basvuru_no", SqlDbType.VarChar).Value = textBox1.Text;
        cmd.ExecuteNonQuery();
    }
}

Also note that you can use the constructors to pass all the properties you have set manually in your code, making the code shorter and more readable.


问:
C# String Length returning the wrong amount
I have a string of 13 characters. 8C4B99823CB9C.
I am assigning it to a string.

```<code> string serialNumber = "8C4B99823CB9C";
</code>```

This string then enters a method

```<code>GenerateCode(proxy, serialNumber, product);
</code>```

Inside this method I have this line...

```<code>codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
</code>```

In the watch this is showing the length as 15.

Here is the full code

```<code>[TestMethod]
public void CanGenerateCodeNumberWithPrefixWithHEX()
{
    string serialNumber = "8C4B99823CB9C";
    Entity product = new Entity();
    product.Attributes["piv_codeseriallength"] = 8;
    product.Attributes["piv_codeprefix"] = "G";
    string result = GenerateCode(proxy, serialNumber, product);
    string expected = "G9823CB9C";
    Assert.AreEqual(expected, result, "The Code was not generated correctly");
}

public static string GenerateCode(IOrganizationService _service, string serial_no, Entity product)
{
    string codeSerial = null;
    //Serial Length
    if (product.Attributes.ContainsKey("piv_codeseriallength"))
    {
        codeSerial = serial_no;
        int codeSerialLength = product.GetAttributeValue<int>("piv_codeseriallength");
        codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
        string prefix = product.Attributes.ContainsKey("piv_codeprefix") ? product.GetAttributeValue<string>("piv_codeprefix") : "";
        codeSerial = prefix + codeSerial;
    }
    return codeSerial;
}
</code>```

This unit test fails because it thinks the string is 15 characters long and so taking the wrong section of the string

答:
You have hidden unicode characters in your string. One good way to find out is to copy&paste the full string into a text editor, then try to move the caret left and right along the string. You'll see that you need to press left or right twice around the quotes, meaning that there's more characters then meet the eye. Of course, another way would be simply to open the string in a hexadecimal editor.

Assuming you only need simple characters, you can sanitize your input with a regex, to strip the extra characters:

```<code>var sanitizedInput = Regex.Replace(input, @"[^\w:/ ]", string.Empty);
</code>```

Body:
I have a string of 13 characters. 8C4B99823CB9C.
I am assigning it to a string.

 string serialNumber = "8C4B99823CB9C";

This string then enters a method

GenerateCode(proxy, serialNumber, product);

Inside this method I have this line...

codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);

In the watch this is showing the length as 15.

Here is the full code

[TestMethod]
public void CanGenerateCodeNumberWithPrefixWithHEX()
{
    string serialNumber = "8C4B99823CB9C";
    Entity product = new Entity();
    product.Attributes["piv_codeseriallength"] = 8;
    product.Attributes["piv_codeprefix"] = "G";
    string result = GenerateCode(proxy, serialNumber, product);
    string expected = "G9823CB9C";
    Assert.AreEqual(expected, result, "The Code was not generated correctly");
}

public static string GenerateCode(IOrganizationService _service, string serial_no, Entity product)
{
    string codeSerial = null;
    //Serial Length
    if (product.Attributes.ContainsKey("piv_codeseriallength"))
    {
        codeSerial = serial_no;
        int codeSerialLength = product.GetAttributeValue<int>("piv_codeseriallength");
        codeSerial = serial_no.Substring(serial_no.Length - codeSerialLength, codeSerialLength);
        string prefix = product.Attributes.ContainsKey("piv_codeprefix") ? product.GetAttributeValue<string>("piv_codeprefix") : "";
        codeSerial = prefix + codeSerial;
    }
    return codeSerial;
}

This unit test fails because it thinks the string is 15 characters long and so taking the wrong section of the string

Body:
You have hidden unicode characters in your string. One good way to find out is to copy&paste the full string into a text editor, then try to move the caret left and right along the string. You'll see that you need to press left or right twice around the quotes, meaning that there's more characters then meet the eye. Of course, another way would be simply to open the string in a hexadecimal editor.

Assuming you only need simple characters, you can sanitize your input with a regex, to strip the extra characters:

var sanitizedInput = Regex.Replace(input, @"[^\w:/ ]", string.Empty);


问:
Javascript algorithm to find elements in array that are not in another array
I'm looking for a good algorithm to get all the elements in one array that are not elements in another array.  So given these arrays:

```<code>var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];
</code>```

I want to end up with this array:

```<code>var z = ["d","e","g"];
</code>```

I'm using jquery, so I can take advantage of $.each() and $.inArray(). Here's the solution I've come up with, but it seems like there should be a better way.

```<code>// goal is to get rid of values in y if they exist in x
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];

var z = [];
$.each(y, function(idx, value){
  if ($.inArray(value,x) == -1) {
    z.push(value);
  }
});
alert(z);  // should be ["d","e","g"]
</code>```

Here is the code in action. Any ideas?

答:
in ES6 simply

const a1 = ["a", "b", "c", "t"];
const a2 = ["d", "a", "t", "e", "g"];

console.log( a2.filter(x => !a1.includes(x)) );```

(another option is a2.filter(x => a1.indexOf(x)===-1) )

Body:
I'm looking for a good algorithm to get all the elements in one array that are not elements in another array.  So given these arrays:

var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];

I want to end up with this array:

var z = ["d","e","g"];

I'm using jquery, so I can take advantage of $.each() and $.inArray(). Here's the solution I've come up with, but it seems like there should be a better way.

// goal is to get rid of values in y if they exist in x
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];

var z = [];
$.each(y, function(idx, value){
  if ($.inArray(value,x) == -1) {
    z.push(value);
  }
});
alert(z);  // should be ["d","e","g"]

Here is the code in action. Any ideas?

Body:
in ES6 simply

const a1 = ["a", "b", "c", "t"];
const a2 = ["d", "a", "t", "e", "g"];

console.log( a2.filter(x => !a1.includes(x)) );

(another option is a2.filter(x => a1.indexOf(x)===-1) )

ContentLicense: CC BY-SA 4.0


问:
Database design - defining a basic many-to-one relationship
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

```<code>PrimaryCustomerID  RelationshipID  SecondaryCustomerID
</code>```

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?

答: A third alternative might be for the key to be (PrimaryCustomerId, SecondaryCustomerId), which would make sense if only one type of relationship is permitted per pair of customers. What keys to implement should be defined by what dependencies you need to represent in the table so that the table accurately represents the reality you are modelling. There's nothing wrong in principle with compound keys or all-key tables.</p>

Body:
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

PrimaryCustomerID  RelationshipID  SecondaryCustomerID

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?


问:
What's the difference between "Layers" and "Tiers"?
What's the difference between "Layers" and "Tiers"?</p>

答:
I like the below description from Microsoft Application Architecture Guide 2

Layers describe the logical groupings of the functionality and components in an application; whereas tiers describe the physical distribution of the functionality and components on separate servers, computers, networks, or remote locations. Although both layers and tiers use the same set of names (presentation, business, services, and data), remember that only tiers imply a physical separation.

OwnerDisplayName: cretzel


问:
PHP date function is returning wrong month and date
I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

```<code>$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;
</code>```

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25.
Is there anyone can help me in this??

答:
Its wrong with input, not with date().

```<code>$data['toDate'] = "2017-04-31";// no 31st in 4th(April) month
echo $data['toDate'] ." : ". date('d-m-Y',strtotime($data['toDate']))." ### ";
die;
</code>```

Its just showing up next date which is 01-05-2017

Body:
I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25.
Is there anyone can help me in this??

Body:
Its wrong with input, not with date().

$data['toDate'] = "2017-04-31";// no 31st in 4th(April) month
echo $data['toDate'] ." : ". date('d-m-Y',strtotime($data['toDate']))." ### ";
die;

Its just showing up next date which is 01-05-2017


问:
Clojurescript: Error: Could not find or load main class clojure.main
I installed Clojurescript following its quick start guide.

I pulled the git repo to ~/clojurescript.
CLOJURESCRIPT_HOME is set ~/clojurescript and clojurescript/bin is added to system path.

When I try to use commands cljsc I get following error

Could not find or load main class clojure.main

How can I solve it?

答:
I was going through this tutorial today.

I checked here for this error. The version of the standalone jar was correct. The problem was caused by a 'typing mistake' in the core.cljs file. The string "Hello world!" was not in double quotes. Initially the string was in single quotes and included a comma.

The other issue I struggled with was getting the java command to work. I was using a Cygwin64 Terminal.

The correct command for the Cygwin64 Terminal is:

```<code>$ java -cp "cljs.jar;src" clojure.main build.clj
</code>```

Body:
I was going through this tutorial today.

I checked here for this error. The version of the standalone jar was correct. The problem was caused by a 'typing mistake' in the core.cljs file. The string "Hello world!" was not in double quotes. Initially the string was in single quotes and included a comma.

The other issue I struggled with was getting the java command to work. I was using a Cygwin64 Terminal.

The correct command for the Cygwin64 Terminal is:

$ java -cp "cljs.jar;src" clojure.main build.clj


问:
How to redirect to previous page using own back button?
I am using ng-routing in application in angularjs. I have my own back button. I want to go back to previous page from where I have redirected to this page? Kindly help me?

答:
A simple directive for that

```<code>app.directive('historyBackward', ['$window', function($window) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind('click', function() {
                $window.history.back();
            });
        }
    };
}]);
</code>```

In your HTML

<button history-backward>back</button>

Body:
A simple directive for that

app.directive('historyBackward', ['$window', function($window) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind('click', function() {
                $window.history.back();
            });
        }
    };
}]);

In your HTML

<button history-backward>back</button>