问:
ggplot2: reorder bars from highest to lowest in each facet
In the df below, I want to reorder bars from highest to lowest in each facet

I tried

```<code>df <- df %>% tidyr::gather("var", "value", 2:4)
ggplot(df, aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity")+facet_wrap(~var, ncol =3)
</code>```

It gave me

It didn't order the bars from highest to lowest in each facet.

I figured out another way to get what I want. I had to plot each variable at a time, then combine all plots using grid.arrange()

```<code>#I got this function from @eipi10's answer
#http://stackoverflow.com/questions/38637261/perfectly-align-several-plots/38640937#38640937
#Function to extract legend
# https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
g_legend<-function(a.gplot) {
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

p1 <- ggplot(df[df$var== "A", ], aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity") + facet_wrap(~var, ncol =3)

fin_legend <- g_legend(p1)
p1 <- p1 + guides(fill= F)

p2 <- ggplot(df[df$var== "B", ], aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity") + facet_wrap(~var, ncol =3)+guides(fill=FALSE)

p3 <- ggplot(df[df$var== "C", ], aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity") + facet_wrap(~var, ncol =3)+guides(fill=FALSE)

grid.arrange(p1, p2, p3, fin_legend, ncol =4, widths = c(1.5, 1.5, 1.5, 0.5))
</code>```

The result is what I want

I wonder if there is a straightforward way that can help me order the bars from highest to lowest in all facets without having to plot each variable separtely and then combine them. Any suggestions will be much appreciated.

DATA

```<code>df <-  read.table(text = c("
id  A   B   C
site1   10  15  20
site2   20  10  30
site3   30  20  25
site4   40  35  40
site5   50  30  35"), header = T)
</code>```

答:
The approach below uses a specially prepared variable for the x-axis with facet_wrap() but uses the labels parameter to scale_x_discrete() to display the correct x-axis labels:

Prepare data

I'm more fluent in data.table, so this is used here. Feel free to use what ever package you prefer for data manipulation.

Edit: Removed second dummy variable, only ord is required

```<code>library(data.table)
# reshape from wide to long
molten <- melt(setDT(df), id.vars = "id")
# create dummy var which reflects order when sorted alphabetically
molten[, ord := sprintf("%02i", frank(molten, variable, -value, ties.method = "first"))]

molten
#       id variable value ord
# 1: site1        A    10  05
# 2: site2        A    20  04
# 3: site3        A    30  03
# 4: site4        A    40  02
# 5: site5        A    50  01
# 6: site1        B    15  09
# 7: site2        B    10  10
# 8: site3        B    20  08
# 9: site4        B    35  06
#10: site5        B    30  07
#11: site1        C    20  15
#12: site2        C    30  13
#13: site3        C    25  14
#14: site4        C    40  11
#15: site5        C    35  12
</code>```

Create plot

```<code>library(ggplot2)
# `ord` is plotted on x-axis instead of `id`
ggplot(molten, aes(x = ord, y = value, fill = id)) +
  # geom_col() is replacement for geom_bar(stat = "identity")
  geom_col() +
  # independent x-axis scale in each facet,
  # drop absent factor levels (not the case here)
  facet_wrap(~ variable, scales = "free_x", drop = TRUE) +
  # use named character vector to replace x-axis labels
  scale_x_discrete(labels = molten[, setNames(as.character(id), ord)]) +
  # replace x-axis title
  xlab("id")
</code>```

Data

```<code>df <- read.table(text = "
id  A   B   C
site1   10  15  20
site2   20  10  30
site3   30  20  25
site4   40  35  40
site5   50  30  35", header = T)
</code>```

Body:
In the df below, I want to reorder bars from highest to lowest in each facet

I tried

df <- df %>% tidyr::gather("var", "value", 2:4)
ggplot(df, aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity")+facet_wrap(~var, ncol =3)

It gave me

It didn't order the bars from highest to lowest in each facet.

I figured out another way to get what I want. I had to plot each variable at a time, then combine all plots using grid.arrange()

#I got this function from @eipi10's answer
#http://stackoverflow.com/questions/38637261/perfectly-align-several-plots/38640937#38640937
#Function to extract legend
# https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
g_legend<-function(a.gplot) {
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

p1 <- ggplot(df[df$var== "A", ], aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity") + facet_wrap(~var, ncol =3)

fin_legend <- g_legend(p1)
p1 <- p1 + guides(fill= F)

p2 <- ggplot(df[df$var== "B", ], aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity") + facet_wrap(~var, ncol =3)+guides(fill=FALSE)

p3 <- ggplot(df[df$var== "C", ], aes (x = reorder(id, -value), y = value, fill = id))+
  geom_bar(stat="identity") + facet_wrap(~var, ncol =3)+guides(fill=FALSE)

grid.arrange(p1, p2, p3, fin_legend, ncol =4, widths = c(1.5, 1.5, 1.5, 0.5))

The result is what I want

I wonder if there is a straightforward way that can help me order the bars from highest to lowest in all facets without having to plot each variable separtely and then combine them. Any suggestions will be much appreciated.

DATA

df <-  read.table(text = c("
id  A   B   C
site1   10  15  20
site2   20  10  30
site3   30  20  25
site4   40  35  40
site5   50  30  35"), header = T)

Body:
The approach below uses a specially prepared variable for the x-axis with facet_wrap() but uses the labels parameter to scale_x_discrete() to display the correct x-axis labels:

Prepare data

I'm more fluent in data.table, so this is used here. Feel free to use what ever package you prefer for data manipulation.

Edit: Removed second dummy variable, only ord is required

library(data.table)
# reshape from wide to long
molten <- melt(setDT(df), id.vars = "id")
# create dummy var which reflects order when sorted alphabetically
molten[, ord := sprintf("%02i", frank(molten, variable, -value, ties.method = "first"))]

molten
#       id variable value ord
# 1: site1        A    10  05
# 2: site2        A    20  04
# 3: site3        A    30  03
# 4: site4        A    40  02
# 5: site5        A    50  01
# 6: site1        B    15  09
# 7: site2        B    10  10
# 8: site3        B    20  08
# 9: site4        B    35  06
#10: site5        B    30  07
#11: site1        C    20  15
#12: site2        C    30  13
#13: site3        C    25  14
#14: site4        C    40  11
#15: site5        C    35  12

Create plot

library(ggplot2)
# `ord` is plotted on x-axis instead of `id`
ggplot(molten, aes(x = ord, y = value, fill = id)) +
  # geom_col() is replacement for geom_bar(stat = "identity")
  geom_col() +
  # independent x-axis scale in each facet,
  # drop absent factor levels (not the case here)
  facet_wrap(~ variable, scales = "free_x", drop = TRUE) +
  # use named character vector to replace x-axis labels
  scale_x_discrete(labels = molten[, setNames(as.character(id), ord)]) +
  # replace x-axis title
  xlab("id")

Data

df <- read.table(text = "
id  A   B   C
site1   10  15  20
site2   20  10  30
site3   30  20  25
site4   40  35  40
site5   50  30  35", header = T)


来源: stackexchange

问:
How to add text translation via resValue
On our Android app we're passing strings resources via build script using the resValue, something like this:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
       resValue "string", "foo", "foo_value"
       resValue "string", "bar", "bar_value"
       ... etc
</code>```

How to add translated version of those strings. To go on values-de, values-ch, values-sp, etc folders?

答:
Apparently it is not possible to do it from the gradle file as mentioned here.
If you just want to use the values, better use the buildConfigField instead

ContentLicense: CC BY-SA 3.0

Body:
On our Android app we're passing strings resources via build script using the resValue, something like this:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
       resValue "string", "foo", "foo_value"
       resValue "string", "bar", "bar_value"
       ... etc

How to add translated version of those strings. To go on values-de, values-ch, values-sp, etc folders?


问:
How to did preg_match_all in rails
Is  Not working in Rails ??

statement= '
As he opened the door, Winston saw that he had left the diary open on the table. DOWN WITH BIG BROTHER was written in it, in letters you could almost read across the room.
\r\n
But everything was all right. A small, sad-looking woman was standing outside.
\r\n
'Oh, Comrade Smith,' she said, in a dull little voice, 'do you think you could come across and help me with our kitchen sink? The water isn't running away and ...'
\r\n

```<code>result = statement.scan('/<span style="text-decoration: underline;">(.*)<\/span>/U')
</code>```

答:
Check whether this helps.
If

```<code>statement= "<p>As he opened the door, Winston saw that he had left the diary open on the table. DOWN WITH BIG BROTHER was written in it, in letters you could almost <span style='text-decoration: underline;'>read</span> across the room.</p>\r\n<p>But everything was all right. A small, sad-looking woman was standing outside.</p>\r\n<p>'Oh, Comrade Smith,' she said, in a dull little voice, 'do you think you could come across and help me with our kitchen sink? The water isn't running away and ...'</p>\r\n<p>".html_safe
</code>```

then

```<code>result = statement.scan(/<span style='text-decoration: underline;'>.*<\/span>/)
#=> ["<span style='text-decoration: underline;'>read</span>"]
</code>```

Title: How to did preg_match_all in rails

Body:
Is  Not working in Rails ??

statement= '
As he opened the door, Winston saw that he had left the diary open on the table. DOWN WITH BIG BROTHER was written in it, in letters you could almost read across the room.
\r\n
But everything was all right. A small, sad-looking woman was standing outside.
\r\n
'Oh, Comrade Smith,' she said, in a dull little voice, 'do you think you could come across and help me with our kitchen sink? The water isn't running away and ...'
\r\n

result = statement.scan('/(.*)<\/span>/U')

Body:
Check whether this helps.
If

statement= "<p>As he opened the door, Winston saw that he had left the diary open on the table. DOWN WITH BIG BROTHER was written in it, in letters you could almost <span style='text-decoration: underline;'>read</span> across the room.</p>\r\n<p>But everything was all right. A small, sad-looking woman was standing outside.</p>\r\n<p>'Oh, Comrade Smith,' she said, in a dull little voice, 'do you think you could come across and help me with our kitchen sink? The water isn't running away and ...'</p>\r\n<p>".html_safe

then

result = statement.scan(/<span style='text-decoration: underline;'>.*<\/span>/)
#=> ["<span style='text-decoration: underline;'>read</span>"]


问:
How to allow only numbers in textbox and format as US mobile number format in react js? ex : (224) - 5623 -2365
I am using React for mobile number validation. The TextField should allow only digits and it will format as US mobile number format. I am restricting to allow only digits, but the format is not happening. I am using material-ui for validation. Below my code.</p>

```<code>import React from 'react';
import TextField from '@material-ui/core/TextField';

export default class myClass extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(e) {
        const re = /[0-9]+/g;
        if (e.target.value === '' || re.test(e.target.value)) {
            this.setState({ value: e.target.value });
        }
    }
    render() {
        return (
            <div>
                <TextField
                    floatingLabelText="mobileNumber"
                    onChange={this.handleChange}
                    value={this.state.value}
                />
            </div>
        );
    }
}
</code>```

答:
I have restricted the textbox to allow only numbers and formatted the mobile number as US mobile number format. Follow the below code.</p>

```<code>handleChange(e) {
    const onlyNums = e.target.value.replace(/[^0-9]/g, '');
    if (onlyNums.length < 10) {
        this.setState({ value: onlyNums });
    } else if (onlyNums.length === 10) {
        const number = onlyNums.replace(
            /(\d{3})(\d{3})(\d{4})/,
            '($1) $2-$3'
        );
        this.setState({ value: number });
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using React for mobile number validation. The TextField should allow only digits and it will format as US mobile number format. I am restricting to allow only digits, but the format is not happening. I am using material-ui for validation. Below my code.

import React from 'react';
import TextField from '@material-ui/core/TextField';

export default class myClass extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(e) {
        const re = /[0-9]+/g;
        if (e.target.value === '' || re.test(e.target.value)) {
            this.setState({ value: e.target.value });
        }
    }
    render() {
        return (

                <TextField
                    floatingLabelText="mobileNumber"
                    onChange={this.handleChange}
                    value={this.state.value}
                />

        );
    }
}

Body:
I have restricted the textbox to allow only numbers and formatted the mobile number as US mobile number format. Follow the below code.

handleChange(e) {
    const onlyNums = e.target.value.replace(/[^0-9]/g, '');
    if (onlyNums.length < 10) {
        this.setState({ value: onlyNums });
    } else if (onlyNums.length === 10) {
        const number = onlyNums.replace(
            /(\d{3})(\d{3})(\d{4})/,
            '($1) $2-$3'
        );
        this.setState({ value: number });
    }
}


问:
ng-repeat shows terrible performance with large lists
I'm experiencing performance issues when using ng-repeat for long lists (thousands of records) that need to be shown within a table.

Here is the HTML I'm using:

```<code>    <table class="table table-hover">
        <thead>
            <tr>
                <th ng-repeat="One_Header in Data_List.Header track by $index">{{One_Header}}</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-model="Data_List" ng-repeat="One_Source in Data_List.Body track by $index" style="cursor:pointer">
                <td ng-repeat="One_Data_Field in One_Source track by $index">{{One_Data_Field}}</td>
            </tr>
        </tbody>
    </table>
</code>```

The received JSON (takes about 1 second to get it from the server) contains the data as follows:

```<code>"Data":{
         "Header":["Title_1","Title_2","Title_3"],
         "Body":[
                 ["Rec_1_Data_1","Rec_1_Data_2","Rec_1_Data_3"],
                 ["Rec_2_Data_1","Rec_2_Data_2","Rec_2_Data_3"],
                 ["Rec_3_Data_1","Rec_3_Data_2","Rec_3_Data_3"],
                 :
                 ["Rec_n_Data_1","Rec_n_Data_2","Rec_n_Data_3"]
                ]
}
</code>```

I also tried one-directional binding (i.e. {{::One_Data_Field}}) without any noticeable improvement.

As stated above, response arrives within a second and then it takes up to 10 seconds for the table to be built.

答:
in order to improve the performance, you can use pagination directives created using angular js.

Angular-Paging

pagination

If you are using Angular material design then I would highly recommend using virtual repeat

virtual repeat

Body:
I'm experiencing performance issues when using ng-repeat for long lists (thousands of records) that need to be shown within a table.

Here is the HTML I'm using:

                {{One_Header}}

                {{One_Data_Field}}

The received JSON (takes about 1 second to get it from the server) contains the data as follows:

"Data":{
         "Header":["Title_1","Title_2","Title_3"],
         "Body":[
                 ["Rec_1_Data_1","Rec_1_Data_2","Rec_1_Data_3"],
                 ["Rec_2_Data_1","Rec_2_Data_2","Rec_2_Data_3"],
                 ["Rec_3_Data_1","Rec_3_Data_2","Rec_3_Data_3"],
                 :
                 ["Rec_n_Data_1","Rec_n_Data_2","Rec_n_Data_3"]
                ]
}

I also tried one-directional binding (i.e. {{::One_Data_Field}}) without any noticeable improvement.

As stated above, response arrives within a second and then it takes up to 10 seconds for the table to be built.


问:
SQLite error 'attempt to write a readonly database' during insert?
I have a SQLite database that I am using for a website. The problem is that when I try to INSERT INTO it, I get a PDOException

```<code>SQLSTATE[HY000]: General error: 8 attempt to write a readonly database
</code>```

I SSH'd into the server and checked permissions, and the database has the permissions

```<code>-rw-rw-r--
</code>```

I'm not that familiar with *nix permissions, but I'm pretty sure this means

Not a directory

Owner has read/write permissions (that's me, according to ls -l)

Group has read/write permissions

Everyone else only has read permissions

I also looked everywhere I knew to using the sqlite3 program, and found nothing relevant.

Because I didn't know with what permissions PDO is trying to open the database, I did

```<code>chmod o+w supplies.db
</code>```

Now, I get another PDOException:

```<code>SQLSTATE[HY000]: General error: 14 unable to open database file
</code>```

But it ONLY occurs when I try to execute an INSERT query after the database is open.

Any ideas on what is going on?

答:
I got this error when I tried to write to a database on an Android system.

Apparently sqlite3 not only needs write permissions to the database file and the containing directory (as @austin-hyde already said in his answer) but also the environment variable TMPDIR has to point to a (possibly writable) directory.

On my Android system I set it to TMPDIR="/data/local/tmp" and now my script runs as expected :)

Edit:

If you can't set environment variables you can use one of the other methods listed here: https://www.sqlite.org/tempfiles.html#temporary_file_storage_locations
like PRAGMA temp_store_directory = 'directory-name';

Body:
I have a SQLite database that I am using for a website. The problem is that when I try to INSERT INTO it, I get a PDOException

SQLSTATE[HY000]: General error: 8 attempt to write a readonly database

I SSH'd into the server and checked permissions, and the database has the permissions

-rw-rw-r--

I'm not that familiar with *nix permissions, but I'm pretty sure this means

Not a directory

Owner has read/write permissions (that's me, according to ls -l)

Group has read/write permissions

Everyone else only has read permissions

I also looked everywhere I knew to using the sqlite3 program, and found nothing relevant.

Because I didn't know with what permissions PDO is trying to open the database, I did

chmod o+w supplies.db

Now, I get another PDOException:

SQLSTATE[HY000]: General error: 14 unable to open database file

But it ONLY occurs when I try to execute an INSERT query after the database is open.

Any ideas on what is going on?


问:
How to share Eclipse configuration over different workspaces
I'm using Eclipse (PDT) as primary IDE on different machines. (like at home, laptop, in office, etc.). How could I share the Eclipse and project configuration pragmatically between multiple computers? Should I version control them, or is there any easier way to do this?

How do you ensure to use the same good and old even so up to date config all of your computers?

答:
You can also copy the .prefs files from ${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings to a folder called .settings in the root folder of your project and then add it to SVN (or CVS or ...)

That way the settings will get distributed to all developers along with the source code during an Update.


问:
Hide button until we upload image or text
we have a button "save design" in page also we have option to upload image or text in the page.
until user upload image or Add text, we dont want to display button "save design"

we are using below code for "save design"

```<code>_getControlPanelHtml: function()
    {
        if (this.config.editorEnabled) {
            return '<div id="aitcg-control-panel">' +
                '<button id="submit-editorApply-{{rand}}" >SAVE DESIGN</button>' +
                '<button >Reset</button>' +
                '</div>';
        }
        return '';
    },

    initObservers: function()
    {
        if (this.config.editorEnabled) {
            $('submit-editorApply-' + this.config.rand).observe('click', this.submitApply.bindAsEventListener(this));
            $('submit-editorReset-' + this.config.rand).observe('click', this.submitReset.bindAsEventListener(this));
        }
    },

    submitApply: function(event)
    {
        Event.stop(event);
        this.option.apply();
    },
</code>```

I tried below code to hide the "save design" until we upload image or text.
i followed this link  i added style="display: none; and than used  show() jQuery method.

```<code><script>
    $('submit-editorApply-').show();
    _getControlPanelHtml: function()
    {
        if (this.config.editorEnabled) {
            return '<div id="aitcg-control-panel">' +
                '<button id="submit-editorApply-{{rand}}" style="display:none;" >SAVE DESIGN</button>' +
                '<button >Reset</button>' +
                '</div>';
        }
        return '';
    },

</script>
</code>```

答: If you are using ajax to upload and apply image/text on svg simplly call  jQuery("#aitcg-control-panel").show(); on that ajax's success(its may be the most easy way if u are using ajax).

Body:
we have a button "save design" in page also we have option to upload image or text in the page.
until user upload image or Add text, we dont want to display button "save design"

we are using below code for "save design"

_getControlPanelHtml: function()
    {
        if (this.config.editorEnabled) {
            return '
' +
                '<button id="submit-editorApply-{{rand}}" >SAVE DESIGN</button>' +
                '<button >Reset</button>' +
                '
';
        }
        return '';
    },

    initObservers: function()
    {
        if (this.config.editorEnabled) {
            $('submit-editorApply-' + this.config.rand).observe('click', this.submitApply.bindAsEventListener(this));
            $('submit-editorReset-' + this.config.rand).observe('click', this.submitReset.bindAsEventListener(this));
        }
    },

    submitApply: function(event)
    {
        Event.stop(event);
        this.option.apply();
    },

I tried below code to hide the "save design" until we upload image or text.
i followed this link  i added style="display: none; and than used  show() jQuery method.


问:
How to integrate Elasticsearch for Realtime Visualization?
I am trying to visualize my data which is in elasticsearch and using Kibana5 for that.

But the problem is what Kibana visualizes is not realtime visualization. If I update my data then I need to visualize that again and need to reflect on my dashboard, but this is not what I am looking for.

This particular problem I am facing while I am trying to embed the iframe with some PHP script.

I want to know how I can automate the process? How I can make the visualization real time and also do not want to interfere many times?

Kindly suggest me what is the possible solution.

答: Kibana5 will constantly listen to the elastic search according to the refresh interval.So set refresh interval to a minimum value (around 5 sec) so that kibana will be update in every 5 seconds


问:
Deleting multiple rows given an array of values in MySQL with Node.js and Express.js
I'm trying to delete multiple rows in a MySQL table that match up with multiple values in an array.

Here's an example of my attempt:

```<code>const query = 'DELETE FROM example_table WHERE (a_id AND b_id AND c_id) IN ?';
const values = [
      { a_id: 1, b_id: 2, c_id: 3},
      { a_id: 4, b_id: 5, c_id: 6},
      { a_id: 7, b_id: 8, c_id: 9}
     ];

connection.query(query, values, function(err, results) {
     // do something
});
</code>```

So, I'm essentially trying to find the rows whose column values matchup with the values in the objects in my array. I think my problem is that my query statement is not necessarily comparing the values at all, or that my logic in tackling this problem is not correct.

What should the query statement be, or should I be doing this another way?

Thank you.

答:
```<code>const query = 'DELETE FROM example_table WHERE a_id in (?) and b_id in (?) AND c_id IN (?)';
const values = [
      { a_id: 1, b_id: 2, c_id: 3},
      { a_id: 4, b_id: 5, c_id: 6},
      { a_id: 7, b_id: 8, c_id: 9}
     ];

connection.query(query, values, function(err, results) {
     // do something
});
</code>```

Body:
I'm trying to delete multiple rows in a MySQL table that match up with multiple values in an array.

Here's an example of my attempt:

const query = 'DELETE FROM example_table WHERE (a_id AND b_id AND c_id) IN ?';
const values = [
      { a_id: 1, b_id: 2, c_id: 3},
      { a_id: 4, b_id: 5, c_id: 6},
      { a_id: 7, b_id: 8, c_id: 9}
     ];

connection.query(query, values, function(err, results) {
     // do something
});

So, I'm essentially trying to find the rows whose column values matchup with the values in the objects in my array. I think my problem is that my query statement is not necessarily comparing the values at all, or that my logic in tackling this problem is not correct.

What should the query statement be, or should I be doing this another way?

Thank you.


问:
Unable to click an input tag with Selenium Chrome driver
I'm running with the following packages:

"Selenium.Support" version="3.3.0" targetFramework="net40"

"Selenium.WebDriver" version="3.3.0" targetFramework="net40"

"Selenium.WebDriver.ChromeDriver" version="2.28.0" targetFramework="net40"

"WebDriver.ChromeDriver" version="26.14.313457.1" targetFramework="net40"

And in my test program I'm trying to log into morningstar.com but the clicking never works to submit the username/password.  Any suggestions?  I've seen may people online having issues trying to click.  I've also tried IE and firefox and both didn't work for me.

```<code>using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Text;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
using System.Threading;

namespace ConsoleApplication1
{

    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://www.morningstar.com/members/login.html");
            Thread.Sleep(5000);
            driver.FindElement(By.Id("uim-uEmail-input")).SendKeys("email");
            driver.FindElement(By.Id("uim-uPassword-input")).SendKeys("password");
            Thread.Sleep(1000);

            driver.FindElement(By.Id("uim-login-submit")).Click();
            Thread.Sleep(10000);
        }
    }
}
</code>```

I've also tried using an Action, and the Javascript workaround like other answers online have suggested:

```<code>        ((IJavaScriptExecutor)(driver)).ExecuteScript("arguments[0].click();", driver.FindElement(By.Id("uim-login-submit")));
</code>```

Any ideas, or is this a bug in selenium?

答:
Click probably works fine, problem could be that your password field is not properly set because value will be stored after onFocus event is triggered and you are clicking on submit directly after you write text in your password field.

To test this, try to perform click() on username field after you set password. Something like this, I added two clicks:

```<code>driver.FindElement(By.Id("uim-uEmail-input")).SendKeys("email");
driver.FindElement(By.Id("uim-uPassword-input")).Click();
driver.FindElement(By.Id("uim-uPassword-input")).SendKeys("password");
driver.FindElement(By.Id("uim-uEmail-input")).Click();
</code>```

Body:
I'm running with the following packages:

"Selenium.Support" version="3.3.0" targetFramework="net40"

"Selenium.WebDriver" version="3.3.0" targetFramework="net40"

"Selenium.WebDriver.ChromeDriver" version="2.28.0" targetFramework="net40"

"WebDriver.ChromeDriver" version="26.14.313457.1" targetFramework="net40"

And in my test program I'm trying to log into morningstar.com but the clicking never works to submit the username/password.  Any suggestions?  I've seen may people online having issues trying to click.  I've also tried IE and firefox and both didn't work for me.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Text;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
using System.Threading;

namespace ConsoleApplication1
{

    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("http://www.morningstar.com/members/login.html");
            Thread.Sleep(5000);
            driver.FindElement(By.Id("uim-uEmail-input")).SendKeys("email");
            driver.FindElement(By.Id("uim-uPassword-input")).SendKeys("password");
            Thread.Sleep(1000);

            driver.FindElement(By.Id("uim-login-submit")).Click();
            Thread.Sleep(10000);
        }
    }
}

I've also tried using an Action, and the Javascript workaround like other answers online have suggested:

        ((IJavaScriptExecutor)(driver)).ExecuteScript("arguments[0].click();", driver.FindElement(By.Id("uim-login-submit")));

Any ideas, or is this a bug in selenium?

Body:
Click probably works fine, problem could be that your password field is not properly set because value will be stored after onFocus event is triggered and you are clicking on submit directly after you write text in your password field.

To test this, try to perform click() on username field after you set password. Something like this, I added two clicks:

driver.FindElement(By.Id("uim-uEmail-input")).SendKeys("email");
driver.FindElement(By.Id("uim-uPassword-input")).Click();
driver.FindElement(By.Id("uim-uPassword-input")).SendKeys("password");
driver.FindElement(By.Id("uim-uEmail-input")).Click();


问:
How to use Scala's singleton-object types?
I'm writing a class which serves as base class for a series of singleton objects. In each singleton objects, there will be vals representing certain properties, and I want to write a method which, for each singleton object, only accepts objects created by it.

So I have the following:

```<code>class Obj[M <: Maker]

class Maker {
  implicit val me: this.type = this
  def make[M <: Maker](implicit maker: M) = new Obj[M]
  def accept(obj: Obj[this.type]) = {...}
}
</code>```

So far, so good. Then I want to declare one of these singleton objects:

```<code>object M extends Maker {
  val a = make
}
</code>```

But then, if I try this:

```<code>M.accept(M.a)
</code>```

then I get a compile-time error:

```<code>type mismatch; found : com.test.Obj[object com.test.M] required: com.test.Obj[com.test.M.type]
</code>```

My questions:

What's the type object com.test.M, and how is it different from com.test.M.type?

How can I do this in a smarter way?

答:
This works:

```<code>class Obj[M <: Maker]

class Maker {
  implicit val me: this.type = this
  def make[M <: Maker](implicit maker: M) = new Obj[M]
  def accept(obj: Obj[this.type]) = ()
}

object M extends Maker {
  val a = make[M.type]
}

M.accept(M.a)
</code>```

The secret "sauce" is using make[M.type] inside the singleton object.

@retronym deserves the credit for explaining this: How to correctly type-annotate this HList?

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a class which serves as base class for a series of singleton objects. In each singleton objects, there will be vals representing certain properties, and I want to write a method which, for each singleton object, only accepts objects created by it.

So I have the following:

class Obj[M <: Maker]

class Maker {
  implicit val me: this.type = this
  def make[M <: Maker](implicit maker: M) = new Obj[M]
  def accept(obj: Obj[this.type]) = {...}
}

So far, so good. Then I want to declare one of these singleton objects:

object M extends Maker {
  val a = make
}

But then, if I try this:

M.accept(M.a)

then I get a compile-time error:

type mismatch; found : com.test.Obj[object com.test.M] required: com.test.Obj[com.test.M.type]

My questions:

What's the type object com.test.M, and how is it different from com.test.M.type?

How can I do this in a smarter way?

Body:
This works:

class Obj[M <: Maker]

class Maker {
  implicit val me: this.type = this
  def make[M <: Maker](implicit maker: M) = new Obj[M]
  def accept(obj: Obj[this.type]) = ()
}

object M extends Maker {
  val a = make[M.type]
}

M.accept(M.a)

The secret "sauce" is using make[M.type] inside the singleton object.

@retronym deserves the credit for explaining this: How to correctly type-annotate this HList?


问:
Can not upload Image, Video Entry in Nougat version in Android Studio
I tried to upload Images / Videos from Android Studio and This working fine in all other Android version but facing issue with nougat.

Anyone can help me to short out this.

package com.ethosapp.ethos.jobs;

```<code>import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.ethosapp.ethos.EthosApplication;
import com.ethosapp.ethos.R;
import com.ethosapp.ethos.models.Entry;
import com.ethosapp.ethos.models.PostEntry;
import com.ethosapp.ethos.services.AmazonSyncService;
import com.ethosapp.ethos.services.ApiServiceFactory;
import com.ethosapp.ethos.services.EntryService;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import retrofit2.Call;

/**
 * Created by jaya on 25/05/16.
 */
public class UploadFileToS3Job extends Job {

    public static final int PRIORITY = 1;

    protected String filename;
    protected String uri;
    protected String extension;
    protected String fileId;
    protected String entryId;
    protected long type;
    protected String state;

    public UploadFileToS3Job(String filename, String uri, String extension, String fileId, String entryId, long type) {
        super(new Params(PRIORITY).requireNetwork().persist());
        this.filename = filename;
        this.uri = uri;
        this.extension = extension;
        this.fileId = fileId;
        this.type = type;
        this.entryId = entryId;

        try {
            Uri fileUri = Uri.parse(uri);
            File f = new File(fileUri.getPath());
            JSONObject props = new JSONObject();
            props.put("entryId", this.entryId);
            props.put("fileId", this.fileId);
            props.put("extension", this.extension);
            props.put("fileSize", f.length());
            EthosApplication.mixPanelTrack("BeginUploadFile", props);
        } catch (JSONException jsonException) {
            Log.e("MYAPP", "Unable to add properties to JSONObject", jsonException);
        }
    }

    public UploadFileToS3Job(String filename) {
        super(new Params(PRIORITY).requireNetwork().persist());
        Log.e("tag", "fileNAAM" + filename);
        this.filename = filename;
    }

    @Override
    public void onAdded() {

    }

    @Override
    public void onRun() throws Throwable {
        switch ((int) this.type) {
            case Entry.Type.IMAGE:
                uploadImageFiles();
                break;
            case Entry.Type.AUDIO:
                uploadVideoAudioFiles();
                break;
            case Entry.Type.VIDEO:
                uploadVideoAudioFiles();
                break;
        }
    }

    @Override
    protected void onCancel(int cancelReason) {

    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount, int maxRunCount) {
        return null;
    }

    @Nullable
    private File saveFileToTempFolder(Uri uri, String name, String extension) throws Throwable {
        InputStream inputStream = EthosApplication.getInstance().getContentResolver().openInputStream(uri);
        File outputDir = EthosApplication.getInstance().getBaseContext().getCacheDir(); // context being the Activity pointer
        File tempFile = File.createTempFile(name, extension, outputDir);
        FileOutputStream out = new FileOutputStream(tempFile);
        IOUtils.copy(inputStream, out);
        inputStream.close();
        out.close();
        return tempFile;
    }

    private void uploadVideoAudioFiles() throws Throwable {

        Uri fileUri = Uri.parse(uri);
        File file = new File(fileUri.getPath());
        Log.e("FFFFFFFFF====","=="+"content://com.ethosapp.ethos.provider/external_files/EthOS/EthOS%20movies/"+filename);

        if (file.exists()) {
            String parent = fileId + "/";
            uploadFileToS3(parent + filename, file, CannedAccessControlList.PublicRead);

            // Now schedule a media-transcode
            // Update the Entry
            PostEntry postEntry = new PostEntry();
            postEntry.setFileId(fileId);

            EntryService service = ApiServiceFactory.createRetrofitService(EntryService.class, ApiServiceFactory.API_BASE_URL);

            Call<Entry> entryCall = service.scheduleMediaTranscode(this.entryId, postEntry);
            Entry entry = entryCall.execute().body();

            PostEntry postEntry1 = new PostEntry();
            postEntry.setType("0");

            Call<Entry> entryCall1 = service.updateEntry(this.entryId, postEntry1);
            Entry entry1 = entryCall1.execute().body();

            // TODO: Some Validation to verify the entry is uploaded successfully

            Intent intent = new Intent();
            intent.setAction("com.ethosapp.ethos.CUSTOM_INTENT");
            EthosApplication.getInstance().getBaseContext().sendBroadcast(intent);

        } else {
            // TODO : Error Handling
        }
    }

    @NonNull
    private void uploadImageFiles() throws Throwable {
        Log.e("tag", "images" + uri);
        Uri fileUri = Uri.parse(uri);
        Log.e("tag", "<----fileUri---->" + uri);

        String fileNameWithOutExt = FilenameUtils.removeExtension(filename);
        String fileExtension = FilenameUtils.getExtension(filename);
        String parent = fileId + "/";

        // Upload preview image
        // name : name-preview.jpg (230x0)
        // Dimensions: 230 x 0
        // Quality: 70
        String previewImageFilename = fileNameWithOutExt + "-preview" + "." + fileExtension;
        File previewImage = resizeImage(fileUri, 230, 230, previewImageFilename, 70);
        uploadFileToS3(parent + previewImageFilename, previewImage, CannedAccessControlList.PublicRead);
        previewImage.delete();

        // Upload resized image
        // name : name-resized.jpg (230x0)
        // Dimensions: 1024 x 768
        // Quality: 70
        String resizedImageFilename = fileNameWithOutExt + "-resized" + "." + fileExtension;
        File resizedImage = resizeImage(fileUri, 1024, 768, resizedImageFilename, 70);
        uploadFileToS3(parent + resizedImageFilename, resizedImage, CannedAccessControlList.PublicRead);
        resizedImage.delete();

        // Upload resized image
        // name : name-resized.jpg (230x0)
        // Dimensions: 480 x 800
        // Quality: 60
        String resized1XImageFilename = fileNameWithOutExt + "-resized-1x" + "." + fileExtension;
        File resized1XImage = resizeImage(fileUri, 480, 800, resized1XImageFilename, 60);
        uploadFileToS3(parent + resizedImageFilename, resized1XImage, CannedAccessControlList.PublicRead);
        resized1XImage.delete();

        // Upload resized image
        // name : name-resized.jpg (230x0)
        // Dimensions: 1024 x 768
        // Quality: 60
        String resized2XImageFilename = fileNameWithOutExt + "-resized-2x" + "." + fileExtension;
        File resized2XImage = resizeImage(fileUri, 1024, 768, resized2XImageFilename, 60);
        uploadFileToS3(parent + resizedImageFilename, resized2XImage, CannedAccessControlList.PublicRead);
        resized2XImage.delete();

        // Upload thumbnail image
        // name : name-tn.jpg (230x0)
        // Dimensions: 80 x 80
        // Quality: 70
        String thumbnailImageFilename = fileNameWithOutExt + "-tn" + "." + fileExtension;
        File thumbnailImage = resizeImage(fileUri, 80, 80, thumbnailImageFilename, 70);
        uploadFileToS3(parent + thumbnailImageFilename, thumbnailImage, CannedAccessControlList.PublicRead);
        thumbnailImage.delete();

        //File image = saveFileToTempFolder(fileUri, filename, extension);
        File image = new File(fileUri.getPath());
        uploadFileToS3(parent + filename, image, CannedAccessControlList.Private);

        // Update the Entry
        PostEntry postEntry = new PostEntry();
        postEntry.setType("0");

        EntryService service = ApiServiceFactory.createRetrofitService(EntryService.class, ApiServiceFactory.API_BASE_URL);

        Call<Entry> entryCall = service.updateEntry(this.entryId, postEntry);
        Entry entry = entryCall.execute().body();

        int id=1;

        Context baseContext = EthosApplication.getInstance().getBaseContext();

//        // intent triggered, you can add other intent for other actions
//        Intent intent = new Intent(baseContext, ProjectEntriesActivity.class);
//        PendingIntent pIntent = PendingIntent.getActivity(baseContext, 0, intent, 0);

        NotificationManager mNotifyManager =
                (NotificationManager) baseContext.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(baseContext);
        mBuilder.setContentTitle("Entry Uploaded")
                .setContentText("Entry has uploaded successfully.")
                .setSmallIcon(R.drawable.ic_logo)
                .setPriority(Notification.PRIORITY_HIGH);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);

        mNotifyManager.notify(id, mBuilder.build());

        //Log.e("tag","1111");
        // TODO: Some Validation to verify the entry is uploaded successfully
        //Intent intent = new Intent();
        //intent.setAction("com.ethosapp.ethos.CUSTOM_INTENT");
        //EthosApplication.getInstance().getBaseContext().sendBroadcast(intent);

    }

    private void uploadFileToS3(String filename, File file, CannedAccessControlList acl) throws Throwable {

        Log.e("FILE=======","=="+file);
        Log.e("FILE=======","=="+filename);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            String ff="content://com.ethosapp.ethos.provider/external_files/EthOS/EthOS%20Pictures/"+filename;
            Log.e("FFFF==","=="+ff);
        }
        String ff="content://com.ethosapp.ethos.provider/external_files/EthOS/EthOS%20Pictures/"+filename;
        Log.e("FFFF==","=="+ff);

        Log.e("1111","===================");
        AmazonSyncService syncService = new AmazonSyncService(EthosApplication.getInstance().getBaseContext());
        TransferObserver transferObserver = syncService.startUpload(filename, file, acl);
        transferObserverListener(transferObserver);

        // Code to make the thread to wait for upload completion.
        // Entire code will be running in a background thread, so there is no
        // issue in waiting for it to complete.
        while (true) {
            if (TransferState.COMPLETED.equals(transferObserver.getState())
                    || TransferState.FAILED.equals(transferObserver.getState())) {
                break;
            }
        }

        if (TransferState.FAILED.equals(transferObserver.getState())) {
            throw new Exception("Upload File to S3 failed.");
        }
    }

    private void transferObserverListener(TransferObserver transferObserver) {
        transferObserver.setTransferListener(new TransferListener() {
            @Override
            public void onStateChanged(int id, TransferState state) {
                Log.e("statechange", state + "");

                try {
                    Uri fileUri = Uri.parse(uri);
                    File f = new File(fileUri.getPath());
                    JSONObject props = new JSONObject();
                    props.put("entryId", entryId);
                    props.put("fileId", fileId);
                    props.put("extension", extension);
                    props.put("fileSize", f.length());
                    EthosApplication.mixPanelTrack("UploadedFile", props);
                } catch (JSONException jsonException) {
                    Log.e("MYAPP", "Unable to add properties to JSONObject", jsonException);
                }
            }

            @Override
            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                int percentage = (int) (bytesCurrent / bytesTotal * 100);
                Log.e("percentage", percentage + "");

                if(type == Entry.Type.VIDEO){
                    try {
                        Uri fileUri = Uri.parse(uri);
                        File f = new File(fileUri.getPath());
                        JSONObject props = new JSONObject();
                        props.put("entryId", entryId);
                        props.put("fileId", fileId);
                        props.put("extension", extension);
                        props.put("fileSize", f.length());
                        props.put("percentage", percentage);
                        EthosApplication.mixPanelTrack("UploadingFile", props);
                    } catch (JSONException jsonException) {
                        Log.e("MYAPP", "Unable to add properties to JSONObject", jsonException);
                    }
                }
            }

            @Override
            public void onError(int id, Exception ex) {
                Log.e("error", "error");
            }
        });
    }

    private File resizeImage(Uri fileUri, int width, int height, String resizedFilename, int quality) throws Throwable {
        int inWidth = 0;
        int inHeight = 0;

        InputStream inputStream = EthosApplication.getInstance().getContentResolver().openInputStream(fileUri);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmapOrg = BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();

        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;

        inputStream = EthosApplication.getInstance().getContentResolver().openInputStream(fileUri);
        options = new BitmapFactory.Options();
        // calc rough re-size (this is no exact resize)
        options.inSampleSize = Math.max(inWidth / width, inHeight / height);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(inputStream, null, options);
        // calc exact destination size
        Matrix m = new Matrix();
        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, width, height);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);

        // resize bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
        File outputDir = EthosApplication.getInstance().getBaseContext().getCacheDir(); // context being the Activity pointer
        File tempFile = File.createTempFile(resizedFilename, "jpg", outputDir);
        Log.e("outputDir=====","=="+outputDir);
        Log.e("tempFile=====","=="+tempFile);
        FileOutputStream out = new FileOutputStream(tempFile);
        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);

        return tempFile;
    }

}

public class    AmazonSyncService {

    // Initialize the Amazon Cognito credentials provider
    public  static CognitoCachingCredentialsProvider credentialsProvider;

    // Create an S3 client
    private AmazonS3 s3;

    private TransferUtility transferUtility;
    private Context context;

    private final String MY_APP_BUCKET = "ethosappcom-production-media";
    private final String MY_APP_BUCKET_PROFILE = "ethosappcom-production-user";

    public AmazonSyncService(Context context){
        this.context = context;
        credentialsProvider = new CognitoCachingCredentialsProvider(
                this.context.getApplicationContext(),
                "us-east-1:e1922be7-9b7a-421e-bf3f-ae41b0a61315", // Identity Pool ID
                Regions.US_EAST_1 // Region
        );

        s3 = new AmazonS3Client(credentialsProvider);
        s3.setRegion(Region.getRegion(Regions.US_EAST_1));

        transferUtility = new TransferUtility(s3, this.context.getApplicationContext());
    }

    public CognitoCachingCredentialsProvider getCredentialProvider(){
        return credentialsProvider;
    }

    public TransferObserver startUpload(String filename, File file, CannedAccessControlList acl){
        return transferUtility.upload(MY_APP_BUCKET, filename, file, acl);
    }

}
</code>```

答:
The issue is in this line (where-ever it's written)

```<code>Uri fileUri = Uri.parse(uri);
</code>```

This behavior is changed in the Android Nougat. To achieve the same with Nougat
please follow  this thread as a reference. It will show you how to use File Provider when you set your targetSDK as 24  and change following. In your private static Uri getImageFileUri() method

Change this line

```<code>Uri fileUri = Uri.parse(uri);
</code>```

to

```<code>Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
</code>```

Hope this will help you to solve your issue.

 For more go to -
Setting Up File Sharing - Offical documentation

Body:
I tried to upload Images / Videos from Android Studio and This working fine in all other Android version but facing issue with nougat.

Anyone can help me to short out this.

package com.ethosapp.ethos.jobs;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.ethosapp.ethos.EthosApplication;
import com.ethosapp.ethos.R;
import com.ethosapp.ethos.models.Entry;
import com.ethosapp.ethos.models.PostEntry;
import com.ethosapp.ethos.services.AmazonSyncService;
import com.ethosapp.ethos.services.ApiServiceFactory;
import com.ethosapp.ethos.services.EntryService;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import retrofit2.Call;

/**
 * Created by jaya on 25/05/16.
 */
public class UploadFileToS3Job extends Job {

    public static final int PRIORITY = 1;

    protected String filename;
    protected String uri;
    protected String extension;
    protected String fileId;
    protected String entryId;
    protected long type;
    protected String state;

    public UploadFileToS3Job(String filename, String uri, String extension, String fileId, String entryId, long type) {
        super(new Params(PRIORITY).requireNetwork().persist());
        this.filename = filename;
        this.uri = uri;
        this.extension = extension;
        this.fileId = fileId;
        this.type = type;
        this.entryId = entryId;

        try {
            Uri fileUri = Uri.parse(uri);
            File f = new File(fileUri.getPath());
            JSONObject props = new JSONObject();
            props.put("entryId", this.entryId);
            props.put("fileId", this.fileId);
            props.put("extension", this.extension);
            props.put("fileSize", f.length());
            EthosApplication.mixPanelTrack("BeginUploadFile", props);
        } catch (JSONException jsonException) {
            Log.e("MYAPP", "Unable to add properties to JSONObject", jsonException);
        }
    }

    public UploadFileToS3Job(String filename) {
        super(new Params(PRIORITY).requireNetwork().persist());
        Log.e("tag", "fileNAAM" + filename);
        this.filename = filename;
    }

    @Override
    public void onAdded() {

    }

    @Override
    public void onRun() throws Throwable {
        switch ((int) this.type) {
            case Entry.Type.IMAGE:
                uploadImageFiles();
                break;
            case Entry.Type.AUDIO:
                uploadVideoAudioFiles();
                break;
            case Entry.Type.VIDEO:
                uploadVideoAudioFiles();
                break;
        }
    }

    @Override
    protected void onCancel(int cancelReason) {

    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount, int maxRunCount) {
        return null;
    }

    @Nullable
    private File saveFileToTempFolder(Uri uri, String name, String extension) throws Throwable {
        InputStream inputStream = EthosApplication.getInstance().getContentResolver().openInputStream(uri);
        File outputDir = EthosApplication.getInstance().getBaseContext().getCacheDir(); // context being the Activity pointer
        File tempFile = File.createTempFile(name, extension, outputDir);
        FileOutputStream out = new FileOutputStream(tempFile);
        IOUtils.copy(inputStream, out);
        inputStream.close();
        out.close();
        return tempFile;
    }

    private void uploadVideoAudioFiles() throws Throwable {

        Uri fileUri = Uri.parse(uri);
        File file = new File(fileUri.getPath());
        Log.e("FFFFFFFFF====","=="+"content://com.ethosapp.ethos.provider/external_files/EthOS/EthOS%20movies/"+filename);

        if (file.exists()) {
            String parent = fileId + "/";
            uploadFileToS3(parent + filename, file, CannedAccessControlList.PublicRead);

            // Now schedule a media-transcode
            // Update the Entry
            PostEntry postEntry = new PostEntry();
            postEntry.setFileId(fileId);

            EntryService service = ApiServiceFactory.createRetrofitService(EntryService.class, ApiServiceFactory.API_BASE_URL);

            Call<Entry> entryCall = service.scheduleMediaTranscode(this.entryId, postEntry);
            Entry entry = entryCall.execute().body();

            PostEntry postEntry1 = new PostEntry();
            postEntry.setType("0");

            Call<Entry> entryCall1 = service.updateEntry(this.entryId, postEntry1);
            Entry entry1 = entryCall1.execute().body();

            // TODO: Some Validation to verify the entry is uploaded successfully

            Intent intent = new Intent();
            intent.setAction("com.ethosapp.ethos.CUSTOM_INTENT");
            EthosApplication.getInstance().getBaseContext().sendBroadcast(intent);

        } else {
            // TODO : Error Handling
        }
    }

    @NonNull
    private void uploadImageFiles() throws Throwable {
        Log.e("tag", "images" + uri);
        Uri fileUri = Uri.parse(uri);
        Log.e("tag", "<----fileUri---->" + uri);

        String fileNameWithOutExt = FilenameUtils.removeExtension(filename);
        String fileExtension = FilenameUtils.getExtension(filename);
        String parent = fileId + "/";

        // Upload preview image
        // name : name-preview.jpg (230x0)
        // Dimensions: 230 x 0
        // Quality: 70
        String previewImageFilename = fileNameWithOutExt + "-preview" + "." + fileExtension;
        File previewImage = resizeImage(fileUri, 230, 230, previewImageFilename, 70);
        uploadFileToS3(parent + previewImageFilename, previewImage, CannedAccessControlList.PublicRead);
        previewImage.delete();

        // Upload resized image
        // name : name-resized.jpg (230x0)
        // Dimensions: 1024 x 768
        // Quality: 70
        String resizedImageFilename = fileNameWithOutExt + "-resized" + "." + fileExtension;
        File resizedImage = resizeImage(fileUri, 1024, 768, resizedImageFilename, 70);
        uploadFileToS3(parent + resizedImageFilename, resizedImage, CannedAccessControlList.PublicRead);
        resizedImage.delete();

        // Upload resized image
        // name : name-resized.jpg (230x0)
        // Dimensions: 480 x 800
        // Quality: 60
        String resized1XImageFilename = fileNameWithOutExt + "-resized-1x" + "." + fileExtension;
        File resized1XImage = resizeImage(fileUri, 480, 800, resized1XImageFilename, 60);
        uploadFileToS3(parent + resizedImageFilename, resized1XImage, CannedAccessControlList.PublicRead);
        resized1XImage.delete();

        // Upload resized image
        // name : name-resized.jpg (230x0)
        // Dimensions: 1024 x 768
        // Quality: 60
        String resized2XImageFilename = fileNameWithOutExt + "-resized-2x" + "." + fileExtension;
        File resized2XImage = resizeImage(fileUri, 1024, 768, resized2XImageFilename, 60);
        uploadFileToS3(parent + resizedImageFilename, resized2XImage, CannedAccessControlList.PublicRead);
        resized2XImage.delete();

        // Upload thumbnail image
        // name : name-tn.jpg (230x0)
        // Dimensions: 80 x 80
        // Quality: 70
        String thumbnailImageFilename = fileNameWithOutExt + "-tn" + "." + fileExtension;
        File thumbnailImage = resizeImage(fileUri, 80, 80, thumbnailImageFilename, 70);
        uploadFileToS3(parent + thumbnailImageFilename, thumbnailImage, CannedAccessControlList.PublicRead);
        thumbnailImage.delete();

        //File image = saveFileToTempFolder(fileUri, filename, extension);
        File image = new File(fileUri.getPath());
        uploadFileToS3(parent + filename, image, CannedAccessControlList.Private);

        // Update the Entry
        PostEntry postEntry = new PostEntry();
        postEntry.setType("0");

        EntryService service = ApiServiceFactory.createRetrofitService(EntryService.class, ApiServiceFactory.API_BASE_URL);

        Call<Entry> entryCall = service.updateEntry(this.entryId, postEntry);
        Entry entry = entryCall.execute().body();

        int id=1;

        Context baseContext = EthosApplication.getInstance().getBaseContext();

//        // intent triggered, you can add other intent for other actions
//        Intent intent = new Intent(baseContext, ProjectEntriesActivity.class);
//        PendingIntent pIntent = PendingIntent.getActivity(baseContext, 0, intent, 0);

        NotificationManager mNotifyManager =
                (NotificationManager) baseContext.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(baseContext);
        mBuilder.setContentTitle("Entry Uploaded")
                .setContentText("Entry has uploaded successfully.")
                .setSmallIcon(R.drawable.ic_logo)
                .setPriority(Notification.PRIORITY_HIGH);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);

        mNotifyManager.notify(id, mBuilder.build());

        //Log.e("tag","1111");
        // TODO: Some Validation to verify the entry is uploaded successfully
        //Intent intent = new Intent();
        //intent.setAction("com.ethosapp.ethos.CUSTOM_INTENT");
        //EthosApplication.getInstance().getBaseContext().sendBroadcast(intent);

    }

    private void uploadFileToS3(String filename, File file, CannedAccessControlList acl) throws Throwable {

        Log.e("FILE=======","=="+file);
        Log.e("FILE=======","=="+filename);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            String ff="content://com.ethosapp.ethos.provider/external_files/EthOS/EthOS%20Pictures/"+filename;
            Log.e("FFFF==","=="+ff);
        }
        String ff="content://com.ethosapp.ethos.provider/external_files/EthOS/EthOS%20Pictures/"+filename;
        Log.e("FFFF==","=="+ff);

        Log.e("1111","===================");
        AmazonSyncService syncService = new AmazonSyncService(EthosApplication.getInstance().getBaseContext());
        TransferObserver transferObserver = syncService.startUpload(filename, file, acl);
        transferObserverListener(transferObserver);

        // Code to make the thread to wait for upload completion.
        // Entire code will be running in a background thread, so there is no
        // issue in waiting for it to complete.
        while (true) {
            if (TransferState.COMPLETED.equals(transferObserver.getState())
                    || TransferState.FAILED.equals(transferObserver.getState())) {
                break;
            }
        }

        if (TransferState.FAILED.equals(transferObserver.getState())) {
            throw new Exception("Upload File to S3 failed.");
        }
    }

    private void transferObserverListener(TransferObserver transferObserver) {
        transferObserver.setTransferListener(new TransferListener() {
            @Override
            public void onStateChanged(int id, TransferState state) {
                Log.e("statechange", state + "");

                try {
                    Uri fileUri = Uri.parse(uri);
                    File f = new File(fileUri.getPath());
                    JSONObject props = new JSONObject();
                    props.put("entryId", entryId);
                    props.put("fileId", fileId);
                    props.put("extension", extension);
                    props.put("fileSize", f.length());
                    EthosApplication.mixPanelTrack("UploadedFile", props);
                } catch (JSONException jsonException) {
                    Log.e("MYAPP", "Unable to add properties to JSONObject", jsonException);
                }
            }

            @Override
            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                int percentage = (int) (bytesCurrent / bytesTotal * 100);
                Log.e("percentage", percentage + "");

                if(type == Entry.Type.VIDEO){
                    try {
                        Uri fileUri = Uri.parse(uri);
                        File f = new File(fileUri.getPath());
                        JSONObject props = new JSONObject();
                        props.put("entryId", entryId);
                        props.put("fileId", fileId);
                        props.put("extension", extension);
                        props.put("fileSize", f.length());
                        props.put("percentage", percentage);
                        EthosApplication.mixPanelTrack("UploadingFile", props);
                    } catch (JSONException jsonException) {
                        Log.e("MYAPP", "Unable to add properties to JSONObject", jsonException);
                    }
                }
            }

            @Override
            public void onError(int id, Exception ex) {
                Log.e("error", "error");
            }
        });
    }

    private File resizeImage(Uri fileUri, int width, int height, String resizedFilename, int quality) throws Throwable {
        int inWidth = 0;
        int inHeight = 0;

        InputStream inputStream = EthosApplication.getInstance().getContentResolver().openInputStream(fileUri);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmapOrg = BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();

        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;

        inputStream = EthosApplication.getInstance().getContentResolver().openInputStream(fileUri);
        options = new BitmapFactory.Options();
        // calc rough re-size (this is no exact resize)
        options.inSampleSize = Math.max(inWidth / width, inHeight / height);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(inputStream, null, options);
        // calc exact destination size
        Matrix m = new Matrix();
        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, width, height);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);

        // resize bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
        File outputDir = EthosApplication.getInstance().getBaseContext().getCacheDir(); // context being the Activity pointer
        File tempFile = File.createTempFile(resizedFilename, "jpg", outputDir);
        Log.e("outputDir=====","=="+outputDir);
        Log.e("tempFile=====","=="+tempFile);
        FileOutputStream out = new FileOutputStream(tempFile);
        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);

        return tempFile;
    }

}

public class    AmazonSyncService {

    // Initialize the Amazon Cognito credentials provider
    public  static CognitoCachingCredentialsProvider credentialsProvider;

    // Create an S3 client
    private AmazonS3 s3;

    private TransferUtility transferUtility;
    private Context context;

    private final String MY_APP_BUCKET = "ethosappcom-production-media";
    private final String MY_APP_BUCKET_PROFILE = "ethosappcom-production-user";

    public AmazonSyncService(Context context){
        this.context = context;
        credentialsProvider = new CognitoCachingCredentialsProvider(
                this.context.getApplicationContext(),
                "us-east-1:e1922be7-9b7a-421e-bf3f-ae41b0a61315", // Identity Pool ID
                Regions.US_EAST_1 // Region
        );

        s3 = new AmazonS3Client(credentialsProvider);
        s3.setRegion(Region.getRegion(Regions.US_EAST_1));

        transferUtility = new TransferUtility(s3, this.context.getApplicationContext());
    }

    public CognitoCachingCredentialsProvider getCredentialProvider(){
        return credentialsProvider;
    }

    public TransferObserver startUpload(String filename, File file, CannedAccessControlList acl){
        return transferUtility.upload(MY_APP_BUCKET, filename, file, acl);
    }

}

Body:
The issue is in this line (where-ever it's written)

Uri fileUri = Uri.parse(uri);

This behavior is changed in the Android Nougat. To achieve the same with Nougat
please follow  this thread as a reference. It will show you how to use File Provider when you set your targetSDK as 24  and change following. In your private static Uri getImageFileUri() method

Change this line

Uri fileUri = Uri.parse(uri);

to

Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());

Hope this will help you to solve your issue.

 For more go to -
Setting Up File Sharing - Offical documentation


问:
Could not run npm install -g create-react-app
Could not run npm install -g create-react-app, it giving an error as below:
Any advise? Thanks</p>

```<code>C:\Learning\ReactJS\basic-react>npm install -g create-react-app
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\node.exe" "C:\\node_modules\\npm\\bin\\npm-cli.js" "install"
"-g" "create-react-app"
npm ERR! node v4.4.4
npm ERR! npm  v2.15.1
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! syscall getaddrinfo

npm ERR! network getaddrinfo ENOTFOUND proxyaddress proxyaddress:80
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Learning\ReactJS\basic-react\npm-debug.log
</code>```

答: It appears you are behind a proxy and need to setup NPM to use the correct proxy settings. Maybe try this guide: https://jjasonclark.com/how-to-setup-node-behind-web-proxy/</p>

Body:
Could not run npm install -g create-react-app, it giving an error as below:
Any advise? Thanks

C:\Learning\ReactJS\basic-react>npm install -g create-react-app
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\node.exe" "C:\\node_modules\\npm\\bin\\npm-cli.js" "install"
"-g" "create-react-app"
npm ERR! node v4.4.4
npm ERR! npm  v2.15.1
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! syscall getaddrinfo

npm ERR! network getaddrinfo ENOTFOUND proxyaddress proxyaddress:80
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Learning\ReactJS\basic-react\npm-debug.log


问:
Firebase javascript background service worker notification icon not show
My firebase-messaging-sw.js working fine to show background notification as it should but it didn't show the icon while notification.title and notification.click_action worked correctly.

This is my service worker's messaging.setBackgroundMessageHandler

```<code>messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
    body: 'Background Message body.',
    icon: '/image/logo.png'
};

return self.registration.showNotification(notificationTitle,
    notificationOptions);
</code>```

});

This is where I placed my icon

This is the result

Thanks for your time to help.

答:
After trying several days, I fixed the problem by adding
{"icon":"/image/logo.png"} inside FCM Server Post request body instead of having it inside firebase-messaging-sw.js as default.

And IIS server need to serve static content for hosted web project so that the logo.png can get as public.

This is my updated Post Request Body in JSON format

```<code>{
"notification": {
    "title": "New Appointment Requested",
    "body": "5 to 1",
    "icon": "/image/logo.png",
    "click_action": "<host>/subpage"
},
 "to": "token"
}
</code>```

Body:
My firebase-messaging-sw.js working fine to show background notification as it should but it didn't show the icon while notification.title and notification.click_action worked correctly.

This is my service worker's messaging.setBackgroundMessageHandler

messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
    body: 'Background Message body.',
    icon: '/image/logo.png'
};

return self.registration.showNotification(notificationTitle,
    notificationOptions);

});

This is where I placed my icon

This is the result

Thanks for your time to help.

Body:
After trying several days, I fixed the problem by adding
{"icon":"/image/logo.png"} inside FCM Server Post request body instead of having it inside firebase-messaging-sw.js as default.

And IIS server need to serve static content for hosted web project so that the logo.png can get as public.

This is my updated Post Request Body in JSON format

{
"notification": {
    "title": "New Appointment Requested",
    "body": "5 to 1",
    "icon": "/image/logo.png",
    "click_action": "<host>/subpage"
},
 "to": "token"
}


问:
Execution failed for task ':app:processDebugResources'. > java.lang.IllegalArgumentException (no error message)
I have updated android studio to 2.3 and getting this error while building project. I have tried Invalidate Cache and Restart, clean but its not getting fixed.

Here is the stacktrace log..

```<code>Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugResources'.
    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.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    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.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    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: java.lang.IllegalArgumentException
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
    at com.android.builder.symbols.Symbol.<init>(Symbol.java:114)
    at com.android.builder.symbols.SymbolIo.read(SymbolIo.java:79)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:896)
    at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:194)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:82)
    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
</code>```

I also searched for this a lot. but not getting proper solution.
what problem can be there?

答:
Judging from this:

```<code>Caused by: java.lang.IllegalArgumentException
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
    at com.android.builder.symbols.Symbol.<init>(Symbol.java:114)
    at com.android.builder.symbols.SymbolIo.read(SymbolIo.java:79)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:896)
</code>```

You have problems with resources. Pay attention to symbols.

Body:
I have updated android studio to 2.3 and getting this error while building project. I have tried Invalidate Cache and Restart, clean but its not getting fixed.

Here is the stacktrace log..

Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugResources'.
    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.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:50)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner$1.execute(RunAsBuildOperationBuildActionRunner.java:40)
    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.tooling.internal.provider.runner.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:75)
    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: java.lang.IllegalArgumentException
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
    at com.android.builder.symbols.Symbol.<init>(Symbol.java:114)
    at com.android.builder.symbols.SymbolIo.read(SymbolIo.java:79)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:896)
    at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:194)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:82)
    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

I also searched for this a lot. but not getting proper solution.
what problem can be there?

Body:
Judging from this:

Caused by: java.lang.IllegalArgumentException
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
    at com.android.builder.symbols.Symbol.<init>(Symbol.java:114)
    at com.android.builder.symbols.SymbolIo.read(SymbolIo.java:79)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:896)

You have problems with resources. Pay attention to symbols.