问:
How to transfer the control from one part of the main to another part of the main in java?
I was writing a program which required me to display a set of statements to the

user then ask him whether he would like to return to the main screen.

But since I was using a case I could not transfer control back to the code before it.I want to know how I can do it.Here's the code:

```<code>    import java.io.*;
    public class main
    {
       public static void main() throws IOException
       {
            InputStreamReader isr=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(isr);
            System.out.println("START");
            int ch=Integer.parseInt(br.readLine());
            switch(ch)
            {
                 case 1:System.out.println("HI");
                        break;
                       /*I want a way to transfer the control from the case
                         such that it is transferred to
                         the print statement START.*/

            }
       }
    }
</code>```

答:
This will work and compile (I've changed the main method signature so you can try it).</p>

```<code>import java.io.*;

public class Test {

   public static void main(String[] args) throws IOException{

        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        int ch;
        do {
            System.out.println("START");
            ch=Integer.parseInt(br.readLine());
            switch(ch)
            {
                 case 1:System.out.println("HI");
                 break;
            }
       } while (ch == 1);
        System.out.println("1 was not entered, exiting");
    }
}
</code>```

Body:
I was writing a program which required me to display a set of statements to the

user then ask him whether he would like to return to the main screen.

But since I was using a case I could not transfer control back to the code before it.I want to know how I can do it.Here's the code:

    import java.io.*;
    public class main
    {
       public static void main() throws IOException
       {
            InputStreamReader isr=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(isr);
            System.out.println("START");
            int ch=Integer.parseInt(br.readLine());
            switch(ch)
            {
                 case 1:System.out.println("HI");
                        break;
                       /*I want a way to transfer the control from the case
                         such that it is transferred to
                         the print statement START.*/

            }
       }
    }

Body:
This will work and compile (I've changed the main method signature so you can try it).

import java.io.*;

public class Test {

   public static void main(String[] args) throws IOException{

        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        int ch;
        do {
            System.out.println("START");
            ch=Integer.parseInt(br.readLine());
            switch(ch)
            {
                 case 1:System.out.println("HI");
                 break;
            }
       } while (ch == 1);
        System.out.println("1 was not entered, exiting");
    }
}


来源: stackexchange

问:
Compatible DDL (CREATE TABLE) across different SQL databases?
I'm working on a desktop application that must support (currently) MS Access and SQL Server back ends.  The application is under constant development and changes are frequently being made to the database, mostly the addition of tables and views to support new features (but also some DROPs and ALTER TABLEs to add new columns).

I have a system that compiles the DDL into the executable, checks the database to see if the executable has any new DDL that has to be executed, and executes it.  This works fine for a single database.

My immediate problem is that SQL Server and Access support wildly different names for data types so a CREATE TABLE statement that executes against Access will not execute against SQL Server (or worse, will execute but create a table with different datatypes).

Is there a method that can be used to create DDL (especially CREATE TABLE commands) that can be executed through ADO against both of these databases without having to craft separate DDL for each provider?

答:
I had the same problem.
I resolved it applying a C preproccessor to the SQL before executing it.
The preprocessor includes macros in order to handle the different dbs.

Stefano

ContentLicense: CC BY-SA 2.5


问:
Zero all filesize in a large directory tree (delete file content, keep files)
How can I delete the content (zero the filesize) of a large directory tree (10 GB, 1K files) but keep the entire tree structure, filenames, extensions. (If I can keep the original last write time [last content modification time] that's a bonus).

I have seen several suggestions for individual files, but can not figure out the way to make this work for the entire CWD.

```<code>def deleteContent(fName):
    with open(fName, "w"):
        pass
</code>```

答:
All good answers, but I can see two more challenges with the answers provided:

When traversing over a directory tree, you may want to limit the depth it goes to, this to protect you from very large directory trees. And secondly Windows has a limitation (enforced by Explorer) of 256 characters in the filename and path. While this limitation will produce various OS errors, there is a workaround for this.

Lets start with the workaround for the maximum length of the filepath, you can do something like the following as a workaround:

```<code>import os
import platform

def full_path_windows(filepath):
    """
    Filenames and paths have a default limitation of 256 characters in Windows.
    By inserting '\\\\?\\' at the start of the path it removes this limitation.

    This function inserts '\\\\?\\' at the start of the path, on Windows only
    Only if the path starts with '<driveletter>:\\' e.g 'C:\\'.

    It will also normalise the characters/case of the path.

    """
    if platform.system() == 'Windows':
        if filepath[1:3] == ':\\':
            return u'\\\\?\\' + os.path.normcase(filepath)
    return os.path.normcase(filepath)
</code>```

There are mentions of write protect, or file in use, or any other condition which may result in not being able to write to the file, this can be checked (without actually writing) by the following:

```<code>import os

def write_access(filepath):
    """
    Usage:

    read_access(filepath)

    This function returns True if Write Access is obtained
    This function returns False if Write Access is not obtained
    This function returns False if the filepath does not exists

    filepath = must be an existing file
    """
    if os.path.isfile(filepath):
        return os.access(filepath, os.W_OK)
    return False
</code>```

For setting minimum depth or maximum depth, you can do something like this:

```<code>import os

def get_all_files(rootdir, mindepth = 1, maxdepth = float('inf')):
    """
    Usage:

    get_all_files(rootdir, mindepth = 1, maxdepth = float('inf'))

    This returns a list of all files of a directory, including all files in
    subdirectories. Full paths are returned.

    WARNING: this may create a very large list if many files exists in the
    directory and subdirectories. Make sure you set the maxdepth appropriately.

    rootdir  = existing directory to start
    mindepth = int: the level to start, 1 is start at root dir, 2 is start
               at the sub direcories of the root dir, and-so-on-so-forth.
    maxdepth = int: the level which to report to. Example, if you only want
               in the files of the sub directories of the root dir,
               set mindepth = 2 and maxdepth = 2. If you only want the files
               of the root dir itself, set mindepth = 1 and maxdepth = 1
    """
    file_paths = []
    root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
    for dirpath, dirs, files in os.walk(rootdir):
        depth = dirpath.count(os.path.sep) - root_depth
        if mindepth <= depth <= maxdepth:
            for filename in files:
                file_paths.append(os.path.join(dirpath, filename))
        elif depth > maxdepth:
            del dirs[:]
    return file_paths
</code>```

Now to roll the above code up in a single function, this should give you an idea:

```<code>import os

def clear_all_files_content(rootdir, mindepth = 1, maxdepth = float('inf')):
    not_cleared = []
    root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
    for dirpath, dirs, files in os.walk(rootdir):
        depth = dirpath.count(os.path.sep) - root_depth
        if mindepth <= depth <= maxdepth:
            for filename in files:
                filename = os.path.join(dirpath, filename)
                if filename[1:3] == ':\\':
                    filename = u'\\\\?\\' + os.path.normcase(filename)
                if (os.path.isfile(filename) and os.access(filename, os.W_OK)):
                    with open(filename, 'w'):
                        pass
                else:
                    not_cleared.append(filename)
        elif depth > maxdepth:
            del dirs[:]
    return not_cleared
</code>```

This does not maintain the "last write time".

It will return the list not_cleared, which you can check for files which encountered a write access problem.

ContentLicense: CC BY-SA 3.0

Body:
How can I delete the content (zero the filesize) of a large directory tree (10 GB, 1K files) but keep the entire tree structure, filenames, extensions. (If I can keep the original last write time [last content modification time] that's a bonus).

I have seen several suggestions for individual files, but can not figure out the way to make this work for the entire CWD.

def deleteContent(fName):
    with open(fName, "w"):
        pass

Body:
All good answers, but I can see two more challenges with the answers provided:

When traversing over a directory tree, you may want to limit the depth it goes to, this to protect you from very large directory trees. And secondly Windows has a limitation (enforced by Explorer) of 256 characters in the filename and path. While this limitation will produce various OS errors, there is a workaround for this.

Lets start with the workaround for the maximum length of the filepath, you can do something like the following as a workaround:

import os
import platform

def full_path_windows(filepath):
    """
    Filenames and paths have a default limitation of 256 characters in Windows.
    By inserting '\\\\?\\' at the start of the path it removes this limitation.

    This function inserts '\\\\?\\' at the start of the path, on Windows only
    Only if the path starts with '<driveletter>:\\' e.g 'C:\\'.

    It will also normalise the characters/case of the path.

    """
    if platform.system() == 'Windows':
        if filepath[1:3] == ':\\':
            return u'\\\\?\\' + os.path.normcase(filepath)
    return os.path.normcase(filepath)

There are mentions of write protect, or file in use, or any other condition which may result in not being able to write to the file, this can be checked (without actually writing) by the following:

import os

def write_access(filepath):
    """
    Usage:

    read_access(filepath)

    This function returns True if Write Access is obtained
    This function returns False if Write Access is not obtained
    This function returns False if the filepath does not exists

    filepath = must be an existing file
    """
    if os.path.isfile(filepath):
        return os.access(filepath, os.W_OK)
    return False

For setting minimum depth or maximum depth, you can do something like this:

import os

def get_all_files(rootdir, mindepth = 1, maxdepth = float('inf')):
    """
    Usage:

    get_all_files(rootdir, mindepth = 1, maxdepth = float('inf'))

    This returns a list of all files of a directory, including all files in
    subdirectories. Full paths are returned.

    WARNING: this may create a very large list if many files exists in the
    directory and subdirectories. Make sure you set the maxdepth appropriately.

    rootdir  = existing directory to start
    mindepth = int: the level to start, 1 is start at root dir, 2 is start
               at the sub direcories of the root dir, and-so-on-so-forth.
    maxdepth = int: the level which to report to. Example, if you only want
               in the files of the sub directories of the root dir,
               set mindepth = 2 and maxdepth = 2. If you only want the files
               of the root dir itself, set mindepth = 1 and maxdepth = 1
    """
    file_paths = []
    root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
    for dirpath, dirs, files in os.walk(rootdir):
        depth = dirpath.count(os.path.sep) - root_depth
        if mindepth <= depth <= maxdepth:
            for filename in files:
                file_paths.append(os.path.join(dirpath, filename))
        elif depth > maxdepth:
            del dirs[:]
    return file_paths

Now to roll the above code up in a single function, this should give you an idea:

import os

def clear_all_files_content(rootdir, mindepth = 1, maxdepth = float('inf')):
    not_cleared = []
    root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
    for dirpath, dirs, files in os.walk(rootdir):
        depth = dirpath.count(os.path.sep) - root_depth
        if mindepth <= depth <= maxdepth:
            for filename in files:
                filename = os.path.join(dirpath, filename)
                if filename[1:3] == ':\\':
                    filename = u'\\\\?\\' + os.path.normcase(filename)
                if (os.path.isfile(filename) and os.access(filename, os.W_OK)):
                    with open(filename, 'w'):
                        pass
                else:
                    not_cleared.append(filename)
        elif depth > maxdepth:
            del dirs[:]
    return not_cleared

This does not maintain the "last write time".

It will return the list not_cleared, which you can check for files which encountered a write access problem.


问:
Appcelerator app crash after taking picture
My app crashes after taking a picture with the camera.
This has never happened before Using titanium SDK 6.3.0 on iOS 11.
Does anyone have a solution?
thanks </p>

```<code>Titanium.Media.showCamera({
                        success: function(event) {
                            lObjPhoto = event.media;
                            parameters.callbackApply(lObjPhoto);
                        },
                        cancel: function() {
                            lObjPhoto = null;
                            lObjThumb = null;
                            parameters.callbackApply(lObjPhoto);
                        },
                        error: function(error) {
                                lObjPhoto = null;
                                var a = Titanium.UI.createAlertDialog({title:'Camera', ok: 'Ok'});
                                if (error.code == Titanium.Media.NO_CAMERA) a.setMessage('Device does not have camera');
                                else a.setMessage('Unexpected error: ' + error.code);
                                a.show();
                                parameters.callbackApply(lObjPhoto);
                        },
                        allowImageEditing: false,
                        saveToPhotoGallery: false,
                    })
</code>```

答:
Make sure you are using these properties in tiapp.xml: NSPhotoLibraryUsageDescription and NSCameraUsageDescription.</p>

```<code>    <ios>
        ...
        <plist>
            <dict>
                ...
                <key>NSPhotoLibraryUsageDescription</key>
                <string>Gallery permissions required</string>
                <key>NSCameraUsageDescription</key>
                <string>Camera permissions required</string>
            </dict>
        </plist>
    </ios>
</code>```

Body:
My app crashes after taking a picture with the camera.
This has never happened before Using titanium SDK 6.3.0 on iOS 11.
Does anyone have a solution?
thanks

Titanium.Media.showCamera({
                        success: function(event) {
                            lObjPhoto = event.media;
                            parameters.callbackApply(lObjPhoto);
                        },
                        cancel: function() {
                            lObjPhoto = null;
                            lObjThumb = null;
                            parameters.callbackApply(lObjPhoto);
                        },
                        error: function(error) {
                                lObjPhoto = null;
                                var a = Titanium.UI.createAlertDialog({title:'Camera', ok: 'Ok'});
                                if (error.code == Titanium.Media.NO_CAMERA) a.setMessage('Device does not have camera');
                                else a.setMessage('Unexpected error: ' + error.code);
                                a.show();
                                parameters.callbackApply(lObjPhoto);
                        },
                        allowImageEditing: false,
                        saveToPhotoGallery: false,
                    })

Body:
Make sure you are using these properties in tiapp.xml: NSPhotoLibraryUsageDescription and NSCameraUsageDescription.

    <ios>
        ...
        <plist>
            <dict>
                ...
                <key>NSPhotoLibraryUsageDescription</key>
                <string>Gallery permissions required</string>
                <key>NSCameraUsageDescription</key>
                <string>Camera permissions required</string>
            </dict>
        </plist>
    </ios>


问:
HttpTwo client on server 2008 (APNS with JWT)
EDIT - Due to probable misintepretation:
This is not about the server side of HTTP/2 - its about a client HTTP/2 request from an older server OS. Also, i got it to work using python (gobiko.apns) , so it seems to me it should be possible.

EDIT 2
It seems this question has not so much to do with HTTP2, but rather the cipher required by apple. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 is not used by the SslStream in versions pre-win10. However, since it can be done using python, it seems to me that it should be possible. Any help would be appreciated.

We found some code here and there to get our connection to the APNS working on our development environment. We are using the .p8 certificate and sign a token as authorization (not the 'old' interface).

This works on my dev pc (win10) but when i transfer it to a server 2008 R2 it gives a weird warning. It seems having to do with the setup of the tls connection, however, i'm not too familiar with that area. I really searched but the only thing i can come up with is that server 2008R2 will not support it due to ciphers or something (which seems unreasonable to me).

The code that is working from my pc (using nuget HttpTwo and Newtonsoft):

```<code>    public static async void Send2(string jwt, string deviceToken)
    {
        var uri = new Uri($"https://{host}:443/3/device/{deviceToken}");

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback = delegate
        {
            Console.WriteLine("ServerCertificateValidationCallback");
            return true;
        };

        string payloadData = Newtonsoft.Json.JsonConvert.SerializeObject(new
        {
            aps = new
            {
                alert = new
                {
                    title = "hi",
                    body = "works"
                }
            }
        });

        //PayloadData always in UTF8 encoding
        byte[] data = System.Text.Encoding.UTF8.GetBytes(payloadData);

        var httpClient = new Http2Client(uri);
        var headers = new NameValueCollection();

        headers.Add("authorization", string.Format("bearer {0}", jwt));
        headers.Add("apns-id", Guid.NewGuid().ToString());
        headers.Add("apns-expiration", "0");
        headers.Add("apns-priority", "10");
        headers.Add("apns-topic", bundleId);

        try
        {
            var responseMessage = await httpClient.Send(uri, HttpMethod.Post, headers, data);
            if (responseMessage.Status == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Send Success");
                return;
            }
            else
            {
                Console.WriteLine("failure {0}", responseMessage.Status);

                return;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("ex");
            Console.WriteLine(ex.ToString());
            return;
        }
    }
</code>```

is throwing

```<code>System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted
</code>```

from server 2008R2.

I also tried it with a WinHttpHandler, which also works from my PC, but throws

```<code>System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: A security error occurred
</code>```

Stacktraces are mostly async thingies, but it boils down to HttpTwo.Http2Connection.<Connect> for the HttpTwo implementation and System.Net.Http.WinHttpHandler.<StartRequest> for the WinHttpHandler.

Is there something i have to add to the server in order to work / will we get it to work?

UPDATE
I included the sourcefiles from HttpTwo in my project and debugged it. The exception occurs on

```<code>      await sslStream.AuthenticateAsClientAsync (
                ConnectionSettings.Host,
                ConnectionSettings.Certificates ?? new X509CertificateCollection (),
                System.Security.Authentication.SslProtocols.Tls12,
                false).ConfigureAwait (false);
</code>```

on my Win8 test pc. Now, when i use the method overload with only the host argument on my own PC it throws the same exception, i guess because the tls protocol is off then.

According to this Github issue it could have to do with the ciphers. I had some problems before in that area, but it seems to me that at least a WIN8 PC must be able to agree upon secure enough ciphers, right?

Schannel is complaining about "A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.", so that points into that direction also afaik.

答:
It's the cipher... The ciphers Apple uses are not included into SChannel below Win10/Server2016.
(see Edit 2)</p>

Body:
EDIT - Due to probable misintepretation:
This is not about the server side of HTTP/2 - its about a client HTTP/2 request from an older server OS. Also, i got it to work using python (gobiko.apns) , so it seems to me it should be possible.

EDIT 2
It seems this question has not so much to do with HTTP2, but rather the cipher required by apple. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 is not used by the SslStream in versions pre-win10. However, since it can be done using python, it seems to me that it should be possible. Any help would be appreciated.

We found some code here and there to get our connection to the APNS working on our development environment. We are using the .p8 certificate and sign a token as authorization (not the 'old' interface).

This works on my dev pc (win10) but when i transfer it to a server 2008 R2 it gives a weird warning. It seems having to do with the setup of the tls connection, however, i'm not too familiar with that area. I really searched but the only thing i can come up with is that server 2008R2 will not support it due to ciphers or something (which seems unreasonable to me).

The code that is working from my pc (using nuget HttpTwo and Newtonsoft):

    public static async void Send2(string jwt, string deviceToken)
    {
        var uri = new Uri($"https://{host}:443/3/device/{deviceToken}");

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback = delegate
        {
            Console.WriteLine("ServerCertificateValidationCallback");
            return true;
        };

        string payloadData = Newtonsoft.Json.JsonConvert.SerializeObject(new
        {
            aps = new
            {
                alert = new
                {
                    title = "hi",
                    body = "works"
                }
            }
        });

        //PayloadData always in UTF8 encoding
        byte[] data = System.Text.Encoding.UTF8.GetBytes(payloadData);

        var httpClient = new Http2Client(uri);
        var headers = new NameValueCollection();

        headers.Add("authorization", string.Format("bearer {0}", jwt));
        headers.Add("apns-id", Guid.NewGuid().ToString());
        headers.Add("apns-expiration", "0");
        headers.Add("apns-priority", "10");
        headers.Add("apns-topic", bundleId);

        try
        {
            var responseMessage = await httpClient.Send(uri, HttpMethod.Post, headers, data);
            if (responseMessage.Status == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Send Success");
                return;
            }
            else
            {
                Console.WriteLine("failure {0}", responseMessage.Status);

                return;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("ex");
            Console.WriteLine(ex.ToString());
            return;
        }
    }

is throwing

System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted

from server 2008R2.

I also tried it with a WinHttpHandler, which also works from my PC, but throws

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: A security error occurred

Stacktraces are mostly async thingies, but it boils down to HttpTwo.Http2Connection.<Connect> for the HttpTwo implementation and System.Net.Http.WinHttpHandler.<StartRequest> for the WinHttpHandler.

Is there something i have to add to the server in order to work / will we get it to work?

UPDATE
I included the sourcefiles from HttpTwo in my project and debugged it. The exception occurs on

      await sslStream.AuthenticateAsClientAsync (
                ConnectionSettings.Host,
                ConnectionSettings.Certificates ?? new X509CertificateCollection (),
                System.Security.Authentication.SslProtocols.Tls12,
                false).ConfigureAwait (false);

on my Win8 test pc. Now, when i use the method overload with only the host argument on my own PC it throws the same exception, i guess because the tls protocol is off then.

According to this Github issue it could have to do with the ciphers. I had some problems before in that area, but it seems to me that at least a WIN8 PC must be able to agree upon secure enough ciphers, right?

Schannel is complaining about "A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.", so that points into that direction also afaik.


问:
Issue in converting date format
I have assigned the value of date to a dictionary like so...

```<code>userDetailsDictionary["birth_date"] = "\(birthDateVar)"
</code>```

Now this gives the date in dd-mm-yyyy. But I want the date in yyyy-mm-dd. For that I tried something like this...

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let bday = dateFormatter.date(from: birthDateVar)
dateFormatter.dateFormat = "yyyy-MM-dd"
let bdayString = dateFormatter.string(from: bday!)
</code>```

Though birthDateVar has the value in it, while I'm trying to convert it, it is showing as nil and so bday is becoming nil. Confused as to what the reason is...

答:
change your date format from

```<code>dateFormatter.dateFormat = "MM-dd-yyyy"
</code>```

to

```<code>dateFormatter.dateFormat = "dd-MM-yyyy"
</code>```

Updated answer

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
let bday = dateFormatter.date(from: birthDateVar)
dateFormatter.dateFormat = "yyyy-MM-dd"
let bdayString = dateFormatter.string(from: bday!)
</code>```

Title: Issue in converting date format

Body:
I have assigned the value of date to a dictionary like so...

userDetailsDictionary["birth_date"] = "\(birthDateVar)"

Now this gives the date in dd-mm-yyyy. But I want the date in yyyy-mm-dd. For that I tried something like this...

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let bday = dateFormatter.date(from: birthDateVar)
dateFormatter.dateFormat = "yyyy-MM-dd"
let bdayString = dateFormatter.string(from: bday!)

Though birthDateVar has the value in it, while I'm trying to convert it, it is showing as nil and so bday is becoming nil. Confused as to what the reason is...

Body:
change your date format from

dateFormatter.dateFormat = "MM-dd-yyyy"

to

dateFormatter.dateFormat = "dd-MM-yyyy"

Updated answer

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
let bday = dateFormatter.date(from: birthDateVar)
dateFormatter.dateFormat = "yyyy-MM-dd"
let bdayString = dateFormatter.string(from: bday!)


问:
How to use PactJS with Angular 2/4/5 to tests services
I'm trying to use PactJS to test some of my Angular Services.  I'm using:

```<code>"@pact-foundation/karma-pact": "^2.1.1",
"pact": "^4.2.1",
"pact-web": "^4.2.1",
</code>```

I can't get the test to run successfully.  Without using async the subscribe callback never gets hit and if I do use async then Pact fails.  This is my code:

```<code>import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ApiService } from '../index';
import { HttpParams } from '@angular/common/http';
import { Group } from '../../grouping/model';
let Pact = require('pact-web');

describe('ApiService', () => {

  let provider;

  beforeAll((done) => {
    provider = Pact({
      consumer: 'client',
      provider: 'server',
      web: true
    });

    // required for slower CI environments
    setTimeout(done, 2000);

    // Required if run with `singleRun: false`
    provider.removeInteractions();
  });

  afterAll((done) => {
    provider.finalize().then(done, e => done.fail(e));
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        ApiService
      ]
    });
  }));

  afterEach((done) => {
    provider.verify().then(done, e => done.fail(e));
  });

  describe('Get all Groups', () => {

    beforeAll((done) => {
      provider.addInteraction({
        given: 'groups exist',
        uponReceiving: 'a request to get groups',
        withRequest: {
          method: 'GET',
          path: '/api/groups'
        },
        willRespondWith: {
          status: 200,
          headers: {'Content-Type': 'application/json'},
          body: [{
            id: Pact.Matchers.somethingLike(1),
            name: Pact.Matchers.somethingLike('a group name'),
            disabled: Pact.Matchers.somethingLike(false),
          }]
        }
      }).then(done, e => done.fail(e));
    });

    it('should return all groups from API', (done) => {

      const apiService: ApiService = TestBed.get(ApiService);
      const groups: Group[] = [{
        id: 1,
        name: false,
        disabled: false
      }];

      apiService.getGroups().subscribe((response: Group[]) => {
        expect(response).toEqual(groups);
        done()
      });
    });
  });
});
</code>```

And the errors I get:

```<code>Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Failed: Actual interactions do not match expected interactions for mock MockService.

Missing requests:
    GET /api/groups

See standard out/err for details.
</code>```

I have been following these two projects

https://paucls.wordpress.com/2017/08/04/pact-consumer-driven-contract-implementation-in-angular/

https://github.com/koelec/angular-pact-example

Has anyone managed to successfully implement PactJS with Angular or what am I missing to get this working?

答:
Your test structure looks good.  One way to validate what is happening is to review the logs for the mock server. That error message is pretty clear - it didn't get a request it was expecting.

If HttpClientTestingModule doesn't actually make a real call, then Pact will fail as it is expecting an interaction - this is how we confirm details of the contract that the Provider needs to comply with. If It's mocked out, we don't get the request and can't confirm your code calls what you expect it to.

So. Make sure your tests do in fact make a real HTTP call, and check that they do in fact hit the Mock Server in the right order with the right details (by checking the logs).

Body:
I'm trying to use PactJS to test some of my Angular Services.  I'm using:

"@pact-foundation/karma-pact": "^2.1.1",
"pact": "^4.2.1",
"pact-web": "^4.2.1",

I can't get the test to run successfully.  Without using async the subscribe callback never gets hit and if I do use async then Pact fails.  This is my code:

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ApiService } from '../index';
import { HttpParams } from '@angular/common/http';
import { Group } from '../../grouping/model';
let Pact = require('pact-web');

describe('ApiService', () => {

  let provider;

  beforeAll((done) => {
    provider = Pact({
      consumer: 'client',
      provider: 'server',
      web: true
    });

    // required for slower CI environments
    setTimeout(done, 2000);

    // Required if run with `singleRun: false`
    provider.removeInteractions();
  });

  afterAll((done) => {
    provider.finalize().then(done, e => done.fail(e));
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        ApiService
      ]
    });
  }));

  afterEach((done) => {
    provider.verify().then(done, e => done.fail(e));
  });

  describe('Get all Groups', () => {

    beforeAll((done) => {
      provider.addInteraction({
        given: 'groups exist',
        uponReceiving: 'a request to get groups',
        withRequest: {
          method: 'GET',
          path: '/api/groups'
        },
        willRespondWith: {
          status: 200,
          headers: {'Content-Type': 'application/json'},
          body: [{
            id: Pact.Matchers.somethingLike(1),
            name: Pact.Matchers.somethingLike('a group name'),
            disabled: Pact.Matchers.somethingLike(false),
          }]
        }
      }).then(done, e => done.fail(e));
    });

    it('should return all groups from API', (done) => {

      const apiService: ApiService = TestBed.get(ApiService);
      const groups: Group[] = [{
        id: 1,
        name: false,
        disabled: false
      }];

      apiService.getGroups().subscribe((response: Group[]) => {
        expect(response).toEqual(groups);
        done()
      });
    });
  });
});

And the errors I get:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Failed: Actual interactions do not match expected interactions for mock MockService.

Missing requests:
    GET /api/groups

See standard out/err for details.

I have been following these two projects

https://paucls.wordpress.com/2017/08/04/pact-consumer-driven-contract-implementation-in-angular/

https://github.com/koelec/angular-pact-example

Has anyone managed to successfully implement PactJS with Angular or what am I missing to get this working?


问:
Reduce time waiting for FTP connection with FtpWebRequest
I'm testing the connection to an FTP server from my c# .NET application which is working. If a connection can be made or the server address is invalid then the response is instant. However, it is very slow if the credentials are valid but no connection can be made.
How can I reduce the timeout time on this?

FTP test code:

```<code>try
{
    FtpWebRequest ftpRequest =
        (FtpWebRequest)WebRequest.Create(new Uri("ftp://"+ftpServer+"/"));
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
    ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    ftpRequest.GetResponse();

    MessageBox.Show("OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error");
}
</code>```

Thanks

答:
Specify a timeout using FtpWebRequest.Timeout.

Or use an asynchronous request using WebRequest.GetResponseAsync.

Then, you can control, how long you wait for an asynchronous response any way you like.

Body:
I'm testing the connection to an FTP server from my c# .NET application which is working. If a connection can be made or the server address is invalid then the response is instant. However, it is very slow if the credentials are valid but no connection can be made.
How can I reduce the timeout time on this?

FTP test code:

try
{
    FtpWebRequest ftpRequest =
        (FtpWebRequest)WebRequest.Create(new Uri("ftp://"+ftpServer+"/"));
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
    ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    ftpRequest.GetResponse();

    MessageBox.Show("OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error");
}

Thanks

ContentLicense: CC BY-SA 4.0


问:
Implementation of quartic equation solver doesn't work
What's going wrong with my implementation of a quartic equation solver?

Here is my code on GitHub. I followed this: http://www.1728.com/quartic2.htm

In fact the real implementation starts at line 271, where I create the monic poly.

If I try it with a polynomial with 4 real roots it works fine (for example with 3x^4 + 6x^3 - 123x^2 - 126x + 1,080), otherwise gives wrong roots.

Thanks,

rubik

P.S. I called the function __quartic because it is still in development

答:
If it isn't a problem with your cubic solver (as phkahler suggested), then I'm betting that it is a case of int division in these lines:

```<code>f = float(c - (3*b**2 / 8))
g = float(d + (b**3/ 8) - (b*c / 2))
h = e - (3*b**4 / 256) + (b**2 * c / 16) - (b*d / 4)
</code>```

If you are using a version of Python that is less than 3.0 and not importing division from __future__, then you can have major problems here. For instance, if b = 3, then (3*b**2/8) is equal to 3 by int division rather than the correct float division value of 3.375. Probably the best way to correct this is to convert a,b,c,d and e to floats before you start doing calculations. Your conversion to float after all of the calculations for f and g are really unnecessary after you've made this correction and they aren't really helping you much now.

For more information about this division issue and its history see:

http://www.python.org/dev/peps/pep-0238/

http://python-history.blogspot.com/2009/03/problem-with-integer-division.html

Body:
If it isn't a problem with your cubic solver (as phkahler suggested), then I'm betting that it is a case of int division in these lines:

f = float(c - (3*b**2 / 8))
g = float(d + (b**3/ 8) - (b*c / 2))
h = e - (3*b**4 / 256) + (b**2 * c / 16) - (b*d / 4)

If you are using a version of Python that is less than 3.0 and not importing division from __future__, then you can have major problems here. For instance, if b = 3, then (3*b**2/8) is equal to 3 by int division rather than the correct float division value of 3.375. Probably the best way to correct this is to convert a,b,c,d and e to floats before you start doing calculations. Your conversion to float after all of the calculations for f and g are really unnecessary after you've made this correction and they aren't really helping you much now.

For more information about this division issue and its history see:

http://www.python.org/dev/peps/pep-0238/

http://python-history.blogspot.com/2009/03/problem-with-integer-division.html


问:
Git move files from 1 branch to another
I am working with git using git-flow.

I was working in the branchA, I modified some file, but these files were supposed to be modified in a branch of a new feature that I haven't created  yet. Is there a way to fix it?

答:
Yes there is, you can soft reset the commit you did to the invalid branch, then stash the changes you introduced and execute

```<code>git stash branch feature/<wahetever>
</code>```

This way, through stash you can move the changes. Another way is to start new feature branch and with cherry-pick move the commits that should be in the new branch.

Title: Git move files from 1 branch to another

Body:
Yes there is, you can soft reset the commit you did to the invalid branch, then stash the changes you introduced and execute

git stash branch feature/<wahetever>

This way, through stash you can move the changes. Another way is to start new feature branch and with cherry-pick move the commits that should be in the new branch.


问:
How to set value of textbox created in code behind in javascript
I'm creating a textbox in the code behind:

```<code>TextBox txt = new TextBox();
txt.ID = "txtRef" + count + dr["DataField"].ToString();
div.Controls.Add(txt);
</code>```

And I'm trying to set the value for this textbox in a jquery function but nothing I have tried so far is updating the textbox.

Using document.getElementById('txtRef1j.3rdPartRef').value = 'test'; returns the error Cannot set property 'value' of null.

I also tried $('#txtRef1j.3rdPartRef').val('test') and $('[id$="txtRef1j.3rdPartRef"]').value = 'test'; but the textbox doesn't update.

答:
Try it: $('[id$="txtRef1j.3rdPartRef"]')[0].value  = 'test';
or document.getElementById('txtRef1j.3rdPartRef')[0].value = 'test'; or
$('[id$="txtRef1j.3rdPartRef"]').get(0).value  = 'test';  or

```<code>    document.querySelector('[id$="txtRef1j.3rdPartRef').value = 'test'
</code>```

or

```<code>$('[id$="txtRef1j.3rdPartRef"]').val('test');`
</code>```

You have errors because jquery object don't has property value,only Dom element has proerty value . When you use document.getElementById,  you get NodeList , it is not a Dom-Element. You can read:  https://developer.mozilla.org/en-US/docs/Web/API/NodeList

Body:
I'm creating a textbox in the code behind:

TextBox txt = new TextBox();
txt.ID = "txtRef" + count + dr["DataField"].ToString();
div.Controls.Add(txt);

And I'm trying to set the value for this textbox in a jquery function but nothing I have tried so far is updating the textbox.

Using document.getElementById('txtRef1j.3rdPartRef').value = 'test'; returns the error Cannot set property 'value' of null.

I also tried $('#txtRef1j.3rdPartRef').val('test') and $('[id$="txtRef1j.3rdPartRef"]').value = 'test'; but the textbox doesn't update.

Body:
Try it: $('[id$="txtRef1j.3rdPartRef"]')[0].value  = 'test';
or document.getElementById('txtRef1j.3rdPartRef')[0].value = 'test'; or
$('[id$="txtRef1j.3rdPartRef"]').get(0).value  = 'test';  or

    document.querySelector('[id$="txtRef1j.3rdPartRef').value = 'test'

or

$('[id$="txtRef1j.3rdPartRef"]').val('test');`

You have errors because jquery object don't has property value,only Dom element has proerty value . When you use document.getElementById,  you get NodeList , it is not a Dom-Element. You can read:  https://developer.mozilla.org/en-US/docs/Web/API/NodeList


问:
java EE installation and setup
I need to develop a simple email client in Java. I will be using JavaMail APIs of Java EE. I installed NetBeans that supports Java EE from this site:

http://netbeans.org/downloads/

If I select the option of creating a Java EE application while creating project, I dont get the drag-n-drop feature of creating GUI with swings. And if I select Java Desktop Application I get the GUI building features but then Java EE libraries are not available. How can I use these two simultaneously?

Also, the NetBeans installer seems to install Java EE SDK. In which folder is this SDK installed?

I have experience of using Java SE but I am totally new to Java EE. Please help me.

答: Java EE are just libraries (no additional language constructs and support), the best solution for you is to download somewhere *.jar you need and add it to your libraries (directly or via maven).</p>

Title: java EE installation and setup


问:
Python Requests Module Doesn't Fetch All The Elements It Ought To
This piece of code works properly

```<code>from lxml import html
import requests
page = requests.get(c)
tree = html.fromstring(page.content)
link = tree.xpath('//script/text()')
</code>```

But it doesn't fetch the whole content. Like it is hidden or something.

I can see this is the case because the next thing I do is this

```<code>print len(link)
</code>```

and it returns nine (9)

I then go to the page, which is the string c, above in the code. I go to the source (view-source:) with mozilla. And I hit ctr+f and I write

答:
If you try

```<code>tree.xpath('//script')
</code>```

I hope you will get 33 matches.

On your page only nine  elements contain something between the opening and closing tags.

Body:
This piece of code works properly

from lxml import html
import requests
page = requests.get(c)
tree = html.fromstring(page.content)
link = tree.xpath('//script/text()')

But it doesn't fetch the whole content. Like it is hidden or something.

I can see this is the case because the next thing I do is this

print len(link)

and it returns nine (9)

I then go to the page, which is the string c, above in the code. I go to the source (view-source:) with mozilla. And I hit ctr+f and I write

Body:
If you try

tree.xpath('//script')

I hope you will get 33 matches.

On your page only nine  elements contain something between the opening and closing tags.


问:
how group the result based on some condition into concatenated results
i want to group my results based on timestamp.

Demo : http://sqlfiddle.com/#!9/ab315b/1

for example if date is 14 having 3 results then i want my output like below

```<code>+                                  results                                                         +
|                                                                                |
+--------------------------------------------------------------------------------------------------+
|   <td> 14</td><td>project name1</td><td><p>project desc 1</p></td><td>created at 1</td>          |
|    <td> 13</td><td>project name2</td><td><p>project desc 2</p></td><td>created at 2</td>
|    <td> 12</td><td>project name3</td><td><p>project desc 3</p></td><td>created at 2</td>
+-------------------------------------------------------------------------------------------------
|                                other results of same date like 13                               |
+-------------------------------------------------------------------------------------------------+
</code>```

ACCORDING TO BELOW IMAGE AND QUERY:

here i have put my for execution: http://sqlfiddle.com/#!9/ab315b/1

Please help me
Thanks in Advance !!!!

答:
You can use Group_concat to concatenate multiple lines here. Something like

```<code>SELECT created_at, Group_concat(project_desc, ' ') FROM work_desc
Group By CAST(created_at AS DATE)
ORDER BY created_at DESC;
</code>```

its output looks like

```<code>created_at  Group_concat(project_desc, ' ')
2017-11-14T10:18:54Z    this my first day report employeee 2222 ,this my first day report employeee 33333 ,this my first day report employeee 44444
2017-11-12T18:30:00Z    this my yesterday day report employeee 2222 ,this my yesterday day report employeee 33333
</code>```

You can work out a bit to generate the output you are looking for I believe.

EDIT

I believe this returns the output you are looking for

```<code>SELECT concat(Group_concat(concat('<tr><td>', project_name,
                           '</td><td>', project_desc, '</td>')
                    SEPARATOR '</tr>'), '</tr>')
FROM work_desc GROUP BY CAST(created_at AS DATE)
ORDER BY created_at DESC
</code>```

Hope this helps.

Body:
i want to group my results based on timestamp.

Demo : http://sqlfiddle.com/#!9/ab315b/1

for example if date is 14 having 3 results then i want my output like below

+                                  results                                                         +
|                                                                                |
+--------------------------------------------------------------------------------------------------+
|    14	project name1
project desc 1
	created at 1	          |
|     13	project name2
project desc 2
	created at 2
|     12	project name3
project desc 3
	created at 2
+-------------------------------------------------------------------------------------------------
|                                other results of same date like 13                               |
+-------------------------------------------------------------------------------------------------+

ACCORDING TO BELOW IMAGE AND QUERY:

here i have put my for execution: http://sqlfiddle.com/#!9/ab315b/1

Please help me
Thanks in Advance !!!!

Body:
You can use Group_concat to concatenate multiple lines here. Something like

SELECT created_at, Group_concat(project_desc, ' ') FROM work_desc
Group By CAST(created_at AS DATE)
ORDER BY created_at DESC;

its output looks like

created_at  Group_concat(project_desc, ' ')
2017-11-14T10:18:54Z    this my first day report employeee 2222 ,this my first day report employeee 33333 ,this my first day report employeee 44444
2017-11-12T18:30:00Z    this my yesterday day report employeee 2222 ,this my yesterday day report employeee 33333

You can work out a bit to generate the output you are looking for I believe.

EDIT

I believe this returns the output you are looking for

SELECT concat(Group_concat(concat('<tr><td>', project_name,
                           '</td><td>', project_desc, '</td>')
                    SEPARATOR '</tr>'), '</tr>')
FROM work_desc GROUP BY CAST(created_at AS DATE)
ORDER BY created_at DESC

Hope this helps.


问:
Make div overlap horizontally the other 4 divs and stretch across the page(height 100%?)
So i have 4 different divs with buttons in them and I'm trying to set up so whenever one of those buttons are being clicked, it will overlap the other divs on the page.

I know it has something to do with z-index and positioning of the divs but I guess it needs to be added to the Jquery rather than the CSS?

I have checked out a previous code, where the divs overlap eachother vertically. Here's that code:

$('#divleft, #divmid, #divright').toggle(function () {
  var cfg = {height:'200', width:'100%'};
  $(this).css({'z-index':100});
  var pct = $(this).css('left').split('p')[0]/$(document).width();

  if(pct <= .33 && pct > 0){
    cfg.left = '0';
    $(this).data('oldLeft', "33%");
  } else if(pct <= .66 && pct > .33) {
    cfg.left = '0';
    $(this).data('oldLeft', "66%");
  }
  $(this).animate(cfg)
}, function () {
  var cfg= {height:'200', width:'33%', 'z-index':1};

  if ($(this).data('oldLeft')) {
    console.log($(this).data('oldLeft'));
    cfg.left = $(this).data('oldLeft');
  }
  $(this).animate(cfg)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#divleft {
  width:33.3%;
  height:200px;
  background:#ccc;
  z-index: 1;
  margin-top: 10px;
  position: absolute;
  left:0;
}

#divmid {
  width:33.3%;
  height: 200px;
  background: #696;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:33%;
}

#divright {
  width:33.3%;
  height:200px;
  background:#000;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:66%;
}</code>```

Click Me!

```
</div>
</div>
</p>

<p>What this code does is that it overlaps the divs using width 100%, vertically. I was just wondering how you would go about if you were to overlap the divs horizontally. </p>

<p>My code so far is this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  width: 80%;
  margin: 0 auto;
}

head {
  text-align:left;
}

head, img {
  width: 350px;
  height: 100px;
  float: left;
  margin-bottom: 1%;
}

.container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

button {
  background-color: #cccccc;
  color: #000000;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  padding-left: 15%;
  outline: none;
  font-size: 17px;
  transition: 0.4s;
  margin-top: 2%;
}

.icon {
  width: 25px;
  height: 25px;
  padding-right: 15%;
  float: right;
}

button.accordion.active, button.accordion:hover {
  background-color: #ddd;
}</code>```

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

```

Thanks!

答:
great solution and thanks for quick response! Just wondering where I would place my jquery code?

$('.container div').click(function(event){
  $(this).toggleClass('active');

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body{
    width: 80%;
    margin: 0 auto;
}

head{
    text-align:left;
}

head, img{
    width: 350px;
    height: 100px;
    float: left;
    margin-bottom: 1%;
}

.container{
    width: 100%;
    height: 100%;
    margin: 0 auto;
    position: relative;
}

button{
    background-color: #cccccc;
    color: #000000;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    padding-left: 15%;
    outline: none;
    font-size: 17px;

    margin-top: 2%;
    position: relative;
}

button h3{
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.icon {
    height: 2.5em;
    width: 1.7em;
    float: right;
}

.icon {
    background-image: url(https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=1b3cdae197be);
}

.container div.active{
 height: 100%;
 background-color: white;
 position:absolute;
 top:0;
 left:0;
 width: 100%;
 z-index: 2;
}
.container div.active button{
   height: 100%;
}
#first,#second,#third,#fourth,#last{
}</code>```

        <button>
Random

</button>

        <button>
Random

</button>

        <button>
Random

</button>

        <button>
Random

</button>

        <button>
Random

</button>

```

Body:
So i have 4 different divs with buttons in them and I'm trying to set up so whenever one of those buttons are being clicked, it will overlap the other divs on the page.

I know it has something to do with z-index and positioning of the divs but I guess it needs to be added to the Jquery rather than the CSS?

I have checked out a previous code, where the divs overlap eachother vertically. Here's that code:

$('#divleft, #divmid, #divright').toggle(function () {
  var cfg = {height:'200', width:'100%'};
  $(this).css({'z-index':100});
  var pct = $(this).css('left').split('p')[0]/$(document).width();

  if(pct <= .33 && pct > 0){
    cfg.left = '0';
    $(this).data('oldLeft', "33%");
  } else if(pct <= .66 && pct > .33) {
    cfg.left = '0';
    $(this).data('oldLeft', "66%");
  }
  $(this).animate(cfg)
}, function () {
  var cfg= {height:'200', width:'33%', 'z-index':1};

  if ($(this).data('oldLeft')) {
    console.log($(this).data('oldLeft'));
    cfg.left = $(this).data('oldLeft');
  }
  $(this).animate(cfg)
})

#divleft {
  width:33.3%;
  height:200px;
  background:#ccc;
  z-index: 1;
  margin-top: 10px;
  position: absolute;
  left:0;
}

#divmid {
  width:33.3%;
  height: 200px;
  background: #696;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:33%;
}

#divright {
  width:33.3%;
  height:200px;
  background:#000;
  margin-top: 10px;
  z-index: 1;
  position:absolute;
  left:66%;
}

Click Me!

What this code does is that it overlaps the divs using width 100%, vertically. I was just wondering how you would go about if you were to overlap the divs horizontally.

My code so far is this:

html, body {
  width: 80%;
  margin: 0 auto;
}

head {
  text-align:left;
}

head, img {
  width: 350px;
  height: 100px;
  float: left;
  margin-bottom: 1%;
}

.container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}

button {
  background-color: #cccccc;
  color: #000000;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  padding-left: 15%;
  outline: none;
  font-size: 17px;
  transition: 0.4s;
  margin-top: 2%;
}

.icon {
  width: 25px;
  height: 25px;
  padding-right: 15%;
  float: right;
}

button.accordion.active, button.accordion:hover {
  background-color: #ddd;
}

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

    <button>
Random
</button>

Thanks!

Body:
great solution and thanks for quick response! Just wondering where I would place my jquery code?

$('.container div').click(function(event){
  $(this).toggleClass('active');

})

html, body{
    width: 80%;
    margin: 0 auto;
}

head{
    text-align:left;
}

head, img{
    width: 350px;
    height: 100px;
    float: left;
    margin-bottom: 1%;
}

.container{
    width: 100%;
    height: 100%;
    margin: 0 auto;
    position: relative;
}

button{
    background-color: #cccccc;
    color: #000000;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    padding-left: 15%;
    outline: none;
    font-size: 17px;

    margin-top: 2%;
    position: relative;
}

button h3{
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.icon {
    height: 2.5em;
    width: 1.7em;
    float: right;
}

.icon {
    background-image: url(https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=1b3cdae197be);
}

.container div.active{
 height: 100%;
 background-color: white;
 position:absolute;
 top:0;
 left:0;
 width: 100%;
 z-index: 2;
}
.container div.active button{
   height: 100%;
}
#first,#second,#third,#fourth,#last{
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div id="first">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="second">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="third">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="fourth">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

    <div id="last">
        <button><h3>Random <div class ="icon" /></h3></button>
    </div>

</div>


问:
how to create a excel function that returns an array of variable size
I am trying to create a excel function that returns the result of a sql query.
I can do it if the result has size 1x1. However if the result is larger than that, I could not make the code work. Is there a solution for that? I am especially struggling with the fact that in all examples I have found, it is required to select exactly the right number of cells, whereas the result of my sql query could be of any size... and changing through time.

here is what I use so far:

```<code>Public Function getTS(field As String) As String
        Set oConnection = New ADODB.Connection
        Dim oRecordset As ADOR.Recordset
        oConnection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=AISDB;Data Source=mydomainlocation\mydatabase;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;"
        Set oRecordset = oConnection.Execute("select " & field & " from mytable where country = 'China'")
        If oRecordset.EOF Then
            getTS = "n/a"
        Else
            getTS = oRecordset(field)
        End If
    End Function
</code>```

答:
Return the recordset itself

```<code>Public Function getTS(field As String) As Recordset
    Set oConnection = New ADODB.Connection
    Dim oRecordset As ADOR.Recordset
    oConnection.Open....
    Set oRecordset = ....
    Set GetTS = oRecordset
End Function
</code>```

and then put the result into cells by specifying only the top left cell using

```<code>  Activesheet.range("a2").CopyFromRecordset GetTS("myField")
</code>```

Body:
I am trying to create a excel function that returns the result of a sql query.
I can do it if the result has size 1x1. However if the result is larger than that, I could not make the code work. Is there a solution for that? I am especially struggling with the fact that in all examples I have found, it is required to select exactly the right number of cells, whereas the result of my sql query could be of any size... and changing through time.

here is what I use so far:

Public Function getTS(field As String) As String
        Set oConnection = New ADODB.Connection
        Dim oRecordset As ADOR.Recordset
        oConnection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=AISDB;Data Source=mydomainlocation\mydatabase;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;"
        Set oRecordset = oConnection.Execute("select " & field & " from mytable where country = 'China'")
        If oRecordset.EOF Then
            getTS = "n/a"
        Else
            getTS = oRecordset(field)
        End If
    End Function

Body:
Return the recordset itself

Public Function getTS(field As String) As Recordset
    Set oConnection = New ADODB.Connection
    Dim oRecordset As ADOR.Recordset
    oConnection.Open....
    Set oRecordset = ....
    Set GetTS = oRecordset
End Function

and then put the result into cells by specifying only the top left cell using

  Activesheet.range("a2").CopyFromRecordset GetTS("myField")


问:
Android MaterialSearchView overlap
I'm using MaterialSearchView in my project.

https://github.com/MiguelCatalan/MaterialSearchView.

I'm creating the the Navigation Drawer Activiti that Android Studio provides, the default xml is using CoordinatorLayout to contain AppBarLayout. However, when integrate with the MaterialSearchView library, only one suggestion is given. I found in their sample xml, they are using RelativeLayout. After I change to RelativeLayout, the suggestions display fine. However, the FrameLayout and AppLayout seems overlap each other. After I click the search menu item, and close it, then it look fine. (Check the below pictures)

Current code is:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.toe.shareyourcuisine.activity.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <FrameLayout
            android:id="@+id/toolbar_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

            <com.miguelcatalan.materialsearchview.MaterialSearchView
                android:id="@+id/search_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </FrameLayout>
    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</RelativeLayout>
</code>```

I also post my issue in this link:

https://github.com/MiguelCatalan/MaterialSearchView/issues/141

Can anyone help me figure it out?

答:
I also faced the same problem and the solution is little tricky. To make all the suggestion displayed just place the FrameLayout containing the Toolbar and MaterialSearch view tag as its child tags at the end of the layout file.
i.e. change you layout file to this</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.toe.shareyourcuisine.activity.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"/>
<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
<FrameLayout
        android:id="@+id/toolbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

        <com.miguelcatalan.materialsearchview.MaterialSearchView
            android:id="@+id/search_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </FrameLayout>

</RelativeLayout>
</code>```

Title: Android MaterialSearchView overlap

Body:
I'm using MaterialSearchView in my project.

https://github.com/MiguelCatalan/MaterialSearchView.

I'm creating the the Navigation Drawer Activiti that Android Studio provides, the default xml is using CoordinatorLayout to contain AppBarLayout. However, when integrate with the MaterialSearchView library, only one suggestion is given. I found in their sample xml, they are using RelativeLayout. After I change to RelativeLayout, the suggestions display fine. However, the FrameLayout and AppLayout seems overlap each other. After I click the search menu item, and close it, then it look fine. (Check the below pictures)

Current code is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.toe.shareyourcuisine.activity.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <FrameLayout
            android:id="@+id/toolbar_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

            <com.miguelcatalan.materialsearchview.MaterialSearchView
                android:id="@+id/search_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </FrameLayout>
    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</RelativeLayout>

I also post my issue in this link:

https://github.com/MiguelCatalan/MaterialSearchView/issues/141

Can anyone help me figure it out?

Body:
I also faced the same problem and the solution is little tricky. To make all the suggestion displayed just place the FrameLayout containing the Toolbar and MaterialSearch view tag as its child tags at the end of the layout file.
i.e. change you layout file to this

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.toe.shareyourcuisine.activity.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"/>
<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
<FrameLayout
        android:id="@+id/toolbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

        <com.miguelcatalan.materialsearchview.MaterialSearchView
            android:id="@+id/search_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </FrameLayout>

</RelativeLayout>


问:
Shuffling biased random numbers
While thinking about this question and conversing with the participants, the idea came up that shuffling a finite set of clearly biased random numbers makes them random because you don't know the order in which they were chosen.  Is this true and if so can someone point to some resources?

EDIT:  I think I might have been a little unclear. Suppose a bad random numbers generator. Take n values. These are biased(the rng is bad). Is there a way through shuffling to make the output of the rng over multiple trials statistically match the output of a known good rng?

答:
Completely and utterly untrue: Shuffling doesn't remove a bias, it just conceals it from the casual observer. It's like removing your dog's fondly-laid present from your carpet by just pushing under the sofa - you really haven't solved the problem, you've just made it less conspicuous. Anyone with a nose knows that there is still a problem that needs removing.

The randomness must be applied evenly over the whole range, so here's one way (off the top of my head, lots of assumptions, yadda yadda. The point is the approach, not the code - start with everything even, then introduce your randomness in a consistent fashion until you're done. The only bias now is dependent on the values chosen for 'target' and 'numberofnumbers', which is part of the question.)

```<code>target = 200
numberofnumbers = 30
numbers = array();
for (i=0; i<numberofnumbers; i++)
  numbers[i] = 9
while (sum(numbers)>target)
  numbers[random(numberofnumbers)]--
</code>```

OwnerDisplayName: JPunyon

Title: Shuffling biased random numbers

LastEditorDisplayName: JPunyon

Body:
Completely and utterly untrue: Shuffling doesn't remove a bias, it just conceals it from the casual observer. It's like removing your dog's fondly-laid present from your carpet by just pushing under the sofa - you really haven't solved the problem, you've just made it less conspicuous. Anyone with a nose knows that there is still a problem that needs removing.

The randomness must be applied evenly over the whole range, so here's one way (off the top of my head, lots of assumptions, yadda yadda. The point is the approach, not the code - start with everything even, then introduce your randomness in a consistent fashion until you're done. The only bias now is dependent on the values chosen for 'target' and 'numberofnumbers', which is part of the question.)

target = 200
numberofnumbers = 30
numbers = array();
for (i=0; i<numberofnumbers; i++)
  numbers[i] = 9
while (sum(numbers)>target)
  numbers[random(numberofnumbers)]--

OwnerDisplayName: grunties


问:
How to work on iOS project with SVN?
When add/removing files/changing setting, the .xcodeproj will get changed. And if multiple people try to do that on the same project, because SVN is not as smart as git, it will cause issue every time, is there way to get around this issue besides talking to everybody each and every time?</p>

答: I think Xcode 4 has built-in support for SVN which helps with these issues quite a bit.</p>

Title: How to work on iOS project with SVN?


问:
Magmi don't update products
I'm using magmi to import in magento several product. My first import work ok, and all products were created and are visible. Now I need to update some information, like title, description and association beewtween them. I've modified my first import csv, the one that was working in the first time, then I lauch the update via ssh with the command "create" and my products are not updated. I control in frontend, backend and DB. Still old information. Do you have some ideas? </p>

答: make sure you give a proper name for attribute which you want to update in your file.</p>

Title: Magmi don't update products


答:
Check whether the textbox name you set is same in the HTML DOM. Right click the textbox and see the ID by inspect element. If it is not same as you built in c#, then add a line of code txt.ClientIDMode = ClientIDMode.Static; The ID will not be same as it generates dynamic textbox ID.

If the ID is same and still if not working, then run the given jquery and javascript statements in browser console and try they are working or not.

F12, goto console, paste $("#ctl00_ContentPlaceHolder1_txtRef1j.3rdPartRef").val('test'); and press enter. If the value is getting set, then its because of dynamic ID. just add the client id mode as static and it will work.

Title: How to set value of textbox created in code behind in javascript


问:
How can I do a window that is always maximized?
I know that I can change the propertie 'WindowState' to 'Maximized' and also change the propertie 'MaximizeBox' to 'false', so my application starts maximized and there's no chance to restore my window by clicking on the restore button.

But I can drag the window and move down, so it automatically restores. Is there any way of universally blocking the restore?

Thank you in advance.

答:
Don't know about universal blocking but in addition to your settings like resetting MaximizeBox and windowState properties, You can block the restore of form using following code. Here, you have to subscribe for LocationChanged event of form

// inside construcotr

```<code> this.LocationChanged += Form1_LocationChanged;
</code>```

// global variable

```<code> private Point desiredLocation;
</code>```

and inside the event definition you will keep the form location persistent.

```<code> void Form1_LocationChanged(object sender, EventArgs e)
        {
            if (this.Location != desiredLocation)
            {
                this.Location = desiredLocation;
            }
        }
</code>```

Body:
Don't know about universal blocking but in addition to your settings like resetting MaximizeBox and windowState properties, You can block the restore of form using following code. Here, you have to subscribe for LocationChanged event of form

// inside construcotr

 this.LocationChanged += Form1_LocationChanged;

// global variable

 private Point desiredLocation;

and inside the event definition you will keep the form location persistent.

 void Form1_LocationChanged(object sender, EventArgs e)
        {
            if (this.Location != desiredLocation)
            {
                this.Location = desiredLocation;
            }
        }


问:
Remove item from ArrayList<ArrayList<T>>>
In following code, I want to remove items which are null or size of arraylist is zero from ArrayList in first "for loop". After running first loop, again I  have a second loop. In second loop, I have tested whether it contains any item which is null or size of item is zero. Although I erase in first loop, ArrayList BS contains items which was deleted from list.</p>

```<code>ArrayList<ArrayList<Record>> BS = new ArrayList<>();
.
.// some codes
.

for (int j = 0; j < BS.size(); j++) {
    if(BS.get(j) == null || BS.get(j).size() == 0){
        BS.remove(j);
    }
}

for (int j = 0; j < BS.size(); j++) {
    if(BS.get(j) == null || BS.get(j).size() == 0){
            System.out.println("Again, fall into if condition");
    }
}
</code>```

答:
When removing items from an Array, usually you want to go from the last item to the first one, otherwwise your index will jump one item each time you do a remove.

This because removing an item shifts the remaining ones back of one position, namely from position "j + 1" to position j. So the next loop you skip the item a position j (that's the item that was in position j+1 in the previous loop).

Try this:

```<code>for (int j = BS.size() - 1; j >= 0; j--) {
    if(BS.get(j) == null || BS.get(j).size() == 0){
        BS.remove(j);
    }
}
</code>```

Body:
In following code, I want to remove items which are null or size of arraylist is zero from ArrayList in first "for loop". After running first loop, again I  have a second loop. In second loop, I have tested whether it contains any item which is null or size of item is zero. Although I erase in first loop, ArrayList BS contains items which was deleted from list.

ArrayList<ArrayList<Record>> BS = new ArrayList<>();
.
.// some codes
.

for (int j = 0; j < BS.size(); j++) {
    if(BS.get(j) == null || BS.get(j).size() == 0){
        BS.remove(j);
    }
}

for (int j = 0; j < BS.size(); j++) {
    if(BS.get(j) == null || BS.get(j).size() == 0){
            System.out.println("Again, fall into if condition");
    }
}

Body:
When removing items from an Array, usually you want to go from the last item to the first one, otherwwise your index will jump one item each time you do a remove.

This because removing an item shifts the remaining ones back of one position, namely from position "j + 1" to position j. So the next loop you skip the item a position j (that's the item that was in position j+1 in the previous loop).

Try this:

for (int j = BS.size() - 1; j >= 0; j--) {
    if(BS.get(j) == null || BS.get(j).size() == 0){
        BS.remove(j);
    }
}


答: If you need just the mail API, get the javamail.jar and add it to your classpath. I'd also recommend commons-email, which is a nice simplification of Java Mail API</p>

Title: java EE installation and setup

Body:
I need to develop a simple email client in Java. I will be using JavaMail APIs of Java EE. I installed NetBeans that supports Java EE from this site:

http://netbeans.org/downloads/

If I select the option of creating a Java EE application while creating project, I dont get the drag-n-drop feature of creating GUI with swings. And if I select Java Desktop Application I get the GUI building features but then Java EE libraries are not available. How can I use these two simultaneously?

Also, the NetBeans installer seems to install Java EE SDK. In which folder is this SDK installed?

I have experience of using Java SE but I am totally new to Java EE. Please help me.


问:
Generator vs List Append in Python
For simple list creations, it is recommended to use list comprehension. However, when it comes to more complicated scenarios, spanning the list creation across multiple lines is more advisable.

e.g. for a simple task

```<code>[x for x in range(10)]
</code>```

e.g. for a more complicated task

```<code>result = []
for x in complicated:
    if y is complex:
        for z in intricate_stuff:
             result.append(convoluted(z))
</code>```

(I probably would still use a multi-line list comprehension for the above example, but anyways you get the idea.)

Recently, I found myself achieve list creation like that using a generator like:

```<code>def gen():
    for x in complicated:
        if y is complex:
            for z in intricate_stuff:
                 yield convoluted(z)

result = [x for x in gen()]
</code>```

It's more natural for me to use a generator like this to create a list (well, generate a list), but I feel it might add unnecessary complexity.

Is this recommended? or, which way is more pythonic?

答:
Generators builds the elements on the go, one at a time.
So for statements like:

```<code>for e in my_generator():
    pass
</code>```

Value of variable e is generated each time during iteration, the value of e in the previous iteration is not stored. Hence it doesn't store the entire elements of the list. So it is memory efficient.

But if you are planning on using generator inside a list comprehension, there is no point in using generator as all the elements need to be generated and stored.

In that case you can use list comprehension like below:

```<code>result = [ convoluted(z) for x in complicated if y is complex for z in intricate_stuff ]
</code>```

Title: Generator vs List Append in Python

Body:
For simple list creations, it is recommended to use list comprehension. However, when it comes to more complicated scenarios, spanning the list creation across multiple lines is more advisable.

e.g. for a simple task

[x for x in range(10)]

e.g. for a more complicated task

result = []
for x in complicated:
    if y is complex:
        for z in intricate_stuff:
             result.append(convoluted(z))

(I probably would still use a multi-line list comprehension for the above example, but anyways you get the idea.)

Recently, I found myself achieve list creation like that using a generator like:

def gen():
    for x in complicated:
        if y is complex:
            for z in intricate_stuff:
                 yield convoluted(z)

result = [x for x in gen()]

It's more natural for me to use a generator like this to create a list (well, generate a list), but I feel it might add unnecessary complexity.

Is this recommended? or, which way is more pythonic?

Body:
Generators builds the elements on the go, one at a time.
So for statements like:

for e in my_generator():
    pass

Value of variable e is generated each time during iteration, the value of e in the previous iteration is not stored. Hence it doesn't store the entire elements of the list. So it is memory efficient.

But if you are planning on using generator inside a list comprehension, there is no point in using generator as all the elements need to be generated and stored.

In that case you can use list comprehension like below:

result = [ convoluted(z) for x in complicated if y is complex for z in intricate_stuff ]


问:
how to clear console data without refreshing the page in chrome
I am reading an ebook, which is about ReactJs,I want to run commands in the same page console but if redeclare the same variable it showing me variable has already been declared

for ex:-

```<code>var pizza = true
pizza = false
console.log(pizza)
</code>```

when i declarce const it show's me

```<code>const pizza = true
pizza = false
</code>```

error:-

Uncaught SyntaxError: Identifier 'pizza' has already been declared

I searched and used these commands but it is not working

```<code>CLTRL + L
</code>```

console.clear();

```<code>window.clear = clear

clear()
</code>```

Can anyone can tell me how to refresh console without refreshing the page

答:
Wrap code into function. When the function ends varibles are deallocated.</p>

```<code>(function() {
    //your code here
})();
</code>```

Body:
I am reading an ebook, which is about ReactJs,I want to run commands in the same page console but if redeclare the same variable it showing me variable has already been declared

for ex:-

var pizza = true
pizza = false
console.log(pizza)

when i declarce const it show's me

const pizza = true
pizza = false

error:-

Uncaught SyntaxError: Identifier 'pizza' has already been declared

I searched and used these commands but it is not working

CLTRL + L

console.clear();

window.clear = clear

clear()

Can anyone can tell me how to refresh console without refreshing the page

Body:
Wrap code into function. When the function ends varibles are deallocated.

(function() {
    //your code here
})();


问:
REDIS - INTERsection with multiple sets
Im kind of new to redis, so this question might be stupid, but Im trying to wrap around SINTER command here.

The problem is I have multiple SET, and Im trying to create an INTER on them.
When I do it individually its getting me the results, but when I pass multiple args its returning empty. I read documentation on INTER, it tells if any supplied arg is an empty SET it would return nothing, but all my SET is non empty could any one help me please!

```<code># below statement should return {'758', '762', '752'}
127.0.0.1:6379> SINTER Asset:all Asset:id:2275 Asset:id:2280 Asset:id:2269
(empty list or set)
127.0.0.1:6379> SINTER Asset:all Asset:id:2275
"758"
127.0.0.1:6379> SINTER Asset:all Asset:id:2280
"762"
127.0.0.1:6379> SINTER Asset:all Asset:id:2269
"752"
</code>```

But all other commands like SUNION, SDIFF are working fine.

答:
got the required behaviour by performing SUNION on sets and then SINTER on newly created set</p>

```<code>127.0.0.1:6379> SUNION ~unionset Asset:id:2275 Asset:id:2280 Asset:id:2269
127.0.0.1:6379> SINTER Asset:all ~unionset
"758"
"762"
"752"
</code>```

Title: REDIS - INTERsection with multiple sets

Body:
Im kind of new to redis, so this question might be stupid, but Im trying to wrap around SINTER command here.

The problem is I have multiple SET, and Im trying to create an INTER on them.
When I do it individually its getting me the results, but when I pass multiple args its returning empty. I read documentation on INTER, it tells if any supplied arg is an empty SET it would return nothing, but all my SET is non empty could any one help me please!

# below statement should return {'758', '762', '752'}
127.0.0.1:6379> SINTER Asset:all Asset:id:2275 Asset:id:2280 Asset:id:2269
(empty list or set)
127.0.0.1:6379> SINTER Asset:all Asset:id:2275
"758"
127.0.0.1:6379> SINTER Asset:all Asset:id:2280
"762"
127.0.0.1:6379> SINTER Asset:all Asset:id:2269
"752"

But all other commands like SUNION, SDIFF are working fine.

Body:
got the required behaviour by performing SUNION on sets and then SINTER on newly created set

127.0.0.1:6379> SUNION ~unionset Asset:id:2275 Asset:id:2280 Asset:id:2269
127.0.0.1:6379> SINTER Asset:all ~unionset
"758"
"762"
"752"


问:
How to convert my sql query to laravel ORM
I'm new in laravel 5 how can i convert this query to laravel ORM

```<code>select m.nombre,c.fecha_control as primer_control,
(select control.fecha_control
  from control
  where m.id = control.id_mascota
  order by control.fecha_control
  DESC limit 1) as ultimo_control
from mascota m
left join control as c on m.id = c.id_mascota
GROUP BY m.nombre
</code>```

i try this but it didn't work...

```<code> DB::table('mascota as m')
        ->leftJoin('control as c','m.id','=','c.id_mascota')
        ->select('m.nombre','c.fecha_control as primer_control',
            \DB::raw('select control.fecha_control  from control
                        where m.id = control.id_mascota
                        order by control.fecha_control
                        DESC limit 1
                        ) as ultimo_control'))
        ->groupBy('m.id');
</code>```

Thanks

答:
I only had syntax errors, it works fine. it take me  3 hours to realize</p>

```<code>DB::table("mascota as m")
 ->leftJoin('control as c','m.id','=','c.id_mascota')
 ->select('m.nombre','c.fecha_control as primer_control'),
    DB::raw("(select control.fecha_control
              from control
              where m.id = control.id_mascota
              order by control.fecha_control
              DESC limit 1) as ult_control"))
  ->groupBy('m.id');
</code>```

Body:
I'm new in laravel 5 how can i convert this query to laravel ORM

select m.nombre,c.fecha_control as primer_control,
(select control.fecha_control
  from control
  where m.id = control.id_mascota
  order by control.fecha_control
  DESC limit 1) as ultimo_control
from mascota m
left join control as c on m.id = c.id_mascota
GROUP BY m.nombre

i try this but it didn't work...

 DB::table('mascota as m')
        ->leftJoin('control as c','m.id','=','c.id_mascota')
        ->select('m.nombre','c.fecha_control as primer_control',
            \DB::raw('select control.fecha_control  from control
                        where m.id = control.id_mascota
                        order by control.fecha_control
                        DESC limit 1
                        ) as ultimo_control'))
        ->groupBy('m.id');

Thanks

Body:
I only had syntax errors, it works fine. it take me  3 hours to realize

DB::table("mascota as m")
 ->leftJoin('control as c','m.id','=','c.id_mascota')
 ->select('m.nombre','c.fecha_control as primer_control'),
    DB::raw("(select control.fecha_control
              from control
              where m.id = control.id_mascota
              order by control.fecha_control
              DESC limit 1) as ult_control"))
  ->groupBy('m.id');


问:
Graphql with mutation spring boot
My schema file is

```<code>type Mutation {
createCustomer(name: String!, email: String!, product: [Product]): Customer
}

input Product {
    id: ID!
    name: String!
    price: Int
}

interface Person {
    id: ID!
    name: String!
    email: String!
}

type Customer implements Person {
    id: ID!
    name: String!
    email: String!
    product: [Product]
}
</code>```

I want to insert customer detail here which has product list as input. My query is

```<code>mutation {
  createCustomer(
    name: "kitte",
    email: "kitte@gmail.com",
    product: [
      {
         name: "soap",
             price: 435,
      }
    ]
  )
  {
    id
    name
    email
    product{name}

  }
}
</code>```

But I am getting exception

```<code>{
  "data": null,
  "errors": [
    {
      "validationErrorType": "WrongType",
      "message": "Validation error of type WrongType: argument value ArrayValue{values=[ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='dars76788hi'}}, ObjectField{name='price', value=IntValue{value=123}}]}, ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='darr'}}, ObjectField{name='price', value=IntValue{value=145}}]}]} has wrong type",
      "locations": [
        {
          "line": 5,
          "column": 5
        }
      ],
      "errorType": "ValidationError"
    }
  ]
}
</code>```

I don't understand what is the error. And how to pass list to mutation. I have referred some examples but not able to insert product as list.

答:
Make sure you are passing the right type of objects to your mutation. GraphQL needs separate types for input fields. In your schema, Product types should be something like this and you should change the mutation accordingly.

```<code>type Product {
    id: ID!
    name: String!
    price: Int
}

input ProductInput {
    name: String!
    price: Int
}

input CustomerInput {
    ...
    products: [ProductInput]
}
</code>```

There are couple of very useful examples in the docs, see Mutations and Input Types

Title: Graphql with mutation spring boot

Body:
My schema file is

type Mutation {
createCustomer(name: String!, email: String!, product: [Product]): Customer
}

input Product {
    id: ID!
    name: String!
    price: Int
}

interface Person {
    id: ID!
    name: String!
    email: String!
}

type Customer implements Person {
    id: ID!
    name: String!
    email: String!
    product: [Product]
}

I want to insert customer detail here which has product list as input. My query is

mutation {
  createCustomer(
    name: "kitte",
    email: "kitte@gmail.com",
    product: [
      {
         name: "soap",
             price: 435,
      }
    ]
  )
  {
    id
    name
    email
    product{name}

  }
}

But I am getting exception

{
  "data": null,
  "errors": [
    {
      "validationErrorType": "WrongType",
      "message": "Validation error of type WrongType: argument value ArrayValue{values=[ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='dars76788hi'}}, ObjectField{name='price', value=IntValue{value=123}}]}, ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='darr'}}, ObjectField{name='price', value=IntValue{value=145}}]}]} has wrong type",
      "locations": [
        {
          "line": 5,
          "column": 5
        }
      ],
      "errorType": "ValidationError"
    }
  ]
}

I don't understand what is the error. And how to pass list to mutation. I have referred some examples but not able to insert product as list.

Body:
Make sure you are passing the right type of objects to your mutation. GraphQL needs separate types for input fields. In your schema, Product types should be something like this and you should change the mutation accordingly.

type Product {
    id: ID!
    name: String!
    price: Int
}

input ProductInput {
    name: String!
    price: Int
}

input CustomerInput {
    ...
    products: [ProductInput]
}

There are couple of very useful examples in the docs, see Mutations and Input Types


问:
SQL Delete conditionally between rows
I have a table with multiple rows for the same ID and I need to keep only one row with the following rules:

NUM = 'AM' prevail on other

If multiple NUM = 'AM' or none then the oldest date prevail

For example :

```<code>|_ID_|_NUM_|______DATE______|
| 99 | AM  |   2015-04-12   |
| 99 | QS  |   2012-05-31   |
| 99 | AM  |   2013-02-18   |
</code>```

I need to keep the last row.

```<code>|_ID_|_NUM_|______DATE______|
| 99 | QS  |   2013-05-31   |
| 99 | QS  |   2016-02-18   |
</code>```

I need to keep the first row.

I'm on a postgres database and I can't use Function or Procedure
Thank you for any help.

答:
If I understand your problem correctly, I think this is what you seek:</p>

```<code>with cte as (
  select
    id, num, date,
    row_number() over (partition by id order by num = 'AM' desc, date) as rn
  from foo
)
select
  id, num, date
from cte
where rn = 1
</code>```

Title: SQL Delete conditionally between rows

Body:
I have a table with multiple rows for the same ID and I need to keep only one row with the following rules:

NUM = 'AM' prevail on other

If multiple NUM = 'AM' or none then the oldest date prevail

For example :

|_ID_|_NUM_|______DATE______|
| 99 | AM  |   2015-04-12   |
| 99 | QS  |   2012-05-31   |
| 99 | AM  |   2013-02-18   |

I need to keep the last row.

|_ID_|_NUM_|______DATE______|
| 99 | QS  |   2013-05-31   |
| 99 | QS  |   2016-02-18   |

I need to keep the first row.

I'm on a postgres database and I can't use Function or Procedure
Thank you for any help.

Body:
If I understand your problem correctly, I think this is what you seek:

with cte as (
  select
    id, num, date,
    row_number() over (partition by id order by num = 'AM' desc, date) as rn
  from foo
)
select
  id, num, date
from cte
where rn = 1