问:
How to use HikariCP in Spring Boot with two datasources in conjunction with Flyway
I want to use HikariCP as JDBC connection pool in my Spring boot application. I have two datasources (MySQL database as the primary database and accessing those data through Hibernate and additionally an Oracle database for reading some other data through JDBCTemplate).

I set the MySQL datasource as primary bean:

```<code>@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties mySQLDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource mySQLDataSource() {
    return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("oracle.datasource")
public DataSourceProperties oracleDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean(name = "oracleDatabase")
@ConfigurationProperties("oracle.datasource")
public DataSource oracleDataSource() {
    return oracleDataSourceProperties().initializeDataSourceBuilder().build();
}

 @Bean
 public JdbcTemplate oracleJdbcTemplate(@Qualifier("oracleDatabase") DataSource oracleDb) {
     return new JdbcTemplate(oracleDb);
 }
</code>```

and I put the following configurations in my application.properties :

```<code>spring.datasource.type=com.zaxxer.hikari.HikariDataSource

spring.datasource.hikari.minimum-idle=7
spring.datasource.hikari.pool-name=Test-1

spring.datasource.hikari.data-source-properties.prepStmtCacheSize=250
spring.datasource.hikari.data-source-properties.prepStmtCacheSqlLimit=2048
spring.datasource.hikari.data-source-properties.cachePrepStmts=true
spring.datasource.hikari.data-source-properties.useServerPrepStmts=true
</code>```

Unforuntately, these HikariCP configurations are not being read :

```<code> HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - maximumPoolSize.................10
 HikariConfig - metricRegistry..................none
 HikariConfig - metricsTrackerFactory...........none
 HikariConfig - minimumIdle.....................10
 HikariConfig - password........................<masked>
 HikariConfig - poolName........................"HikariPool-1"
</code>```

Creating the HikariCP beans and deactivating the DataSource autoconfiguration and removing  "spring.datasource" :

```<code>@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@SpringBootApplication
@ComponentScan
public class SpringApplication {

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public HikariConfig hikariConfig() {
    return new HikariConfig();
}

@Bean
public DataSource dataSource() {
    return new HikariDataSource(hikariConfig());
}
</code>```

solves my problem :

```<code> HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>, prepStmtCacheSqlLimit=2048, cachePrepStmts=true, useServerPrepStmts=true, prepStmtCacheSize=250}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB?autoReconnect=true"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - poolName........................"Test-1"
</code>```

But then the Flyway showing some weird warnings which were not shown before and I have to create the database Schema manually before running the Spring application, that is : the create schema does not work anymore.

```<code>[WARN ] JdbcTemplate - DB: Can't create database 'test'; database exists (SQL State: HY000 - Error Code: 1007)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.tenant' (SQL State: 42S02 - Error Code: 1051)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.user' (SQL State: 42S02 - Error Code: 1051)
</code>```

My Flyway SQL scripts are plain DDL scripts :

```<code>CREATE SCHEMA IF NOT EXISTS `testSchema` DEFAULT CHARACTER SET utf8 ;

DROP TABLE IF EXISTS `testSchema`.`tenant`;

CREATE TABLE `testSchema`.`tenant` (
  `id` int NOT NULL AUTO_INCREMENT,
</code>```

I think that disabling the Auto-Datasource configuration is not the best solution since Flyway stops creating the schema and showing warnings.  Is there any other way to solve this ?

答:
Thank you Andy for your fast and valuable answer ! You set me on the right track. After fiddling around, I found this configuration is working for me :

```<code>    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource")
  //@ConfigurationProperties("spring.datasource.hikari") can also be used, no difference
    public DataSourceProperties mySQLDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.hikari")
    public DataSource mySQLDataSource() {
        return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public HikariConfig hikariConfig() {
        return new HikariConfig();
    }

    @Bean
    public DataSource dataSource() {
        return new HikariDataSource(hikariConfig());
    }
</code>```

and I had to add these settings in the application.properties:

```<code># this is absolutely mandatory otherwise BeanInstantiationException in mySQLDataSource !
spring.datasource.url=${JDBC_CONNECTION_STRING}

spring.datasource.hikari.jdbc-url=${JDBC_CONNECTION_STRING}

spring.datasource.hikari.username=user
spring.datasource.hikari.password=pass
</code>```

Body:
I want to use HikariCP as JDBC connection pool in my Spring boot application. I have two datasources (MySQL database as the primary database and accessing those data through Hibernate and additionally an Oracle database for reading some other data through JDBCTemplate).

I set the MySQL datasource as primary bean:

@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties mySQLDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource mySQLDataSource() {
    return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("oracle.datasource")
public DataSourceProperties oracleDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean(name = "oracleDatabase")
@ConfigurationProperties("oracle.datasource")
public DataSource oracleDataSource() {
    return oracleDataSourceProperties().initializeDataSourceBuilder().build();
}

 @Bean
 public JdbcTemplate oracleJdbcTemplate(@Qualifier("oracleDatabase") DataSource oracleDb) {
     return new JdbcTemplate(oracleDb);
 }

and I put the following configurations in my application.properties :

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

spring.datasource.hikari.minimum-idle=7
spring.datasource.hikari.pool-name=Test-1

spring.datasource.hikari.data-source-properties.prepStmtCacheSize=250
spring.datasource.hikari.data-source-properties.prepStmtCacheSqlLimit=2048
spring.datasource.hikari.data-source-properties.cachePrepStmts=true
spring.datasource.hikari.data-source-properties.useServerPrepStmts=true

Unforuntately, these HikariCP configurations are not being read :

 HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - maximumPoolSize.................10
 HikariConfig - metricRegistry..................none
 HikariConfig - metricsTrackerFactory...........none
 HikariConfig - minimumIdle.....................10
 HikariConfig - password........................<masked>
 HikariConfig - poolName........................"HikariPool-1"

Creating the HikariCP beans and deactivating the DataSource autoconfiguration and removing  "spring.datasource" :

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@SpringBootApplication
@ComponentScan
public class SpringApplication {

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public HikariConfig hikariConfig() {
    return new HikariConfig();
}

@Bean
public DataSource dataSource() {
    return new HikariDataSource(hikariConfig());
}

solves my problem :

 HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>, prepStmtCacheSqlLimit=2048, cachePrepStmts=true, useServerPrepStmts=true, prepStmtCacheSize=250}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB?autoReconnect=true"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - poolName........................"Test-1"

But then the Flyway showing some weird warnings which were not shown before and I have to create the database Schema manually before running the Spring application, that is : the create schema does not work anymore.

[WARN ] JdbcTemplate - DB: Can't create database 'test'; database exists (SQL State: HY000 - Error Code: 1007)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.tenant' (SQL State: 42S02 - Error Code: 1051)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.user' (SQL State: 42S02 - Error Code: 1051)

My Flyway SQL scripts are plain DDL scripts :

CREATE SCHEMA IF NOT EXISTS `testSchema` DEFAULT CHARACTER SET utf8 ;

DROP TABLE IF EXISTS `testSchema`.`tenant`;

CREATE TABLE `testSchema`.`tenant` (
  `id` int NOT NULL AUTO_INCREMENT,

I think that disabling the Auto-Datasource configuration is not the best solution since Flyway stops creating the schema and showing warnings.  Is there any other way to solve this ?

Body:
Thank you Andy for your fast and valuable answer ! You set me on the right track. After fiddling around, I found this configuration is working for me :

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource")
  //@ConfigurationProperties("spring.datasource.hikari") can also be used, no difference
    public DataSourceProperties mySQLDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.hikari")
    public DataSource mySQLDataSource() {
        return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public HikariConfig hikariConfig() {
        return new HikariConfig();
    }

    @Bean
    public DataSource dataSource() {
        return new HikariDataSource(hikariConfig());
    }

and I had to add these settings in the application.properties:

# this is absolutely mandatory otherwise BeanInstantiationException in mySQLDataSource !
spring.datasource.url=${JDBC_CONNECTION_STRING}

spring.datasource.hikari.jdbc-url=${JDBC_CONNECTION_STRING}

spring.datasource.hikari.username=user
spring.datasource.hikari.password=pass


来源: stackexchange

问:
When using MVVM on Android, should each Activity have one (and only one) ViewModel?
On MVVM pattern, the ViewModel contains business logic and notifies the View when it needs to be updated. It is also notified by the view about user events.

As I understood it, each Model should have an associated ViewModel. So, if we have the following models:

User

Account

We would have the following ViewModels:

UserViewModel

AccountViewModel

However, all examples I find about data binding with MVVM, use a single ViewModel for a layout. And recently, Google has introduced the ViewModel class within Architecture Components. This leads me to believe an Activity would have a single ViewModel that would connect to all related Models:

User / Account  --> ActivityViewModel

This gets even more complicated if we think of a RecyclerView. Each adapter item could be a ViewModel itself, so an Activity with a RecyclerView would have multiple ViewModels within the list and plus a master one for the remaining view contents (assuming they require information from a ViewModel). For instance:

In this example, we have a list of Account ViewModels and one UserViewModel. How would this be embedded into a single ActivityViewModel?

答: What is the relationship between Users and Accounts? If these are two separate, unrelated models, then they should each have their own views and view models. Remember the single responsibility principle: each module should be responsible for only a single part of your logic. That way, any changes to your domain logic or models will only affect that part, and that part only.</p>

ContentLicense: CC BY-SA 3.0


问:
express routing triggers: "Can't set headers after they are sent." error
I am new to Express, and having trouble sending data from backend to front end. Here is what I want to do: I have a Google Map API on the homepage (home.ejs). app.js is the server code: when the homepage is loaded, app.js generate some random locations and send to home.ejs, so home.ejs use those locations as Markers. Now I want to add an event listener to each of these Markers, so that when the mouse is over the Marker, it sends a GET request to server, to request a picture to display.

I feel it a big challenge for me to send the request/data back and forth. When the mouse is over, the home.ejs sends a GET Request to /getImage/:num route, and app.get("/getImage/:num", function(req, res){}) responds to that request by retrieving the image url, and redirect to "/" and sends the url to it. This is where I get the "Can't set headers after they are sent".

I am so new to Express and ejs that I don't even know if I am on the right track. How should I implement this to get the communication through?

This is the app.js server file

```<code>var express = require("express");
var app = express();
//app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname));
app.set("view engine","ejs");

var lng_min = -84.161;
var lng_max = -83.688;
var lat_min = 35.849;
var lat_max = 36.067;

var urls = [
    "http://cdn1-www.dogtime.com/assets/uploads/2015/01/file_21032_the-most-popular-dog-and-cat-names.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Sad-Dog-and-Cat.jpg",
    "https://blog-photos.dogvacay.com/blog/wp-content/uploads/2015/07/dog-cat-smarter-ftr.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Dog-and-Cat-on-a-Log.jpg",
    "http://images.boomsbeat.com/data/images/full/31730/cat-and-dog_1-jpg.jpg",
    "http://www.vetlocator.com/dailypaws/wp-content/uploads/2012/04/dog-cat2.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Old-Dog-and-Cat-Sleepy-Embrace.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXNMdvNfc3WYMqbPrJrnjgHJRp2zB1y9vx545LfO-_U5_yvgBo",
    "http://www.vetlocator.com/dailypaws/wp-content/uploads/2012/04/dog-cat8.jpg",
    "http://www.maddiesfund.org/assets/metaImage/robust-dog-cat-foster.jpg"
]

var numLocations = 10;
var data = [];

function generateData() {
    // generate random locations and the url to download pictures
    for (var i = 0; i < numLocations; ++i) {
        var lng = Math.random() * (lng_max - lng_min) + lng_min;
        var lat = Math.random() * (lat_max - lat_min) + lat_min;
        var tuple = {
            id: i,
            lng: lng,
            lat: lat,
            pic: urls[i]
        };
        data.push(tuple);
    }
}

app.get("/", function(req, res) {
    //res.send("Hello it works");
    data = [];
    generateData();
    res.render("home.ejs", {data: data});
});

app.get("/getImg/:num", function(req, res) {
  console.log(req.params.num);
  var i = Number(req.params.num);
  res.redirect("/");
  res.send({imgUrl: data[i].pic});
});

app.listen(process.env.PORT, process.env.IP, function() {
   console.log("Server Started!");
});
</code>```

home.ejs file:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <link rel="stylesheet" type="text/css" href="/public/app.css">

</head>
<body>
    <div id="map">
    </div>

    <script>
      var data = <%- JSON.stringify(data) %>;
      console.log(data.length);
      function initMap() {
        var loc = {lat: 35.9606, lng: -83.9207};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 10,
          center: loc
        });
        for (var i = 0; i < data.length; ++i) {
            var loc = {lat: data[i].lat, lng: data[i].lng};
            var marker = new google.maps.Marker({
                  position: loc,
                  map: map
                  // id: i
            });

            var infowindow = new google.maps.InfoWindow();
            google.maps.event.addListener(marker, 'mouseover', (function(marker) {
            return function() {
                  // var content = '<div id="imgDisplay">'
                  //                   + '<img src="http://www.maddiesfund.org/assets/metaImage/robust-dog-cat-foster.jpg">'
                  //                 + '</div>';
                  // infowindow.setContent(content);
                  // infowindow.open(map, marker);

              var xhr = new XMLHttpRequest();
              var params = 3;
              xhr.open('GET','/getImg/'+params, true);
                  xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                      console.log(responseText);
                }
                  }
            //xhr.send(params);
            xhr.send();

            }
         })(marker));

         }
      }
    </script>

    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAOwfkV_GbUXyH2s8iD0gS6pje9J3R96dM&callback=initMap">
    </script>

</body>
</html>
</code>```

答:
You misunderstand the purpose of redirect. Express's redirect function says, "This path does not have an answer; instead try sending a request to this other path and see what it says." (This is done by a 3xx response like 301 or 302.)

Your confusion is that you think you need to tell the client which page should render the given URL. But that is not necessary: the server doesn't tell the client how to render the data it sends. The server just sends data, and the client decides what to do with it.

The good news is that your client-side JavaScript is doing its job correctly. It's using an XMLHttpRequest to fetch data from the server. Simply have the server actually send that data with the send function and don't call redirect. Once your client-side has the URL to load, you can load it in an  element with

```<code>var img = new Image();
img.src=responseText;
document.body.appendChild(img);
</code>```

inside your onreadystatechange listener. You can use document.getElementById(...)
 to get a different element if you don't want to add the element to your body.

Body:
I am new to Express, and having trouble sending data from backend to front end. Here is what I want to do: I have a Google Map API on the homepage (home.ejs). app.js is the server code: when the homepage is loaded, app.js generate some random locations and send to home.ejs, so home.ejs use those locations as Markers. Now I want to add an event listener to each of these Markers, so that when the mouse is over the Marker, it sends a GET request to server, to request a picture to display.

I feel it a big challenge for me to send the request/data back and forth. When the mouse is over, the home.ejs sends a GET Request to /getImage/:num route, and app.get("/getImage/:num", function(req, res){}) responds to that request by retrieving the image url, and redirect to "/" and sends the url to it. This is where I get the "Can't set headers after they are sent".

I am so new to Express and ejs that I don't even know if I am on the right track. How should I implement this to get the communication through?

This is the app.js server file

var express = require("express");
var app = express();
//app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname));
app.set("view engine","ejs");

var lng_min = -84.161;
var lng_max = -83.688;
var lat_min = 35.849;
var lat_max = 36.067;

var urls = [
    "http://cdn1-www.dogtime.com/assets/uploads/2015/01/file_21032_the-most-popular-dog-and-cat-names.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Sad-Dog-and-Cat.jpg",
    "https://blog-photos.dogvacay.com/blog/wp-content/uploads/2015/07/dog-cat-smarter-ftr.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Dog-and-Cat-on-a-Log.jpg",
    "http://images.boomsbeat.com/data/images/full/31730/cat-and-dog_1-jpg.jpg",
    "http://www.vetlocator.com/dailypaws/wp-content/uploads/2012/04/dog-cat2.jpg",
    "http://qltyctrl.com/wp-content/uploads/2014/03/Old-Dog-and-Cat-Sleepy-Embrace.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXNMdvNfc3WYMqbPrJrnjgHJRp2zB1y9vx545LfO-_U5_yvgBo",
    "http://www.vetlocator.com/dailypaws/wp-content/uploads/2012/04/dog-cat8.jpg",
    "http://www.maddiesfund.org/assets/metaImage/robust-dog-cat-foster.jpg"
]

var numLocations = 10;
var data = [];

function generateData() {
    // generate random locations and the url to download pictures
    for (var i = 0; i < numLocations; ++i) {
        var lng = Math.random() * (lng_max - lng_min) + lng_min;
        var lat = Math.random() * (lat_max - lat_min) + lat_min;
        var tuple = {
            id: i,
            lng: lng,
            lat: lat,
            pic: urls[i]
        };
        data.push(tuple);
    }
}

app.get("/", function(req, res) {
    //res.send("Hello it works");
    data = [];
    generateData();
    res.render("home.ejs", {data: data});
});

app.get("/getImg/:num", function(req, res) {
  console.log(req.params.num);
  var i = Number(req.params.num);
  res.redirect("/");
  res.send({imgUrl: data[i].pic});
});

app.listen(process.env.PORT, process.env.IP, function() {
   console.log("Server Started!");
});

home.ejs file:

<!DOCTYPE html>

    <title>Demo</title>
    <link rel="stylesheet" type="text/css" href="/public/app.css">

Body:
You misunderstand the purpose of redirect. Express's redirect function says, "This path does not have an answer; instead try sending a request to this other path and see what it says." (This is done by a 3xx response like 301 or 302.)

Your confusion is that you think you need to tell the client which page should render the given URL. But that is not necessary: the server doesn't tell the client how to render the data it sends. The server just sends data, and the client decides what to do with it.

The good news is that your client-side JavaScript is doing its job correctly. It's using an XMLHttpRequest to fetch data from the server. Simply have the server actually send that data with the send function and don't call redirect. Once your client-side has the URL to load, you can load it in an <img> element with

var img = new Image();
img.src=responseText;
document.body.appendChild(img);

inside your onreadystatechange listener. You can use document.getElementById(...)
 to get a different element if you don't want to add the element to your body.


问:
Expected ',' seperator When adding images
```<code>@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var Button: UIButton!

Imagenames = ["#imageLiteral(resourceName: "image2")", "#imageLiteral(resourceName: "image1"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Buttonpress(_ sender: UIButton) {

    let imageV = Int(arc4random_uniform(2))

    ImageView.image = UIImage(named: Imagenames[ImageView])
}
</code>```

How can I fix this issue? please help. Running the latest version of Xcode

答:
You forget a simple ) in your code, and you have an extra ":

```<code>Imagenames = [#imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image1")]
</code>```

That should save your life :) haha, sometimes happens

Body:
@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var Button: UIButton!

Imagenames = ["#imageLiteral(resourceName: "image2")", "#imageLiteral(resourceName: "image1"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Buttonpress(_ sender: UIButton) {

    let imageV = Int(arc4random_uniform(2))

    ImageView.image = UIImage(named: Imagenames[ImageView])
}

How can I fix this issue? please help. Running the latest version of Xcode

Body:
You forget a simple ) in your code, and you have an extra ":

Imagenames = [#imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image1")]

That should save your life :) haha, sometimes happens


问:
Using reflection to get methods with certain attribute value
I have this delegate:

```<code> public delegate void PacketHandler(Client client, Packet packet);
</code>```

I have this attribute:

```<code>[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class PacketHandlerAttribute : Attribute
{
    public ServerType Server { get; private set; }
    public int Code { get; private set; }

    public PacketHandlerAttribute(ServerType server, int code)
    {
        this.Server = server;
        this.Code = code;
    }
}
</code>```

I wanted to make a method to return an IEnumerable<Tuple<PacketHandlerAttribute, PacketHandler>> based on the given ServerType value. So, if I call this method with ServerType.Server, it will return all methods containing Server1 as their attribute.

I made this so far:

```<code>public static IEnumerable<Doublet<PacketHandlerAttribute, PacketHandler>> GetPacketHandlers(ServerType server)
    {
        foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
        {
            foreach (MethodInfo method in type.GetMethods())
            {
                PacketHandlerAttribute attribute = (PacketHandlerAttribute)method.GetCustomAttribute(typeof(PacketHandlerAttribute));

                if (attribute != null)
                {
                    if (attribute.Server == server)
                    {
                        yield return new Doublet<PacketHandlerAttribute, PacketHandler>(attribute, (PacketHandler)Delegate.CreateDelegate(typeof(PacketHandler), method));
                    }
                }
            }
        }
    }
</code>```

I wanted to ask if that's the correct way of doing this, and how can this be shortened with LINQ?

答:
Here is something that I think will help.

```<code> var methods = from type in assembly.GetTypes()
                      from method in type.GetMethods()
                      let attribute = method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).Cast<PacketHandlerAttribute>().FirstOrDefault()
                      where attribute?.Code == 1
                      select new { method, attribute };
</code>```

Your method

```<code>public IEnumerable<(PacketHandlerAttribute attribute, PacketHandler handler)> GetPacketHandlers(ServerType server)
        {
            var assembly = Assembly.GetEntryAssembly();

            return from type in assembly.GetTypes()
                          from method in type.GetMethods()
                          let attribute = method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).Cast<PacketHandlerAttribute>().FirstOrDefault()
                          where attribute?.Server == server
                          select (attribute, (PacketHandler)method.CreateDelegate(typeof(PacketHandler)));
        }
</code>```

Body:
I have this delegate:

 public delegate void PacketHandler(Client client, Packet packet);

I have this attribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class PacketHandlerAttribute : Attribute
{
    public ServerType Server { get; private set; }
    public int Code { get; private set; }

    public PacketHandlerAttribute(ServerType server, int code)
    {
        this.Server = server;
        this.Code = code;
    }
}

I wanted to make a method to return an IEnumerable<Tuple<PacketHandlerAttribute, PacketHandler>> based on the given ServerType value. So, if I call this method with ServerType.Server, it will return all methods containing Server1 as their attribute.

I made this so far:

public static IEnumerable<Doublet<PacketHandlerAttribute, PacketHandler>> GetPacketHandlers(ServerType server)
    {
        foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
        {
            foreach (MethodInfo method in type.GetMethods())
            {
                PacketHandlerAttribute attribute = (PacketHandlerAttribute)method.GetCustomAttribute(typeof(PacketHandlerAttribute));

                if (attribute != null)
                {
                    if (attribute.Server == server)
                    {
                        yield return new Doublet<PacketHandlerAttribute, PacketHandler>(attribute, (PacketHandler)Delegate.CreateDelegate(typeof(PacketHandler), method));
                    }
                }
            }
        }
    }

I wanted to ask if that's the correct way of doing this, and how can this be shortened with LINQ?

Body:
Here is something that I think will help.

 var methods = from type in assembly.GetTypes()
                      from method in type.GetMethods()
                      let attribute = method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).Cast<PacketHandlerAttribute>().FirstOrDefault()
                      where attribute?.Code == 1
                      select new { method, attribute };

Your method

public IEnumerable<(PacketHandlerAttribute attribute, PacketHandler handler)> GetPacketHandlers(ServerType server)
        {
            var assembly = Assembly.GetEntryAssembly();

            return from type in assembly.GetTypes()
                          from method in type.GetMethods()
                          let attribute = method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).Cast<PacketHandlerAttribute>().FirstOrDefault()
                          where attribute?.Server == server
                          select (attribute, (PacketHandler)method.CreateDelegate(typeof(PacketHandler)));
        }


问:
What is the best way to get a dump of unique partition keys from Cassandra from a large column family?
```<code>create table t(
key string,
time timeuuid,
val string
) primary key (key,time)
</code>```

I found 2 methods.

1 - use COPY. But when using COPY I am getting multiple lines for combination of key,time. I just want unique row keys.

2 - Through code using select *.

Above methods are also slower.
Is there a better and faster way to do this ?

答:
use the sstablekeys utility to dump the keys from the Cassandra table. Here is the reference

sstablekeys utility

Body:
create table t(
key string,
time timeuuid,
val string
) primary key (key,time)

I found 2 methods.

1 - use COPY. But when using COPY I am getting multiple lines for combination of key,time. I just want unique row keys.

2 - Through code using select *.

Above methods are also slower.
Is there a better and faster way to do this ?


问:
Why do you have to use fetch for Rails params?
In the docs, they have:

```<code>params = ActionController::Parameters.new(person: { name: "Francesco" })
</code>```

and then use params.fetch(:person) to get person, but can't you just do params[:person]? to get the same data?

答:
I suppose it depends on the behavior you desire.

```<code>params = ActionController::Parameters.new
params.fetch(:person)
</code>```

Will raise an error. As reflected in the docs, you can specify further behavior with fetch, if you so desire.

```<code>params = ActionController::Parameters.new
params[:person]
</code>```

Will return nil.

Body:
In the docs, they have:

params = ActionController::Parameters.new(person: { name: "Francesco" })

and then use params.fetch(:person) to get person, but can't you just do params[:person]? to get the same data?

Body:
I suppose it depends on the behavior you desire.

params = ActionController::Parameters.new
params.fetch(:person)

Will raise an error. As reflected in the docs, you can specify further behavior with fetch, if you so desire.

params = ActionController::Parameters.new
params[:person]

Will return nil.


问:
How to watch object changes with rxjs 5
I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before,
yet the answer is irrelevant since RXjs verion 5 do not include the ofObjectChanges in it's API anymore.

I've looked at some "hacks" like creating an observer which return a function:

```<code>let myObservable =  new Observable((observer) => {
  return (data) => {
    observer.next(data)
  }
})
//...
myObservable.subscribe()('someData')
</code>```

However, I'm sure there is more elegant way of doing it.
Any Ideas?

答: You need to use Behavior Subject . https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md</p>

Title: How to watch object changes with rxjs 5

Body:
I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before,
yet the answer is irrelevant since RXjs verion 5 do not include the ofObjectChanges in it's API anymore.

I've looked at some "hacks" like creating an observer which return a function:

let myObservable =  new Observable((observer) => {
  return (data) => {
    observer.next(data)
  }
})
//...
myObservable.subscribe()('someData')

However, I'm sure there is more elegant way of doing it.
Any Ideas?


问:
Does Cython support the ternary style if statement (if ? then : else)?
I forget the technical term for the (if ? then : else) format in C/C++. Also, is this syntax supported in the Cython (a C variant of Python)?

I need to know the technical name so I can lookup if Cython supports this feature.

UPDATE: Does anyone know if Cython supports this?

Solution: In cython/python this is written as (b if a else c) compare to (a ? b : c)

答:
It's called the ternary conditional operator. It's often just called the ternary operator, but being ternary is not necessarily (but in practice usually is) unique to the conditional operator.

EDIT: In regards to whether Cython supports (x ? y : z), it appears not to based on some preliminary Googling. But Python (and theoretically Cython I think? Disclaimer: I don't use Cython) supports the same result (if/else expression) with (y if x else z). EDIT 2: The Cython documentation I've found says that it works the same as in regular Python.

ContentLicense: CC BY-SA 2.5


问:
How to have an automatic timestamp in SQLite?
I have an SQLite database, version 3 and I am using C# to create an application that uses this database.

I want to use a timestamp field in a table for concurrency, but I notice that when I insert a new record, this field is not set, and is null.

For example, in MS SQL Server if I use a timestamp field it is updated by the database and I don't have to set it by myself. Is this possible in SQLite?

答:
To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then
go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

```<code>modelBuilder.Entity<YourEntity>()
                .Property(b => b.Timestamp)
                .ValueGeneratedOnAddOrUpdate()
                .IsConcurrencyToken()
                .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");
</code>```

It will make a default value to every data that will be insert into this table.

ContentLicense: CC BY-SA 4.0

Body:
To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then
go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

modelBuilder.Entity<YourEntity>()
                .Property(b => b.Timestamp)
                .ValueGeneratedOnAddOrUpdate()
                .IsConcurrencyToken()
                .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");

It will make a default value to every data that will be insert into this table.


问:
C# String Interning Garbage Collection
While referring to CLR via C# according to Jeff, C# interning enhance performance substantially in CLR. When the CLR initializes, it creates an internal hash table in which the keys are strings and the values are references to String objects in the managed heap. The public static String Intern(String str) method, Intern, takes a String, obtains a hash code for it, and checks the internal hash table for a match. Till here its perfect and the way of working too. But here is the game changer "String objects referred to by the internal hash table can’t be freed until the AppDomain is unloaded or the process terminates." So every string you creates, its hash code will be maintained and freed only at the time of Appdomain Unloads so is it a bad design? or is my understanding is not clear? please explain.

答:
Your understanding is clear.

Your reasons for worrying are not.

If you do something like this:

```<code>for( int i = 0;  i < 100000;  i++ )
   String.Intern( "bla-bla-bla-bla-bla" + i );
</code>```

then you will be creating lots of strings that will never be garbage-collected.

But if you just do

```<code>String.Intern( myName );
String.Intern( myApp );
String.Intern( myCompany );
</code>```

then you will be creating just 3 strings that will never be garbage-collected.

So, if you just make sure that you use String.intern() in situations like the second, rather than the first, you will be fine.

Generally, as (Marc points out), you don't have to invoke String.Intern() yourself.  The compiler in collaboration with the runtime will make sure to intern everything that is worth interning, or potentially worth interning.

To give you an example of a situation where you may potentially want to intern strings: say, you are going to create a finite number of threads, and you want to name them, say "Thread0" through "Thread9", by appending a counter from 0 to 9 to the string "Thread".  And say, you want to maintain a Dictionary<String,Thread> so you can lookup threads by name.  In this case, it pays to intern these thread names.  The thread names do not already exist as constants in your program, so they are not already interned, and you will not be creating many of them, and they will remain constant throughout the runtime of your program, so they are good candidates for interning.

Title: C# String Interning Garbage Collection

Body:
Your understanding is clear.

Your reasons for worrying are not.

If you do something like this:

for( int i = 0;  i < 100000;  i++ )
   String.Intern( "bla-bla-bla-bla-bla" + i );

then you will be creating lots of strings that will never be garbage-collected.

But if you just do

String.Intern( myName );
String.Intern( myApp );
String.Intern( myCompany );

then you will be creating just 3 strings that will never be garbage-collected.

So, if you just make sure that you use String.intern() in situations like the second, rather than the first, you will be fine.

Generally, as (Marc points out), you don't have to invoke String.Intern() yourself.  The compiler in collaboration with the runtime will make sure to intern everything that is worth interning, or potentially worth interning.

To give you an example of a situation where you may potentially want to intern strings: say, you are going to create a finite number of threads, and you want to name them, say "Thread0" through "Thread9", by appending a counter from 0 to 9 to the string "Thread".  And say, you want to maintain a Dictionary<String,Thread> so you can lookup threads by name.  In this case, it pays to intern these thread names.  The thread names do not already exist as constants in your program, so they are not already interned, and you will not be creating many of them, and they will remain constant throughout the runtime of your program, so they are good candidates for interning.


问:
Date object in Sparklyr
I have a string that is yyyymmdd and want to turn it into a date object in using sparklyr so that I can subtract one date from the other.

This code works for yyyy-mm-dd hr:min:sec

```<code>temp_table <- taxi %>%
mutate(hrs = (unix_timestamp(tpep_dropoff_datetime) - unix_timestamp(tpep_pickup_datetime))
</code>```

What cide would I use if instead of it being a string if yyyy-mm-dd hr:min:sec it was a string of just yyyymmdd?

I tried something like this but does not work.

```<code>temp_table <- taxi %>%
mutate(hrs = (datetime.strptime(tpep_dropoff_datetime) - datetime.strptime(tpep_pickup_datetime))
</code>```

答:
Try this:</p>

```<code>temp_table <- taxi %>%
mutate(hrs = (unix_timestamp(tpep_dropoff_datetime,'yyyyMMdd') - unix_timestamp(tpep_pickup_datetime,'yyyyMMdd'))
</code>```

Title: Date object in Sparklyr

Body:
I have a string that is yyyymmdd and want to turn it into a date object in using sparklyr so that I can subtract one date from the other.

This code works for yyyy-mm-dd hr:min:sec

temp_table <- taxi %>%
mutate(hrs = (unix_timestamp(tpep_dropoff_datetime) - unix_timestamp(tpep_pickup_datetime))

What cide would I use if instead of it being a string if yyyy-mm-dd hr:min:sec it was a string of just yyyymmdd?

I tried something like this but does not work.

temp_table <- taxi %>%
mutate(hrs = (datetime.strptime(tpep_dropoff_datetime) - datetime.strptime(tpep_pickup_datetime))

Body:
Try this:

temp_table <- taxi %>%
mutate(hrs = (unix_timestamp(tpep_dropoff_datetime,'yyyyMMdd') - unix_timestamp(tpep_pickup_datetime,'yyyyMMdd'))


问:
A TextView's String is being set wrong - How can I fix it?
I have been working with android studio for about five weeks. In this time, I have learned how to set a TextView's string and set a string variable containing that string. I have been trying to make an app game for android devices, and have encountered a problem whilst changing some code.

The textView myText is supposed to specify a coloured button to press, but when I press the start button in the android emulator, the randomly generated text and button never correlate with each other, even though I have a series of if statements to make sure that they do.

for some reason when I run the code the first colour button is always the correct button, and then runs the method colourSwitch as it should if it is correct, but I do not know what the problem is regarding connecting the correct coloured button to the correct text. Oh, and I am connecting this activity with a losing game activity which is called when any wrong button is pressed. If you want the code for the other activity, I am happy to show.

Here is my xml file for the game activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/game_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.a2118667.red.MainActivity"
    tools:layout_editor_absoluteX="0dp"
    android:layout_marginTop="0dp"
    app:layout_constraintTop_toBottomOf="@+id/indicatorText">

    <Button
        android:id="@+id/startButton"
        android:layout_width="175dp"
        android:layout_height="75dp"
        android:layout_marginTop="8dp"
        android:text="@string/Game_Start_Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.502"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.156" />

    <GridLayout
        android:id="@+id/gridLayout"
        android:layout_width="299dp"
        android:layout_height="301dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.505"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.88">

        <Button
            android:id="@+id/button1"
            android:layout_width="150dp"
            android:layout_height="150dp" />

        <Button
            android:id="@+id/button3"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_column="0"
            android:layout_row="1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_column="1"
            android:layout_row="0" />

        <Button
            android:id="@+id/button4"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_column="1"
            android:layout_row="1" />
    </GridLayout>

    <TextView
        android:id="@+id/indicatorText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text=" "
        android:textAppearance="@style/TextAppearance.AppCompat.Button"
        android:textSize="34sp"
        app:layout_constraintBottom_toTopOf="@+id/startButton"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>
</code>```

Here is my Java file for the game activity.

```<code>    package com.example.a2118667.red;
//imports
import android.content.Intent;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;
import android.widget.TextView;
import java.util.Random;

import static  com.example.a2118667.red.R.id.startButton;

public class MainActivity extends AppCompatActivity {

    final int[] cowbears = {0};
    final int[] cowbears2 = {0};
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView myText = (TextView) findViewById(R.id.indicatorText);

        final Button myButton = (Button) findViewById(R.id.startButton);

        final Button button1 = (Button) findViewById(R.id.button1);
        final Button button2 = (Button) findViewById(R.id.button2);
        final Button button3 = (Button) findViewById(R.id.button3);
        final Button button4 = (Button) findViewById(R.id.button4);

        myButton.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        ((ViewGroup) myButton.getParent()).removeView(myButton);
                        colourSwitch();
                    }
                }
        );

        button4.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        myText.setText("cowBears rock");
                        // if button says yellow and button is yellow
                        if (cowbears[0] == 2 && cowbears2[0] <= 1 || cowbears[0] == 6 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] == 3 && cowbears2[0] == 2 || cowbears[0] == 7 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] == 4 && cowbears2[0] == 3 || cowbears[0] == 8 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] <= 1 && cowbears2[0] == 4 || cowbears[0] == 5 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();
                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }

                    }
                }

        );

        button3.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        myText.setText("cowBears rock");
                        // if button says yellow and button is yellow
                        if (cowbears[0] == 3 && cowbears2[0] <= 1 || cowbears[0] == 8 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] == 4 && cowbears2[0] == 2 || cowbears[0] == 5 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] <= 1 && cowbears2[0] == 3 || cowbears[0] == 6 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] == 2 && cowbears2[0] == 4 || cowbears[0] == 7 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();
                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }
                    }
                }
        );

        button2.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        myText.setText("cowBears rock");
                        // if button says yellow and button yellow
                        if (cowbears[0] == 4 && cowbears2[0] <= 1 || cowbears[0] == 7 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] <= 1 && cowbears2[0] == 2 || cowbears[0] == 8 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] == 2 && cowbears2[0] == 3 || cowbears[0] == 5 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] == 3 && cowbears2[0] == 4 || cowbears[0] == 6 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();
                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }
                    }
                }
        );

        // onClick Listeners for buttons
        button1.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        //debugged

                        myText.setText("cowBears rock");
                        // if button says yellow and button yellow
                        if (cowbears[0] <= 1 && cowbears2[0] <= 1 || cowbears[0] == 5 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] == 2 && cowbears2[0] == 2 || cowbears[0] == 6 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] == 3 && cowbears2[0] == 3 || cowbears[0] == 7 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] == 4 && cowbears2[0] == 4 || cowbears[0] == 8 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();

                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }

                    }
                }
        );

    }

    private void losedThegameBoi() {
        Intent intent = new Intent(this, Loser_Activity.class);
        startActivity(intent);
    }

    private void colourSwitch() {
        final TextView myText = (TextView) findViewById(R.id.indicatorText);

        final Button button1 = (Button) findViewById(R.id.button1);
        final Button button2 = (Button) findViewById(R.id.button2);
        final Button button3 = (Button) findViewById(R.id.button3);
        final Button button4 = (Button) findViewById(R.id.button4);

        final int[] cowBears = {0};
        final int[] cowBears2 = {0};

        final int[] cowbears = {0};
        final int[] cowbears2 = {0};

        //Random number generator for randomizing colour layout
        Random randomGenerator = new Random();
        //For generating what colour pattern to be displayed
        int randomInt = randomGenerator.nextInt(9);
        myText.setText("Generated : " + randomInt);
        cowBears[0] = randomInt;
        cowbears[0] = randomInt;
        //Colour patterns based on what integer is generated
        //Random number generator for randomizing button click stuff
        Random randomGenerator2 = new Random();
        //For generating which text to be displayed
        int randomInt2 = randomGenerator2.nextInt(5);
        myText.setText("Generated : " + randomInt2);
        cowBears2[0] = randomInt2;
        cowbears2[0] = randomInt2;

        // if statements for the colour scheme
        if (cowBears[0] <= 1) {
            button1.setBackgroundResource(R.drawable.yellow);
            button2.setBackgroundResource(R.drawable.blue);
            button3.setBackgroundResource(R.drawable.green);
            button4.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 2) {
            button4.setBackgroundResource(R.drawable.yellow);
            button1.setBackgroundResource(R.drawable.blue);
            button2.setBackgroundResource(R.drawable.green);
            button3.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 3) {
            button3.setBackgroundResource(R.drawable.yellow);
            button4.setBackgroundResource(R.drawable.blue);
            button1.setBackgroundResource(R.drawable.green);
            button2.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 4) {
            button2.setBackgroundResource(R.drawable.yellow);
            button3.setBackgroundResource(R.drawable.blue);
            button4.setBackgroundResource(R.drawable.green);
            button1.setBackgroundResource(R.drawable.download);
        }
        if (cowBears[0] == 5) {
            button1.setBackgroundResource(R.drawable.yellow);
            button3.setBackgroundResource(R.drawable.blue);
            button2.setBackgroundResource(R.drawable.green);
            button4.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 6) {
            button4.setBackgroundResource(R.drawable.yellow);
            button1.setBackgroundResource(R.drawable.blue);
            button3.setBackgroundResource(R.drawable.green);
            button2.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 7) {
            button2.setBackgroundResource(R.drawable.yellow);
            button4.setBackgroundResource(R.drawable.blue);
            button1.setBackgroundResource(R.drawable.green);
            button3.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 8) {
            button3.setBackgroundResource(R.drawable.yellow);
            button2.setBackgroundResource(R.drawable.blue);
            button4.setBackgroundResource(R.drawable.green);
            button1.setBackgroundResource(R.drawable.download);
        }

        //Here we have the randomizing of the button text based on what integer is genetated for cowbears2
        if (cowBears2[0] <= 1) {
            myText.setText("yellow" + cowBears[0] + cowBears2[0]);
        }

        if (cowBears2[0] == 2) {
            myText.setText("Blue" + cowBears[0] + cowBears2[0]);
        }

        if (cowBears2[0] == 3) {
            myText.setText("Green" + cowBears[0] + cowBears2[0]);
        }

        if (cowBears2[0] == 4) {
            myText.setText("Red" + cowBears[0] + cowBears2[0]);
        }
    }
}
</code>```

If anyone could figure out why my code behaves like this, that would be appreciated.

答:
I found the answer. You see my cowbears, and cowBears integers were being randomized differently.

The cowBears, cowBears2, cowbears, and cowbears2 final integers must be declared directly above the onCreate method, as the upper case cowBear integers were being redeclared during a button press.

Body:
I have been working with android studio for about five weeks. In this time, I have learned how to set a TextView's string and set a string variable containing that string. I have been trying to make an app game for android devices, and have encountered a problem whilst changing some code.

The textView myText is supposed to specify a coloured button to press, but when I press the start button in the android emulator, the randomly generated text and button never correlate with each other, even though I have a series of if statements to make sure that they do.

for some reason when I run the code the first colour button is always the correct button, and then runs the method colourSwitch as it should if it is correct, but I do not know what the problem is regarding connecting the correct coloured button to the correct text. Oh, and I am connecting this activity with a losing game activity which is called when any wrong button is pressed. If you want the code for the other activity, I am happy to show.

Here is my xml file for the game activity:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/game_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.a2118667.red.MainActivity"
    tools:layout_editor_absoluteX="0dp"
    android:layout_marginTop="0dp"
    app:layout_constraintTop_toBottomOf="@+id/indicatorText">

    <Button
        android:id="@+id/startButton"
        android:layout_width="175dp"
        android:layout_height="75dp"
        android:layout_marginTop="8dp"
        android:text="@string/Game_Start_Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.502"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.156" />

    <GridLayout
        android:id="@+id/gridLayout"
        android:layout_width="299dp"
        android:layout_height="301dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.505"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.88">

        <Button
            android:id="@+id/button1"
            android:layout_width="150dp"
            android:layout_height="150dp" />

        <Button
            android:id="@+id/button3"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_column="0"
            android:layout_row="1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_column="1"
            android:layout_row="0" />

        <Button
            android:id="@+id/button4"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_column="1"
            android:layout_row="1" />
    </GridLayout>

    <TextView
        android:id="@+id/indicatorText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:text=" "
        android:textAppearance="@style/TextAppearance.AppCompat.Button"
        android:textSize="34sp"
        app:layout_constraintBottom_toTopOf="@+id/startButton"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>

Here is my Java file for the game activity.

    package com.example.a2118667.red;
//imports
import android.content.Intent;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;
import android.widget.TextView;
import java.util.Random;

import static  com.example.a2118667.red.R.id.startButton;

public class MainActivity extends AppCompatActivity {

    final int[] cowbears = {0};
    final int[] cowbears2 = {0};
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView myText = (TextView) findViewById(R.id.indicatorText);

        final Button myButton = (Button) findViewById(R.id.startButton);

        final Button button1 = (Button) findViewById(R.id.button1);
        final Button button2 = (Button) findViewById(R.id.button2);
        final Button button3 = (Button) findViewById(R.id.button3);
        final Button button4 = (Button) findViewById(R.id.button4);

        myButton.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        ((ViewGroup) myButton.getParent()).removeView(myButton);
                        colourSwitch();
                    }
                }
        );

        button4.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        myText.setText("cowBears rock");
                        // if button says yellow and button is yellow
                        if (cowbears[0] == 2 && cowbears2[0] <= 1 || cowbears[0] == 6 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] == 3 && cowbears2[0] == 2 || cowbears[0] == 7 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] == 4 && cowbears2[0] == 3 || cowbears[0] == 8 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] <= 1 && cowbears2[0] == 4 || cowbears[0] == 5 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();
                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }

                    }
                }

        );

        button3.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        myText.setText("cowBears rock");
                        // if button says yellow and button is yellow
                        if (cowbears[0] == 3 && cowbears2[0] <= 1 || cowbears[0] == 8 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] == 4 && cowbears2[0] == 2 || cowbears[0] == 5 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] <= 1 && cowbears2[0] == 3 || cowbears[0] == 6 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] == 2 && cowbears2[0] == 4 || cowbears[0] == 7 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();
                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }
                    }
                }
        );

        button2.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        myText.setText("cowBears rock");
                        // if button says yellow and button yellow
                        if (cowbears[0] == 4 && cowbears2[0] <= 1 || cowbears[0] == 7 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] <= 1 && cowbears2[0] == 2 || cowbears[0] == 8 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] == 2 && cowbears2[0] == 3 || cowbears[0] == 5 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] == 3 && cowbears2[0] == 4 || cowbears[0] == 6 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();
                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }
                    }
                }
        );

        // onClick Listeners for buttons
        button1.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        //debugged

                        myText.setText("cowBears rock");
                        // if button says yellow and button yellow
                        if (cowbears[0] <= 1 && cowbears2[0] <= 1 || cowbears[0] == 5 && cowbears2[0] <= 1) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says blue and button blue
                        if (cowbears[0] == 2 && cowbears2[0] == 2 || cowbears[0] == 6 && cowbears2[0] == 2) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says green and button green
                        if (cowbears[0] == 3 && cowbears2[0] == 3 || cowbears[0] == 7 && cowbears2[0] == 3) {
                            myText.setText("You did it, mommy!");
                        }
                        // if button says red and button red
                        if (cowbears[0] == 4 && cowbears2[0] == 4 || cowbears[0] == 8 && cowbears2[0] == 4) {
                            myText.setText("You did it, mommy!");
                        }
                        String verify = myText.getText().toString();
                        if (verify.equals("cowBears rock")){
                            losedThegameBoi();

                        }

                        String check = myText.getText().toString();
                        if (check.equals("You did it, mommy!")) {
                            colourSwitch();
                        }

                    }
                }
        );

    }

    private void losedThegameBoi() {
        Intent intent = new Intent(this, Loser_Activity.class);
        startActivity(intent);
    }

    private void colourSwitch() {
        final TextView myText = (TextView) findViewById(R.id.indicatorText);

        final Button button1 = (Button) findViewById(R.id.button1);
        final Button button2 = (Button) findViewById(R.id.button2);
        final Button button3 = (Button) findViewById(R.id.button3);
        final Button button4 = (Button) findViewById(R.id.button4);

        final int[] cowBears = {0};
        final int[] cowBears2 = {0};

        final int[] cowbears = {0};
        final int[] cowbears2 = {0};

        //Random number generator for randomizing colour layout
        Random randomGenerator = new Random();
        //For generating what colour pattern to be displayed
        int randomInt = randomGenerator.nextInt(9);
        myText.setText("Generated : " + randomInt);
        cowBears[0] = randomInt;
        cowbears[0] = randomInt;
        //Colour patterns based on what integer is generated
        //Random number generator for randomizing button click stuff
        Random randomGenerator2 = new Random();
        //For generating which text to be displayed
        int randomInt2 = randomGenerator2.nextInt(5);
        myText.setText("Generated : " + randomInt2);
        cowBears2[0] = randomInt2;
        cowbears2[0] = randomInt2;

        // if statements for the colour scheme
        if (cowBears[0] <= 1) {
            button1.setBackgroundResource(R.drawable.yellow);
            button2.setBackgroundResource(R.drawable.blue);
            button3.setBackgroundResource(R.drawable.green);
            button4.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 2) {
            button4.setBackgroundResource(R.drawable.yellow);
            button1.setBackgroundResource(R.drawable.blue);
            button2.setBackgroundResource(R.drawable.green);
            button3.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 3) {
            button3.setBackgroundResource(R.drawable.yellow);
            button4.setBackgroundResource(R.drawable.blue);
            button1.setBackgroundResource(R.drawable.green);
            button2.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 4) {
            button2.setBackgroundResource(R.drawable.yellow);
            button3.setBackgroundResource(R.drawable.blue);
            button4.setBackgroundResource(R.drawable.green);
            button1.setBackgroundResource(R.drawable.download);
        }
        if (cowBears[0] == 5) {
            button1.setBackgroundResource(R.drawable.yellow);
            button3.setBackgroundResource(R.drawable.blue);
            button2.setBackgroundResource(R.drawable.green);
            button4.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 6) {
            button4.setBackgroundResource(R.drawable.yellow);
            button1.setBackgroundResource(R.drawable.blue);
            button3.setBackgroundResource(R.drawable.green);
            button2.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 7) {
            button2.setBackgroundResource(R.drawable.yellow);
            button4.setBackgroundResource(R.drawable.blue);
            button1.setBackgroundResource(R.drawable.green);
            button3.setBackgroundResource(R.drawable.download);
        }

        if (cowBears[0] == 8) {
            button3.setBackgroundResource(R.drawable.yellow);
            button2.setBackgroundResource(R.drawable.blue);
            button4.setBackgroundResource(R.drawable.green);
            button1.setBackgroundResource(R.drawable.download);
        }

        //Here we have the randomizing of the button text based on what integer is genetated for cowbears2
        if (cowBears2[0] <= 1) {
            myText.setText("yellow" + cowBears[0] + cowBears2[0]);
        }

        if (cowBears2[0] == 2) {
            myText.setText("Blue" + cowBears[0] + cowBears2[0]);
        }

        if (cowBears2[0] == 3) {
            myText.setText("Green" + cowBears[0] + cowBears2[0]);
        }

        if (cowBears2[0] == 4) {
            myText.setText("Red" + cowBears[0] + cowBears2[0]);
        }
    }
}

If anyone could figure out why my code behaves like this, that would be appreciated.


问:
Python sum elements between two numbers
I'm sure this is very simple. I've searched google and here and not found the specific answer

```<code>a = rnd.randn(100)
print np.sum(a)
</code>```

gives sum of elements in a

```<code>np.sum(a[a>0.])
</code>```

gives sum of elements greater than 0

```<code>print np.sum((a < 2.0) & (a > -2.0))
</code>```

ok so this returns the number of elements between 2 and -2.

how do I get the sum of the elements between2 and -2??? I've tried lots of things for example

```<code>np.sum(a[a >0.] & a[a<1.])
</code>```

etc and can't find the correct way to do it :-(

答:
You could do it in just in a very basic direct way, something like:</p>

```<code>function getSum(numArray, lowVal, highVal):
    mySum = 0
    for i in range(len(numArray)):
        if(numArray[i] >= lowVal and numArray[i] <= highVal):
             mySum = mySum + numArray[i]

    return mySum

yourAnswer = getSum(a, -2, 2)
</code>```

Title: Python sum elements between two numbers

Body:
I'm sure this is very simple. I've searched google and here and not found the specific answer

a = rnd.randn(100)
print np.sum(a)

gives sum of elements in a

np.sum(a[a>0.])

gives sum of elements greater than 0

print np.sum((a < 2.0) & (a > -2.0))

ok so this returns the number of elements between 2 and -2.

how do I get the sum of the elements between2 and -2??? I've tried lots of things for example

np.sum(a[a >0.] & a[a<1.])

etc and can't find the correct way to do it :-(

Body:
You could do it in just in a very basic direct way, something like:

function getSum(numArray, lowVal, highVal):
    mySum = 0
    for i in range(len(numArray)):
        if(numArray[i] >= lowVal and numArray[i] <= highVal):
             mySum = mySum + numArray[i]

    return mySum

yourAnswer = getSum(a, -2, 2)