问:
How to store variables for further use from User-input in Java Swing Gui?
I currently have a simple Java AWT/Swing code that creates a simple GUI that takes multiple String User-input and stores and displays it in the Intellij terminal like so:

```<code>import javax.swing.*;
import java.awt.*;        // Using AWT container and component classes
import java.awt.event.*;  // Using AWT event classes and listener interfaces
import java.util.ArrayList;
import java.util.Scanner;

// An AWT program inherits from the top-level container java.awt.Frame
public class DateTime extends JFrame implements ActionListener {
    private Label lblCount, lblsource, lbldate1, lbldate2;    // Declare a Label component
    private JTextField tfCount, date1, date2; // Declare a TextField component
    private Button btnCount;   // Declare a Button component
    private int count = 0;     // Counter's value
    static String type = null;
    private JCheckBox source1, source2;
    boolean a = false;
    boolean b= false;
    static String source, datedefined1, datedefined2;
    ArrayList<String> texts = new ArrayList<String>();
    // Constructor to setup GUI components and event handlers
    public DateTime () {
        setLayout(new FlowLayout());
        // "super" Frame, which is a Container, sets its layout to FlowLayout to arrange
        // the components from left-to-right, and flow to next row from top-to-bottom.

        lblCount = new Label("Enter the type of report you want generated; Hourly/ Daily/ Weekly/ EventComparison:");  // construct the Label component
        add(lblCount);                    // "super" Frame container adds Label component

        tfCount = new JTextField("", 20); // construct the TextField component
        tfCount.setEditable(true);       // set to read-only
                          // "super" Frame container adds TextField component

        tfCount.setBounds(10,50,200,40);
        add(tfCount);
        tfCount.addActionListener(this);

        lblsource = new Label("Now choose the source type:");
        add(lblsource);
        source1 = new JCheckBox("Drivetest", a);
        source1.setBounds(10,100,50,30);
        add(source1);
        source2 = new JCheckBox("Ookla Dump",b);
        add(source2);
        source1.addActionListener(this);
        source2.addActionListener(this);

            lbldate1 = new Label("Please enter the Start DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS) :");
            add(lbldate1);
            date1 = new JTextField("", 30); // construct the TextField component
            date1.setEditable(true);
            add(date1);
            date1.addActionListener(this);
            lbldate2 = new Label("Please enter the end DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS): ");
            add(lbldate2);
            date2 = new JTextField("",30);
            date2.setEditable(true);
            add(date2);
            date2.addActionListener(this);

            // set to read-only
            // "super" Frame container adds TextField component

        // "btnCount" is the source object that fires an ActionEvent when clicked.
        // The source add "this" instance as an ActionEvent listener, which provides
        //   an ActionEvent handler called actionPerformed().
        // Clicking "btnCount" invokes actionPerformed().

        setTitle("Report Generator");  // "super" Frame sets its title
        setSize(800, 700);        // "super" Frame sets its initial window size

        // For inspecting the Container/Components objects
        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);

        setVisible(true);         // "super" Frame shows

        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);
    }

    // The entry main() method
    public static void main(String[] args) {
        // Invoke the constructor to setup the GUI, by allocating an instance
        DateTime app = new DateTime();

        // or simply "new AWTCounter();" for an anonymous instance

    }

    // ActionEvent handler - Called back upon button-click.
    @Override
    public void actionPerformed(ActionEvent evt) {
        Object actionsource = evt.getSource();
        if(actionsource instanceof JTextField){
            JTextField dateget1 = (JTextField) evt.getSource();
            JTextField dateget2 = (JTextField) evt.getSource();

            if (dateget1 == date1){
            datedefined1 = date1.getText();
                System.out.println(datedefined1);}
            else if(dateget2 == date2){

            datedefined2 = date2.getText();
            System.out.println(datedefined2);}
            else{
                type = tfCount.getText();
                System.out.println(type);

            }

        }
        else if(actionsource instanceof JCheckBox){
            JCheckBox cb = (JCheckBox) evt.getSource();
            if(cb == source1){
                source = "Drivetest";
                System.out.println(source);
            }
            else if(cb == source2){
                source = "Ookla Data Dump";
                System.out.println(source);
            }

        }

    }
}
</code>```

The thing is, my main program needs to take in and store multiple string variables(ie. type, source, date1 AND date2) before it should execute.

My code for a normal terminal-style running of the program would look like this:

```<code> System.out.println("Enter the report type you would like: DailyComparison or HourlyComparison or WeeklyComparison or EventComparison; Type the exact words!");
    type = scan.next();
    System.out.println("Now enter the type of data you would like analysed: OOKLA or ManualTest: ");
    source = scan.next();
    if("DailyComparison".equals(type) || "HourlyComparison".equals(type) || "WeeklyComparison".equals(type) ){
        Scanner scan2 = new Scanner((System.in));
        System.out.println("Now enter the lower bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date1 = scan2.nextLine();
        System.out.println("Now enter the upper bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date2 = scan2.nextLine();
    }
</code>```

Where user-input is taken through the terminal as normal.

The user input is then used to run the rest of the program, calling the methods in other classes i have defined:

```<code>Report.report(date1, date2, type, filename, source);// Creates the excel .xlsx file report

MailSender.MailSender(filename, type); // Send a email containing the attached report xlsx file
</code>```

So my question is: How do i extend this GUI code's functionality so that the user-input string variables can ALL be gathered first then used to run the rest of the program?

EDIT:

Thanks for the advice guys.

I sort of got it to work, but I'm not sure if the structure is sound. What was happening previously was that since each component was handling a different variable and i wanted to store all the variables first before calling the main method classes that would process these variables.

So i created an additional button called "Generate Report" and under the actionlistener condition+action for this button, I placed the class.methods like so. Where basically I key in all my variables in the respective components(checkboxes, button etc) THEN press "generate report"

```<code> if (evt.getActionCommand() == "Generate Report") {

                if ("DailyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Daily SpeedTest Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("WeeklyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Weekly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("HourlyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + "Hourly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                }
                if("HourlyComparison".equals(type)|"DailyComparison".equals(type)|"WeeklyComparison".equals(type)) {
                    Report.report(datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, type, filename, source);// Creates the base excel .xlsx file report
                    LinechartGenerator.chartgen(0, "upload", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "download", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "latency", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
        }

    }
</code>```

Although the code has its limitations where I cannot press generate report first or the program will just throw an error seeing as no variables were stored.

I also faced a roadblock where I'm trying to find the Swing-equivalent of the Flush Scanner function to allow the user to generate multiple reports in the same program instance.

答:
You may break down this in two different jars:

Read the input and write that in a temp file.

Once the input has been read and written to the file, invoke your GUI jar application this can read contents from the temp file.

You may refer to this question on how to invoke jar from java application.

Body:
I currently have a simple Java AWT/Swing code that creates a simple GUI that takes multiple String User-input and stores and displays it in the Intellij terminal like so:

import javax.swing.*;
import java.awt.*;        // Using AWT container and component classes
import java.awt.event.*;  // Using AWT event classes and listener interfaces
import java.util.ArrayList;
import java.util.Scanner;

// An AWT program inherits from the top-level container java.awt.Frame
public class DateTime extends JFrame implements ActionListener {
    private Label lblCount, lblsource, lbldate1, lbldate2;    // Declare a Label component
    private JTextField tfCount, date1, date2; // Declare a TextField component
    private Button btnCount;   // Declare a Button component
    private int count = 0;     // Counter's value
    static String type = null;
    private JCheckBox source1, source2;
    boolean a = false;
    boolean b= false;
    static String source, datedefined1, datedefined2;
    ArrayList<String> texts = new ArrayList<String>();
    // Constructor to setup GUI components and event handlers
    public DateTime () {
        setLayout(new FlowLayout());
        // "super" Frame, which is a Container, sets its layout to FlowLayout to arrange
        // the components from left-to-right, and flow to next row from top-to-bottom.

        lblCount = new Label("Enter the type of report you want generated; Hourly/ Daily/ Weekly/ EventComparison:");  // construct the Label component
        add(lblCount);                    // "super" Frame container adds Label component

        tfCount = new JTextField("", 20); // construct the TextField component
        tfCount.setEditable(true);       // set to read-only
                          // "super" Frame container adds TextField component

        tfCount.setBounds(10,50,200,40);
        add(tfCount);
        tfCount.addActionListener(this);

        lblsource = new Label("Now choose the source type:");
        add(lblsource);
        source1 = new JCheckBox("Drivetest", a);
        source1.setBounds(10,100,50,30);
        add(source1);
        source2 = new JCheckBox("Ookla Dump",b);
        add(source2);
        source1.addActionListener(this);
        source2.addActionListener(this);

            lbldate1 = new Label("Please enter the Start DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS) :");
            add(lbldate1);
            date1 = new JTextField("", 30); // construct the TextField component
            date1.setEditable(true);
            add(date1);
            date1.addActionListener(this);
            lbldate2 = new Label("Please enter the end DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS): ");
            add(lbldate2);
            date2 = new JTextField("",30);
            date2.setEditable(true);
            add(date2);
            date2.addActionListener(this);

            // set to read-only
            // "super" Frame container adds TextField component

        // "btnCount" is the source object that fires an ActionEvent when clicked.
        // The source add "this" instance as an ActionEvent listener, which provides
        //   an ActionEvent handler called actionPerformed().
        // Clicking "btnCount" invokes actionPerformed().

        setTitle("Report Generator");  // "super" Frame sets its title
        setSize(800, 700);        // "super" Frame sets its initial window size

        // For inspecting the Container/Components objects
        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);

        setVisible(true);         // "super" Frame shows

        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);
    }

    // The entry main() method
    public static void main(String[] args) {
        // Invoke the constructor to setup the GUI, by allocating an instance
        DateTime app = new DateTime();

        // or simply "new AWTCounter();" for an anonymous instance

    }

    // ActionEvent handler - Called back upon button-click.
    @Override
    public void actionPerformed(ActionEvent evt) {
        Object actionsource = evt.getSource();
        if(actionsource instanceof JTextField){
            JTextField dateget1 = (JTextField) evt.getSource();
            JTextField dateget2 = (JTextField) evt.getSource();

            if (dateget1 == date1){
            datedefined1 = date1.getText();
                System.out.println(datedefined1);}
            else if(dateget2 == date2){

            datedefined2 = date2.getText();
            System.out.println(datedefined2);}
            else{
                type = tfCount.getText();
                System.out.println(type);

            }

        }
        else if(actionsource instanceof JCheckBox){
            JCheckBox cb = (JCheckBox) evt.getSource();
            if(cb == source1){
                source = "Drivetest";
                System.out.println(source);
            }
            else if(cb == source2){
                source = "Ookla Data Dump";
                System.out.println(source);
            }

        }

    }
}

The thing is, my main program needs to take in and store multiple string variables(ie. type, source, date1 AND date2) before it should execute.

My code for a normal terminal-style running of the program would look like this:

 System.out.println("Enter the report type you would like: DailyComparison or HourlyComparison or WeeklyComparison or EventComparison; Type the exact words!");
    type = scan.next();
    System.out.println("Now enter the type of data you would like analysed: OOKLA or ManualTest: ");
    source = scan.next();
    if("DailyComparison".equals(type) || "HourlyComparison".equals(type) || "WeeklyComparison".equals(type) ){
        Scanner scan2 = new Scanner((System.in));
        System.out.println("Now enter the lower bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date1 = scan2.nextLine();
        System.out.println("Now enter the upper bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date2 = scan2.nextLine();
    }

Where user-input is taken through the terminal as normal.

The user input is then used to run the rest of the program, calling the methods in other classes i have defined:

Report.report(date1, date2, type, filename, source);// Creates the excel .xlsx file report

MailSender.MailSender(filename, type); // Send a email containing the attached report xlsx file

So my question is: How do i extend this GUI code's functionality so that the user-input string variables can ALL be gathered first then used to run the rest of the program?

EDIT:

Thanks for the advice guys.

I sort of got it to work, but I'm not sure if the structure is sound. What was happening previously was that since each component was handling a different variable and i wanted to store all the variables first before calling the main method classes that would process these variables.

So i created an additional button called "Generate Report" and under the actionlistener condition+action for this button, I placed the class.methods like so. Where basically I key in all my variables in the respective components(checkboxes, button etc) THEN press "generate report"

 if (evt.getActionCommand() == "Generate Report") {

                if ("DailyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Daily SpeedTest Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("WeeklyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Weekly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("HourlyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + "Hourly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                }
                if("HourlyComparison".equals(type)|"DailyComparison".equals(type)|"WeeklyComparison".equals(type)) {
                    Report.report(datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, type, filename, source);// Creates the base excel .xlsx file report
                    LinechartGenerator.chartgen(0, "upload", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "download", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "latency", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
        }

    }

Although the code has its limitations where I cannot press generate report first or the program will just throw an error seeing as no variables were stored.

I also faced a roadblock where I'm trying to find the Swing-equivalent of the Flush Scanner function to allow the user to generate multiple reports in the same program instance.


来源: stackexchange

问:
matching rows between dataframes in pandas in python
I have two dataframes,

df1,

```<code> Names
 one two three
 Sri is a good player
 Ravi is a mentor
 Kumar is a cricketer
</code>```

df2,

```<code> values
 sri
 NaN
 sri, is
 kumar,cricketer
</code>```

I am trying to get the row in df1 which contains the all the items in df2

My expected output is,

```<code> values             Names
 sri                Sri is a good player
 NaN
 sri, is            Sri is a good player
 kumar,cricketer    Kumar is a cricketer
</code>```

i tried, df1["Names"].str.contains("|".join(df2["values"].values.tolist()))

but I cannot achieve my expected output as it has (","). Please help

答:
Using sets</p>

```<code>s1 = df1.Names.dropna()
s1.loc[:] = [set(x.lower().split()) for x in s1.values.tolist()]
a1 = s1.values

s2 = df2['values'].dropna()
s2.loc[:] = [set(x.replace(' ', '').lower().split(',')) for x in s2.values.tolist()]
a2 = s2.values

i = np.column_stack([a1 >= a2[:, None], [True] * len(a2)]).argmax(1)

df2.assign(Names=pd.Series(
    np.append(df1.Names.values, np.nan)[i], s2.index
))

            values                 Names
0              sri  Sri is a good player
1              NaN                   NaN
2          sri, is  Sri is a good player
3  kumar,cricketer  Kumar is a cricketer
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two dataframes,

df1,

 Names
 one two three
 Sri is a good player
 Ravi is a mentor
 Kumar is a cricketer

df2,

 values
 sri
 NaN
 sri, is
 kumar,cricketer

I am trying to get the row in df1 which contains the all the items in df2

My expected output is,

 values             Names
 sri                Sri is a good player
 NaN
 sri, is            Sri is a good player
 kumar,cricketer    Kumar is a cricketer

i tried, df1["Names"].str.contains("|".join(df2["values"].values.tolist()))

but I cannot achieve my expected output as it has (","). Please help

Body:
Using sets

s1 = df1.Names.dropna()
s1.loc[:] = [set(x.lower().split()) for x in s1.values.tolist()]
a1 = s1.values

s2 = df2['values'].dropna()
s2.loc[:] = [set(x.replace(' ', '').lower().split(',')) for x in s2.values.tolist()]
a2 = s2.values

i = np.column_stack([a1 >= a2[:, None], [True] * len(a2)]).argmax(1)

df2.assign(Names=pd.Series(
    np.append(df1.Names.values, np.nan)[i], s2.index
))

            values                 Names
0              sri  Sri is a good player
1              NaN                   NaN
2          sri, is  Sri is a good player
3  kumar,cricketer  Kumar is a cricketer


问:
How to convert a Task into a Task<T>?
I'm sure this has been asked before but I can't seem to phrase the question right to get any answers that solve my question.

I've got a base class that implements an interface with a Save method that returns a Task:

```<code>public interface ICanSave
{
    Task Save();
}

public class Base : ICanSave
{
    public Task Save()
    {
        return Task.CompletedTask;
    }
}
</code>```

Of course the Save method will actually do something, like saving to a database, which is why it's a Task, so it can be awaited. If I have a Foo class that inherits from the base class:

```<code>public class Foo : Base { }
</code>```

Currently, you'd have to do the instantiation and save in two distinct steps:

```<code>var foo = new Foo();

await foo.Save();
</code>```

However I'd like to be able to do the instantiation and the save as an expression and return a Task also. I've come up with this helper:

```<code>public static class Helper<T> where T : ICanSave
{
    public static Task<T> Save(T obj)
    {
        var source = new TaskCompletionSource<T>();

        ThreadPool.QueueUserWorkItem(_ =>
        {
            obj.Save();
            source.SetResult(obj);
        });

        return source.Task;
    }
}
</code>```

Which could then be used to do:

```<code>var foo = await Helper<Foo>.Save(new Foo());
</code>```

Which is more like the result I'm trying to achieve, but it seems pretty cumbersome, plus the helper seems to be pushing the Save to a Task twice (once for the original Task and a second time in the helper).

Is there a more simple way to do this conversion from a Task to a Task of T?

答:
I don't see a point of such helper method, but if you really want you can like this:</p>

```<code>public static class Helper<T> where T : ICanSave {
    public static async Task<T> Save(T obj) {
        await obj.Save();
        return obj;
    }
}
</code>```

Title: How to convert a Task into a Task<T>?

Body:
I'm sure this has been asked before but I can't seem to phrase the question right to get any answers that solve my question.

I've got a base class that implements an interface with a Save method that returns a Task:

public interface ICanSave
{
    Task Save();
}

public class Base : ICanSave
{
    public Task Save()
    {
        return Task.CompletedTask;
    }
}

Of course the Save method will actually do something, like saving to a database, which is why it's a Task, so it can be awaited. If I have a Foo class that inherits from the base class:

public class Foo : Base { }

Currently, you'd have to do the instantiation and save in two distinct steps:

var foo = new Foo();

await foo.Save();

However I'd like to be able to do the instantiation and the save as an expression and return a Task also. I've come up with this helper:

public static class Helper<T> where T : ICanSave
{
    public static Task<T> Save(T obj)
    {
        var source = new TaskCompletionSource<T>();

        ThreadPool.QueueUserWorkItem(_ =>
        {
            obj.Save();
            source.SetResult(obj);
        });

        return source.Task;
    }
}

Which could then be used to do:

var foo = await Helper<Foo>.Save(new Foo());

Which is more like the result I'm trying to achieve, but it seems pretty cumbersome, plus the helper seems to be pushing the Save to a Task twice (once for the original Task and a second time in the helper).

Is there a more simple way to do this conversion from a Task to a Task of T?

Body:
I don't see a point of such helper method, but if you really want you can like this:

public static class Helper<T> where T : ICanSave {
    public static async Task<T> Save(T obj) {
        await obj.Save();
        return obj;
    }
}


问:
Ruby FileList filtering
I have a FileList with *.js and *.tc extensions. How can I split it into two arrays of FileList, one with only *.js files and the other with *.tc files?

答:
Enumerable#partition comes to the rescue.

```<code>["aaa.js", "bbb.js", "ccc.js",
 "xxx.tc", "yyy.tc", "zzz.tc" ].partition do |e|
    e[/(?<=\.).*\z/] == "tc"
  end
#⇒ [["xxx.tc", "yyy.tc", "zzz.tc"],
#   ["aaa.js", "bbb.js", "ccc.js"]]
</code>```

or, more explicit:

```<code>["aaa.js", "bbb.js", "ccc.js",
 "xxx.tc", "yyy.tc", "zzz.tc" ].partition(&/\.tc\z/.method(:=~))
</code>```

Title: Ruby FileList filtering

Body:
Enumerable#partition comes to the rescue.

["aaa.js", "bbb.js", "ccc.js",
 "xxx.tc", "yyy.tc", "zzz.tc" ].partition do |e|
    e[/(?<=\.).*\z/] == "tc"
  end
#⇒ [["xxx.tc", "yyy.tc", "zzz.tc"],
#   ["aaa.js", "bbb.js", "ccc.js"]]

or, more explicit:

["aaa.js", "bbb.js", "ccc.js",
 "xxx.tc", "yyy.tc", "zzz.tc" ].partition(&/\.tc\z/.method(:=~))


问:
What is the meaning of this regular expression? ['`?!\"-/]
What is the meaning of this regular expression?

```<code>    ['`?!\"-/]
</code>```

Why it matches parenthesis?

I used Java for development

答:
You have to use following
You need to escape -, otherwise, parentheses are matching.
Seems like "-/ will include parentheses as well. Like [A-C], which matches ASCII chars between A to C

```<code>[\'`?!\"\-/]
</code>```

It will match following characters in a string.

```<code>'`?"-/
</code>```

Check in the regex101

Body:
What is the meaning of this regular expression?

    ['`?!\"-/]

Why it matches parenthesis?

I used Java for development

Body:
You have to use following
You need to escape -, otherwise, parentheses are matching.
Seems like "-/ will include parentheses as well. Like [A-C], which matches ASCII chars between A to C

[\'`?!\"\-/]

It will match following characters in a string.

'`?"-/

Check in the regex101


问:
compile for SDK21 android app
My app works fine with targetSdkversion = 25 and compileSdkversion = 25

Now I need to make it work for targetSdkversion as 21. The app is failing with an error app stopped working.

Do I need to change any tool version or any other parameters?

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "MY.APP.NAME"
    minSdkVersion 17
    targetSdkVersion 21
    versionCode 11
    versionName "1.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    exclude group: 'com.google.code.findbugs'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-location:11.0.4'
compile 'com.android.support:design:25.3.1'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
testCompile 'junit:junit:4.12'
</code>```

}

答:
Please share the error log you are getting , because as stated in the link, you should compile your application against the lowest possible version of the platform that your application can support.
Should compile sdk be lower than target sdk</p>

Title: compile for SDK21 android app

Body:
My app works fine with targetSdkversion = 25 and compileSdkversion = 25

Now I need to make it work for targetSdkversion as 21. The app is failing with an error app stopped working.

Do I need to change any tool version or any other parameters?

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "MY.APP.NAME"
    minSdkVersion 17
    targetSdkVersion 21
    versionCode 11
    versionName "1.1"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    exclude group: 'com.google.code.findbugs'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-location:11.0.4'
compile 'com.android.support:design:25.3.1'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
testCompile 'junit:junit:4.12'

}


问:
Convert from string(yyyyMMddHHmmss) to DateTime with SQL Server
I am migrating from Oracle's to_date function to SQL Server's convert function.

I want to know a good way to convert a string of format yyyyMMddHHmmss to DateTime type.

I could write a program, but it is too redundant, so I would like to know how to improve it.

```<code>'Get String Date (yyyyMMddHHmmss)
Dim strNowDate = Strings.Format(Now, "yyyyMMddHHmmss") 'format cannot be changed. (Because, referenced from many)

'some logics...

'Oracle script before migration.
sqlBuf.Append(" ,to_date('" & strNowDate & "', 'YYYYMMDDHH24MISS')" & vbCrLf)

'SQL Server script after migration.(too redundancy... I want to make it more cool.)
sqlBuf.Append(" ,convert(DATETIME, '" & DateTime.ParseExact(strNowDate, "yyyyMMddHHmmss", Globalization.DateTimeFormatInfo.InvariantInfo).ToString("yyyy-MM-dd HH:mm:ss") & "')" & vbCrLf)
</code>```

Body:
I am migrating from Oracle's to_date function to SQL Server's convert function.

I want to know a good way to convert a string of format yyyyMMddHHmmss to DateTime type.

I could write a program, but it is too redundant, so I would like to know how to improve it.

'Get String Date (yyyyMMddHHmmss)
Dim strNowDate = Strings.Format(Now, "yyyyMMddHHmmss") 'format cannot be changed. (Because, referenced from many)

'some logics...

'Oracle script before migration.
sqlBuf.Append(" ,to_date('" & strNowDate & "', 'YYYYMMDDHH24MISS')" & vbCrLf)

'SQL Server script after migration.(too redundancy... I want to make it more cool.)
sqlBuf.Append(" ,convert(DATETIME, '" & DateTime.ParseExact(strNowDate, "yyyyMMddHHmmss", Globalization.DateTimeFormatInfo.InvariantInfo).ToString("yyyy-MM-dd HH:mm:ss") & "')" & vbCrLf)

Body:
It's my variant from my comment

SELECT CONVERT(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20171116115733',5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':'),120) -- yyyy-mm-dd hh:mm:ss


问:
D3 stuck in queue
Hello Iam loading 3 different csv with a d3.queue. But when I try to display my page it never call the function after loading the data.

data.js

```<code>function process(d){
       var processed = {
            code : d["Institution code (UKPRN)"],
            name : d["Institution name"],
            iSorte : d["Institution sort order"],
            nbAssess : d["Unit of assessment number"],
            naAsses: d["Unit of assessment name"],
            subLetter : d["Multiple submission letter"],
            subName : d["Multiple subimission name"],
            jSub : d["Joint submission"],
            profile : d["Profile"],
            fte : d["FTE Category A staff submitted"],
            one: d["1*"],
            two: d["2*"],
            three: d["3*"],
            four: d["4*"],
            unclassified: d["unclassified"]
                }
                return processed;
        }

function dataManager(){

    var dmObj = {}; // main object

    var ref14data;
    var townsCSV;
    var refUniversitiesByUKPRN;
    var learningProviders;
    var heriotWattCS;
    var dataset =[];
    // ---- PUBLIC API

    // function loading json data from url
    // parameters:
    //      - url, url of data in string format
    //      - callbackError, callback in case of error
    //      - callbackSuccess, callback if data loads normally
    // returns:
    //      - Nothing

    // function returning filtered data: money per year
    // parameters:
    //      - None
    // returns:
    //      - nestedData, data with following format:
    //          [{"key": year, "value": money}, {...}, ...]
    dmObj.getByName = function(){

        // using nest function from d3 to "classify" data into years
        // then rollup to change array of values into sum of money
        var nestedData = d3.nest()
            .key(function(d){return d.name;})
            .sortKeys(d3.ascending)
            .rollup(function(values){return values.length;})
            .entries(dataset);

        console.log("databyname",nestedData);

        return nestedData;
    }

    // function returning filtered data: money per area
    // parameters:
    //      - None
    // returns:
    //      - nestedData, data with following format:
    //          [{"key": area, "value": money}, {...}, ...]
    dmObj.getArea = function(key){

        var nestedData = d3.nest()
            .key(function (d) {return d.name;})
            .key(function (d) {return d.naAsses;})
            .rollup(function(values) {return values.length})
            .map(dataset);

        return nestedData["$"+key];
    }

    dmObj.loadAllData = function (url1,url2,url3) {
        d3.queue()
            .defer(d3.csv, url1)
            .defer(d3.csv, url2)
            .defer(d3.csv, url3)
            .await(processus);

        function processus(error,data1, data2, data3) {
            ref14data = data1;
            townsCSV = data2;
            learningProviders = data3;

            //Create master table
            combineLPwithTownData(learningProviders, townsCSV);
            console.log('ref data ',learningProviders);
            console.log('town',townsCSV);

            combineREFwithLPdata(ref14data, learningProviders);

            //Just consider "overall" assessments
            ref14data = ref14data.filter(function (e) { return e.Profile === "Overall" })

            console.log('ref', ref14data);
            return ref14data;
        }
    }

    dmObj.getHierarchy = function(){
        var hierarchyJSON = createJSONhierarchy(ref14data, "root",
            ["Country","County", "Institution name"])

        return hierarchyJSON;
    }

    function combineLPwithTownData(learningProviders, townsCSV){
        // For each learning provider university - add learning provider entry as field
        // 'lp' in relevant REF14 table entry
        learningProviders.forEach(addTownDetailsToProvider);

        function addTownDetailsToProvider(provider){
            provider.townInfo = townsCSV.find(function(townDetails){
                return townDetails.Town === provider["Town-lc"];
            })
        }
    }

    function combineREFwithLPdata(ref14data, learningProviders){
        // For each learning provider university - add learning provider entry as field
        // 'lp' in relevant REF14 table entry
        ref14data.forEach(addLP);

        function addLP(refEntry){
            refEntry.lp = learningProviders.find(function(provider){
                return provider.UKPRN == refEntry["Institution code (UKPRN)"]
            });
            if (refEntry.lp){
                refEntry.County = refEntry.lp.townInfo.County;
                refEntry.Country = refEntry.lp.townInfo.Country;
            }
        }
    }

        return dmObj; // returning the main object
}
</code>```

main.js

```<code>var dataManager = {};

function startApplication(){

    dataManager = dataManager();

    dataManager.loadAllData("csvFiles/REF2014_Results.csv","csvFiles/Towns_List.csv","csvFiles/learning-providers-plus.csv",
        function(error){ // to call in case of error
            console.log("Error");
            console.log(error);
        },
        function(){ // to call if everything ok
            makePage();
        });
}

function makePage(){
    console.log("etstests");
    var dash = d3.select('div#dashboard');

    // EDIT PAGE STRUCTURE
    dash.append('div')
        .attr('id', 'bar1') // for renderer generation
        .classed("barchart", true) // for styling
            .append("h3").text("Number of submission per Univsersity");
</code>```

I putted a console.log to see if it enter but never see that console.log.

Is a d3 queue an endless loop ? If yes how can I return my data value after load it.

答:
The problem is the loadAllData signature is like below

dmObj.loadAllData = function (url1,url2,url3)

and you are calling like this:

```<code>dataManager.loadAllData("URL 1","URL 2","URL 3",
        function(error){ // to call in case of error
        console.log("Error");
        console.log(error);
    },
    function(){ // to call if everything ok
        makePage();
    });
</code>```

So success and error function will never be called as its not wired accordingly in the loadAllData

So it should be

```<code> dmObj.loadAllData = function (url1,url2,url3, callbackError, callBackSuccess) {
        d3.queue()
            .defer(d3.csv, url1)
            .defer(d3.csv, url2)
            .defer(d3.csv, url3)
            .await(processus);

        function processus(error,data1, data2, data3) {
            if(error){
               return callbackError(error);
            }
            callBackSuccess(data1, data2, data3);//make the success callback

            ref14data = data1;
            townsCSV = data2;
            learningProviders = data3;
</code>```

Title: D3 stuck in queue

Body:
Hello Iam loading 3 different csv with a d3.queue. But when I try to display my page it never call the function after loading the data.

data.js

function process(d){
       var processed = {
            code : d["Institution code (UKPRN)"],
            name : d["Institution name"],
            iSorte : d["Institution sort order"],
            nbAssess : d["Unit of assessment number"],
            naAsses: d["Unit of assessment name"],
            subLetter : d["Multiple submission letter"],
            subName : d["Multiple subimission name"],
            jSub : d["Joint submission"],
            profile : d["Profile"],
            fte : d["FTE Category A staff submitted"],
            one: d["1*"],
            two: d["2*"],
            three: d["3*"],
            four: d["4*"],
            unclassified: d["unclassified"]
                }
                return processed;
        }

function dataManager(){

    var dmObj = {}; // main object

    var ref14data;
    var townsCSV;
    var refUniversitiesByUKPRN;
    var learningProviders;
    var heriotWattCS;
    var dataset =[];
    // ---- PUBLIC API

    // function loading json data from url
    // parameters:
    //      - url, url of data in string format
    //      - callbackError, callback in case of error
    //      - callbackSuccess, callback if data loads normally
    // returns:
    //      - Nothing

    // function returning filtered data: money per year
    // parameters:
    //      - None
    // returns:
    //      - nestedData, data with following format:
    //          [{"key": year, "value": money}, {...}, ...]
    dmObj.getByName = function(){

        // using nest function from d3 to "classify" data into years
        // then rollup to change array of values into sum of money
        var nestedData = d3.nest()
            .key(function(d){return d.name;})
            .sortKeys(d3.ascending)
            .rollup(function(values){return values.length;})
            .entries(dataset);

        console.log("databyname",nestedData);

        return nestedData;
    }

    // function returning filtered data: money per area
    // parameters:
    //      - None
    // returns:
    //      - nestedData, data with following format:
    //          [{"key": area, "value": money}, {...}, ...]
    dmObj.getArea = function(key){

        var nestedData = d3.nest()
            .key(function (d) {return d.name;})
            .key(function (d) {return d.naAsses;})
            .rollup(function(values) {return values.length})
            .map(dataset);

        return nestedData["$"+key];
    }

    dmObj.loadAllData = function (url1,url2,url3) {
        d3.queue()
            .defer(d3.csv, url1)
            .defer(d3.csv, url2)
            .defer(d3.csv, url3)
            .await(processus);

        function processus(error,data1, data2, data3) {
            ref14data = data1;
            townsCSV = data2;
            learningProviders = data3;

            //Create master table
            combineLPwithTownData(learningProviders, townsCSV);
            console.log('ref data ',learningProviders);
            console.log('town',townsCSV);

            combineREFwithLPdata(ref14data, learningProviders);

            //Just consider "overall" assessments
            ref14data = ref14data.filter(function (e) { return e.Profile === "Overall" })

            console.log('ref', ref14data);
            return ref14data;
        }
    }

    dmObj.getHierarchy = function(){
        var hierarchyJSON = createJSONhierarchy(ref14data, "root",
            ["Country","County", "Institution name"])

        return hierarchyJSON;
    }

    function combineLPwithTownData(learningProviders, townsCSV){
        // For each learning provider university - add learning provider entry as field
        // 'lp' in relevant REF14 table entry
        learningProviders.forEach(addTownDetailsToProvider);

        function addTownDetailsToProvider(provider){
            provider.townInfo = townsCSV.find(function(townDetails){
                return townDetails.Town === provider["Town-lc"];
            })
        }
    }

    function combineREFwithLPdata(ref14data, learningProviders){
        // For each learning provider university - add learning provider entry as field
        // 'lp' in relevant REF14 table entry
        ref14data.forEach(addLP);

        function addLP(refEntry){
            refEntry.lp = learningProviders.find(function(provider){
                return provider.UKPRN == refEntry["Institution code (UKPRN)"]
            });
            if (refEntry.lp){
                refEntry.County = refEntry.lp.townInfo.County;
                refEntry.Country = refEntry.lp.townInfo.Country;
            }
        }
    }

        return dmObj; // returning the main object
}

main.js

var dataManager = {};

function startApplication(){

    dataManager = dataManager();

    dataManager.loadAllData("csvFiles/REF2014_Results.csv","csvFiles/Towns_List.csv","csvFiles/learning-providers-plus.csv",
        function(error){ // to call in case of error
            console.log("Error");
            console.log(error);
        },
        function(){ // to call if everything ok
            makePage();
        });
}

function makePage(){
    console.log("etstests");
    var dash = d3.select('div#dashboard');

    // EDIT PAGE STRUCTURE
    dash.append('div')
        .attr('id', 'bar1') // for renderer generation
        .classed("barchart", true) // for styling
            .append("h3").text("Number of submission per Univsersity");

I putted a console.log to see if it enter but never see that console.log.

Is a d3 queue an endless loop ? If yes how can I return my data value after load it.

Body:
The problem is the loadAllData signature is like below

dmObj.loadAllData = function (url1,url2,url3)

and you are calling like this:

dataManager.loadAllData("URL 1","URL 2","URL 3",
        function(error){ // to call in case of error
        console.log("Error");
        console.log(error);
    },
    function(){ // to call if everything ok
        makePage();
    });

So success and error function will never be called as its not wired accordingly in the loadAllData

So it should be

 dmObj.loadAllData = function (url1,url2,url3, callbackError, callBackSuccess) {
        d3.queue()
            .defer(d3.csv, url1)
            .defer(d3.csv, url2)
            .defer(d3.csv, url3)
            .await(processus);

        function processus(error,data1, data2, data3) {
            if(error){
               return callbackError(error);
            }
            callBackSuccess(data1, data2, data3);//make the success callback

            ref14data = data1;
            townsCSV = data2;
            learningProviders = data3;


问:
Calculating list cumulative sum in Haskell
Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?</p>

```<code>sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)
</code>```

答:
I think you want a combination of scanl1 and (+), so something like

```<code>scanl1 (+) *your list here*
</code>```

scanl1 will apply the given function across a list, and report each intermediate value into the returned list.

Like, to write it out in pseudo code,

```<code>scanl1 (+) [1,2,3]
</code>```

would output a list like:

```<code>[a, b, c] where { a = 1, b = a+2, c = b+3 }
</code>```

or in other words,

```<code>[1, 3, 6]
</code>```

Learn You A Haskell has a lot of great examples and descriptions of scans, folds, and much more of Haskell's goodies.

Hope this helps.

Body:
Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?

sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)

Body:
I think you want a combination of scanl1 and (+), so something like

scanl1 (+) *your list here*

scanl1 will apply the given function across a list, and report each intermediate value into the returned list.

Like, to write it out in pseudo code,

scanl1 (+) [1,2,3]

would output a list like:

[a, b, c] where { a = 1, b = a+2, c = b+3 }

or in other words,

[1, 3, 6]

Learn You A Haskell has a lot of great examples and descriptions of scans, folds, and much more of Haskell's goodies.

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
HTML label center aligned getting cropped on both sides
I'm seeing a bug that is intermittently reproducible only on iPhone Safari (not on any other mobile or desktop browser not even macbook safari). The code looks like:

```<code><div style="overflow: auto; height: calc(100% - 55px); background-color: cyan;">
   <ul ...><li..></li> <!-- some ul containing li omitted for brevity-->

   <label class="certainClassname" style="font-size: small; font-style: italic; width: 100%; text-align: center; background-color: yellow">
{{"msg" | translate}}
   </label>
</div>
</code>```

In other style sheet I have:

```<code>.certainClassname {
    cursor: pointer;
    word-break: break-all;
}
</code>```

msg = "PKtest!" for my testing though it usually has another value.

The problem is that this label is getting cropped at the edges when the bug is reproduced as below:

This bug is only seen on Safari iPhone and none of the other browsers, and seems to only happen the first time that page is loaded, and not later. It could be related to zooming because even the tiniest pinch-to-zoom on iPhone fixes it and the label text (and yellow) expands fully.

Could someone please help me diagnosing this in CSS above? I've tried to fix using each in css of label but none have worked:

```<code>display: inline;
display: inline-block;
display: block;
padding: 2px 10px 2px 10px;
margin-left: auto;
margin-right: auto;
z-index: 999;
clear: both;
(all these above tested but none fixes this issue seen intermittently and only on iPhone Safari).
</code>```

答:
It's difficult to get the idea without reviewing working code. But I tried to run your code, regenerate the bug and here is the possible solution. Let me know, is it something you are looking for?

.certainClassname {
    cursor: pointer;
    word-break: break-all;
    font-size: small;
    font-style: italic;
    width: 100%;
    text-align: center;
    background-color: yellow;
    display: inline-block;
}
ul {
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="overflow: auto; height: calc(100% - 55px); background-color: cyan;">
   <ul ...><li..></li> <!-- some ul containing li omitted for brevity-->

   <label class="certainClassname">
{{"msg" | translate}}
   </label>
</div></code>```

Body:
I'm seeing a bug that is intermittently reproducible only on iPhone Safari (not on any other mobile or desktop browser not even macbook safari). The code looks like:

{{"msg" | translate}}

In other style sheet I have:

.certainClassname {
    cursor: pointer;
    word-break: break-all;
}

msg = "PKtest!" for my testing though it usually has another value.

The problem is that this label is getting cropped at the edges when the bug is reproduced as below:

This bug is only seen on Safari iPhone and none of the other browsers, and seems to only happen the first time that page is loaded, and not later. It could be related to zooming because even the tiniest pinch-to-zoom on iPhone fixes it and the label text (and yellow) expands fully.

Could someone please help me diagnosing this in CSS above? I've tried to fix using each in css of label but none have worked:

display: inline;
display: inline-block;
display: block;
padding: 2px 10px 2px 10px;
margin-left: auto;
margin-right: auto;
z-index: 999;
clear: both;
(all these above tested but none fixes this issue seen intermittently and only on iPhone Safari).

Body:
It's difficult to get the idea without reviewing working code. But I tried to run your code, regenerate the bug and here is the possible solution. Let me know, is it something you are looking for?

.certainClassname {
    cursor: pointer;
    word-break: break-all;
    font-size: small;
    font-style: italic;
    width: 100%;
    text-align: center;
    background-color: yellow;
    display: inline-block;
}
ul {
  padding: 0;
}

<div style="overflow: auto; height: calc(100% - 55px); background-color: cyan;">
   <ul ...><li..></li> <!-- some ul containing li omitted for brevity-->

   <label class="certainClassname">
{{"msg" | translate}}
   </label>
</div>


问:
Laravel retrieve only the email address column in database for users table
Hi I had code that stated

```<code>    $users = User::all();
</code>```

But I only want the email addresses of the users in a collection. So I tried:

```<code>    $users = User::select('id', 'email')->first();
</code>```

This does not work as I want. When I do a var_dump I only want to see the users email addresses. Any tips?

UPDATE: I inserted my blade code as well. I use a Vue component that has a dropdown and I filter the data in the Vue method and insert the filtered data under userEmail:

The component:

```<code>    <commands-component
                :entity-config="commandConfig(command.id, command.signature, command.hasUser, command.title, command.groupID, command.groupName)">
                <input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title" v-on:click='disableEmailText(command.hasUser)'>
        </commands-component>
</code>```

The Vue:

```<code>    var systemadmin = new Vue({
    el: "#sysadmin",
    data: function() {
        return {
          users: <?php echo $users ?>,
          userData: [],
          commands: <?php echo $commands ?>,
        }
    },

    methods: {
      commandConfig: function(ident, signature, hasUser, title, groupId, groupName){
        var that =  this;
        var commandsGetUsers = [];

        commandsGetUsers  = _.map(that.users, function(value) {
            var newValue = {};
            newValue.value = value.id;
            newValue.text = value.email;
            return newValue;
        });

        return {
          id: { text: 'commandModal' + ident, id: null },
          modalTitle: title,
          buttons: [
              {
                  buttonTitle: 'Run Command',
                  buttonClass: 'btn btn-success pull-right',
                  submitUrl: {
                      url: '/admin/artisan/commands/run',

                  },
              }
          ],
          attributes: [
            {name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text",  col: "12" },
            {name: "signature", displayName: "Command Signature", type:'text', col:"6"},
            {name: "userEmail", displayName: "Users", type: 'select', options: commandsGetUsers, col:'6'}
          ],
          data: {
              signature:signature,
              hasUser:hasUser
          }
        };

      },
</code>```

答:
If you want all users:

$users = User::get(['id', 'email']);

Single user by Id:

$user = User::find(1, ['id', 'email']);

The above will return a collection (first case), or a single model (second case);

if want to get the email only from the result:

```<code>$users->pluck('email');

$user->email; // obviously :)
</code>```

You get better performance when you limit your query to return only the columns you need which is done by passing an array to get() and find methods.

Body:
Hi I had code that stated

    $users = User::all();

But I only want the email addresses of the users in a collection. So I tried:

    $users = User::select('id', 'email')->first();

This does not work as I want. When I do a var_dump I only want to see the users email addresses. Any tips?

UPDATE: I inserted my blade code as well. I use a Vue component that has a dropdown and I filter the data in the Vue method and insert the filtered data under userEmail:

The component:

    <commands-component
                :entity-config="commandConfig(command.id, command.signature, command.hasUser, command.title, command.groupID, command.groupName)">
                <input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title" v-on:click='disableEmailText(command.hasUser)'>
        </commands-component>

The Vue:

    var systemadmin = new Vue({
    el: "#sysadmin",
    data: function() {
        return {
          users: <?php echo $users ?>,
          userData: [],
          commands: <?php echo $commands ?>,
        }
    },

    methods: {
      commandConfig: function(ident, signature, hasUser, title, groupId, groupName){
        var that =  this;
        var commandsGetUsers = [];

        commandsGetUsers  = _.map(that.users, function(value) {
            var newValue = {};
            newValue.value = value.id;
            newValue.text = value.email;
            return newValue;
        });

        return {
          id: { text: 'commandModal' + ident, id: null },
          modalTitle: title,
          buttons: [
              {
                  buttonTitle: 'Run Command',
                  buttonClass: 'btn btn-success pull-right',
                  submitUrl: {
                      url: '/admin/artisan/commands/run',

                  },
              }
          ],
          attributes: [
            {name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text",  col: "12" },
            {name: "signature", displayName: "Command Signature", type:'text', col:"6"},
            {name: "userEmail", displayName: "Users", type: 'select', options: commandsGetUsers, col:'6'}
          ],
          data: {
              signature:signature,
              hasUser:hasUser
          }
        };

      },

Body:
If you want all users:

$users = User::get(['id', 'email']);

Single user by Id:

$user = User::find(1, ['id', 'email']);

The above will return a collection (first case), or a single model (second case);

if want to get the email only from the result:

$users->pluck('email');

$user->email; // obviously :)

You get better performance when you limit your query to return only the columns you need which is done by passing an array to get() and find methods.


问:
Get the UserId from AbpSession in SignalR Hub
I can't get the UserId from AbpSession inside a class that implements ITransientDependency.

```<code>public class Chat : Hub, ITransientDependency
{
    public IAbpSession AbpSession { get; set; }

    public ILogger Logger { get; set; }

    public Chat()
    {
        AbpSession = NullAbpSession.Instance;
        Logger = NullLogger.Instance;
    }

    private static List<MemberDto> _members = new List<MemberDto>();

    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", string.Format("User {0}: {1}", UserId(), message));
    }

    public long? UserId()
    {
        return AbpSession.UserId;
    }
}
</code>```

Properties UserId and TenantId are still null.

Chat class is inside the "Application" layer where AbpSession is working well.

答:
I think that the problem can be related to property injection you are using:

```<code>public IAbpSession AbpSession { get; set; }
</code>```

While SignalR uses DI, it does not create Chat class from DI container. That means property injection does not work. But constructor injection would work since it passes ctor parameters from DI container.

So, use constructor injection instead of property injection.

Body:
I can't get the UserId from AbpSession inside a class that implements ITransientDependency.

public class Chat : Hub, ITransientDependency
{
    public IAbpSession AbpSession { get; set; }

    public ILogger Logger { get; set; }

    public Chat()
    {
        AbpSession = NullAbpSession.Instance;
        Logger = NullLogger.Instance;
    }

    private static List<MemberDto> _members = new List<MemberDto>();

    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", string.Format("User {0}: {1}", UserId(), message));
    }

    public long? UserId()
    {
        return AbpSession.UserId;
    }
}

Properties UserId and TenantId are still null.

Chat class is inside the "Application" layer where AbpSession is working well.

Body:
I think that the problem can be related to property injection you are using:

public IAbpSession AbpSession { get; set; }

While SignalR uses DI, it does not create Chat class from DI container. That means property injection does not work. But constructor injection would work since it passes ctor parameters from DI container.

So, use constructor injection instead of property injection.


问:
Reaching Form Instances
I'm creating a level editor application designed in a MDI project. The application has two main view modes, the WorldEditor mode and ObjectEditor mode. Depending on the mode, I want a separate property window to show a property setup specific for the current mode.

I've thought of using the Activated event, and from that event tell the property form to load the appropriate setup. I need to reach the PropertyForm from within the World or Object Form class to accomplish this. This is where I'm stuck.

I believe I should be able to solve this by declaring the PropertyForm class as static. Since I only use one of it's types at a time, I want to be able to reach it globally. However declaring a form class as static gives me compiler errors. I'm doing it wrong, if it's even possible.

How can I reach and search for different forms that are active in the application?

答:
What you need is a singleton, not a static class.

Without much loss of performance you can create different objects of PropertyForm - one for each type of 'view' you have. You can add a parametrized constructor - should take an object that has the details specific to each view. This will allow you to create the PropertyForm specific for each view.

If you really want to have just one copy of the PropertyForm, then a simpler approach is to hide the form. In the "show" event handler you can customize it per the current view. Consider the singleton approach as the last.

OwnerDisplayName: Erik

Title: Reaching Form Instances

OwnerDisplayName: Sesh

ContentLicense: CC BY-SA 2.5


答:
The reason the label is getting cropped might be because of style="overflow: auto; height: calc(100% - 55px)" for div. </p>

<p>div is the parent of label. Therefore label is inheriting its style from its parent. You may consider removing height: calc(100% - 55px) to see if it works   </p>

Title: HTML label center aligned getting cropped on both sides

Body:
The reason the label is getting cropped might be because of style="overflow: auto; height: calc(100% - 55px)" for div.

div is the parent of label. Therefore label is inheriting its style from its parent. You may consider removing height: calc(100% - 55px) to see if it works


问:
Creating 10 blank records in a database file
I'm using a for loop to try to create a "blank" file of 10 records where the values are set to 0 or blank using a constructor from my class, found below:

```<code>class employee {

char name[30], hire_date[30], salary[30];
int ID;

public:

employee(string = "", int = 0, string = "", string = "") {
    void setHireDate(string);
    string getHireDate();

    void setname(string);
    string getName();

    void setsal(string);
    string getsal();

    void setId(int);
    int getId();

}
</code>```

See below the beginning of int main(). The section where my program supposedly creates the blank database file

```<code>int main()
{
int a, id;
string name, hire_date, salary;

cout << "Welcome to Mahendra Pruitt's Employee Database!\nEnter a number for the option you would like to select:\nPlease choose option 0 if you haven't already chosen that one.\n" <<
    "0 - Create a blank new database file that will overwrite all existing data." << endl
    << "1 - Choose employee IDs (1-10) and change or add information to their file" << endl
    << "2 - Select whether or not you would like to update, view, or add a new record." << endl;

cin >> a;

// creating a blank database file
employee blankelist;

if (a == 0) {
    while (a == 0) {
        if (a == 0) {

            ofstream outdatabase("database.dat", ios::out | ios::binary);
            for (int i = 0; i < 10; i++) {
                outdatabase.write(reinterpret_cast <const char *> (&blankelist), sizeof(employee));
            }

            cout << "Enter the number 1 or 2: " << endl
                << "1 - Choose employee IDs (1-10) and change or add information to their file" << endl
                << "2 - Select whether or not you would like to update, view, or add a new record." << endl;
            cin >> a;

        }
    }
}
</code>```

Throughout the rest of my program, I use a separate instance of employee that i call "employed" ... see example of one of my functions, whose purpose is to output stored information to be viewed:

```<code>void outputLine(ostream &output, employee &employed, int i, fstream &readfromfile)
{
int id = i;
readfromfile.seekg((id - 1) * sizeof(employee));
readfromfile.read(reinterpret_cast <char *>(&employed), sizeof(employee));
output << "ID: " << employed.getId() << endl
    << "Name: " << employed.getName() << endl
    << "Salary: " << employed.getsal() << endl
    << "Hire date: " << employed.getHireDate() << endl;
}
</code>```

When I run the option to create these blank files and try to view a record, it rather shows numbers/gibberish... See output below:

```<code>Enter your choice:
1 - Update an account
2 - Add a new account
3 - View record
4 - End program
3
Which record would you like to view? (1-10). Enter 0 to go back to the menu.:
1
ID: -858993460
Name:  ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Salary: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Hire date:
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
</code>```

How do I get my program to set it up so that whenever I run the section that creates blank records, it creates them, and if I try to view the record, it shows up as blank?

I've tried the following statement as well:

```<code> outdatabase.write(reinterpret_cast <const char *> (&employed), sizeof(employee));
</code>```

instead of

```<code> outdatabase.write(reinterpret_cast <const char *> (&blankelist), sizeof(employee));
</code>```

In my for loop, but that didn't work either.

Looking forward to your responses!

答:
In constructor employee::employee() you are declaring some functions instead of calling them. It appears you need to call some member functions and those functions should set the members to a sensible value.

BTW you should learn serialization and deserialization of classes for such tasks.

Further readings:

Serialization and Unserialization, C++ FAQ - ISO C++

A practical guide to C++ serialization

Boost Serialization

Serialization in MFC

Body:
I'm using a for loop to try to create a "blank" file of 10 records where the values are set to 0 or blank using a constructor from my class, found below:

class employee {

char name[30], hire_date[30], salary[30];
int ID;

public:

employee(string = "", int = 0, string = "", string = "") {
    void setHireDate(string);
    string getHireDate();

    void setname(string);
    string getName();

    void setsal(string);
    string getsal();

    void setId(int);
    int getId();

}

See below the beginning of int main(). The section where my program supposedly creates the blank database file

int main()
{
int a, id;
string name, hire_date, salary;

cout << "Welcome to Mahendra Pruitt's Employee Database!\nEnter a number for the option you would like to select:\nPlease choose option 0 if you haven't already chosen that one.\n" <<
    "0 - Create a blank new database file that will overwrite all existing data." << endl
    << "1 - Choose employee IDs (1-10) and change or add information to their file" << endl
    << "2 - Select whether or not you would like to update, view, or add a new record." << endl;

cin >> a;

// creating a blank database file
employee blankelist;

if (a == 0) {
    while (a == 0) {
        if (a == 0) {

            ofstream outdatabase("database.dat", ios::out | ios::binary);
            for (int i = 0; i < 10; i++) {
                outdatabase.write(reinterpret_cast <const char *> (&blankelist), sizeof(employee));
            }

            cout << "Enter the number 1 or 2: " << endl
                << "1 - Choose employee IDs (1-10) and change or add information to their file" << endl
                << "2 - Select whether or not you would like to update, view, or add a new record." << endl;
            cin >> a;

        }
    }
}

Throughout the rest of my program, I use a separate instance of employee that i call "employed" ... see example of one of my functions, whose purpose is to output stored information to be viewed:

void outputLine(ostream &output, employee &employed, int i, fstream &readfromfile)
{
int id = i;
readfromfile.seekg((id - 1) * sizeof(employee));
readfromfile.read(reinterpret_cast <char *>(&employed), sizeof(employee));
output << "ID: " << employed.getId() << endl
    << "Name: " << employed.getName() << endl
    << "Salary: " << employed.getsal() << endl
    << "Hire date: " << employed.getHireDate() << endl;
}

When I run the option to create these blank files and try to view a record, it rather shows numbers/gibberish... See output below:

Enter your choice:
1 - Update an account
2 - Add a new account
3 - View record
4 - End program
3
Which record would you like to view? (1-10). Enter 0 to go back to the menu.:
1
ID: -858993460
Name:  ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Salary: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Hire date:
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

How do I get my program to set it up so that whenever I run the section that creates blank records, it creates them, and if I try to view the record, it shows up as blank?

I've tried the following statement as well:

 outdatabase.write(reinterpret_cast <const char *> (&employed), sizeof(employee));

instead of

 outdatabase.write(reinterpret_cast <const char *> (&blankelist), sizeof(employee));

In my for loop, but that didn't work either.

Looking forward to your responses!


问:
How to get ID of button when clicked while it is looped
[i am using this loop to select existing data from database table and assigning them to html  element. it works fine but I have no idea how to select its ID when the button is clicked.

I tried using document.GetElementByID but cannot choose particular ID when the button is clicked. Any suggestions on how to get the ID Of that button when it is clicked using javascript?

```<code><?php
include "connect.php";
$stmnt = "select * from tbl_category";
$run = $con->query($stmnt);
$num=$run->num_rows;
if($num>0)
{
while($data = $run->fetch_array()){
$btn1 = $data['id'];
echo $btn1;
?>
<button id="<?php $btn1;?>" class="btn"><?php echo $data['category']; ?>
</button>
<?php
}
}
?>`
</code>```

答:
Use javascript function:    </p>

```<code><button id="<?php $btn1;?>" class="btn" onclick="javascript:get_buttonid(this);"><?php echo $data['category']; ?>
    </button>
    <script>
    function get_buttonid(ths){
        alert(ths.id);
    }
    </script>
</code>```

Body:
[i am using this loop to select existing data from database table and assigning them to html  element. it works fine but I have no idea how to select its ID when the button is clicked.

I tried using document.GetElementByID but cannot choose particular ID when the button is clicked. Any suggestions on how to get the ID Of that button when it is clicked using javascript?

<?php
include "connect.php";
$stmnt = "select * from tbl_category";
$run = $con->query($stmnt);
$num=$run->num_rows;
if($num>0)
{
while($data = $run->fetch_array()){
$btn1 = $data['id'];
echo $btn1;
?>
<button id="<?php $btn1;?>" class="btn"><?php echo $data['category']; ?>
</button>
<?php
}
}
?>`

Body:
Use javascript function:

<button id="<?php $btn1;?>" class="btn" onclick="javascript:get_buttonid(this);"><?php echo $data['category']; ?>
    </button>
    <script>
    function get_buttonid(ths){
        alert(ths.id);
    }
    </script>


问:
Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details
```<code>Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details
</code>```

build:gradle(Module:app)

```<code>buildscript {
    repositories {
        maven {
            url 'https://jitpack.io'
            url 'https://maven.fabric.io/public'
        }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android-extensions'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    mavenCentral()
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    useLibrary 'org.apache.http.legacy'

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    defaultConfig {
        applicationId "uxx.xx.xxe"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 17
        versionName "0.1.14"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            ext.enableCrashlytics = false
            debuggable true
            minifyEnabled true
            shrinkResources true

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
            res.srcDirs = ['src/main/res', 'src/main/assets/fonts']
        }
    }

    dexOptions {
        jumboMode true
        javaMaxHeapSize "4g"

    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/ECLIPSE_.SF'
        exclude 'META-INF/ECLIPSE_.RSA'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    compile "com.android.support:cardview-v7:${rootProject.supportLibraryVersion}"
       compile "com.google.android.gms:play-services-ads:${rootProject.googlePlayServicesVersion}"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'org.igniterealtime.smack:smack-android-extensions:4.1.9'
    compile 'org.igniterealtime.smack:smack-tcp:4.1.9'
    compile 'org.igniterealtime.smack:smack-experimental:4.1.9'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.getkeepsafe.dexcount'
</code>```

build:gradle(Project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

```<code>buildscript {
    ext.kotlin_version = '1.1.2-2'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.google.gms:google-services:3.0.0'
        //visualize the method count
        classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

ext.googlePlayServicesVersion = '10.2.0'
ext.supportLibraryVersion = '25.3.1'

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Solution Tried:

Invalidate Caches/Restart

Build -> Clean Project

Update kotlin plugin, used lastest version of kotlin, google APIs.

EDIT

```<code>./gradlew build --stacktrace > logs.txt 2>logErrors.txt
</code>```

logErrors.txt

```<code>* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:8)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:286)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:260)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:160)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:141)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 70 more
</code>```

答:
I Had the same issue and finally discovered the reason. In my case it was a badly written Java method:

```<code>@FormUrlEncoded
@POST("register-user/")
Call<RegisterUserApiResponse> registerUser(
        @Field("email") String email,
        @Field("password") String password,
        @Field("date") String birthDate,
);
</code>```

Note the illegal comma after the "date" field. For some reason the compiler could not reveal this exact error, and came with the ':app:compileDebugKotlin'. > Compilation error thing.

Body:
Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

build:gradle(Module:app)

buildscript {
    repositories {
        maven {
            url 'https://jitpack.io'
            url 'https://maven.fabric.io/public'
        }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android-extensions'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    mavenCentral()
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    useLibrary 'org.apache.http.legacy'

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    defaultConfig {
        applicationId "uxx.xx.xxe"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 17
        versionName "0.1.14"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            ext.enableCrashlytics = false
            debuggable true
            minifyEnabled true
            shrinkResources true

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
            res.srcDirs = ['src/main/res', 'src/main/assets/fonts']
        }
    }

    dexOptions {
        jumboMode true
        javaMaxHeapSize "4g"

    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/ECLIPSE_.SF'
        exclude 'META-INF/ECLIPSE_.RSA'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    compile "com.android.support:cardview-v7:${rootProject.supportLibraryVersion}"
       compile "com.google.android.gms:play-services-ads:${rootProject.googlePlayServicesVersion}"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'org.igniterealtime.smack:smack-android-extensions:4.1.9'
    compile 'org.igniterealtime.smack:smack-tcp:4.1.9'
    compile 'org.igniterealtime.smack:smack-experimental:4.1.9'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.getkeepsafe.dexcount'

build:gradle(Project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-2'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.google.gms:google-services:3.0.0'
        //visualize the method count
        classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

ext.googlePlayServicesVersion = '10.2.0'
ext.supportLibraryVersion = '25.3.1'

task clean(type: Delete) {
    delete rootProject.buildDir
}

Solution Tried:

Invalidate Caches/Restart

Build -> Clean Project

Update kotlin plugin, used lastest version of kotlin, google APIs.

EDIT

./gradlew build --stacktrace > logs.txt 2>logErrors.txt

logErrors.txt

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
    at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
    at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:8)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:286)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:260)
    at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:160)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:141)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
    ... 70 more

Body:
I Had the same issue and finally discovered the reason. In my case it was a badly written Java method:

@FormUrlEncoded
@POST("register-user/")
Call<RegisterUserApiResponse> registerUser(
        @Field("email") String email,
        @Field("password") String password,
        @Field("date") String birthDate,
);

Note the illegal comma after the "date" field. For some reason the compiler could not reveal this exact error, and came with the ':app:compileDebugKotlin'. > Compilation error thing.