问:
asp.net core 2 webapi invalid characters
I'm having an Asp.net Core 2.0 WebApi project, and trying to access a Get () method and generating a purposeful error in it for the client.
I am sending information from Http errors to the consumer client:

```<code>context.Result = new BadRequestResult();
context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Não foi encontrado.";
</code>```

When client receives ReasonPhrase it has invalid characters where it is accented:

"N?o foi encontrado"

the correct would be:

"Não foi encontrado"

I imagine I would have how to configure encoding for UTF-8 but I can not figure out ways to do that. Can you help me?

答:
you can use
HttpContext.Response.ContentEncoding = Encoding.GetEncoding("utf-8") </p>

<p>but as far as I know it is by default utf-8, again it is what I know and I may be very wrong </p>

Body:
I'm having an Asp.net Core 2.0 WebApi project, and trying to access a Get () method and generating a purposeful error in it for the client.
I am sending information from Http errors to the consumer client:

context.Result = new BadRequestResult();
context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Não foi encontrado.";

When client receives ReasonPhrase it has invalid characters where it is accented:

"N?o foi encontrado"

the correct would be:

"Não foi encontrado"

I imagine I would have how to configure encoding for UTF-8 but I can not figure out ways to do that. Can you help me?

Body:
you can use
HttpContext.Response.ContentEncoding = Encoding.GetEncoding("utf-8")

but as far as I know it is by default utf-8, again it is what I know and I may be very wrong


来源: stackexchange

问:
How to use $lookup as INNER JOIN in MongoDB Aggregation?
I have used $lookup in my aggregate query.
But as I am seeing it works as LEFT OUTER JOIN.

I want to fetch exact matches document(INNER JOIN) with $lookup.

Is there any way to get it done?

This is my inventory collection:

```<code>/* 1 */
{
    "_id" : 1,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120
}

/* 2 */
{
    "_id" : 2,
    "sku" : "def",
    "description" : "product 2",
    "instock" : 80
}

/* 3 */
{
    "_id" : 3,
    "sku" : "ijk",
    "description" : "product 3",
    "instock" : 60
}

/* 4 */
{
    "_id" : 4,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70
}

/* 5 */
{
    "_id" : 5,
    "sku" : null,
    "description" : "Incomplete"
}
</code>```

This is my orders collection

```<code>/* 1 */
{
    "_id" : 1,
    "item" : "abc",
    "price" : 12,
    "quantity" : 2
}

/* 2 */
{
    "_id" : 2,
    "item" : "jkl",
    "price" : 20,
    "quantity" : 1
}

/* 3 */
{
    "_id" : 10,
    "item" : "jklw",
    "price" : 20,
    "quantity" : 1
}
</code>```

And this is query

```<code>db.getCollection('inventory').aggregate([
   {
     $lookup:
       {
         from: "orders",
         localField: "sku",
         foreignField: "item",
         as: "inventory_docs"
       }
  }
])
</code>```

In this query I am getting all the inventory's document matches with orders documents

Expected Result

```<code>/* 1 */
{
    "_id" : 1,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120,
    "inventory_docs" : [
        {
            "_id" : 1,
            "item" : "abc",
            "price" : 12,
            "quantity" : 2
        }
    ]
}

/* 2 */
{
    "_id" : 4,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70,
    "inventory_docs" : [
        {
            "_id" : 2,
            "item" : "jkl",
            "price" : 20,
            "quantity" : 1
        }
    ]
}
</code>```

答:
Just add the $match pipeline stage which skips documents with empty inventory_docs field. There no other way to achieve that.

Query:

```<code>db.getCollection('inventory').aggregate([
    {
        $lookup: {
            from: "orders",
            localField: "sku",
            foreignField: "item",
            as: "inventory_docs"
        }
    },
    {
        $match: {
            "inventory_docs": {$ne: []}
        }
    }
])
</code>```

Result:

```<code>{
    "_id" : 1.0,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120.0,
    "inventory_docs" : [
        {
            "_id" : 1.0,
            "item" : "abc",
            "price" : 12.0,
            "quantity" : 2.0
        }
    ]
}

{
    "_id" : 4.0,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70.0,
    "inventory_docs" : [
        {
            "_id" : 2.0,
            "item" : "jkl",
            "price" : 20.0,
            "quantity" : 1.0
        }
    ]
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have used $lookup in my aggregate query.
But as I am seeing it works as LEFT OUTER JOIN.

I want to fetch exact matches document(INNER JOIN) with $lookup.

Is there any way to get it done?

This is my inventory collection:

/* 1 */
{
    "_id" : 1,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120
}

/* 2 */
{
    "_id" : 2,
    "sku" : "def",
    "description" : "product 2",
    "instock" : 80
}

/* 3 */
{
    "_id" : 3,
    "sku" : "ijk",
    "description" : "product 3",
    "instock" : 60
}

/* 4 */
{
    "_id" : 4,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70
}

/* 5 */
{
    "_id" : 5,
    "sku" : null,
    "description" : "Incomplete"
}

This is my orders collection

/* 1 */
{
    "_id" : 1,
    "item" : "abc",
    "price" : 12,
    "quantity" : 2
}

/* 2 */
{
    "_id" : 2,
    "item" : "jkl",
    "price" : 20,
    "quantity" : 1
}

/* 3 */
{
    "_id" : 10,
    "item" : "jklw",
    "price" : 20,
    "quantity" : 1
}

And this is query

db.getCollection('inventory').aggregate([
   {
     $lookup:
       {
         from: "orders",
         localField: "sku",
         foreignField: "item",
         as: "inventory_docs"
       }
  }
])

In this query I am getting all the inventory's document matches with orders documents

Expected Result

/* 1 */
{
    "_id" : 1,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120,
    "inventory_docs" : [
        {
            "_id" : 1,
            "item" : "abc",
            "price" : 12,
            "quantity" : 2
        }
    ]
}

/* 2 */
{
    "_id" : 4,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70,
    "inventory_docs" : [
        {
            "_id" : 2,
            "item" : "jkl",
            "price" : 20,
            "quantity" : 1
        }
    ]
}

Body:
Just add the $match pipeline stage which skips documents with empty inventory_docs field. There no other way to achieve that.

Query:

db.getCollection('inventory').aggregate([
    {
        $lookup: {
            from: "orders",
            localField: "sku",
            foreignField: "item",
            as: "inventory_docs"
        }
    },
    {
        $match: {
            "inventory_docs": {$ne: []}
        }
    }
])

Result:

{
    "_id" : 1.0,
    "sku" : "abc",
    "description" : "product 1",
    "instock" : 120.0,
    "inventory_docs" : [
        {
            "_id" : 1.0,
            "item" : "abc",
            "price" : 12.0,
            "quantity" : 2.0
        }
    ]
}

{
    "_id" : 4.0,
    "sku" : "jkl",
    "description" : "product 4",
    "instock" : 70.0,
    "inventory_docs" : [
        {
            "_id" : 2.0,
            "item" : "jkl",
            "price" : 20.0,
            "quantity" : 1.0
        }
    ]
}


问:
JavaFX - TableView not populating
I'm trying to populate a TableView that consists of two columns (name and email), but the columns remain empty.

Here's the controller code:

```<code>public class GUIMainController
{
   @FXML private TableView<Member> tableMembers;

   @FXML private TableColumn<Member, String> tcMemberName;
   @FXML private TableColumn<Member, String> tcMemberEmail;

   public void initialize()
   {
    tcMemberName.setCellValueFactory(new PropertyValueFactory<Member, String>("name"));
    tcMemberEmail.setCellValueFactory(new PropertyValueFactory<Member, String>("email"));

    tableMembers.setItems(getList());
   }

   public ObservableList<Member> getList()
   {
     ObservableList<Member> members = FXCollections.observableArrayList();

     members.add(new Member("Frank","frankie678@gmail.com"));

     System.out.println(members);
     return members;
   }
}
</code>```

And the constructor for data:

```<code>public Member(String name, String email)
{
    this.name = name;
    this.email = email;
}
public String getMemberName()
{
    return this.name;
}

public void setMemberName(String name)
{
    this.name = name;
}

public String getMemberEmail()
{
    return this.email;
}

public void setMemberEmail(String email)
{
    this.email = email;
}
</code>```

I can see the correct data on the console, but it does not show in the table itself.

Can anyone help? Thanks in advance!

答: Thanks, I ended up by removing my getters and setters and generating them inside Eclipse. Worked like a charm!</p>

Title: JavaFX - TableView not populating

Body:
I'm trying to populate a TableView that consists of two columns (name and email), but the columns remain empty.

Here's the controller code:

public class GUIMainController
{
   @FXML private TableView<Member> tableMembers;

   @FXML private TableColumn<Member, String> tcMemberName;
   @FXML private TableColumn<Member, String> tcMemberEmail;

   public void initialize()
   {
    tcMemberName.setCellValueFactory(new PropertyValueFactory<Member, String>("name"));
    tcMemberEmail.setCellValueFactory(new PropertyValueFactory<Member, String>("email"));

    tableMembers.setItems(getList());
   }

   public ObservableList<Member> getList()
   {
     ObservableList<Member> members = FXCollections.observableArrayList();

     members.add(new Member("Frank","frankie678@gmail.com"));

     System.out.println(members);
     return members;
   }
}

And the constructor for data:

public Member(String name, String email)
{
    this.name = name;
    this.email = email;
}
public String getMemberName()
{
    return this.name;
}

public void setMemberName(String name)
{
    this.name = name;
}

public String getMemberEmail()
{
    return this.email;
}

public void setMemberEmail(String email)
{
    this.email = email;
}

I can see the correct data on the console, but it does not show in the table itself.

Can anyone help? Thanks in advance!


问:
Recovering implicit information from existentials in Coq
Suppose we have something like this:

Suppose x is a real number. Show that if there is a real number y such that (y + 1) / (y - 2) = x, then x <> 1".

If one formulates it in an obvious way: forall x : R, (exists y, ((y + 1) * / (y - 2)) = x) -> x <> 1, one runs into an issue very soon.

We have an assumption of existence of y such that ((y + 1) * / (y - 2)) = x). Am I wrong to assume that this should also imply that y <> 2? Is there a way to recover this information in Coq?

Surely, if such y exists, then it is not 2. How does one recover this information in Coq - do I need to explicitly assume it (that is, there is no way to recover it by existential instantiation somehow?).

Of course, destruct H as [y] just gives us ((y + 1) * / (y - 2)) = x) for y : R, but now we don't know y <> 2.

答:
Am I wrong to assume that this should also imply that y <> 2?

Yes. In Coq, division is a total, unconstrained function: you can apply it to any pair of numbers, including a zero divisor.  If you want to assume y <> 2, you need to add that as an explicit assumption to your lemma.

You may find this scary: how could we be allowed to divide something by zero? The answer is that it doesn't matter, as long as you do not try to argue that 0 * (x / 0) = x.  This question discusses the issue in  more detail.


问:
Swift decodable : check is a nested structure is present
I have a JSON data that goes something like this. I have used a separate structure approach rather than having nested keys for very structure  in a single one. The point to be noted is that the keys in the Given Json are not consistent and may be absent. Hence a check has to be made for each key before trying to parse it with the built structure.

```<code> {  "ProductInfo": [
      {
        "productCode": "ABC",
        "productWeight": "2.3",
      }
    ],
    "ProductService": [
      {
        "serviceCode": "00",
        "serviceSite": 0
      }],

"ProductName": "StackSite"
}
</code>```

to Parse this I have created swift structure like these

```<code>struct ProductStructure: Decodable{
var ProductInfo: productInfo
var ProductService: [productService]
var ProductName:String

enum ProductStructureKeys: String , CodingKey{
case ProductInfo
case ProductService
case ProductName

}

struct productInfo : Decodable {
   var productCode:String
   var productWeight:String
}

struct ProductService : Decodable {
    var serviceCode:String
    var serviceSite: Int
}

**// the decoder for the Main Structure**
extension ProductStructure{
  init(from decoder: Decoder) throws {

let container = try decoder.container(
      keyedBy: ProductStructureKeys.self)

//checks if product name key is present
 let product: String = try container.decodeIfPresent(String.self, forKey: . ProductName)

*//What code should I put here to check if my other two structures are present and parse them if they are present.*

}
</code>```

答:
The easiest solution is to declare the properties productInfo and productService as optional (and with names starting with a lowercase letter). By the way both objects are arrays

```<code>struct ProductStructure: Decodable {
    let productInfo: [ProductInfo]?
    let productService: [ProductService]?
    let productName: String

    enum CodingKeys: String, CodingKey {
        case productInfo = "ProductInfo"
        case productService = "ProductService"
        case productName = "ProductName"
    }

    struct ProductInfo : Decodable {
        let productCode: String
        let productWeight: String
    }

    struct ProductService : Decodable {
        let serviceCode: String
        let serviceSite: Int
    }
}
</code>```

If the key serviceCode in ProductService can be missing, too, declare the property the same way as optional

```<code> let serviceCode: String?
</code>```

A custom initializer is not needed, assuming data contains the JSON as Data

```<code>let productStructure = try decoder.decode(ProductStructure.self, from: data)
</code>```

Body:
I have a JSON data that goes something like this. I have used a separate structure approach rather than having nested keys for very structure  in a single one. The point to be noted is that the keys in the Given Json are not consistent and may be absent. Hence a check has to be made for each key before trying to parse it with the built structure.

 {  "ProductInfo": [
      {
        "productCode": "ABC",
        "productWeight": "2.3",
      }
    ],
    "ProductService": [
      {
        "serviceCode": "00",
        "serviceSite": 0
      }],

"ProductName": "StackSite"
}

to Parse this I have created swift structure like these

struct ProductStructure: Decodable{
var ProductInfo: productInfo
var ProductService: [productService]
var ProductName:String

enum ProductStructureKeys: String , CodingKey{
case ProductInfo
case ProductService
case ProductName

}

struct productInfo : Decodable {
   var productCode:String
   var productWeight:String
}

struct ProductService : Decodable {
    var serviceCode:String
    var serviceSite: Int
}

**// the decoder for the Main Structure**
extension ProductStructure{
  init(from decoder: Decoder) throws {

let container = try decoder.container(
      keyedBy: ProductStructureKeys.self)

//checks if product name key is present
 let product: String = try container.decodeIfPresent(String.self, forKey: . ProductName)

*//What code should I put here to check if my other two structures are present and parse them if they are present.*

}

Body:
The easiest solution is to declare the properties productInfo and productService as optional (and with names starting with a lowercase letter). By the way both objects are arrays

struct ProductStructure: Decodable {
    let productInfo: [ProductInfo]?
    let productService: [ProductService]?
    let productName: String

    enum CodingKeys: String, CodingKey {
        case productInfo = "ProductInfo"
        case productService = "ProductService"
        case productName = "ProductName"
    }

    struct ProductInfo : Decodable {
        let productCode: String
        let productWeight: String
    }

    struct ProductService : Decodable {
        let serviceCode: String
        let serviceSite: Int
    }
}

If the key serviceCode in ProductService can be missing, too, declare the property the same way as optional

 let serviceCode: String?

A custom initializer is not needed, assuming data contains the JSON as Data

let productStructure = try decoder.decode(ProductStructure.self, from: data)


问:
MySql, trying to figure out my some queries run a lot slower sometimes, need some proof why
I've optimized my queries and they all run faster than 0.6 seconds. However, sometimes they can take 2 or 3 seconds.

I'm using a shared server, however the server is only used by a static html site and my database. I've added functionality so  I get an email if a query takes longer than 0.6 seconds. I get about 20 to 30 a day. The site gets around 800 hits a day. So the queries are ok most of the time.

I'm looking for a way in PHP using mysql that i can find out if I'm running other queries aka if the server is busy.

I want to add something in my php so I can add this to my slow query email

Any ideas ?

答:
Check the execution plan for those queries that do sometimes take long with EXPLAIN and see if you can rewrite them or add indexes to speed them up

Make sure you're flushing the query cache between tests, otherwise it could be the case that the queries are ALWAYS 2-3 seconds, you're just getting cached results from the earlier run when you think it's faster. The query is slow again when the cache is full or an update to the table invalidates the cached results.

When you start getting mails about slow queries occurring, check the server load and memory usage. Maybe you're running out of resources (cpu/memory/disk IO) when you receive a higher number of queries during some period of the day.

Regarding your update "I want to add something in my php so I can add this to my slow query email":

Run the query SHOW PROCESSLIST to get a list of all queries currently running. You can dump those results in your mail.

Use exec or shell_exec to run top, uptime and other system commands that will give you an idea of the server's state at the time of the slow queries. Save the output to a string and add it to your mails.

ContentLicense: CC BY-SA 2.5


问:
Snappy insertion into druid
Facing problem in snappy ingestion to druid. Things start break after org.apache.hadoop.mapred.LocalJobRunner - map task executor complete. Its able to fetch the input file.

My specs json file -

```<code>{
    "hadoopCoordinates": "org.apache.hadoop:hadoop-client:2.6.0",
    "spec": {
        "dataSchema": {
            "dataSource": "apps_searchprivacy",
            "granularitySpec": {
                "intervals": [
                    "2017-01-23T00:00:00.000Z/2017-01-23T01:00:00.000Z"
                ],
                "queryGranularity": "HOUR",
                "segmentGranularity": "HOUR",
                "type": "uniform"
            },
            "metricsSpec": [
                {
                    "name": "count",
                    "type": "count"
                },
                {
                    "fieldName": "event_value",
                    "name": "event_value",
                    "type": "longSum"
                },
                {
                    "fieldName": "landing_impression",
                    "name": "landing_impression",
                    "type": "longSum"
                },
                 {
                    "fieldName": "user",
                    "name": "DistinctUsers",
                    "type": "hyperUnique"
                },
                {
                    "fieldName": "cost",
                    "name": "cost",
                    "type": "doubleSum"
                }
            ],
            "parser": {
                "parseSpec": {
                    "dimensionsSpec": {
                        "dimensionExclusions": [
                            "landing_page",
                            "skip_url",
                            "ua",
                            "user_id"
                            ],
                        "dimensions": [
                            "t3",
                            "t2",
                            "t1",
                            "aff_id",
                            "customer",
                            "evt_id",
                            "install_date",
                            "install_week",
                            "install_month",
                            "install_year",
                            "days_since_install",
                            "months_since_install",
                            "weeks_since_install",
                            "success_url",
                            "event",
                            "chrome_version",
                            "value",
                            "event_label",
                            "rand",
                            "type_tag_id",
                            "channel_name",
                            "cid",
                            "log_id",
                            "extension",
                            "os",
                            "device",
                            "browser",
                            "cli_ip",
                            "t4",
                            "t5",
                            "referal_url",
                            "week",
                            "month",
                            "year",
                            "browser_version",
                            "browser_name",
                            "landing_template",
                            "strvalue",
                            "customer_group",
                            "extname",
                            "countrycode",
                            "issp",
                            "spdes",
                            "spsc"

                            ],
                        "spatialDimensions": []
                    },
                    "format": "json",
                    "timestampSpec": {
                        "column": "time_stamp",
                        "format": "yyyy-MM-dd HH:mm:ss"
                    }
                },
                "type": "hadoopyString"
            }
        },
        "ioConfig": {
            "inputSpec": {
                "dataGranularity": "hour",
                "filePattern": ".*\\..*",
                "inputPath": "hdfs://c8-auto-hadoop-service-1.srv.media.net:8020/data/apps_test_output",
                "pathFormat": "'ts'=yyyyMMddHH",
                "type": "granularity"
            },
            "type": "hadoop"
        },
        "tuningConfig": {
            "ignoreInvalidRows": "true",
            "type": "hadoop",
            "useCombiner": "false"
        }
    },
    "type": "index_hadoop"
}
</code>```

Error Getting

```<code>2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - (EQUATOR) 0 kvi 26214396(104857584)
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - mapreduce.task.io.sort.mb: 100
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - soft limit at 83886080
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - bufstart = 0; bufvoid = 104857600
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - kvstart = 26214396; length = 6553600
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
2017-02-03T14:39:50,847 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - Starting flush of map output
2017-02-03T14:39:50,849 INFO [Thread-22] org.apache.hadoop.mapred.LocalJobRunner - map task executor complete.
2017-02-03T14:39:50,850 WARN [Thread-22] org.apache.hadoop.mapred.LocalJobRunner - job_local233667772_0001
java.lang.Exception: java.lang.UnsatisfiedLinkError: org.apache.hadoop.util.NativeCodeLoader.buildSupportsSnappy()Z
    at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462) ~[hadoop-mapreduce-client-common-2.6.0.jar:?]
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:522) [hadoop-mapreduce-client-common-2.6.0.jar:?]
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.util.NativeCodeLoader.buildSupportsSnappy()Z
    at org.apache.hadoop.util.NativeCodeLoader.buildSupportsSnappy(Native Method) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.io.compress.SnappyCodec.checkNativeCodeLoaded(SnappyCodec.java:63) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.io.compress.SnappyCodec.getDecompressorType(SnappyCodec.java:192) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.io.compress.CodecPool.getDecompressor(CodecPool.java:176) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.mapreduce.lib.input.LineRecordReader.initialize(LineRecordReader.java:90) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapreduce.lib.input.DelegatingRecordReader.initialize(DelegatingRecordReader.java:84) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.initialize(MapTask.java:545) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:783) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:243) ~[hadoop-mapreduce-client-common-2.6.0.jar:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_121]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[?:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) ~[?:1.8.0_121]
2017-02-03T14:39:51,130 INFO [task-runner-0-priority-0] org.apache.hadoop.mapreduce.Job - Job job_local233667772_0001 failed with state FAILED due to: NA
2017-02-03T14:39:51,139 INFO [task-runner-0-priority-0] org.apache.hadoop.mapreduce.Job - Counters: 0
2017-02-03T14:39:51,143 INFO [task-runner-0-priority-0] io.druid.indexer.JobHelper - Deleting path[var/druid/hadoop-tmp/apps_searchprivacy/2017-02-03T143903.262Z_bb7a812bc0754d4aabcd4bc103ed648a]
2017-02-03T14:39:51,158 ERROR [task-runner-0-priority-0] io.druid.indexing.overlord.ThreadPoolTaskRunner - Exception while running task[HadoopIndexTask{id=index_hadoop_apps_searchprivacy_2017-02-03T14:39:03.257Z, type=index_hadoop, dataSource=apps_searchprivacy}]
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.google.common.base.Throwables.propagate(Throwables.java:160) ~[guava-16.0.1.jar:?]
    at io.druid.indexing.common.task.HadoopTask.invokeForeignLoader(HadoopTask.java:204) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    at io.druid.indexing.common.task.HadoopIndexTask.run(HadoopIndexTask.java:208) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    at io.druid.indexing.overlord.ThreadPoolTaskRunner$ThreadPoolTaskRunnerCallable.call(ThreadPoolTaskRunner.java:436) [druid-indexing-service-0.9.2.jar:0.9.2]
    at io.druid.indexing.overlord.ThreadPoolTaskRunner$ThreadPoolTaskRunnerCallable.call(ThreadPoolTaskRunner.java:408) [druid-indexing-service-0.9.2.jar:0.9.2]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_121]
    at io.druid.indexing.common.task.HadoopTask.invokeForeignLoader(HadoopTask.java:201) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    ... 7 more
Caused by: com.metamx.common.ISE: Job[class io.druid.indexer.IndexGeneratorJob] failed!
    at io.druid.indexer.JobHelper.runJobs(JobHelper.java:369) ~[druid-indexing-hadoop-0.9.2.jar:0.9.2]
    at io.druid.indexer.HadoopDruidIndexerJob.run(HadoopDruidIndexerJob.java:94) ~[druid-indexing-hadoop-0.9.2.jar:0.9.2]
    at io.druid.indexing.common.task.HadoopIndexTask$HadoopIndexGeneratorInnerProcessing.runTask(HadoopIndexTask.java:261) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_121]
    at io.druid.indexing.common.task.HadoopTask.invokeForeignLoader(HadoopTask.java:201) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    ... 7 more
2017-02-03T14:39:51,165 INFO [task-runner-0-priority-0] io.druid.indexing.overlord.TaskRunnerUtils - Task [index_hadoop_apps_searchprivacy_2017-02-03T14:39:03.257Z] status changed to [FAILED].
2017-02-03T14:39:51,168 INFO [task-runner-0-priority-0] io.druid.indexing.worker.executor.ExecutorLifecycle - Task completed with status: {
  "id" : "index_hadoop_apps_searchprivacy_2017-02-03T14:39:03.257Z",
  "status" : "FAILED",
  "duration" : 43693
}
</code>```

答: It seems that jvm can't load native shared library (like .dll or .so), check is it available on machine(s) running the task, and if so check is its dir on the classpath of the jvm.</p>

Title: Snappy insertion into druid

Body:
Facing problem in snappy ingestion to druid. Things start break after org.apache.hadoop.mapred.LocalJobRunner - map task executor complete. Its able to fetch the input file.

My specs json file -

{
    "hadoopCoordinates": "org.apache.hadoop:hadoop-client:2.6.0",
    "spec": {
        "dataSchema": {
            "dataSource": "apps_searchprivacy",
            "granularitySpec": {
                "intervals": [
                    "2017-01-23T00:00:00.000Z/2017-01-23T01:00:00.000Z"
                ],
                "queryGranularity": "HOUR",
                "segmentGranularity": "HOUR",
                "type": "uniform"
            },
            "metricsSpec": [
                {
                    "name": "count",
                    "type": "count"
                },
                {
                    "fieldName": "event_value",
                    "name": "event_value",
                    "type": "longSum"
                },
                {
                    "fieldName": "landing_impression",
                    "name": "landing_impression",
                    "type": "longSum"
                },
                 {
                    "fieldName": "user",
                    "name": "DistinctUsers",
                    "type": "hyperUnique"
                },
                {
                    "fieldName": "cost",
                    "name": "cost",
                    "type": "doubleSum"
                }
            ],
            "parser": {
                "parseSpec": {
                    "dimensionsSpec": {
                        "dimensionExclusions": [
                            "landing_page",
                            "skip_url",
                            "ua",
                            "user_id"
                            ],
                        "dimensions": [
                            "t3",
                            "t2",
                            "t1",
                            "aff_id",
                            "customer",
                            "evt_id",
                            "install_date",
                            "install_week",
                            "install_month",
                            "install_year",
                            "days_since_install",
                            "months_since_install",
                            "weeks_since_install",
                            "success_url",
                            "event",
                            "chrome_version",
                            "value",
                            "event_label",
                            "rand",
                            "type_tag_id",
                            "channel_name",
                            "cid",
                            "log_id",
                            "extension",
                            "os",
                            "device",
                            "browser",
                            "cli_ip",
                            "t4",
                            "t5",
                            "referal_url",
                            "week",
                            "month",
                            "year",
                            "browser_version",
                            "browser_name",
                            "landing_template",
                            "strvalue",
                            "customer_group",
                            "extname",
                            "countrycode",
                            "issp",
                            "spdes",
                            "spsc"

                            ],
                        "spatialDimensions": []
                    },
                    "format": "json",
                    "timestampSpec": {
                        "column": "time_stamp",
                        "format": "yyyy-MM-dd HH:mm:ss"
                    }
                },
                "type": "hadoopyString"
            }
        },
        "ioConfig": {
            "inputSpec": {
                "dataGranularity": "hour",
                "filePattern": ".*\\..*",
                "inputPath": "hdfs://c8-auto-hadoop-service-1.srv.media.net:8020/data/apps_test_output",
                "pathFormat": "'ts'=yyyyMMddHH",
                "type": "granularity"
            },
            "type": "hadoop"
        },
        "tuningConfig": {
            "ignoreInvalidRows": "true",
            "type": "hadoop",
            "useCombiner": "false"
        }
    },
    "type": "index_hadoop"
}

Error Getting

2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - (EQUATOR) 0 kvi 26214396(104857584)
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - mapreduce.task.io.sort.mb: 100
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - soft limit at 83886080
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - bufstart = 0; bufvoid = 104857600
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - kvstart = 26214396; length = 6553600
2017-02-03T14:39:50,738 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
2017-02-03T14:39:50,847 INFO [LocalJobRunner Map Task Executor #0] org.apache.hadoop.mapred.MapTask - Starting flush of map output
2017-02-03T14:39:50,849 INFO [Thread-22] org.apache.hadoop.mapred.LocalJobRunner - map task executor complete.
2017-02-03T14:39:50,850 WARN [Thread-22] org.apache.hadoop.mapred.LocalJobRunner - job_local233667772_0001
java.lang.Exception: java.lang.UnsatisfiedLinkError: org.apache.hadoop.util.NativeCodeLoader.buildSupportsSnappy()Z
    at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462) ~[hadoop-mapreduce-client-common-2.6.0.jar:?]
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:522) [hadoop-mapreduce-client-common-2.6.0.jar:?]
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.util.NativeCodeLoader.buildSupportsSnappy()Z
    at org.apache.hadoop.util.NativeCodeLoader.buildSupportsSnappy(Native Method) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.io.compress.SnappyCodec.checkNativeCodeLoaded(SnappyCodec.java:63) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.io.compress.SnappyCodec.getDecompressorType(SnappyCodec.java:192) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.io.compress.CodecPool.getDecompressor(CodecPool.java:176) ~[hadoop-common-2.6.0.jar:?]
    at org.apache.hadoop.mapreduce.lib.input.LineRecordReader.initialize(LineRecordReader.java:90) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapreduce.lib.input.DelegatingRecordReader.initialize(DelegatingRecordReader.java:84) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.initialize(MapTask.java:545) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:783) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341) ~[hadoop-mapreduce-client-core-2.6.0.jar:?]
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:243) ~[hadoop-mapreduce-client-common-2.6.0.jar:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[?:1.8.0_121]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[?:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) ~[?:1.8.0_121]
2017-02-03T14:39:51,130 INFO [task-runner-0-priority-0] org.apache.hadoop.mapreduce.Job - Job job_local233667772_0001 failed with state FAILED due to: NA
2017-02-03T14:39:51,139 INFO [task-runner-0-priority-0] org.apache.hadoop.mapreduce.Job - Counters: 0
2017-02-03T14:39:51,143 INFO [task-runner-0-priority-0] io.druid.indexer.JobHelper - Deleting path[var/druid/hadoop-tmp/apps_searchprivacy/2017-02-03T143903.262Z_bb7a812bc0754d4aabcd4bc103ed648a]
2017-02-03T14:39:51,158 ERROR [task-runner-0-priority-0] io.druid.indexing.overlord.ThreadPoolTaskRunner - Exception while running task[HadoopIndexTask{id=index_hadoop_apps_searchprivacy_2017-02-03T14:39:03.257Z, type=index_hadoop, dataSource=apps_searchprivacy}]
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.google.common.base.Throwables.propagate(Throwables.java:160) ~[guava-16.0.1.jar:?]
    at io.druid.indexing.common.task.HadoopTask.invokeForeignLoader(HadoopTask.java:204) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    at io.druid.indexing.common.task.HadoopIndexTask.run(HadoopIndexTask.java:208) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    at io.druid.indexing.overlord.ThreadPoolTaskRunner$ThreadPoolTaskRunnerCallable.call(ThreadPoolTaskRunner.java:436) [druid-indexing-service-0.9.2.jar:0.9.2]
    at io.druid.indexing.overlord.ThreadPoolTaskRunner$ThreadPoolTaskRunnerCallable.call(ThreadPoolTaskRunner.java:408) [druid-indexing-service-0.9.2.jar:0.9.2]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_121]
    at io.druid.indexing.common.task.HadoopTask.invokeForeignLoader(HadoopTask.java:201) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    ... 7 more
Caused by: com.metamx.common.ISE: Job[class io.druid.indexer.IndexGeneratorJob] failed!
    at io.druid.indexer.JobHelper.runJobs(JobHelper.java:369) ~[druid-indexing-hadoop-0.9.2.jar:0.9.2]
    at io.druid.indexer.HadoopDruidIndexerJob.run(HadoopDruidIndexerJob.java:94) ~[druid-indexing-hadoop-0.9.2.jar:0.9.2]
    at io.druid.indexing.common.task.HadoopIndexTask$HadoopIndexGeneratorInnerProcessing.runTask(HadoopIndexTask.java:261) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_121]
    at io.druid.indexing.common.task.HadoopTask.invokeForeignLoader(HadoopTask.java:201) ~[druid-indexing-service-0.9.2.jar:0.9.2]
    ... 7 more
2017-02-03T14:39:51,165 INFO [task-runner-0-priority-0] io.druid.indexing.overlord.TaskRunnerUtils - Task [index_hadoop_apps_searchprivacy_2017-02-03T14:39:03.257Z] status changed to [FAILED].
2017-02-03T14:39:51,168 INFO [task-runner-0-priority-0] io.druid.indexing.worker.executor.ExecutorLifecycle - Task completed with status: {
  "id" : "index_hadoop_apps_searchprivacy_2017-02-03T14:39:03.257Z",
  "status" : "FAILED",
  "duration" : 43693
}


问:
Relative URL does not get resolved correctly by jQuery
I am building a Rails (3.0.3) application with some JavaScript using jQuery (1.4.4). On one of the sites I added a click event listener and want to load some content using a AJAX request.

```<code>$(document).ready(function() {
  $("a#settings").click(function() {
    $("div#box").load("settings.js");
    return false;
  });
});
</code>```

When I now open the site "http://localhost:3000/entities/3" where the link with the bound click listener is located and click the link I get a 404 error. This happens because the AJAX request uses the URL "http://localhost:3000/entities/settings.js" and not (as I would exect) "http://localhost:3000/entities/3/settings.js".

答:
There is an answer by some of a very similar but library independent question:

This is how relative paths is supposed to work.

protocol://some.domain.name/dir1/dir2/filename

If you specify only a new filename "foo", you get the same protocol, host and dirs, only the file name is changed:

protocol://some.domain.name/dir1/dir2/foo

If you specify a whole path "/dir3/filename2" you get the same protocol and hostname but with another path:

protocol://some.domain.name/dir3/filename2

You can also specify host name "//another.domain.name/dir5/filename3" and get the same protocol but another host, dir and filename:

protocol://another.domain.name/dir5/filename3

What might be confusing is that a webserver internally can add a / at the end of the url if the specified url points to a directory and not to a file.

protocol://some.domain.name/somename

If "somename" is a directory the webserver translates it to

protocol://some.domain.name/somename/

For reference, see step 6 in section 4 of RFC 1808

Body:
I am building a Rails (3.0.3) application with some JavaScript using jQuery (1.4.4). On one of the sites I added a click event listener and want to load some content using a AJAX request.

$(document).ready(function() {
  $("a#settings").click(function() {
    $("div#box").load("settings.js");
    return false;
  });
});

When I now open the site "http://localhost:3000/entities/3" where the link with the bound click listener is located and click the link I get a 404 error. This happens because the AJAX request uses the URL "http://localhost:3000/entities/settings.js" and not (as I would exect) "http://localhost:3000/entities/3/settings.js".


问:
Set a Property in a ViewModel from Another ViewModel
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

```<code>public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}
</code>```

View model 2: (RouteStopPopOverViewModel)

```<code>public static string RouteName { get; set; }
</code>```

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

答:
here the sample you can achieve your requirement easily with navigation </p>

```<code>public class ViewModelFrom : BaseViewModel
{
    async Task ExecuteCommand()
     {
        string routeName="value to trasfer";
        Navigation.PushAsync(new View(routeName));
     }
}

public partial class View : ContentPage
{
    public View(string routeName)
    {
        InitializeComponent();
        BindingContext = new ViewModelTo(routeName);
     }
}

public class ViewModelTo : BaseViewModel
{
    public string RouteName { get; set; }

    public ViewModelTo(string routeName)
    {
         RouteName=routeName;
    }
}
</code>```

Body:
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}

View model 2: (RouteStopPopOverViewModel)

public static string RouteName { get; set; }

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

Body:
here the sample you can achieve your requirement easily with navigation

public class ViewModelFrom : BaseViewModel
{
    async Task ExecuteCommand()
     {
        string routeName="value to trasfer";
        Navigation.PushAsync(new View(routeName));
     }
}

public partial class View : ContentPage
{
    public View(string routeName)
    {
        InitializeComponent();
        BindingContext = new ViewModelTo(routeName);
     }
}

public class ViewModelTo : BaseViewModel
{
    public string RouteName { get; set; }

    public ViewModelTo(string routeName)
    {
         RouteName=routeName;
    }
}


问:
nosetests config file python
I am working on nosetests. I know that we have to use -s so that stdout will not be captured during execution. Another way is to create nose.cfg file.

Can I know where should I create this file, I tried it in the folder from where I am running nosetests in command window, it didn't work.

Thanks

答:
This error means you need nose testconfig library download nose-testconfig from here:
https://pypi.python.org/pypi/nose-testconfig

or use easyinstall or pip

this will resolve the issue !

Title: nosetests config file python


问:
how to get every instance of a word( i.e alphanumeric) from a string and change it?
I have a string such as:

```<code>{
    props: {
        options: {
            type: Array
        }
    }
}
</code>```

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

```<code>{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}
</code>```

If you have any suggestion don't hesitate to share. Thank you.

答:
```<code>str.replace(/([a-z]+)/ig, "'$1'")
</code>```

This worked for me.

Body:
I have a string such as:

{
    props: {
        options: {
            type: Array
        }
    }
}

Now i want to change props into "props" and option into "option" and similarly every word which this whole string might have.

I am doing this because in the original format JSON.parse() is throwing error as this is not in JSON string which should look like this:

{
    "props": {
        "options": {
            "type": "Array"
        }
    }
}

If you have any suggestion don't hesitate to share. Thank you.

Body:
str.replace(/([a-z]+)/ig, "'$1'")

This worked for me.


问:
How to make a Volley class a public method
I have to call web service in multiple classes I am using Volley. so what should I do in onresponse method to trigger the other class for the response?
I want to make syncData as a generic function for my all classes.

```<code>  public String syncData(Context mContext, String url) {
    try {
        RequestQueue queue = Volley.newRequestQueue(mContext);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    Log.e("Response", "error");
                    //  updateForecastUI(isCentigradeType);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.MY_SOCKET_TIMEOUT_MS,
                Constants.MAX_RETRY,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        jsonObjectRequest.setShouldCache(false);
        queue.add(jsonObjectRequest);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  jsonResponse;
}
</code>```

答:
Create  a interface VolleyResultCallBack

```<code>public interface VolleyResultCallBack {

void onVolleyResultListener(String response, String requestUrl);

void onVolleyErrorListener(VolleyError error);

}
</code>```

make activity implement this interface ,

your method will be like

```<code> public static void syncData(Context mContext, String url,VolleyResultCallBack resultCallBack) {
try {
    RequestQueue queue = Volley.newRequestQueue(mContext);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved
               resultCallBack.onVolleyResultListener(jsonResponse,url);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            try {
                Log.e("Response", "error");
                resultCallBack.onVolleyErrorListener(error);
                //  updateForecastUI(isCentigradeType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
            Constants.MY_SOCKET_TIMEOUT_MS,
            Constants.MAX_RETRY,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    jsonObjectRequest.setShouldCache(false);
    queue.add(jsonObjectRequest);

} catch (Exception e) {
    e.printStackTrace();
}
return  jsonResponse;
}
</code>```

.

In your activity make request like this

```<code>  YourClassName.syncData(this,url,this);
</code>```

you will get responce in  onVolleyResultListener method;

```<code> @Override
 public void onVolleyResultListener(String response, String requestUrl) {

      if(requestUrl.contains(url){  //  required to check because there may be multiple requests in same activity

        //do something with responce
      }
    }
</code>```

handle error in  onVolleyErrorListener

```<code>@Override
public void onVolleyErrorListener(VolleyError error) {

 //do something with error ,may be show a toast

 }
</code>```

Body:
I have to call web service in multiple classes I am using Volley. so what should I do in onresponse method to trigger the other class for the response?
I want to make syncData as a generic function for my all classes.

  public String syncData(Context mContext, String url) {
    try {
        RequestQueue queue = Volley.newRequestQueue(mContext);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    Log.e("Response", "error");
                    //  updateForecastUI(isCentigradeType);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.MY_SOCKET_TIMEOUT_MS,
                Constants.MAX_RETRY,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        jsonObjectRequest.setShouldCache(false);
        queue.add(jsonObjectRequest);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return  jsonResponse;
}

Body:
Create  a interface VolleyResultCallBack

public interface VolleyResultCallBack {

void onVolleyResultListener(String response, String requestUrl);

void onVolleyErrorListener(VolleyError error);

}

make activity implement this interface ,

your method will be like

 public static void syncData(Context mContext, String url,VolleyResultCallBack resultCallBack) {
try {
    RequestQueue queue = Volley.newRequestQueue(mContext);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved
               resultCallBack.onVolleyResultListener(jsonResponse,url);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            try {
                Log.e("Response", "error");
                resultCallBack.onVolleyErrorListener(error);
                //  updateForecastUI(isCentigradeType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
            Constants.MY_SOCKET_TIMEOUT_MS,
            Constants.MAX_RETRY,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    jsonObjectRequest.setShouldCache(false);
    queue.add(jsonObjectRequest);

} catch (Exception e) {
    e.printStackTrace();
}
return  jsonResponse;
}

.

In your activity make request like this

  YourClassName.syncData(this,url,this);

you will get responce in  onVolleyResultListener method;

 @Override
 public void onVolleyResultListener(String response, String requestUrl) {

      if(requestUrl.contains(url){  //  required to check because there may be multiple requests in same activity

        //do something with responce
      }
    }

handle error in  onVolleyErrorListener

@Override
public void onVolleyErrorListener(VolleyError error) {

 //do something with error ,may be show a toast

 }


问:
Element type is invalid when creating DragDropContext
Given the following....

```<code>var root2 = <div />;

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(root2);

ReactDOM.render(root2, document.getElementById('content'));
</code>```

I get...

Warning: React.createElement: type should not be null, undefined,
  boolean, or number. It should be a string (for DOM elements) or a
  ReactClass (for composite components). Check the render method of
  DragDropContext(Component).

and...

Uncaught Error: Element type is invalid: expected a string (for
  built-in components) or a class/function (for composite components)
  but got: object. Check the render method of
  DragDropContext(Component)

The null mentioned in the warning seems to be a result of the following generated code...

```<code>React.createElement(AppDnD, null)
</code>```

How do I fix this?

When did Javascript get so sophisticated?

Libraries are basic...

```<code>   <script src="~/lib/ReactDnD.min.js"></script>
    <script src="~/lib/ReactDnDMultiBackend.min.js"></script>
    <script src="~/lib/RDMBHTML5toTouch.min.js"></script>
</code>```

答:
DragDropContext wants a component rather than an element.

Thus, for example, given...

```<code>class MyComponent extends React.Component {

    render() {

        return (<div />);
    }
};
</code>```

Instead of...

```<code>var root2 = <MyComponent/>;

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(root2);

ReactDOM.render(root2, document.getElementById('content'));
</code>```

... one does...

```<code>var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(MyComponent);

ReactDOM.render(<AppDnD />, document.getElementById('content'));
</code>```

Body:
Given the following....

var root2 =
;

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(root2);

ReactDOM.render(root2, document.getElementById('content'));

I get...

Warning: React.createElement: type should not be null, undefined,
  boolean, or number. It should be a string (for DOM elements) or a
  ReactClass (for composite components). Check the render method of
  DragDropContext(Component).

and...

Uncaught Error: Element type is invalid: expected a string (for
  built-in components) or a class/function (for composite components)
  but got: object. Check the render method of
  DragDropContext(Component)

The null mentioned in the warning seems to be a result of the following generated code...

React.createElement(AppDnD, null)

How do I fix this?

When did Javascript get so sophisticated?

Libraries are basic...

Body:
DragDropContext wants a component rather than an element.

Thus, for example, given...

class MyComponent extends React.Component {

    render() {

        return (<div />);
    }
};

Instead of...

var root2 = <MyComponent/>;

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(root2);

ReactDOM.render(root2, document.getElementById('content'));

... one does...

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(MyComponent);

ReactDOM.render(<AppDnD />, document.getElementById('content'));


问:
SpingBoot Log file missing in deployed war (tomcat)
When I ran with the java -jar command, my LOG configuration came into effect. But when I deployed to an external tomcat container, I found that my LOG configuration was not in effect and the LOG files were lost.

I looked into a lot of questions and answers, found a tomcat LOG covered the default configuration, but I didn't find the way to solve the problem.

Here is my log configuration

```<code>logging.config=classpath:config/logging-config.xml
logging.path=src/main/resources/log
</code>```

答:
This is happening when running in outer tomcat, because the tomcat will set the logging.config properties into the system environment, and will override the spring default logging.config context file.

you can break on

```<code>org.springframework.boot.logging.LoggingApplicationListener#initializeSystem
</code>```

step into the String logConfig = environment.getProperty(CONFIG_PROPERTY);

then you can find the reason.

To solve this, you can run System.setProperty("loggin.config", "you log file") to override tomcat's logging.properties

Body:
When I ran with the java -jar command, my LOG configuration came into effect. But when I deployed to an external tomcat container, I found that my LOG configuration was not in effect and the LOG files were lost.

I looked into a lot of questions and answers, found a tomcat LOG covered the default configuration, but I didn't find the way to solve the problem.

Here is my log configuration

logging.config=classpath:config/logging-config.xml
logging.path=src/main/resources/log

Body:
This is happening when running in outer tomcat, because the tomcat will set the logging.config properties into the system environment, and will override the spring default logging.config context file.

you can break on

org.springframework.boot.logging.LoggingApplicationListener#initializeSystem

step into the String logConfig = environment.getProperty(CONFIG_PROPERTY);

then you can find the reason.

To solve this, you can run System.setProperty("loggin.config", "you log file") to override tomcat's logging.properties


问:
Iterating through HashMap by values
I need to loop through a HashMap, but to give importance to the values' order.
For example, consider the following hash map of <String, Integer>:

```<code>{"dog" : 2, "bird": 3, "cat" : 1}
</code>```

Now, I need to loop through the hasp map in order of ascending values, so that

```<code>for () {
 System.out.println( currentKey );
}
</code>```

will always output

"cat", "dog", "bird"

答:
Another example using Guava:

Pros:

Returns entries (not just keys)

Does not require the keys to be Comparable

```<code>static <K, V>Set<Map.Entry<V, K>>
entriesByValue(Map<K, V> source, Comparator<V> cmp) {
    SortedMap<V, Collection<K>> inverseMap = Maps.newTreeMap(cmp);
    Supplier<Set<K>> setFactory = new Supplier<Set<K>>() {
        public Set<K> get() {
            return Sets.newHashSet();
        }
    };
    SetMultimap<V, K> inverseMM =
        Multimaps.newSetMultimap(inverseMap, setFactory);
    Multimaps.invertFrom(Multimaps.forMap(source), inverseMM);
    return Collections.unmodifiableSet(inverseMM.entries());
}
</code>```

Title: Iterating through HashMap by values

Body:
I need to loop through a HashMap, but to give importance to the values' order.
For example, consider the following hash map of <String, Integer>:

{"dog" : 2, "bird": 3, "cat" : 1}

Now, I need to loop through the hasp map in order of ascending values, so that

for () {
 System.out.println( currentKey );
}

will always output

"cat", "dog", "bird"

Body:
Another example using Guava:

Pros:

Returns entries (not just keys)

Does not require the keys to be Comparable

static <K, V>Set<Map.Entry<V, K>>
entriesByValue(Map<K, V> source, Comparator<V> cmp) {
    SortedMap<V, Collection<K>> inverseMap = Maps.newTreeMap(cmp);
    Supplier<Set<K>> setFactory = new Supplier<Set<K>>() {
        public Set<K> get() {
            return Sets.newHashSet();
        }
    };
    SetMultimap<V, K> inverseMM =
        Multimaps.newSetMultimap(inverseMap, setFactory);
    Multimaps.invertFrom(Multimaps.forMap(source), inverseMM);
    return Collections.unmodifiableSet(inverseMM.entries());
}


问:
How do I loop a HTML name value with PHP
I have a PHP page pulls mobile phones from a database. Depending on how many phones are in the database, the PHP page will determine how many fields to create. I have a session in place to only allow those who are logged in, able to edit and access certain features.

I want the checkbox to update the database with a 1 (as active) and a 0 (as inactive) devices so I will be able to show only those which are active.

Edit: session_start(); is in every page within header.php connected to the top of each page. I have left that out in the code.

phones.php

```<code><?php
    if (isset($_SESSION['u_name'])) {
        echo ' <button type="submit" name="submit"
        form="activeForm">Save</button>';
    }
    for($x = 1; $x <= deviceCount("phones"); $x++) {
?>
    </section>
        <?php
            if (isset($_SESSION['u_name'])) {
        ?>
        <form id="activeForm" method="POST" action="save.php">
            <input type="checkbox" echo ' name="active'.$x.'"';?>>
        </form>
    <?php
        }
    }
    ?>
</code>```

Below is my PHP. I am wanting to check if each check box is selected. The issue I am having is that after the first checkbox is checked, the rest are always not selected.

save.php

```<code><?php

if (isset($_POST['submit'])) {
    include_once 'connect.inc.php';

    $query = "SELECT * FROM phones";
    if ($result=mysqli_query($conn, $query)) {
        // Return the number of rows in result set
        $rowcount=mysqli_num_rows($result);
    }

    for($x = 1; $x < $rowcount + 1; $x++) {
        $select = 'active'.$x;
        if (isset($_POST[$select])) {
            $sql = "UPDATE phones SET active='1' WHERE id=$x";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE phones SET active='0' WHERE id=$x";
            mysqli_query($conn, $sql);
        }
    }
}
</code>```

Let's say I have 4 devices. The first checkbox would be responsive, however, the next 3 would all say not selected.

答:
1.You need to put form code outside of the loop.

2.Use input name as array-type

3.You need to have session_start();

4.Based on array-type name change php code accordingly.

Do like below:-

HTML:-

```<code><form id="activeForm" method="POST" action="save.php">
<?php
    session_start();//needed
    if (isset($_SESSION['u_name'])) {
        for($x = 1; $x <= deviceCount("phones"); $x++) {
?>
            <input type="checkbox" name="active[<?php echo $x;?>]" />
<?php
        }
    }
?>
    <button type="submit" name="submit">Save</button>
</form>
</code>```

PHP:-

```<code><?php

if (isset($_POST['submit'])) {
    include_once 'connect.inc.php';
    foreach($_POST['active'] as $key =>$x) {
        if ($x) {
            $sql = "UPDATE phones SET active='1' WHERE id=$key";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE phones SET active='0' WHERE id=$key";
            mysqli_query($conn, $sql);
        }
    }
}
</code>```

Body:
I have a PHP page pulls mobile phones from a database. Depending on how many phones are in the database, the PHP page will determine how many fields to create. I have a session in place to only allow those who are logged in, able to edit and access certain features.

I want the checkbox to update the database with a 1 (as active) and a 0 (as inactive) devices so I will be able to show only those which are active.

Edit: session_start(); is in every page within header.php connected to the top of each page. I have left that out in the code.

phones.php

<?php
    if (isset($_SESSION['u_name'])) {
        echo ' <button type="submit" name="submit"
        form="activeForm">Save</button>';
    }
    for($x = 1; $x <= deviceCount("phones"); $x++) {
?>

        <?php
            if (isset($_SESSION['u_name'])) {
        ?>
        <form id="activeForm" method="POST" action="save.php">
            <input type="checkbox" echo ' name="active'.$x.'"';?>>
        </form>
    <?php
        }
    }
    ?>

Below is my PHP. I am wanting to check if each check box is selected. The issue I am having is that after the first checkbox is checked, the rest are always not selected.

save.php

<?php

if (isset($_POST['submit'])) {
    include_once 'connect.inc.php';

    $query = "SELECT * FROM phones";
    if ($result=mysqli_query($conn, $query)) {
        // Return the number of rows in result set
        $rowcount=mysqli_num_rows($result);
    }

    for($x = 1; $x < $rowcount + 1; $x++) {
        $select = 'active'.$x;
        if (isset($_POST[$select])) {
            $sql = "UPDATE phones SET active='1' WHERE id=$x";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE phones SET active='0' WHERE id=$x";
            mysqli_query($conn, $sql);
        }
    }
}

Let's say I have 4 devices. The first checkbox would be responsive, however, the next 3 would all say not selected.

Body:
1.You need to put form code outside of the loop.

2.Use input name as array-type

3.You need to have session_start();

4.Based on array-type name change php code accordingly.

Do like below:-

HTML:-

<form id="activeForm" method="POST" action="save.php">
<?php
    session_start();//needed
    if (isset($_SESSION['u_name'])) {
        for($x = 1; $x <= deviceCount("phones"); $x++) {
?>
            <input type="checkbox" name="active[<?php echo $x;?>]" />
<?php
        }
    }
?>
    <button type="submit" name="submit">Save</button>
</form>

PHP:-

<?php

if (isset($_POST['submit'])) {
    include_once 'connect.inc.php';
    foreach($_POST['active'] as $key =>$x) {
        if ($x) {
            $sql = "UPDATE phones SET active='1' WHERE id=$key";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE phones SET active='0' WHERE id=$key";
            mysqli_query($conn, $sql);
        }
    }
}


问:
Is it possible to achieve a <fieldset>-like effect without using the <fieldset> tag?
I personally like the <fieldset> tag because of how it draws a box and puts the <legend> at the top of it, over the border. Like this.

However, the fieldset element was made to organize forms, and using it for general design is no better than using tables for general design. So, my question is... how can I achieve the same result using another tag? The border has to be erased under the <legend> (or whatever other tag will be used), and since there could be a "complex" body background image, I can't afford to just set the background-color of the legend to match the one of the element under.

I'd like it to work without JavaScript, but CSS3 and XML-based formats (such as SVG or XHTML) are fine.

答:
Here a possible solution with a focus on simplicity (if you can loose your requirement for transparent background a bit). No additional elements.

section {
  border: 2px groove threedface;
  padding: 1em;
}

section h2 {
  float: left;
  margin: -1.7em 0 0;
  padding: 0 .5em;
  background: #fff;
  font-size: 1em;
  font-weight: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id=foo>
  <h2>
    Foo
  </h2>
  bar
</section></code>```

Body:
Here a possible solution with a focus on simplicity (if you can loose your requirement for transparent background a bit). No additional elements.

section {
  border: 2px groove threedface;
  padding: 1em;
}

section h2 {
  float: left;
  margin: -1.7em 0 0;
  padding: 0 .5em;
  background: #fff;
  font-size: 1em;
  font-weight: normal;
}

<section id=foo>
  <h2>
    Foo
  </h2>
  bar
</section>


问:
IHostingEnvironment for testing
I'm trying to use the unit test project in ABP 2.0.2 and I get the following error when I run the selected test GetUsers_Test().

```<code>Message: Castle.MicroKernel.Handlers.HandlerException : Can't create component 'imfundoplatform.imfundoplatformCoreModule' as it has dependencies to be satisfied.

'imfundoplatform.imfundoplatformCoreModule' is waiting for the following dependencies:
- Service 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' which was not registered.
</code>```

The constructor for my Core module:

```<code>public imfundoplatformCoreModule(IHostingEnvironment env)
{
    _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
}
</code>```

I cannot figure out how to pass this to the module or get unit tests working. Please help!

答:
you cannot inject IHostingEnvironment ... To get the content root path use;

```<code>Directory.GetCurrentDirectory
</code>```

Title: IHostingEnvironment for testing

Body:
I'm trying to use the unit test project in ABP 2.0.2 and I get the following error when I run the selected test GetUsers_Test().

Message: Castle.MicroKernel.Handlers.HandlerException : Can't create component 'imfundoplatform.imfundoplatformCoreModule' as it has dependencies to be satisfied.

'imfundoplatform.imfundoplatformCoreModule' is waiting for the following dependencies:
- Service 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' which was not registered.

The constructor for my Core module:

public imfundoplatformCoreModule(IHostingEnvironment env)
{
    _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
}

I cannot figure out how to pass this to the module or get unit tests working. Please help!

Body:
you cannot inject IHostingEnvironment ... To get the content root path use;

Directory.GetCurrentDirectory


问:
failed to open a new window after push button pyqt5
i learning pyqt5 and trying to open a new window by click a button from another window. if there are not input() function it will close the open window immediately, so i put input() to keep the window open.  the window will open for long, but then it has stopped working. Can some one help me ? Thank you</p>

```<code>import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App1(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'open window'
        self.left = 60
        self.top = 60
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.show()
        m.getch()
        input()                  '''here is the problem'''

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):

        app1 = QApplication(sys.argv)
        ex1 = App1()
        sys.exit(app1.exec_())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

答:
```<code>import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App1(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'open window'
        self.left = 60
        self.top = 60
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.show()
        input()

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        self.ex1 = App1()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()

    sys.exit(app.exec_())
</code>```

Body:
i learning pyqt5 and trying to open a new window by click a button from another window. if there are not input() function it will close the open window immediately, so i put input() to keep the window open.  the window will open for long, but then it has stopped working. Can some one help me ? Thank you

import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App1(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'open window'
        self.left = 60
        self.top = 60
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.show()
        m.getch()
        input()                  '''here is the problem'''

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):

        app1 = QApplication(sys.argv)
        ex1 = App1()
        sys.exit(app1.exec_())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


问:
Google translate api on android gives error 'GoogleJsonResponseException: 400 Bad Request'
When trying to access google translate api from an android application it gives the following error:

```<code>java.lang.RuntimeException: An error occurred while executing doInBackground()
....
Caused by: com.google.cloud.translate.TranslateException: Invalid Value
...
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"
</code>```

The code inside doInBackground method() is:

```<code> Translate translate = TranslateOptions.newBuilder()
                .setApiKey("myAPI_key").build().getService();

        Translation translation = translate.translate(
                params[0],
                Translate.TranslateOption.sourceLanguage("en"),
                Translate.TranslateOption.targetLanguage("al"));

        return translation.getTranslatedText();                                                }
</code>```

The string I pass is in english. Can anyone help me figuring out this error?
 Thanks in advance.

答:
Your problem is in the line:

```<code>Translate.TranslateOption.targetLanguage("al"));
</code>```

al is not a correct code for any supported language.

You can check the complete list of supported languages in the Google APIs Explorer.

Body:
When trying to access google translate api from an android application it gives the following error:

java.lang.RuntimeException: An error occurred while executing doInBackground()
....
Caused by: com.google.cloud.translate.TranslateException: Invalid Value
...
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
} ],
"message" : "Invalid Value"

The code inside doInBackground method() is:

 Translate translate = TranslateOptions.newBuilder()
                .setApiKey("myAPI_key").build().getService();

        Translation translation = translate.translate(
                params[0],
                Translate.TranslateOption.sourceLanguage("en"),
                Translate.TranslateOption.targetLanguage("al"));

        return translation.getTranslatedText();                                                }

The string I pass is in english. Can anyone help me figuring out this error?
 Thanks in advance.

Body:
Your problem is in the line:

Translate.TranslateOption.targetLanguage("al"));

al is not a correct code for any supported language.

You can check the complete list of supported languages in the Google APIs Explorer.


问:
Android calendar app crashes after creating a new event
I am adding a new event to the calendar using this piece of code.

```<code>    ContentResolver cr = context.getContentResolver();
    ContentValues values = new ContentValues();
    values.put(Events.DTSTART, event.getStartTime());
    values.put(Events.DTEND, event.getEndTime());
    values.put(Events.TITLE, event.getSubject());
    values.put(Events.EVENT_LOCATION, event.getLocation());
    values.put(Events.DESCRIPTION, event.getDescription());
    values.put(Events.CALENDAR_ID, calendarId);
    values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    Uri uri = cr.insert(Events.CONTENT_URI, values);
</code>```

When the piece of code runs it doesn't seem to error at all. However when I open the calendar using the default Android calendar app, it crashes when I try to view the added event.

Logcat comes back with this error

```<code>01-15 21:57:24.091: E/AndroidRuntime(19125): android.database.sqlite.SQLiteException:
unknown error (code 0): Unable to convert BLOB to string
</code>```

I would imagine that I am doing something wrong when entering the event. Any ideas?

Edit:

This is the dump of the values

01-15 22:39:47.561: I/System.out(25804): Values: calendar_id=2 eventLocation=fndn title=dndbdb dtstart=1421386255183 dtend=1421389801672 description=fnfbd eventTimezone=America/New_York

答: Code is correct for adding event. To resolve the issue, either put all the source code or put break point for debugging to analyze where the issue is rising. As far as my knowledge, you are trying to save some thing in sqllite database after event or before event placing and that is where error is occurring because the value you are passing is not according to the datatype defined for the variable in database. </p>

Body:
I am adding a new event to the calendar using this piece of code.

    ContentResolver cr = context.getContentResolver();
    ContentValues values = new ContentValues();
    values.put(Events.DTSTART, event.getStartTime());
    values.put(Events.DTEND, event.getEndTime());
    values.put(Events.TITLE, event.getSubject());
    values.put(Events.EVENT_LOCATION, event.getLocation());
    values.put(Events.DESCRIPTION, event.getDescription());
    values.put(Events.CALENDAR_ID, calendarId);
    values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    Uri uri = cr.insert(Events.CONTENT_URI, values);

When the piece of code runs it doesn't seem to error at all. However when I open the calendar using the default Android calendar app, it crashes when I try to view the added event.

Logcat comes back with this error

01-15 21:57:24.091: E/AndroidRuntime(19125): android.database.sqlite.SQLiteException:
unknown error (code 0): Unable to convert BLOB to string

I would imagine that I am doing something wrong when entering the event. Any ideas?

Edit:

This is the dump of the values

01-15 22:39:47.561: I/System.out(25804): Values: calendar_id=2 eventLocation=fndn title=dndbdb dtstart=1421386255183 dtend=1421389801672 description=fnfbd eventTimezone=America/New_York


问:
cannot find symbol class NotificationManagerCompat
I am trying to build a notification method that would result in a notification appearing on the locked screen when a particular beacon is detected.  My understanding is that I need to include .setVisibility(0) in the following code:

```<code>public void showNotification(Beacon beacon) {

    Resources r = getResources();
    int random = (int)System.currentTimeMillis();
    Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(android.R.drawable.ic_popup_reminder)
            .setContentTitle("Beacons Found")
            .setContentText(beacon.getID().toString())
            .setVisibility(0)  // allow notification to appear on locked screen
            .setAutoCancel(true)
            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(random, notification);

}
</code>```

I have the above code, but when I run it it says "cannot find symbol variable SetVisibility".  I have done some research online and it seems I need to import this:

```<code> import android.support.v4.app.NotificationManagerCompat;
</code>```

But if I include this import statement, it would say "cannot find symbol class NotificationManagerCompat"

What should I do?  I have already installed Android Support Repository SDK and have the "android-support-v4.jar in the libs folder of the project

答:
Maybe you have this error come up, because you added a new module to your project.

To fix it, change minSdkVersion, targetSdkVersion, buildToolsVersion, and compileSdkVersion to match the build.gradle in your original module.

After that set minifyEnabled to false.

What it actually fixed it for me (while using Android Studio 3.0.1) was setting facebook to

```<code>compile 'com.facebook.android:facebook-android-sdk:4.26.0'
</code>```

Also check your other libs and dependencies and your build file.

My current build file:

```<code>allprojects {
    repositories {
        jcenter()
        maven  {
            url "http://repo1.maven.org/maven2"
        }
        // maven  {
        //    url 'https://maven.google.com'
        // }
        // since Android Studio 3.0.0
        // or google()
        flatDir {
            dirs 'libs'
        }
    }
}
</code>```

Body:
I am trying to build a notification method that would result in a notification appearing on the locked screen when a particular beacon is detected.  My understanding is that I need to include .setVisibility(0) in the following code:

public void showNotification(Beacon beacon) {

    Resources r = getResources();
    int random = (int)System.currentTimeMillis();
    Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(android.R.drawable.ic_popup_reminder)
            .setContentTitle("Beacons Found")
            .setContentText(beacon.getID().toString())
            .setVisibility(0)  // allow notification to appear on locked screen
            .setAutoCancel(true)
            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(random, notification);

}

I have the above code, but when I run it it says "cannot find symbol variable SetVisibility".  I have done some research online and it seems I need to import this:

 import android.support.v4.app.NotificationManagerCompat;

But if I include this import statement, it would say "cannot find symbol class NotificationManagerCompat"

What should I do?  I have already installed Android Support Repository SDK and have the "android-support-v4.jar in the libs folder of the project

Body:
Maybe you have this error come up, because you added a new module to your project.

To fix it, change minSdkVersion, targetSdkVersion, buildToolsVersion, and compileSdkVersion to match the build.gradle in your original module.

After that set minifyEnabled to false.

What it actually fixed it for me (while using Android Studio 3.0.1) was setting facebook to

compile 'com.facebook.android:facebook-android-sdk:4.26.0'

Also check your other libs and dependencies and your build file.

My current build file:

allprojects {
    repositories {
        jcenter()
        maven  {
            url "http://repo1.maven.org/maven2"
        }
        // maven  {
        //    url 'https://maven.google.com'
        // }
        // since Android Studio 3.0.0
        // or google()
        flatDir {
            dirs 'libs'
        }
    }
}


问:
Android Toast showing too late after clicking on a button
Please i need your help !!

when i finished my Android app i discovered that all my Toast in the app doesn't show at the moment when i click on the button but too late!

i didn't know why !
and i didn't know which part of code to screen to you !

this some of code :

```<code>envoyer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
                v.startAnimation(buttonClick);

                if (nom_compte.getText().toString().equals("") || num_compte.getText().toString().equals("") || num_tel.getText().toString().equals("") || (dropdown.getSelectedItem().toString().equals("Votre banque..")) ) {
                    Toast.makeText(Get_My_Money_Activity.this, "remplir tous les champs !", Toast.LENGTH_SHORT).show();
                }else{
                    MyAsyncTaskresources2 attemptLogin2= new MyAsyncTaskresources2();
                    attemptLogin2.execute("http://example.com/demandes_de_paiement.php?id_user="+session.getId()+"&nom_compte="+URLEncoder.encode(nom_compte.getText().toString())+"&num_compte="+URLEncoder.encode(num_compte.getText().toString())+"&num_tel="+URLEncoder.encode(num_tel.getText().toString())+"&nom_banque="+URLEncoder.encode(dropdown.getSelectedItem().toString()));
                }

            }
        });
</code>```

答:
ok i solved the problem.

it was in my service notification where i put a Toast empty and who run every 2 sec so block the background for the other Toast.

Body:
Please i need your help !!

when i finished my Android app i discovered that all my Toast in the app doesn't show at the moment when i click on the button but too late!

i didn't know why !
and i didn't know which part of code to screen to you !

this some of code :

envoyer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
                v.startAnimation(buttonClick);

                if (nom_compte.getText().toString().equals("") || num_compte.getText().toString().equals("") || num_tel.getText().toString().equals("") || (dropdown.getSelectedItem().toString().equals("Votre banque..")) ) {
                    Toast.makeText(Get_My_Money_Activity.this, "remplir tous les champs !", Toast.LENGTH_SHORT).show();
                }else{
                    MyAsyncTaskresources2 attemptLogin2= new MyAsyncTaskresources2();
                    attemptLogin2.execute("http://example.com/demandes_de_paiement.php?id_user="+session.getId()+"&nom_compte="+URLEncoder.encode(nom_compte.getText().toString())+"&num_compte="+URLEncoder.encode(num_compte.getText().toString())+"&num_tel="+URLEncoder.encode(num_tel.getText().toString())+"&nom_banque="+URLEncoder.encode(dropdown.getSelectedItem().toString()));
                }

            }
        });