问:
Swift Output Weekdays as Strings
I want to use an enum to convert integers to the String name of Weekdays. I have come up with the following

```<code>// Enum to output days
enum EnumDays : Int
{
    case MONDAY = 0
    case TUESDAY
    case WEDNESDAY
    case THURSDAY
    case FRIDAY
    case SATURDAY
    case SUNDAY
}

var weekDay = EnumDays.init(rawValue: 0)
print("Day = \(String(describing: weekDay))")
</code>```

But we output the type as in

"Day = Optional(SubscriptInSwift.EnumDays.MONDAY)"

how can I produce an output as a String i.e.:

"Day = Monday"

This question is a minimum example of a problem I have had for some time, and although this example is about weekdays I am looking for a solution of how to generally convert Integers to String.

答:
This is an alternative pattern that I use that allows for localisation. I'll use your example of a calendar. Using an explicit value for each allows you to use phrases with spaces or other punctuation, and then means you can easily use localisation if other languages are required. You pay for elegance with extra code - you can decide if this is worthwhile.</p>

```<code>enum DaysOfWeek : Int
{
  case MONDAY = 0
  case TUESDAY
  case WEDNESDAY
  case THURSDAY
  case FRIDAY
  case SATURDAY
  case SUNDAY

  var asString : String
  {
    var resource = ""
    switch self
    {
      case .MONDAY: resource =  "Monday"
      case .TUESDAY : resource =  "Tuesday"
      case .WEDNESDAY:  resource =  "Wednesday"
      ...
    }

    // Use Internationalization, as appropriate.
    return NSLocalizedString(resource, comment: resource)
  }

}
</code>```

Title: Swift Output Weekdays as Strings

Body:
I want to use an enum to convert integers to the String name of Weekdays. I have come up with the following

// Enum to output days
enum EnumDays : Int
{
    case MONDAY = 0
    case TUESDAY
    case WEDNESDAY
    case THURSDAY
    case FRIDAY
    case SATURDAY
    case SUNDAY
}

var weekDay = EnumDays.init(rawValue: 0)
print("Day = \(String(describing: weekDay))")

But we output the type as in

"Day = Optional(SubscriptInSwift.EnumDays.MONDAY)"

how can I produce an output as a String i.e.:

"Day = Monday"

This question is a minimum example of a problem I have had for some time, and although this example is about weekdays I am looking for a solution of how to generally convert Integers to String.

Body:
This is an alternative pattern that I use that allows for localisation. I'll use your example of a calendar. Using an explicit value for each allows you to use phrases with spaces or other punctuation, and then means you can easily use localisation if other languages are required. You pay for elegance with extra code - you can decide if this is worthwhile.

enum DaysOfWeek : Int
{
  case MONDAY = 0
  case TUESDAY
  case WEDNESDAY
  case THURSDAY
  case FRIDAY
  case SATURDAY
  case SUNDAY

  var asString : String
  {
    var resource = ""
    switch self
    {
      case .MONDAY: resource =  "Monday"
      case .TUESDAY : resource =  "Tuesday"
      case .WEDNESDAY:  resource =  "Wednesday"
      ...
    }

    // Use Internationalization, as appropriate.
    return NSLocalizedString(resource, comment: resource)
  }

}


来源: stackexchange

问:
How to create multipart HTTP request in Node-RED
I'm trying to send a multipart request with the following form-data:

```<code>------WebKitFormBoundaryjFqPRXY6RQpdTRvE
Content-Disposition: form-data; name="file"; filename="Sample.csv"
Content-Type: application/vnd.ms-excel

------WebKitFormBoundaryjFqPRXY6RQpdTRvE
Content-Disposition: form-data; name="data"; filename="blob"
Content-Type: application/json

{"name":"Sample5","type":"Csv","firstRowIsHeader":true,"columns":[{ ... }]}
------WebKitFormBoundaryjFqPRXY6RQpdTRvE--
</code>```

The above data is normally being created and sent by a web service.

I'm trying to replicate the exact same HTTP request from Node-RED.

JSON data is already prepared so it's just creation of the multipart request.

I've tried using node-red-contrib-http-multipart but I'm not really sure how to configure it.

```<code>[{"id":"e0fde1bd.e0aa","type":"httpInMultipart","z":"fc689d44.1c52","name":"","url":"/test/upload","method":"post","fields":"[ { \"name\": \"file\", \"maxCount\": 1}, { \"name\": \"data\", \"maxCount\": 1} ]","swaggerDoc":"","x":1390,"y":820,"wires":[["d109ed84.14d1d","8a39aaa0.6934c8","d0bc5b20.45f3a8"]]},{"id":"a2318dfd.bae7d","type":"http in","z":"fc689d44.1c52","name":"","url":"/test/send","method":"get","upload":false,"swaggerDoc":"","x":1380,"y":680,"wires":[["d7cfc418.89eb98"]]},{"id":"14c992f3.8652ad","type":"http response","z":"fc689d44.1c52","name":"","x":1750,"y":680,"wires":[]},{"id":"d109ed84.14d1d","type":"debug","z":"fc689d44.1c52","name":"","active":true,"console":"false","complete":"true","x":1570,"y":780,"wires":[]},{"id":"8a39aaa0.6934c8","type":"http response","z":"fc689d44.1c52","name":"","statusCode":"","headers":{},"x":1570,"y":860,"wires":[]},{"id":"1a646c83.8da7d3","type":"debug","z":"fc689d44.1c52","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1790,"y":780,"wires":[]},{"id":"d7cfc418.89eb98","type":"template","z":"fc689d44.1c52","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<form action=\"/test/upload\" method=\"POST\" enctype=\"multipart/form-data\">\n  <div>\n    <input type=\"file\" name=\"file\">\n    <input type=\"submit\" value=\"Submit\">\n  </div>\n</form>","output":"str","x":1580,"y":680,"wires":[["2971b104.12737e","14c992f3.8652ad"]]},{"id":"d0bc5b20.45f3a8","type":"change","z":"fc689d44.1c52","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"{\t   \"file\": req.files.file[0].buffer,\t   \"data\": \"test\"\t}","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":1620,"y":820,"wires":[["1a646c83.8da7d3"]]},{"id":"2971b104.12737e","type":"debug","z":"fc689d44.1c52","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1730,"y":640,"wires":[]}]
</code>```

Any kind of pointers on how to tackle the problem would be greatly appreciated.

答:
It appears creating a multipart/form-data request directly on the HTTP request node is not yet supported. However, it's possible to manually create the multipart payload on a function node and feed it to the out-of-the-box HTTP request node.

Basically, feed to the HTTP request node a payload like so (a snippet from flows.nodered):

```<code>msg.headers = {
    "Content-Type": "multipart/form-data; boundary=------------------------d74496d66958873e"
}

msg.payload = '--------------------------d74496d66958873e\r\n'+
'Content-Disposition: form-data; name="select"\r\n'+
'\r\n'+
'true\r\n'+
'--------------------------d74496d66958873e\r\n'+
'Content-Disposition: form-data; name="print"\r\n'+
'\r\n'+
'true\r\n'+
'--------------------------d74496d66958873e\r\n'+
'Content-Disposition: form-data; name="file"; filename="'+msg.filename+'"\r\n'+
'Content-Type: application/octet-stream\r\n'+
'\r\n'+
msg.payload+'\r\n'+
'--------------------------d74496d66958873e--\r\n';

return msg;
</code>```

The format of the multipart payload is thoroughly discussed in discourse.nodered.

A sample flow is also provided in flows.nodered.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to send a multipart request with the following form-data:

------WebKitFormBoundaryjFqPRXY6RQpdTRvE
Content-Disposition: form-data; name="file"; filename="Sample.csv"
Content-Type: application/vnd.ms-excel

------WebKitFormBoundaryjFqPRXY6RQpdTRvE
Content-Disposition: form-data; name="data"; filename="blob"
Content-Type: application/json

{"name":"Sample5","type":"Csv","firstRowIsHeader":true,"columns":[{ ... }]}
------WebKitFormBoundaryjFqPRXY6RQpdTRvE--

The above data is normally being created and sent by a web service.

I'm trying to replicate the exact same HTTP request from Node-RED.

JSON data is already prepared so it's just creation of the multipart request.

I've tried using node-red-contrib-http-multipart but I'm not really sure how to configure it.

[{"id":"e0fde1bd.e0aa","type":"httpInMultipart","z":"fc689d44.1c52","name":"","url":"/test/upload","method":"post","fields":"[ { \"name\": \"file\", \"maxCount\": 1}, { \"name\": \"data\", \"maxCount\": 1} ]","swaggerDoc":"","x":1390,"y":820,"wires":[["d109ed84.14d1d","8a39aaa0.6934c8","d0bc5b20.45f3a8"]]},{"id":"a2318dfd.bae7d","type":"http in","z":"fc689d44.1c52","name":"","url":"/test/send","method":"get","upload":false,"swaggerDoc":"","x":1380,"y":680,"wires":[["d7cfc418.89eb98"]]},{"id":"14c992f3.8652ad","type":"http response","z":"fc689d44.1c52","name":"","x":1750,"y":680,"wires":[]},{"id":"d109ed84.14d1d","type":"debug","z":"fc689d44.1c52","name":"","active":true,"console":"false","complete":"true","x":1570,"y":780,"wires":[]},{"id":"8a39aaa0.6934c8","type":"http response","z":"fc689d44.1c52","name":"","statusCode":"","headers":{},"x":1570,"y":860,"wires":[]},{"id":"1a646c83.8da7d3","type":"debug","z":"fc689d44.1c52","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1790,"y":780,"wires":[]},{"id":"d7cfc418.89eb98","type":"template","z":"fc689d44.1c52","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<form action=\"/test/upload\" method=\"POST\" enctype=\"multipart/form-data\">\n
\n    <input type=\"file\" name=\"file\">\n    <input type=\"submit\" value=\"Submit\">\n
\n</form>","output":"str","x":1580,"y":680,"wires":[["2971b104.12737e","14c992f3.8652ad"]]},{"id":"d0bc5b20.45f3a8","type":"change","z":"fc689d44.1c52","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"{\t   \"file\": req.files.file[0].buffer,\t   \"data\": \"test\"\t}","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":1620,"y":820,"wires":[["1a646c83.8da7d3"]]},{"id":"2971b104.12737e","type":"debug","z":"fc689d44.1c52","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1730,"y":640,"wires":[]}]

Any kind of pointers on how to tackle the problem would be greatly appreciated.

Body:
It appears creating a multipart/form-data request directly on the HTTP request node is not yet supported. However, it's possible to manually create the multipart payload on a function node and feed it to the out-of-the-box HTTP request node.

Basically, feed to the HTTP request node a payload like so (a snippet from flows.nodered):

msg.headers = {
    "Content-Type": "multipart/form-data; boundary=------------------------d74496d66958873e"
}

msg.payload = '--------------------------d74496d66958873e\r\n'+
'Content-Disposition: form-data; name="select"\r\n'+
'\r\n'+
'true\r\n'+
'--------------------------d74496d66958873e\r\n'+
'Content-Disposition: form-data; name="print"\r\n'+
'\r\n'+
'true\r\n'+
'--------------------------d74496d66958873e\r\n'+
'Content-Disposition: form-data; name="file"; filename="'+msg.filename+'"\r\n'+
'Content-Type: application/octet-stream\r\n'+
'\r\n'+
msg.payload+'\r\n'+
'--------------------------d74496d66958873e--\r\n';

return msg;

The format of the multipart payload is thoroughly discussed in discourse.nodered.

A sample flow is also provided in flows.nodered.


问:
how to run SmartStore.NET in visual studio 2015?
how start smartstore.net in visual studio localhost without any error

i download github code and open project file from

SmartStoreNET-3.x\src\SmartStoreNET.sln
The download link https://github.com/smartstoreag/SmartStoreNET

答:
I recently went through this integration/configuration procedure trying to get a local instance of SmartStore.NET up and running with demo data. I was able to get there eventually, but the development environment setup was by far the most tricky.

I would suggest starting with these two links:

http://docs.smartstore.com/display/SMNET30/Installing+SmartStore.NET
http://docs.smartstore.com/display/SMNET30/How+to+build+SmartStore.NET

I have a hunch you're issue may be your development environment configuration is not fully correct. Check out this page for more details about requirements:

Technology and Prerequisites
http://docs.smartstore.com/pages/viewpage.action?pageId=35555597

*NOTE: they reference ASP.NET 4.5.1 but I had to use 4.61 to take advantage of some newer features in C# 7.0 - Tuples, and several others)

Probably the most significant discovery I found was their were dependency issues when trying to restore the NuGet packages referenced in the solution. I had to go through this process maybe 4 or 5 times to finally get the app running locally.

Once all of this was complete, getting it working in 2015 required little effort.

I would also suggest narrowing your question to more specific problems. (that's just me)

ContentLicense: CC BY-SA 3.0


问:
Why does this Pandas series where function not return any values?
I am using the Pandas library within Python and having some trouble getting expected results from filtering a specific series within a Dataframe:

```<code>csdf[0].unique()
</code>```

returns:

```<code>array(['GWA_BTC', 'GWA_ETH', 'GWA_LTC', 'GWA_XLM', 'GWA_XRP',
       'MWA_BTC_CNY', 'MWA_BTC_EUR', 'MWA_BTC_GBP', 'MWA_BTC_JPY',
       'MWA_BTC_USD', 'MWA_ETH_CNY', 'MWA_ETH_EUR', 'MWA_ETH_GBP',
       'MWA_ETH_JPY', 'MWA_ETH_USD', 'MWA_LTC_CNY', 'MWA_LTC_EUR',
       'MWA_LTC_GBP', 'MWA_LTC_JPY', 'MWA_LTC_USD', 'MWA_XLM_CNY',
       'MWA_XLM_EUR', 'MWA_XLM_USD', 'MWA_XRP_CNY', 'MWA_XRP_EUR',
       'MWA_XRP_GBP', 'MWA_XRP_JPY', 'MWA_XRP_USD'], dtype=object)
</code>```

But when I do this:

```<code>csdf[0].where(lambda x: x[0:3] == 'GWA').dropna()
</code>```

I get:

```<code>Series([], Name: 0, dtype: object)
</code>```

I am trying to get all values in the series that begin with "GWA."

答:
You should do:</p>

```<code>csdf[0].where(csdf[0].str[0:3] == 'GWA').dropna()
</code>```

Body:
I am using the Pandas library within Python and having some trouble getting expected results from filtering a specific series within a Dataframe:

csdf[0].unique()

returns:

array(['GWA_BTC', 'GWA_ETH', 'GWA_LTC', 'GWA_XLM', 'GWA_XRP',
       'MWA_BTC_CNY', 'MWA_BTC_EUR', 'MWA_BTC_GBP', 'MWA_BTC_JPY',
       'MWA_BTC_USD', 'MWA_ETH_CNY', 'MWA_ETH_EUR', 'MWA_ETH_GBP',
       'MWA_ETH_JPY', 'MWA_ETH_USD', 'MWA_LTC_CNY', 'MWA_LTC_EUR',
       'MWA_LTC_GBP', 'MWA_LTC_JPY', 'MWA_LTC_USD', 'MWA_XLM_CNY',
       'MWA_XLM_EUR', 'MWA_XLM_USD', 'MWA_XRP_CNY', 'MWA_XRP_EUR',
       'MWA_XRP_GBP', 'MWA_XRP_JPY', 'MWA_XRP_USD'], dtype=object)

But when I do this:

csdf[0].where(lambda x: x[0:3] == 'GWA').dropna()

I get:

Series([], Name: 0, dtype: object)

I am trying to get all values in the series that begin with "GWA."

Body:
You should do:

csdf[0].where(csdf[0].str[0:3] == 'GWA').dropna()


问:
error: AWS session token not found when using rs_create_table
I was running the following code:

```<code>install.packages("aws.ec2metadata", repos = c(cloudyr = "http://cloudyr.github.io/drat", getOption("repos")))

install.packages(c('devtools', 'httr', 'aws.s3', 'Rcpp', 'DBI'))

library(RPostgreSQL)
library(redshiftTools)
library(RPostgres)

devtools::install_github("sicarul/redshiftTools")

drv <- dbDriver("PostgreSQL")

pconn_rsql <- dbConnect(drv,
                         host = "host",
                         port = port,
                         user = "user",
                         password = "password",
                         dbname = "dbname")

rs_create_table(df = mtcars,
            dbcon = conn,
            table_name = "table_name",
            bucket = "my-bucket",
            region = "region",
            access_key = "acess-key",
            secret_key = "secret-key",
            split_files = 4)

dbDisconnect(pconn_rsql)
</code>```

It was running as a script perfectly until this morning when I updated the R packages. I checked the GitHub for any cues about it, but none worked.
Has anyone already faced it and can shed a light on it?

答:
Faced a similar issue, one way you could do is revert back to version 0.3.900 (this was the one that was working for me).

Alternatively you could fix the underlying source code. Download the github version and make some changes before you install.

1. script internal.R function s3ToRedshift add else if condition for session

```<code>  if (nchar(iam_role_arn) > 0) {
    credsStr = sprintf("iam_role '%s'", iam_role_arn)
  } else if (nchar(session) > 0){
    credsStr = sprintf("credentials 'aws_access_key_id=%s;aws_secret_access_key=%s;token=%s'", access_key, secret_key, session)
  } else {
    # creds string now includes a token in case it is needed.
    credsStr = sprintf("credentials 'aws_access_key_id=%s;aws_secret_access_key=%s'", access_key, secret_key)
  }
</code>```

2. script replace.R function rs_replace_table add Sys.setenv

After split_files = pmin(split_files, numRows), add following lines.

```<code>  # Set env variables for S3 upload
  Sys.setenv(
    'AWS_DEFAULT_REGION'=region,
    'AWS_ACCESS_KEY_ID'=access_key,
    'AWS_SECRET_ACCESS_KEY'=secret_key,
    'AWS_IAM_ROLE_ARN'=iam_role_arn
  )
</code>```

So it will look something like:

```<code>split_files = pmin(split_files, numRows)

  # Set env variables for S3 upload
  Sys.setenv(
    'AWS_DEFAULT_REGION'=region,
    'AWS_ACCESS_KEY_ID'=access_key,
    'AWS_SECRET_ACCESS_KEY'=secret_key,
    'AWS_IAM_ROLE_ARN'=iam_role_arn
  )
  prefix = uploadToS3(df, bucket, split_files)
</code>```

Install this and rs_create_table should now work, haven't tested the other functions though.

Body:
I was running the following code:

install.packages("aws.ec2metadata", repos = c(cloudyr = "http://cloudyr.github.io/drat", getOption("repos")))

install.packages(c('devtools', 'httr', 'aws.s3', 'Rcpp', 'DBI'))

library(RPostgreSQL)
library(redshiftTools)
library(RPostgres)

devtools::install_github("sicarul/redshiftTools")

drv <- dbDriver("PostgreSQL")

pconn_rsql <- dbConnect(drv,
                         host = "host",
                         port = port,
                         user = "user",
                         password = "password",
                         dbname = "dbname")

rs_create_table(df = mtcars,
            dbcon = conn,
            table_name = "table_name",
            bucket = "my-bucket",
            region = "region",
            access_key = "acess-key",
            secret_key = "secret-key",
            split_files = 4)

dbDisconnect(pconn_rsql)

It was running as a script perfectly until this morning when I updated the R packages. I checked the GitHub for any cues about it, but none worked.
Has anyone already faced it and can shed a light on it?

Body:
Faced a similar issue, one way you could do is revert back to version 0.3.900 (this was the one that was working for me).

Alternatively you could fix the underlying source code. Download the github version and make some changes before you install.

1. script internal.R function s3ToRedshift add else if condition for session

  if (nchar(iam_role_arn) > 0) {
    credsStr = sprintf("iam_role '%s'", iam_role_arn)
  } else if (nchar(session) > 0){
    credsStr = sprintf("credentials 'aws_access_key_id=%s;aws_secret_access_key=%s;token=%s'", access_key, secret_key, session)
  } else {
    # creds string now includes a token in case it is needed.
    credsStr = sprintf("credentials 'aws_access_key_id=%s;aws_secret_access_key=%s'", access_key, secret_key)
  }

2. script replace.R function rs_replace_table add Sys.setenv

After split_files = pmin(split_files, numRows), add following lines.

  # Set env variables for S3 upload
  Sys.setenv(
    'AWS_DEFAULT_REGION'=region,
    'AWS_ACCESS_KEY_ID'=access_key,
    'AWS_SECRET_ACCESS_KEY'=secret_key,
    'AWS_IAM_ROLE_ARN'=iam_role_arn
  )

So it will look something like:

split_files = pmin(split_files, numRows)

  # Set env variables for S3 upload
  Sys.setenv(
    'AWS_DEFAULT_REGION'=region,
    'AWS_ACCESS_KEY_ID'=access_key,
    'AWS_SECRET_ACCESS_KEY'=secret_key,
    'AWS_IAM_ROLE_ARN'=iam_role_arn
  )
  prefix = uploadToS3(df, bucket, split_files)

Install this and rs_create_table should now work, haven't tested the other functions though.


问:
Bottom Overflowed using SingleChildScrollView
```<code>@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Color(0xff003859),
  appBar: AppBar(
    title: Text(
      "Conversor de moedas 360",
      style: TextStyle(
        color: Color(0xff003859)
      )
    ),
    backgroundColor: Color(0xffffa300),
  ),
  body: FutureBuilder<Map>(
    future: getData(),
    builder: (context, snapshot) {
      switch(snapshot.connectionState){
        case ConnectionState.none:
        case ConnectionState.waiting:
        return Center(
          child: Text(
            "Carregando Dados...",
            style: TextStyle(
              color: Color(0xffffa300),
              fontSize: 25.0
            ),
            textAlign: TextAlign.center,
          )
        );
        default:
        if (snapshot.hasError){
          return Center(
              child: Text(
                "Erro ao carregar dados...",
                style: TextStyle(
                    color: Color(0xffffa300),
                    fontSize: 25.0
                ),
                textAlign: TextAlign.center,
              )
          );
        } else {
          dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
          euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
          return Column(
            children: <Widget>[
              Image.asset(
              "images/360Tecnologia.jpg",
                fit: BoxFit.fitWidth,
              ),
              SingleChildScrollView(
                padding: EdgeInsets.all(10.0),
                child: Column(
                  children: <Widget>[
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Reais",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "R\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Dólares",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "U\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Euros",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "€ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Libra",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "£\$ "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Bitcoin",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "BTC "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                        decoration: InputDecoration(
                            labelText: "Bitcoin",
                            labelStyle: TextStyle(
                              color: Color(0xffffa300),
                            ),
                            border: OutlineInputBorder(),
                            prefixText: "BTC "
                        ),
                        style: TextStyle(
                            color: Color(0xffffa300),
                            fontSize: 25.0
                        )
                    ),
                  ],
                )
              )
            ],
          );
        }
      }
    }
  )
);
}
}
</code>```

I want to show an image on top below the top bar. The image is fixed.

Below the top bar I have any text field inside the SingleChildScrollView widget, but this not work when I try to scroll the elements.

The text field can't rolling when I roll the screen to up or to down.

The stackoverflow want I type more text because I put many code, but my doubt is explained on text up...

Any help?

答:
```<code>Column(
   children: <Widget>[
</code>```

replace that with:

```<code>Stack(
    children: <Widget>[
</code>```

You are seeing that error because your SingleChildScrollView is inside a Column.

Another solution is to wrap your Parent Column with SingleChildScrollView instead of second one. But that will scroll your image too.

Or, if your image is a fixed one, you can add that to AppBar bottom:

```<code>  AppBar(
    //...
    bottom: PreferredSize(
      preferredSize: Size.fromHeight(129.0),
      child: Image.asset(
        "images/360Tecnologia.jpg",
        fit: BoxFit.fitWidth,
      ),
    ),
  ),
</code>```

Of course in this case if your snapshot.hasError or when connection is waiting, you will see this image(You can have a condition like isDataAvailable and make it true when connection state done and check it in bottom).

Another way is wrap parent Column with another SingleChildScrollView but that will make two scroll views. So to avoid image (Outher scroll view) to not to scroll add scrollPysics: NeverScrollPhysics()(But I dont recommend unnecessary wrap with extra widget).

Body:
@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Color(0xff003859),
  appBar: AppBar(
    title: Text(
      "Conversor de moedas 360",
      style: TextStyle(
        color: Color(0xff003859)
      )
    ),
    backgroundColor: Color(0xffffa300),
  ),
  body: FutureBuilder<Map>(
    future: getData(),
    builder: (context, snapshot) {
      switch(snapshot.connectionState){
        case ConnectionState.none:
        case ConnectionState.waiting:
        return Center(
          child: Text(
            "Carregando Dados...",
            style: TextStyle(
              color: Color(0xffffa300),
              fontSize: 25.0
            ),
            textAlign: TextAlign.center,
          )
        );
        default:
        if (snapshot.hasError){
          return Center(
              child: Text(
                "Erro ao carregar dados...",
                style: TextStyle(
                    color: Color(0xffffa300),
                    fontSize: 25.0
                ),
                textAlign: TextAlign.center,
              )
          );
        } else {
          dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
          euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
          return Column(
            children: <Widget>[
              Image.asset(
              "images/360Tecnologia.jpg",
                fit: BoxFit.fitWidth,
              ),
              SingleChildScrollView(
                padding: EdgeInsets.all(10.0),
                child: Column(
                  children: <Widget>[
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Reais",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "R\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Dólares",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "U\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Euros",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "€ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Libra",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "£\$ "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Bitcoin",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "BTC "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                        decoration: InputDecoration(
                            labelText: "Bitcoin",
                            labelStyle: TextStyle(
                              color: Color(0xffffa300),
                            ),
                            border: OutlineInputBorder(),
                            prefixText: "BTC "
                        ),
                        style: TextStyle(
                            color: Color(0xffffa300),
                            fontSize: 25.0
                        )
                    ),
                  ],
                )
              )
            ],
          );
        }
      }
    }
  )
);
}
}

I want to show an image on top below the top bar. The image is fixed.

Below the top bar I have any text field inside the SingleChildScrollView widget, but this not work when I try to scroll the elements.

The text field can't rolling when I roll the screen to up or to down.

The stackoverflow want I type more text because I put many code, but my doubt is explained on text up...

Any help?

Body:
Column(
   children: <Widget>[

replace that with:

Stack(
    children: <Widget>[

You are seeing that error because your SingleChildScrollView is inside a Column.

Another solution is to wrap your Parent Column with SingleChildScrollView instead of second one. But that will scroll your image too.

Or, if your image is a fixed one, you can add that to AppBar bottom:

  AppBar(
    //...
    bottom: PreferredSize(
      preferredSize: Size.fromHeight(129.0),
      child: Image.asset(
        "images/360Tecnologia.jpg",
        fit: BoxFit.fitWidth,
      ),
    ),
  ),

Of course in this case if your snapshot.hasError or when connection is waiting, you will see this image(You can have a condition like isDataAvailable and make it true when connection state done and check it in bottom).

Another way is wrap parent Column with another SingleChildScrollView but that will make two scroll views. So to avoid image (Outher scroll view) to not to scroll add scrollPysics: NeverScrollPhysics()(But I dont recommend unnecessary wrap with extra widget).


问:
The peculiar case of disappearing data
I am trying following code:

```<code>import std.stdio;
import std.range;

void main(){
    auto data = [[1,2,3], [4,5,6]];     // putting auto instead of int[][] here makes no difference;
    auto coldata =  data.transposed;
    writeln("coldata: ", coldata);          // prints ok;
    writeln("transposed data: ", coldata);  // Empty list is printed. Data disappears/evaporates!
}
</code>```

The output is:

```<code>$ rdmd evapor.d
coldata: [[1, 4], [2, 5], [3, 6]]
transposed data: []
</code>```

In the second call, an empty list is printed. The data seems to just disappear/evaporate!

Why the data is not priting on second call?

Edit: Empty list is printed even if I call transpose each time:

```<code>writeln("coldata: ", data.transposed);          // prints ok;
writeln("transposed data: ", data.transposed);  // data disappears / evaporates!
</code>```

Also, using coldata.dup does not work. I produces following error:

```<code>soq_evapor.d(10): Error: template object.dup cannot deduce function from argument types !()(Transposed!(int[][], cast(TransverseOptions)0)), candidates are:
/usr/include/dmd/druntime/import/object.d(3169):        object.dup(T : V[K], K, V)(T aa)
/usr/include/dmd/druntime/import/object.d(3206):        object.dup(T : V[K], K, V)(T* aa)
/usr/include/dmd/druntime/import/object.d(4482):        object.dup(T)(T[] a) if (!is(const(T) : T))
/usr/include/dmd/druntime/import/object.d(4508):        object.dup(T)(const(T)[] a) if (is(const(T) : T))
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_evapor.d", "-I."]
</code>```

答:
The range is being "consumed". If you need to reuse it like you have, you will need to make sure to call save before you use it.

https://forum.dlang.org/post/migwtldccpwryusyolkq@forum.dlang.org
https://forum.dlang.org/post/n2m1jl$2dqf$1@digitalmars.com

You can find more info about this here: https://forum.dlang.org/thread/plsuntcmsezxpjbxkfnz@forum.dlang.org

```<code>import std.stdio;
import std.range;

void main(){
    auto data = [[1,2,3], [4,5,6]];     // putting auto instead of int[][] here makes no difference;

    auto coldata =  data.dup();
    auto otherData =  data.dup();

    writeln("coldata: ", coldata.transposed);          // prints ok;
    writeln("transposed data: ", otherData.transposed);  // this also prints ok.

}
</code>```

is one such way of doing this.

The main reason for doing this is how the API is designed in D. Not all ranges are destructively iterated, it just depends on the kind. In general, though you can.

The D Lang site has this to say:

Most of the ranges in the standard library are structs and so foreach iteration is usually non-destructive, though not guaranteed. If this guarantee is important, an specialization of an InputRange can be used— forward ranges with a .save method:

https://tour.dlang.org/tour/en/basics/ranges

Title: The peculiar case of disappearing data

Body:
I am trying following code:

import std.stdio;
import std.range;

void main(){
    auto data = [[1,2,3], [4,5,6]];     // putting auto instead of int[][] here makes no difference;
    auto coldata =  data.transposed;
    writeln("coldata: ", coldata);          // prints ok;
    writeln("transposed data: ", coldata);  // Empty list is printed. Data disappears/evaporates!
}

The output is:

$ rdmd evapor.d
coldata: [[1, 4], [2, 5], [3, 6]]
transposed data: []

In the second call, an empty list is printed. The data seems to just disappear/evaporate!

Why the data is not priting on second call?

Edit: Empty list is printed even if I call transpose each time:

writeln("coldata: ", data.transposed);          // prints ok;
writeln("transposed data: ", data.transposed);  // data disappears / evaporates!

Also, using coldata.dup does not work. I produces following error:

soq_evapor.d(10): Error: template object.dup cannot deduce function from argument types !()(Transposed!(int[][], cast(TransverseOptions)0)), candidates are:
/usr/include/dmd/druntime/import/object.d(3169):        object.dup(T : V[K], K, V)(T aa)
/usr/include/dmd/druntime/import/object.d(3206):        object.dup(T : V[K], K, V)(T* aa)
/usr/include/dmd/druntime/import/object.d(4482):        object.dup(T)(T[] a) if (!is(const(T) : T))
/usr/include/dmd/druntime/import/object.d(4508):        object.dup(T)(const(T)[] a) if (is(const(T) : T))
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_evapor.d", "-I."]

Body:
The range is being "consumed". If you need to reuse it like you have, you will need to make sure to call save before you use it.

https://forum.dlang.org/post/migwtldccpwryusyolkq@forum.dlang.org
https://forum.dlang.org/post/n2m1jl$2dqf$1@digitalmars.com

You can find more info about this here: https://forum.dlang.org/thread/plsuntcmsezxpjbxkfnz@forum.dlang.org

import std.stdio;
import std.range;

void main(){
    auto data = [[1,2,3], [4,5,6]];     // putting auto instead of int[][] here makes no difference;

    auto coldata =  data.dup();
    auto otherData =  data.dup();

    writeln("coldata: ", coldata.transposed);          // prints ok;
    writeln("transposed data: ", otherData.transposed);  // this also prints ok.

}

is one such way of doing this.

The main reason for doing this is how the API is designed in D. Not all ranges are destructively iterated, it just depends on the kind. In general, though you can.

The D Lang site has this to say:

Most of the ranges in the standard library are structs and so foreach iteration is usually non-destructive, though not guaranteed. If this guarantee is important, an specialization of an InputRange can be used— forward ranges with a .save method:

https://tour.dlang.org/tour/en/basics/ranges


答:
You can use CustomStringConvertible

```<code>enum EnumDays: Int, CustomStringConvertible
{
    var description: String {
        switch self {
        case .MONDAY:
            return "Monday"
        case .TUESDAY:
            return "Tuesday"
        case .WEDNESDAY:
            return "Wednesday"
        case .THURSDAY:
            return "Thursday"
        case .FRIDAY:
            return "Friday"
        case .SATURDAY:
            return "Saturday"
        case .SUNDAY:
            return "Sunday"
        }
    }
    case MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}
</code>```

And use if let to unwrap the enum object

```<code>if let weekDay = EnumDays.init(rawValue: 0) {
    print("Day = \(weekDay)")
}
</code>```

You can get the week days from the Calendar.current.weekdaySymbols

```<code>print(Calendar.current.weekdaySymbols)//["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print(Calendar.current.shortWeekdaySymbols)//["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
</code>```

Title: Swift Output Weekdays as Strings

Body:
You can use CustomStringConvertible

enum EnumDays: Int, CustomStringConvertible
{
    var description: String {
        switch self {
        case .MONDAY:
            return "Monday"
        case .TUESDAY:
            return "Tuesday"
        case .WEDNESDAY:
            return "Wednesday"
        case .THURSDAY:
            return "Thursday"
        case .FRIDAY:
            return "Friday"
        case .SATURDAY:
            return "Saturday"
        case .SUNDAY:
            return "Sunday"
        }
    }
    case MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}

And use if let to unwrap the enum object

if let weekDay = EnumDays.init(rawValue: 0) {
    print("Day = \(weekDay)")
}

You can get the week days from the Calendar.current.weekdaySymbols

print(Calendar.current.weekdaySymbols)//["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
print(Calendar.current.shortWeekdaySymbols)//["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]


问:
How do I perform either a push UIViewController or a present of UIAlertController?
After some API calls, I have a check to either navigate to another screen or show an alert on the same screen. Currently, I am doing this by creating an observable that returns a UIViewController type but pushing a UIAlertController causes problem.

Any suggestions/ideas on how this should be done?

ViewModel.swift

```<code>let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                              resultSelector:
        { appVersion, _, _ -> UIViewController in
            if appVersion.currentAppVersion == "1.0.0" {
                let appServiceAvailability = Availability.shared.getAppStatus()
                if appServiceAvailability {
                    return LoginLandingViewController()
                } else {
                    return ServiceMaintenanceViewController()
                }
            } else {
                return UIAlertController()
            }
        })
</code>```

ViewController.swift

```<code>viewModel.output.nextAction
        .subscribe(onNext: { [weak self] screen in
            self?.navigationController?.pushViewController(screen, animated: true)
        }) // PROBLEM FACED: Pushing a UIAlertController
        .disposed(by: disposeBag)
</code>```

答:
There’re a few options.

The first option is the adoption of your current implementation.
You could pass an information in addition to ViewController in onNext event of nextAction observable, that will tell how to show the VC.

For instance, you can create an associated enum

```<code>// you can call it NextAction, Action etc
enum PresentationType {
    case
    push(UIViewController),
    present(UIViewController)
}
</code>```

and reuse it like this:

```<code>let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                          resultSelector:
    { appVersion, _, _ -> PresentationType in
        if appVersion.currentAppVersion == "1.0.0" {
            let appServiceAvailability = Availability.shared.getAppStatus()
            if appServiceAvailability {
                return .push(LoginLandingViewController())
            } else {
                return .push(ServiceMaintenanceViewController()) // use .present if should present modally
            }
        } else {
            return .present(UIAlertController())
        }
})

// somewhere in viewController

viewModel.output.nextAction
        .subscribe(onNext: { [weak self] action in
        switch action {
            case .push(let vc):
                self?.navigationController?.pushViewController(vc, animated: true)
            case .present(let vc):
                self?.present(vc, animated: true, completion: nil)

        })
        .disposed(by: disposeBag)
</code>```

The second (and more flexible and testable in some sense) option would be to create a separate Router class which is responsible for creating and showing next screens (with functions showLogin, showAlert etc). The router can be directly injected in ViewModel and you can call the Router to show next screens in, for example, do(onNext) events in your observables.

Body:
After some API calls, I have a check to either navigate to another screen or show an alert on the same screen. Currently, I am doing this by creating an observable that returns a UIViewController type but pushing a UIAlertController causes problem.

Any suggestions/ideas on how this should be done?

ViewModel.swift

let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                              resultSelector:
        { appVersion, _, _ -> UIViewController in
            if appVersion.currentAppVersion == "1.0.0" {
                let appServiceAvailability = Availability.shared.getAppStatus()
                if appServiceAvailability {
                    return LoginLandingViewController()
                } else {
                    return ServiceMaintenanceViewController()
                }
            } else {
                return UIAlertController()
            }
        })

ViewController.swift

viewModel.output.nextAction
        .subscribe(onNext: { [weak self] screen in
            self?.navigationController?.pushViewController(screen, animated: true)
        }) // PROBLEM FACED: Pushing a UIAlertController
        .disposed(by: disposeBag)

Body:
There’re a few options.

The first option is the adoption of your current implementation.
You could pass an information in addition to ViewController in onNext event of nextAction observable, that will tell how to show the VC.

For instance, you can create an associated enum

// you can call it NextAction, Action etc
enum PresentationType {
    case
    push(UIViewController),
    present(UIViewController)
}

and reuse it like this:

let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                          resultSelector:
    { appVersion, _, _ -> PresentationType in
        if appVersion.currentAppVersion == "1.0.0" {
            let appServiceAvailability = Availability.shared.getAppStatus()
            if appServiceAvailability {
                return .push(LoginLandingViewController())
            } else {
                return .push(ServiceMaintenanceViewController()) // use .present if should present modally
            }
        } else {
            return .present(UIAlertController())
        }
})

// somewhere in viewController

viewModel.output.nextAction
        .subscribe(onNext: { [weak self] action in
        switch action {
            case .push(let vc):
                self?.navigationController?.pushViewController(vc, animated: true)
            case .present(let vc):
                self?.present(vc, animated: true, completion: nil)

        })
        .disposed(by: disposeBag)

The second (and more flexible and testable in some sense) option would be to create a separate Router class which is responsible for creating and showing next screens (with functions showLogin, showAlert etc). The router can be directly injected in ViewModel and you can call the Router to show next screens in, for example, do(onNext) events in your observables.


答:
You can try to use the startswith funtion on the series.</p>

```<code>filtered = csdf[csdf[0].str.strartswith("GWA", na=False)]

</code>```

Title: Why does this Pandas series where function not return any values?

Body:
You can try to use the startswith funtion on the series.

filtered = csdf[csdf[0].str.strartswith("GWA", na=False)]


问:
How to get a data from an URL
An API like http://www.yourWebService.com/PIP.jsp?request=aaa&param=2

Lets consider the above API gives an JSON value. I use the below coding to get that JSON:

```<code>NSURL *url =[NSURL URLWithString:@"http://www.yourWebService.com/PIP.jsp?request=aaa&param=2"];

NSString *resultedString=[[NSString alloc] initWithContentsOfURL:url];
</code>```

It returns the JSON to the resultedString variable. It is somewhat small amount of Data.
If that API has large amount of data like in 100's of KB's then whether this coding will work fine, or It will crash?

答:
Better you should go with ASIHTTPRequest class which wrapper around NSUrlRequest , following links will be useful

http://allseeing-i.com/ASIHTTPRequest/How-to-use

http://allseeing-i.com/ASIHTTPRequest-CFNetwork-wrapper-for-HTTP-requests

Title: How to get a data from an URL

Body:
An API like http://www.yourWebService.com/PIP.jsp?request=aaa&param=2

Lets consider the above API gives an JSON value. I use the below coding to get that JSON:

NSURL *url =[NSURL URLWithString:@"http://www.yourWebService.com/PIP.jsp?request=aaa&param=2"];

NSString *resultedString=[[NSString alloc] initWithContentsOfURL:url];

It returns the JSON to the resultedString variable. It is somewhat small amount of Data.
If that API has large amount of data like in 100's of KB's then whether this coding will work fine, or It will crash?


问:
Asp.Net Core SPA vs separated solution (Asp.Net Core WebApi + Web app)
What is the major difference between Asp.Net Core SPA and separate them into Asp.Net Core WebAPI + independent web app. Here is my 2cent that separated solution looks no diff with using SPA template but the former makes backend code and folder structure more clear. Does it have any advantage to use Asp.Net Core SPA template?</p>

答:
WebAPI + independent web app benefits

Hosting : You can host your web app on low cost hosting solutions e.g. AWS S3/Azure blob storage.

Cloud native : Depending on your solution you can use cloud native technologies very easily . e.g. if you are using Serverless APIs , this kind of architecture works best in that case.

Flexibility : Your solution is hosting agnostic. Which means you publish apps on-prem or anywhere , as long as API contract is the same it will work.

Separate UI Team : UI team can focus solely on web app with out knowing anything about backend.

ASP.NET CORE SPA benefits

Better integration : Like someone mentioned you don't have worry about CORS.

Out of box Authentication/Authorization : If you are using ASP.NET CORE you can use out of box authentication solution. In the case above you have to write and implement your own authentication/Authorization logic.  Also If you are deploying your solution to Azure. You can use Identity-tokens instead of Access-token to access your APIs which is handy.


问:
How to modify this piece of code to create a KeyListener that listens to keyboard input even when it's not typed into a text field?
I want to write a program that will read the user's keyboard inputs regardless of what the user is clicking on. I've only gotten it working by having the user input text into a text field, even though my KeyListener is testing for the KeyPressed event and not the KeyTyped one.

This is for a simulation of Conway's Game of Life. The intent is to read the user's key inputs to see if they input a specific key, which will pause the simulation. I tried not including the TextField and adding the KeyListener to the JFrame directly but it wouldn't read my inputs. I tried setting the TextField's visibility to false, which also wouldn't read my inputs.

Here's what I have right now:

```<code>import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Listener
{
    private JFrame j;
    private KeyInput k;

    public Listener()
    {
        j = new JFrame();
        Container c = j.getContentPane();
        k = new KeyInput();
        JTextField t = new JTextField();
        t.addKeyListener(k);
        c.add(t);
        j.setFocusable(true);
        j.pack();
        j.setVisible(true);
        t.setVisible(true);
    }

    public char getKeyPressed()
    {
        return k.getKeyPressed();
    }

    public class KeyInput extends KeyAdapter
    {
        private char ch = 0;

        public void keyPressed(KeyEvent ev)
        {
            ch = ev.getKeyChar();
        }

        public char getKeyPressed()
        {
            return ch;
        }
    }
}
</code>```

I'd like to modify this code somehow so that the program can read user input without the need for a text field.

答:
If i didn't get you wrong, this would be helpful :)  </p>

```<code>import javax.swing.* ;
import java.awt.event.* ;
public class Test {

    public Test () {
        JFrame jFrame = new JFrame();
        // this line is optionnel, i just wrote it to see the JFrame when testing
        jFrame.setSize(300, 180);
        jFrame.setVisible(true);
        KeyInput keyInput = new KeyInput() ;
        jFrame.addKeyListener (new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                // stores the pressed key value in the currentCaracter field of keyInput
                keyInput.setCurrentCaracter (e.getKeyChar()) ;
                // prints out the value stored, for testing
                System.out.println(keyInput.getCurrentCaracter());
            }
        }) ;

    }

    public static void main (String args[]) {
        new Test();
    }

}

class KeyInput{
    public KeyInput() {
    }
    public void setCurrentCaracter (char currentCaracter)
    {
        this.currentCaracter = currentCaracter ;
    }

    public char getCurrentCaracter() {
        return currentCaracter;
    }

    private char currentCaracter ;
}
</code>```

Body:
I want to write a program that will read the user's keyboard inputs regardless of what the user is clicking on. I've only gotten it working by having the user input text into a text field, even though my KeyListener is testing for the KeyPressed event and not the KeyTyped one.

This is for a simulation of Conway's Game of Life. The intent is to read the user's key inputs to see if they input a specific key, which will pause the simulation. I tried not including the TextField and adding the KeyListener to the JFrame directly but it wouldn't read my inputs. I tried setting the TextField's visibility to false, which also wouldn't read my inputs.

Here's what I have right now:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Listener
{
    private JFrame j;
    private KeyInput k;

    public Listener()
    {
        j = new JFrame();
        Container c = j.getContentPane();
        k = new KeyInput();
        JTextField t = new JTextField();
        t.addKeyListener(k);
        c.add(t);
        j.setFocusable(true);
        j.pack();
        j.setVisible(true);
        t.setVisible(true);
    }

    public char getKeyPressed()
    {
        return k.getKeyPressed();
    }

    public class KeyInput extends KeyAdapter
    {
        private char ch = 0;

        public void keyPressed(KeyEvent ev)
        {
            ch = ev.getKeyChar();
        }

        public char getKeyPressed()
        {
            return ch;
        }
    }
}

I'd like to modify this code somehow so that the program can read user input without the need for a text field.

Body:
If i didn't get you wrong, this would be helpful :)

import javax.swing.* ;
import java.awt.event.* ;
public class Test {

    public Test () {
        JFrame jFrame = new JFrame();
        // this line is optionnel, i just wrote it to see the JFrame when testing
        jFrame.setSize(300, 180);
        jFrame.setVisible(true);
        KeyInput keyInput = new KeyInput() ;
        jFrame.addKeyListener (new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                // stores the pressed key value in the currentCaracter field of keyInput
                keyInput.setCurrentCaracter (e.getKeyChar()) ;
                // prints out the value stored, for testing
                System.out.println(keyInput.getCurrentCaracter());
            }
        }) ;

    }

    public static void main (String args[]) {
        new Test();
    }

}

class KeyInput{
    public KeyInput() {
    }
    public void setCurrentCaracter (char currentCaracter)
    {
        this.currentCaracter = currentCaracter ;
    }

    public char getCurrentCaracter() {
        return currentCaracter;
    }

    private char currentCaracter ;
}


问:
Create thumbnail and reduce image size
I have very large images (jpg) and i want to write a csharp program to loop through the files and reduce the size of each image by 75%.

I tried this:

```<code>Image thumbNail = image.GetThumbnailImage(800, 600, null, new IntPtr());
</code>```

but the file size is still very large.

Is there anyway to create thumbnails and have the filesize be much smaller?

答:
This method helped me very well. Low image size, maintains aspect ratio

```<code> ShellFile shellFile = ShellFile.FromFilePath(ImageWithPath); //original image path
 Bitmap shellThumbSmall = shellFile.Thumbnail.ExtraLargeBitmap; //change image size
 shellThumbSmall.Save(ImageWithPathThumbnail, ImageFormat.Jpeg); // new image path and format
</code>```

These are needed

```<code>PM> Install-Package WindowsAPICodePack-Core
PM> Install-Package WindowsAPICodePack-Shell

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack;
</code>```

OwnerDisplayName: mek

ContentLicense: CC BY-SA 2.5

Title: Create thumbnail and reduce image size

Body:
I have very large images (jpg) and i want to write a csharp program to loop through the files and reduce the size of each image by 75%.

I tried this:

Image thumbNail = image.GetThumbnailImage(800, 600, null, new IntPtr());

but the file size is still very large.

Is there anyway to create thumbnails and have the filesize be much smaller?

LastEditorDisplayName: mek

Body:
This method helped me very well. Low image size, maintains aspect ratio

 ShellFile shellFile = ShellFile.FromFilePath(ImageWithPath); //original image path
 Bitmap shellThumbSmall = shellFile.Thumbnail.ExtraLargeBitmap; //change image size
 shellThumbSmall.Save(ImageWithPathThumbnail, ImageFormat.Jpeg); // new image path and format

These are needed

PM> Install-Package WindowsAPICodePack-Core
PM> Install-Package WindowsAPICodePack-Shell

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack;


问:
Why do we need virtual functions in C++?
I'm learning C++ and I'm just getting into virtual functions.

From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes.

But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual.

So what am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly. I just can't find a straightforward answer online.

答:
The bottom line is that virtual functions make life easier. Let's use some of M Perry's ideas and describe what would happen if we didn't have virtual functions and instead only could use member-function pointers. We have, in the normal estimation without virtual functions:

```<code> class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
  };

 class derived: public base {
 public:
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main () {
      base hwOne;
      derived hwTwo = new derived();
      base->helloWorld(); //prints "Hello World!"
      derived->helloWorld(); //prints "Hello World!"
</code>```

Ok, so that is what we know. Now let's try to do it with member-function pointers:

```<code> #include <iostream>
 using namespace std;

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
 };

 class derived : public base {
 public:
 void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
 void(derived::*hwBase)();
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main()
 {
 base* b = new base(); //Create base object
 b->helloWorld(); // Hello World!
 void(derived::*hwBase)() = &derived::helloWorld; //create derived member
 function pointer to base function
 derived* d = new derived(); //Create derived object.
 d->displayHWDerived(hwBase); //Greetings World!

 char ch;
 cin >> ch;
 }
</code>```

While we can do some things with member-function pointers, they aren't as flexible as virtual functions. It is tricky to use a member-function pointer in a class; the member-function pointer almost, at least in my practice, always must be called in the main function or from within a member function as in the above example.

On the other hand, virtual functions, while they might have some function-pointer overhead, do simplify things dramatically.

EDIT: There is another method which is similar by eddietree: c++ virtual function vs member function pointer (performance comparison) .

Body:
The bottom line is that virtual functions make life easier. Let's use some of M Perry's ideas and describe what would happen if we didn't have virtual functions and instead only could use member-function pointers. We have, in the normal estimation without virtual functions:

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
  };

 class derived: public base {
 public:
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main () {
      base hwOne;
      derived hwTwo = new derived();
      base->helloWorld(); //prints "Hello World!"
      derived->helloWorld(); //prints "Hello World!"

Ok, so that is what we know. Now let's try to do it with member-function pointers:

 #include <iostream>
 using namespace std;

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
 };

 class derived : public base {
 public:
 void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
 void(derived::*hwBase)();
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main()
 {
 base* b = new base(); //Create base object
 b->helloWorld(); // Hello World!
 void(derived::*hwBase)() = &derived::helloWorld; //create derived member
 function pointer to base function
 derived* d = new derived(); //Create derived object.
 d->displayHWDerived(hwBase); //Greetings World!

 char ch;
 cin >> ch;
 }

While we can do some things with member-function pointers, they aren't as flexible as virtual functions. It is tricky to use a member-function pointer in a class; the member-function pointer almost, at least in my practice, always must be called in the main function or from within a member function as in the above example.

On the other hand, virtual functions, while they might have some function-pointer overhead, do simplify things dramatically.

EDIT: There is another method which is similar by eddietree: c++ virtual function vs member function pointer (performance comparison) .


问:
Remove duplicate files from IIS for same application
I have X the same applications in IIS(some code/exe, but different config file).
Would it be possible to put duplicate files to some folder?

For example I have applications:

```<code>Canada.weather.com
usa.weather.com
mexico.weather.com
</code>```

Uses same .dll and .exe, but have different config.

答:
As Lex says, we don't suggest you to put duplicate files to some folder. If one of the dll is missed or not, it will make all the sites down.

If you still want to do this , you could apply the setting in applicationHost.config and wrapping it in a  tag.

The applicationhost.config file path :

```<code>%windir%\system32\inetsrv\config\applicationHost.config
</code>```

Each sites will have its own location, you could add the custome configuration inside each location tag.

Like belowl, I enable the windows auth for "BrandoTestSite":

```<code><location path="BrandoTestSite">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>
</code>```

Notice: This way is lower maintainability. We don't suggest you choose this way to manage mutiple application.

Body:
I have X the same applications in IIS(some code/exe, but different config file).
Would it be possible to put duplicate files to some folder?

For example I have applications:

Canada.weather.com
usa.weather.com
mexico.weather.com

Uses same .dll and .exe, but have different config.

Body:
As Lex says, we don't suggest you to put duplicate files to some folder. If one of the dll is missed or not, it will make all the sites down.

If you still want to do this , you could apply the setting in applicationHost.config and wrapping it in a  tag.

The applicationhost.config file path :

%windir%\system32\inetsrv\config\applicationHost.config

Each sites will have its own location, you could add the custome configuration inside each location tag.

Like belowl, I enable the windows auth for "BrandoTestSite":

<location path="BrandoTestSite">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

Notice: This way is lower maintainability. We don't suggest you choose this way to manage mutiple application.


问:
Assist me in finding the error: invalid method declaration; return type required
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

```<code>public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}
</code>```

This is my last homework for this class I just want this over with any help is appreciated.

答:
Whats wrong in your code is your class name and constructor names are different.

You have two options, one is to rename the constructor to Exercise01_01 or meke the return type of the Rectangle as void.

```<code>public class Exercise01_01 {

    private double width = 1;
    private double height = 1;

    public Exercise01_01() {
    }

    public Exercise01_01(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Exercise01_01 rectangle1 = new Exercise01_01(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " + rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " + rectangle1.getPerimeter());
        Exercise01_01 rectangle2 = new Exercise01_01(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " + rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " + rectangle2.getPerimeter());
    }

}
</code>```

Body:
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}

This is my last homework for this class I just want this over with any help is appreciated.

Body:
Whats wrong in your code is your class name and constructor names are different.

You have two options, one is to rename the constructor to Exercise01_01 or meke the return type of the Rectangle as void.

public class Exercise01_01 {

    private double width = 1;
    private double height = 1;

    public Exercise01_01() {
    }

    public Exercise01_01(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Exercise01_01 rectangle1 = new Exercise01_01(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " + rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " + rectangle1.getPerimeter());
        Exercise01_01 rectangle2 = new Exercise01_01(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " + rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " + rectangle2.getPerimeter());
    }

}


问:
Is it neccesary to make audio files public in S3 in order to play on alexa devices
I am making an alexa skill where user can listen to audio which I have uploaded in S3 but these doesn't play untill I make them public, is there any way to fix it? Why is it required to make the files public, isn't it risky?

There is one way they have suggested in javascript, they provide an api in their Utils package a function with name "getS3PreSignedURL" which will make object public for 60 seconds but what if my audio plays more than 60 seconds and I am working on Java, I am not so confident on javascript.
Have anyone faced similar issue, any thoughts will be helpful.

答:
See AWS S3 Public Object vs Private Object?

I think that answers your concerns on risk, and some other options.

You might also be able to find a parameter to make that function return a longer window - as an aside, it looks like it's still authenticating your user to use that link, as opposed to making it truly public (available to anyone without authentication).


问:
LuaJ (Java Lua Library): Calling Lua functions in other files from a Lua file
To begin, I'm aware of this question, but I don't think it quite fits what I'm doing. Either way, the answer is a bit confusing my opinion. I'd like to find an answer for my problem that's more specific to what I'm doing.

The goal here is for the lua file chatterToolsTest to successfully print "Test success" to the console. Unfortunately, my current approach isn't quite working. Can someone please help? I'm not the best at Lua, so maybe my Lua code is just wrong in this case. Please check out the snippets below.

Another constraint: I can't enable to use of modules from the java-side. Any referencing done between the two Lua files has to be obtained through Lua only. This is because I'm developing a modding system for a Java project and need the Lua to be able to work with minimal change on the Java-side.

Please keep in mind that I'm not storing my Lua files inside of the JAR file or any packages, they are contained in a folder in the root working directory of the Java program, like a folder of resources.

chatterToolsTest.lua:

```<code>function main()
  print("Test start.");

  local test = require("chatterTools");
  chatterTools:test();
end
</code>```

chatterTools.lua, the class called by chatterToolsTest.lua:

```<code>function test()
  print("Test success");
end
</code>```

Both of these files are in a folder called world/NOKORIWARE/lua/:

And lastly, here's the Java test class using LuaJ that calls them:

```<code>public class LuaTest {
    public static void main(String args[]) {
        new LuaTest().run("NOKORIWARE/lua/chatterToolsTest.lua", "main");
    }

    private Globals buildGlobals() {
        Globals globals = new Globals();

        globals.load(new JseBaseLib());
        globals.load(new PackageLib());
        globals.load(new Bit32Lib());
        globals.load(new TableLib());
        globals.load(new StringLib());
        globals.load(new JseMathLib());
        globals.load(new WhitelistedLuajavaLib());

        LoadState.install(globals);
        LuaC.install(globals);

        return globals;
    }

    /**
     * Runs the given lua file. It must be relative to the lua path.
     */
    private void run(String luaPath, String functionName, Object... arguments) {
        LuaValue[] coercedValues = null;

        if (arguments != null) {
            //Coerce arguments into LuaValues
            coercedValues = new LuaValue[arguments.length];

            for (int i = 0; i < arguments.length; i++) {
                coercedValues[i] = CoerceJavaToLua.coerce(arguments[i]);
            }
        }

        //Configure lua file
        Globals globals = buildGlobals();
        globals.get("dofile").call(LuaValue.valueOf("./world/" + luaPath));

        //Call the passed-in function of the lua file.
        try {
            LuaValue call = globals.get(functionName);
            if (arguments != null) {
                call.invoke(coercedValues);
            }else {
                call.invoke();
            }
        } catch (Exception e) {
            e.printStackTrace();
            TinyFileDialog.showMessageDialog("Caught " + e.getClass().getName(), e.getMessage(), TinyFileDialog.Icon.INFORMATION);
        }
    }
}
</code>```

This is the error that's printed when I run the Java program:

```<code>org.luaj.vm2.LuaError: @./world/NOKORIWARE/lua/chatterToolsTest.lua:4 module 'chatterTools' not found: chatterTools
    no field package.preload['chatterTools']
    chatterTools.lua
    no class 'chatterTools'
    at org.luaj.vm2.LuaValue.error(Unknown Source)
    at org.luaj.vm2.lib.PackageLib$require.call(Unknown Source)
    at org.luaj.vm2.LuaClosure.execute(Unknown Source)
    at org.luaj.vm2.LuaClosure.onInvoke(Unknown Source)
    at org.luaj.vm2.LuaClosure.invoke(Unknown Source)
    at org.luaj.vm2.LuaValue.invoke(Unknown Source)
    at nokori.robotfarm.test.LuaTest.run(LuaTest.java:64)
    at nokori.robotfarm.test.LuaTest.main(LuaTest.java:21)
</code>```

Any help or links to relevant resources is appreciated.

答:
The default LuaJ working directory is the same as Java's. Once I figured that out, I was able to correctly use require().

chatterTools.lua was changed to this:

```<code>local chatterTools = {}

function chatterTools.test()
  print("Test success");
end

return chatterTools;
</code>```

And finally chatterToolsTest.lua had to be changed like this:

```<code>function main()
  print(package.path);

  local chatterTools = require("world.NOKORIWARE.lua.chatterTools");
  chatterTools:test();
end
</code>```

Lua handles packages like above, so instead of world/NOKORIWARE/lua/chatterTools.lua it turns into what you see in the require() call.

After these changes, I ran the program and got the following:

```<code>?.lua
Test success
</code>```

All of this considered, this solution is a lot more straight-forward than the answer in the question I linked at the start of this question. Hopefully this will help some of you out there.

To read more on how I figured this out, check these resources out:

how to call function between 2 .lua

https://forums.coronalabs.com/topic/38127-how-to-call-a-function-from-another-lua-file/

Body:
To begin, I'm aware of this question, but I don't think it quite fits what I'm doing. Either way, the answer is a bit confusing my opinion. I'd like to find an answer for my problem that's more specific to what I'm doing.

The goal here is for the lua file chatterToolsTest to successfully print "Test success" to the console. Unfortunately, my current approach isn't quite working. Can someone please help? I'm not the best at Lua, so maybe my Lua code is just wrong in this case. Please check out the snippets below.

Another constraint: I can't enable to use of modules from the java-side. Any referencing done between the two Lua files has to be obtained through Lua only. This is because I'm developing a modding system for a Java project and need the Lua to be able to work with minimal change on the Java-side.

Please keep in mind that I'm not storing my Lua files inside of the JAR file or any packages, they are contained in a folder in the root working directory of the Java program, like a folder of resources.

chatterToolsTest.lua:

function main()
  print("Test start.");

  local test = require("chatterTools");
  chatterTools:test();
end

chatterTools.lua, the class called by chatterToolsTest.lua:

function test()
  print("Test success");
end

Both of these files are in a folder called world/NOKORIWARE/lua/:

And lastly, here's the Java test class using LuaJ that calls them:

public class LuaTest {
    public static void main(String args[]) {
        new LuaTest().run("NOKORIWARE/lua/chatterToolsTest.lua", "main");
    }

    private Globals buildGlobals() {
        Globals globals = new Globals();

        globals.load(new JseBaseLib());
        globals.load(new PackageLib());
        globals.load(new Bit32Lib());
        globals.load(new TableLib());
        globals.load(new StringLib());
        globals.load(new JseMathLib());
        globals.load(new WhitelistedLuajavaLib());

        LoadState.install(globals);
        LuaC.install(globals);

        return globals;
    }

    /**
     * Runs the given lua file. It must be relative to the lua path.
     */
    private void run(String luaPath, String functionName, Object... arguments) {
        LuaValue[] coercedValues = null;

        if (arguments != null) {
            //Coerce arguments into LuaValues
            coercedValues = new LuaValue[arguments.length];

            for (int i = 0; i < arguments.length; i++) {
                coercedValues[i] = CoerceJavaToLua.coerce(arguments[i]);
            }
        }

        //Configure lua file
        Globals globals = buildGlobals();
        globals.get("dofile").call(LuaValue.valueOf("./world/" + luaPath));

        //Call the passed-in function of the lua file.
        try {
            LuaValue call = globals.get(functionName);
            if (arguments != null) {
                call.invoke(coercedValues);
            }else {
                call.invoke();
            }
        } catch (Exception e) {
            e.printStackTrace();
            TinyFileDialog.showMessageDialog("Caught " + e.getClass().getName(), e.getMessage(), TinyFileDialog.Icon.INFORMATION);
        }
    }
}

This is the error that's printed when I run the Java program:

org.luaj.vm2.LuaError: @./world/NOKORIWARE/lua/chatterToolsTest.lua:4 module 'chatterTools' not found: chatterTools
    no field package.preload['chatterTools']
    chatterTools.lua
    no class 'chatterTools'
    at org.luaj.vm2.LuaValue.error(Unknown Source)
    at org.luaj.vm2.lib.PackageLib$require.call(Unknown Source)
    at org.luaj.vm2.LuaClosure.execute(Unknown Source)
    at org.luaj.vm2.LuaClosure.onInvoke(Unknown Source)
    at org.luaj.vm2.LuaClosure.invoke(Unknown Source)
    at org.luaj.vm2.LuaValue.invoke(Unknown Source)
    at nokori.robotfarm.test.LuaTest.run(LuaTest.java:64)
    at nokori.robotfarm.test.LuaTest.main(LuaTest.java:21)

Any help or links to relevant resources is appreciated.

Body:
The default LuaJ working directory is the same as Java's. Once I figured that out, I was able to correctly use require().

chatterTools.lua was changed to this:

local chatterTools = {}

function chatterTools.test()
  print("Test success");
end

return chatterTools;

And finally chatterToolsTest.lua had to be changed like this:

function main()
  print(package.path);

  local chatterTools = require("world.NOKORIWARE.lua.chatterTools");
  chatterTools:test();
end

Lua handles packages like above, so instead of world/NOKORIWARE/lua/chatterTools.lua it turns into what you see in the require() call.

After these changes, I ran the program and got the following:

?.lua
Test success

All of this considered, this solution is a lot more straight-forward than the answer in the question I linked at the start of this question. Hopefully this will help some of you out there.

To read more on how I figured this out, check these resources out:

how to call function between 2 .lua

https://forums.coronalabs.com/topic/38127-how-to-call-a-function-from-another-lua-file/


问:
PHP, loop through dynamic array by count
So I am working on a JQuery Step Form. It is being populated with dynamic information from the database. I have a particular list of items that is 21 items in the array. I would like to break these down into groups of 5 or 6 per step, so the form isn't so long.

I know I could use array_slice for example, but since this list is dynamic, I don't know how many there will always be. It will kind of be paginated in a sense but I don't need pagination links and such. Just a way to return 5 items, then 5 items and if the last iteration only has 2 items then that is it.

So for example:

```<code>$array = (
  array(
    "name" => "Peter Parker",
    "alterego" => "Spiderman",
  ),
  array(
    "name" => "Clark Kent",
    "alterego" => "Superman",
  ),
  array(
    "name" => "Bruce Wayne",
    "alterego" => "Batman",
  ),
);
</code>```

And then I want to break this down to only list 2 items per group.

答:
You can use array_chunk for example:

```<code>$chunks = array_chunk($array, 5);
foreach ($chunks as $chunk) {
    // display form for these 5 values
}
</code>```

Body:
So I am working on a JQuery Step Form. It is being populated with dynamic information from the database. I have a particular list of items that is 21 items in the array. I would like to break these down into groups of 5 or 6 per step, so the form isn't so long.

I know I could use array_slice for example, but since this list is dynamic, I don't know how many there will always be. It will kind of be paginated in a sense but I don't need pagination links and such. Just a way to return 5 items, then 5 items and if the last iteration only has 2 items then that is it.

So for example:

$array = (
  array(
    "name" => "Peter Parker",
    "alterego" => "Spiderman",
  ),
  array(
    "name" => "Clark Kent",
    "alterego" => "Superman",
  ),
  array(
    "name" => "Bruce Wayne",
    "alterego" => "Batman",
  ),
);

And then I want to break this down to only list 2 items per group.

Body:
You can use array_chunk for example:

$chunks = array_chunk($array, 5);
foreach ($chunks as $chunk) {
    // display form for these 5 values
}


问:
Android - jmdns doesn't discover devices
I'm trying to implement a class to discover services on the network.
I've tried working with Android's NSD and it does discover the services fine, but it supports only API levels 16 and up, and I can't seem to retrieve the txtRecord field within the service info (it returns null for some reason). Turns out it's a known problem...

So now I'm trying to work with jmDNS, which doesn't seem to find services at all.
here's my class (I'm working with the AndroidAnnotations framework) MDnsHelper:

```<code>@EBean
public class MDnsHelper implements ServiceListener {

public static final String SERVICE_TYPE = "_http._tcp.local";

Activity activity;
private JmDNS jmdns;
private MulticastLock multicastLock;
WifiManager wm;
InetAddress bindingAddress;
boolean isDiscovering;

public void init(Activity activity) {
    this.activity = activity;
    isDiscovering = false;
    wm = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
    multicastLock = wm.createMulticastLock(activity.getPackageName());
    multicastLock.setReferenceCounted(false);
}

@Background
public void startDiscovery() {
    if (isDiscovering)
        return;
    System.out.println("starting...");
    multicastLock.acquire();
    try {
        System.out.println("creating jmdns");
        jmdns = JmDNS.create();
        System.out.println("jmdns created");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (jmdns != null) {
            jmdns.addServiceListener(SERVICE_TYPE, MDnsHelper.this);
            isDiscovering = true;
            System.out.println("discovering services of type: " + SERVICE_TYPE);
        }
    }
}

@Background
public void stopDiscovery() {
    if (!isDiscovering || jmdns == null)
        return;
    System.out.println("stopping...");
    multicastLock.release();
    jmdns.removeServiceListener(SERVICE_TYPE, MDnsHelper.this);
    System.out.println("listener for " + SERVICE_TYPE + " removed");
    try {
        jmdns.close();
        isDiscovering = false;
        System.out.println("jmdns closed");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void serviceAdded(ServiceEvent service) {
    System.out.println("found: " + service.getInfo().toString());
}

@Override
public void serviceRemoved(ServiceEvent service) {
    System.out.println("lost: " + service.getInfo().toString());
}

@Override
public void serviceResolved(ServiceEvent service) {
    System.out.println("resolved: " + service.getInfo().toString());
}
}
</code>```

And in my app I call:

```<code>init(getActivity());
</code>```

And then startDiscovery(); to start scanning and stopDiscovery(); to stop scanning.

And of course, I gave the app the required permissions in the manifest...
What am I missing here?
If you need me to provide additional code/info - just ask.
thanks!!

答:
If you are having this error in Android Oreo 8.x, this might help you.

First, Remember to make sure you have added these permissions into your Android manifest.xml.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
```

<p>Acquire a multicast lock to allow multi-cast packets.</p>

<pre class="lang-java prettyprint-override"><code>WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("jmdns-multicast-lock");
lock.setReferenceCounted(true);
lock.acquire();
</code>```

Now, use only this constructor JmDNS.create(InetAddress addr, String name) to create an instance of JmDNS and bind it to a specific network interface given its IP-address, like this:

try {
    jmDNS = JmDNS.create(InetAddress.getByName(obtainIPv4Address(info)), HOST_NAME);
} catch (IOException e) {
    LogHelper.e(TAG, "Error in JmDNS creation: " + e);
}
```

<p>Finally, just make sure to call <code>JmDNSunreisterAllServices()</code>, and <code>JmDNS.close()</code> to stop JmDNS stream and releases any system resources associated with it. Also, call <code>MulticastLock.release()</code> to unlock the multicast lock when you're done with it.</p>

<pre class="lang-java prettyprint-override"><code>try {
    if (jmDNS != null) {
        jmDNS.unregisterAllServices();
        jmDNS.close();
        jmDNS = null;
    }
    if (lock != null) {
        lock.release();
        lock = null;
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Body:
I'm trying to implement a class to discover services on the network.
I've tried working with Android's NSD and it does discover the services fine, but it supports only API levels 16 and up, and I can't seem to retrieve the txtRecord field within the service info (it returns null for some reason). Turns out it's a known problem...

So now I'm trying to work with jmDNS, which doesn't seem to find services at all.
here's my class (I'm working with the AndroidAnnotations framework) MDnsHelper:

@EBean
public class MDnsHelper implements ServiceListener {

public static final String SERVICE_TYPE = "_http._tcp.local";

Activity activity;
private JmDNS jmdns;
private MulticastLock multicastLock;
WifiManager wm;
InetAddress bindingAddress;
boolean isDiscovering;

public void init(Activity activity) {
    this.activity = activity;
    isDiscovering = false;
    wm = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
    multicastLock = wm.createMulticastLock(activity.getPackageName());
    multicastLock.setReferenceCounted(false);
}

@Background
public void startDiscovery() {
    if (isDiscovering)
        return;
    System.out.println("starting...");
    multicastLock.acquire();
    try {
        System.out.println("creating jmdns");
        jmdns = JmDNS.create();
        System.out.println("jmdns created");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (jmdns != null) {
            jmdns.addServiceListener(SERVICE_TYPE, MDnsHelper.this);
            isDiscovering = true;
            System.out.println("discovering services of type: " + SERVICE_TYPE);
        }
    }
}

@Background
public void stopDiscovery() {
    if (!isDiscovering || jmdns == null)
        return;
    System.out.println("stopping...");
    multicastLock.release();
    jmdns.removeServiceListener(SERVICE_TYPE, MDnsHelper.this);
    System.out.println("listener for " + SERVICE_TYPE + " removed");
    try {
        jmdns.close();
        isDiscovering = false;
        System.out.println("jmdns closed");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void serviceAdded(ServiceEvent service) {
    System.out.println("found: " + service.getInfo().toString());
}

@Override
public void serviceRemoved(ServiceEvent service) {
    System.out.println("lost: " + service.getInfo().toString());
}

@Override
public void serviceResolved(ServiceEvent service) {
    System.out.println("resolved: " + service.getInfo().toString());
}
}

And in my app I call:

init(getActivity());

And then startDiscovery(); to start scanning and stopDiscovery(); to stop scanning.

And of course, I gave the app the required permissions in the manifest...
What am I missing here?
If you need me to provide additional code/info - just ask.
thanks!!

Body:
If you are having this error in Android Oreo 8.x, this might help you.

First, Remember to make sure you have added these permissions into your Android manifest.xml.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

Acquire a multicast lock to allow multi-cast packets.

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("jmdns-multicast-lock");
lock.setReferenceCounted(true);
lock.acquire();

Now, use only this constructor JmDNS.create(InetAddress addr, String name) to create an instance of JmDNS and bind it to a specific network interface given its IP-address, like this:

try {
    jmDNS = JmDNS.create(InetAddress.getByName(obtainIPv4Address(info)), HOST_NAME);
} catch (IOException e) {
    LogHelper.e(TAG, "Error in JmDNS creation: " + e);
}

Finally, just make sure to call JmDNSunreisterAllServices(), and JmDNS.close() to stop JmDNS stream and releases any system resources associated with it. Also, call MulticastLock.release() to unlock the multicast lock when you're done with it.

try {
    if (jmDNS != null) {
        jmDNS.unregisterAllServices();
        jmDNS.close();
        jmDNS = null;
    }
    if (lock != null) {
        lock.release();
        lock = null;
    }
} catch (Exception e) {
    e.printStackTrace();
}


问:
What causes DriveInfo.IsReady to be false?

Situation

I'm debugging some legacy code that performs some existence checks on directory paths. First, DirectoryPathA is checked and returned if it exists. This should be the usual case. If that fails, DirectoryPathB is checked and returned. (If that fails too, other things happen, not part of this question). Here's how the code looks:

```<code>if (!string.IsNullOrEmpty(DirectoryPathA))
{
    driveInfo = new DriveInfo(DirectoryPathA);
    if (driveInfo.IsReady)
    {
        dInf = new DirectoryInfo(DirectoryPathA);
        if (dInf.Exists)
        {
            return DirectoryPathA;
        }
    }
}

if (!string.IsNullOrEmpty(DirectoryPathB))
{
    dInf = new DirectoryInfo(DirectoryPathB);
    if (dInf.Exists)
    {
        return DirectoryPathB;
    }
}
</code>```

As you can see, the first check has an additional guard based on DriveInfo.IsReady. There have been problems with file access on the network before, so my assumption is (again, this is legacy code) that this was introduced to establish DirectoryPathBas an alternative if DirectoryPathA is not available. I have no idea why no such check for DriveInfo.IsReady is performed on DirectoryPathB.

Problem

Even if DirectoryPathA is a local directory (so no network outage), the code above sporadically returns DirectoryPathB. The code is executed several times and is assumed to be idempotent, which it is not, which breaks things.
This only happens occasionally on some machines over the course of several hours. I cannot reproduce the problem.

There's a fundamental problem with the assumption that the drive state would never change throughout the execution of a program. I understand that. However, this code seems to be fine most of the time and has been in the past.

Question

What can cause DriveInfo.IsReady to be false?

The documentation states

true if the drive is ready; false if the drive is not ready.

Thanks for nothing. The remarks section adds

IsReady indicates whether a drive is ready. For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and it is not ready, querying the drive using DriveInfo will raise an IOException.

It's not a removable drive. We're talking plain old C:\.

It's not a permission issue because it sometimes works and sometimes doesn't for the same user.

It's not a matter of the drive becoming unavailable due to power saving mode, because

power saving mode is not active and

it's an SSD.

The old documentation states that

Thread Safety

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Does that mean that DriveInfo.IsReady might be false if some other thread is performing some operation on the drive at the same time?
Is it even necessary for DriveInfo.IsReady to be true in order to check if a directory exists?

答: I met a situation that Ntfs file system corrupted and event 55 of Ntfs triggered. At this time DriveInfo.isReady() returns false.</p>

Body:
Situation

I'm debugging some legacy code that performs some existence checks on directory paths. First, DirectoryPathA is checked and returned if it exists. This should be the usual case. If that fails, DirectoryPathB is checked and returned. (If that fails too, other things happen, not part of this question). Here's how the code looks:

if (!string.IsNullOrEmpty(DirectoryPathA))
{
    driveInfo = new DriveInfo(DirectoryPathA);
    if (driveInfo.IsReady)
    {
        dInf = new DirectoryInfo(DirectoryPathA);
        if (dInf.Exists)
        {
            return DirectoryPathA;
        }
    }
}

if (!string.IsNullOrEmpty(DirectoryPathB))
{
    dInf = new DirectoryInfo(DirectoryPathB);
    if (dInf.Exists)
    {
        return DirectoryPathB;
    }
}

As you can see, the first check has an additional guard based on DriveInfo.IsReady. There have been problems with file access on the network before, so my assumption is (again, this is legacy code) that this was introduced to establish DirectoryPathBas an alternative if DirectoryPathA is not available. I have no idea why no such check for DriveInfo.IsReady is performed on DirectoryPathB.

Problem

Even if DirectoryPathA is a local directory (so no network outage), the code above sporadically returns DirectoryPathB. The code is executed several times and is assumed to be idempotent, which it is not, which breaks things.
This only happens occasionally on some machines over the course of several hours. I cannot reproduce the problem.

There's a fundamental problem with the assumption that the drive state would never change throughout the execution of a program. I understand that. However, this code seems to be fine most of the time and has been in the past.

Question

What can cause DriveInfo.IsReady to be false?

The documentation states

true if the drive is ready; false if the drive is not ready.

Thanks for nothing. The remarks section adds

IsReady indicates whether a drive is ready. For example, it indicates whether a CD is in a CD drive or whether a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and it is not ready, querying the drive using DriveInfo will raise an IOException.

It's not a removable drive. We're talking plain old C:\.

It's not a permission issue because it sometimes works and sometimes doesn't for the same user.

It's not a matter of the drive becoming unavailable due to power saving mode, because

power saving mode is not active and

it's an SSD.

The old documentation states that

Thread Safety

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Does that mean that DriveInfo.IsReady might be false if some other thread is performing some operation on the drive at the same time?
Is it even necessary for DriveInfo.IsReady to be true in order to check if a directory exists?