问:
Custom CheckBoxPreference, how to disable title and summary from clicking
I hate the regular CheckBoxPreference because you can click anywhere on the preference and toggle the value.  I'm trying to create a custom CheckBoxPreference where I can allow ONLY the checkbox to be clicked, and ignore the title or summary.  However, I can't seem to figure this out.

My custom CheckBoxPreference looks like the standard form:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/talkButtonText"
        android:layout_width="0dp"
        android:layout_weight="85"
        android:layout_height="fill_parent"
        android:orientation="vertical">

    <TextView
        android:id="@android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="5dp"
        android:gravity="left"
        android:textColor="#FFFFFF"
        android:textSize="24sp" />

    <TextView
        android:id="@android:id/summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+android:id/title"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="2dp"
        android:gravity="left"
        android:textColor="#c0c0c0"
        android:textSize="14sp" />

</LinearLayout>

<CheckBox
    android:id="@+android:id/checkbox"
    android:layout_width="0dp"
    android:layout_weight="15"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:focusable="false"
    android:clickable="false"
    android:layout_alignParentRight="true"
    android:layout_margin="16dp"/>

</LinearLayout>
</code>```

Currently, this functions exactly like the standard CheckBoxPreference, where clicking anywhere on the entire width changes the check box value.  Is there any simply way to disable the title and summary from being clicked?

答: Remove the clickable/focusable=false from the check box and add it to the linear layout. </p>

Body:
I hate the regular CheckBoxPreference because you can click anywhere on the preference and toggle the value.  I'm trying to create a custom CheckBoxPreference where I can allow ONLY the checkbox to be clicked, and ignore the title or summary.  However, I can't seem to figure this out.

My custom CheckBoxPreference looks like the standard form:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/talkButtonText"
        android:layout_width="0dp"
        android:layout_weight="85"
        android:layout_height="fill_parent"
        android:orientation="vertical">

    <TextView
        android:id="@android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="5dp"
        android:gravity="left"
        android:textColor="#FFFFFF"
        android:textSize="24sp" />

    <TextView
        android:id="@android:id/summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+android:id/title"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="2dp"
        android:gravity="left"
        android:textColor="#c0c0c0"
        android:textSize="14sp" />

</LinearLayout>

<CheckBox
    android:id="@+android:id/checkbox"
    android:layout_width="0dp"
    android:layout_weight="15"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:focusable="false"
    android:clickable="false"
    android:layout_alignParentRight="true"
    android:layout_margin="16dp"/>

</LinearLayout>

Currently, this functions exactly like the standard CheckBoxPreference, where clicking anywhere on the entire width changes the check box value.  Is there any simply way to disable the title and summary from being clicked?


来源: stackexchange

问:
Swagger Schema error should NOT have additional properties
I am trying to create swagger json and trying to check it's validity in
http://editor.swagger.io

Upon validating the json, the above mentioned editor gives the following error:

```<code>Schema error should NOT have additional properties
additionalProperty: components
Jump to line 0
</code>```

If for some reason I can't define an element named components at root level where i am going to have some sort of json schema, what is the right way to do a $ref on the schema for requestBody for an API operation as I intend to do as seen in my example below. Also, do you see anything wrong with my swagger json ?

My swagger json for swagger2.0 look like this.

```<code>{
    "swagger": "2.0",
    "info": {
        "version": "1.0",
        "title": "My swagger API",
        "contact": {
            "name": "myName",
            "email": "abc@gmail.com"
        }
    },
    "host": "localhost:1234",
    "basePath": "/",
    "tags": [{
        "name": "someTagName",
        "description": "this is a try"
    }],
    "components":{"schemas": {"myEndPoint": ""}},
    "paths": {
        "/myEndPoint": {
            "post": {
                "tags": ["some-tag"],
                "summary": "myEndPoint endpoint will give you something",
                "description": "some description will go here",
                "operationId": "getMyEndPoint",
                "consumes": ["application/json"],
                "produces": ["application/json"],
                "parameters": [{
                    "in": "body",
                    "name": "somePayload",
                    "description": "somePayload is what this is",
                    "required": true,
                    "schema": {
                        "$ref": "#components/schemas/myEndPoint"
                    }
                },
                {
                    "in": "header",
                    "name": "Authorization",
                    "description": "auth token goes here",
                    "required": true,
                    "type": "string"
                }],
                "responses": {
                    "200": {
                        "description": "Success",
                        "schema": {
                            "type": "string"
                        }
                    },
                    "400": {
                        "description": "Bad Request"
                    }
                }
            }
        }
    }
}
</code>```

答:
You are mixing up OpenAPI 3.0 and 2.0 syntax. The components keyword is used in OpenAPI 3.0. In OpenAPI/Swagger 2.0, reusable schemas live under definitions:

```<code>"definitions": {
  "myEndPoint": {
    ...
  }
}
</code>```

Make sure to also change the $ref to

```<code>"$ref": "#/definitions/myEndPoint"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create swagger json and trying to check it's validity in
http://editor.swagger.io

Upon validating the json, the above mentioned editor gives the following error:

Schema error should NOT have additional properties
additionalProperty: components
Jump to line 0

If for some reason I can't define an element named components at root level where i am going to have some sort of json schema, what is the right way to do a $ref on the schema for requestBody for an API operation as I intend to do as seen in my example below. Also, do you see anything wrong with my swagger json ?

My swagger json for swagger2.0 look like this.

{
    "swagger": "2.0",
    "info": {
        "version": "1.0",
        "title": "My swagger API",
        "contact": {
            "name": "myName",
            "email": "abc@gmail.com"
        }
    },
    "host": "localhost:1234",
    "basePath": "/",
    "tags": [{
        "name": "someTagName",
        "description": "this is a try"
    }],
    "components":{"schemas": {"myEndPoint": ""}},
    "paths": {
        "/myEndPoint": {
            "post": {
                "tags": ["some-tag"],
                "summary": "myEndPoint endpoint will give you something",
                "description": "some description will go here",
                "operationId": "getMyEndPoint",
                "consumes": ["application/json"],
                "produces": ["application/json"],
                "parameters": [{
                    "in": "body",
                    "name": "somePayload",
                    "description": "somePayload is what this is",
                    "required": true,
                    "schema": {
                        "$ref": "#components/schemas/myEndPoint"
                    }
                },
                {
                    "in": "header",
                    "name": "Authorization",
                    "description": "auth token goes here",
                    "required": true,
                    "type": "string"
                }],
                "responses": {
                    "200": {
                        "description": "Success",
                        "schema": {
                            "type": "string"
                        }
                    },
                    "400": {
                        "description": "Bad Request"
                    }
                }
            }
        }
    }
}

Body:
You are mixing up OpenAPI 3.0 and 2.0 syntax. The components keyword is used in OpenAPI 3.0. In OpenAPI/Swagger 2.0, reusable schemas live under definitions:

"definitions": {
  "myEndPoint": {
    ...
  }
}

Make sure to also change the $ref to

"$ref": "#/definitions/myEndPoint"


问:
Fill vector with sequence
Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

```<code>sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19
</code>```

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

答:
The reason why you have NAs in the test vector is that you assign the first, third, fifth, seventh, etc element in the test vector to be 1, 3, 5, 7 etc...

I am still not very clear what you are trying to do, but one solution is that you can remove all the NAs after the for loop.

```<code>sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
  test[j] = j
}
test
# [1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19
test <- test[-c(which(is.na(test)))]
test
# [1]  1  3  5  7  9 11 13 15 17 19
</code>```

As @PoGibas suggested, this also works if you want to remove NAs:

```<code>test <- na.omit(test)
test
# [1]  1  3  5  7  9 11 13 15 17 19
</code>```

Title: Fill vector with sequence

Body:
Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

Body:
The reason why you have NAs in the test vector is that you assign the first, third, fifth, seventh, etc element in the test vector to be 1, 3, 5, 7 etc...

I am still not very clear what you are trying to do, but one solution is that you can remove all the NAs after the for loop.

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
  test[j] = j
}
test
# [1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19
test <- test[-c(which(is.na(test)))]
test
# [1]  1  3  5  7  9 11 13 15 17 19

As @PoGibas suggested, this also works if you want to remove NAs:

test <- na.omit(test)
test
# [1]  1  3  5  7  9 11 13 15 17 19


问:
let image shrink and replace by another image and then scroll through

html, body{
  margin: 0;
  height: 100%;
}

.sky,.water,.underwater{
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.sky{
  background-image: url(https://i.stack.imgur.com/18r3B.jpg);
  height: 100%;
}

.water{
  background-image: url(https://i.stack.imgur.com/BfgRt.jpg);
  height: 100%;
}

.underwater{
background-image: url(https://i.stack.imgur.com/5LCuq.jpg);
height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="sky"></div>
  <div class="water"></div>
  <div class="underwater"></div></code>```

I want this image to be the first thing (full screen) you see when you open the website. I have the sky and the water as seperate images.
If you scroll down, I want 'the water' image to shrink in height so it looks like your view goes down while it gets replaced by under water  (that wasn't visible yet) that's located under it.
When the 'under the water' image reaches the top of the water image / the bottom of the sky image, I want the sky image just to scroll up together with the 'under water' image.

I had difficulties with explaining this haha but i hope you understand.
Thanks for helping!

答:
You could show us some of the work you already tried, it will help to make your question clearer.

Anyway, is something like that a good start?

.top-contain {
  min-height: 100vh;
  background: teal;
}

.sky {
  background: url('https://i.stack.imgur.com/18r3B.jpg') center fixed;
  background-size: cover;
  height: 50vh;
}

.water {
  background: url('https://i.stack.imgur.com/BfgRt.jpg') center;
  background-size: cover;
  height: 50vh;
}

.underwater {
  background: url('https://cdn.pixabay.com/photo/2013/02/20/10/32/wallpaper-83671_960_720.jpg');
  background-size: cover;
  height: 100vh
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top-contain">
  <div class="sky"></div>
  <div class="water"></div>
</div>
<div class="underwater"></div></code>```

Body:
html, body{
  margin: 0;
  height: 100%;
}

.sky,.water,.underwater{
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.sky{
  background-image: url(https://i.stack.imgur.com/18r3B.jpg);
  height: 100%;
}

.water{
  background-image: url(https://i.stack.imgur.com/BfgRt.jpg);
  height: 100%;
}

.underwater{
background-image: url(https://i.stack.imgur.com/5LCuq.jpg);
height: 100%;
}

I want this image to be the first thing (full screen) you see when you open the website. I have the sky and the water as seperate images.
If you scroll down, I want 'the water' image to shrink in height so it looks like your view goes down while it gets replaced by under water  (that wasn't visible yet) that's located under it.
When the 'under the water' image reaches the top of the water image / the bottom of the sky image, I want the sky image just to scroll up together with the 'under water' image.

I had difficulties with explaining this haha but i hope you understand.
Thanks for helping!

Body:
You could show us some of the work you already tried, it will help to make your question clearer.

Anyway, is something like that a good start?

.top-contain {
  min-height: 100vh;
  background: teal;
}

.sky {
  background: url('https://i.stack.imgur.com/18r3B.jpg') center fixed;
  background-size: cover;
  height: 50vh;
}

.water {
  background: url('https://i.stack.imgur.com/BfgRt.jpg') center;
  background-size: cover;
  height: 50vh;
}

.underwater {
  background: url('https://cdn.pixabay.com/photo/2013/02/20/10/32/wallpaper-83671_960_720.jpg');
  background-size: cover;
  height: 100vh
}

<div class="top-contain">
  <div class="sky"></div>
  <div class="water"></div>
</div>
<div class="underwater"></div>


问:
How to retrieve an array from an AJAX call?
I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :

```<code>$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
                        });
</code>```

Here is the method that is called :

```<code><?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');

    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array.
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo $data; //returning the array
}
</code>```

Thanks

答:
Problem

You are trying to return am array. But as AJAX calls works on HTTP protocol, you can transfer only text, normally. So your ajaxmethod.php will print the array and the rendered page i.e. the text will be returned as it is displayed, not an array.

Solution

Convert the array into a JSON object using json_encode() (PHP) andreturn that. Then decode it on the page that made the ajax call, using JSON.parse() (JavaScript). This will give an array.

Code

```<code>$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
   var array = JSON.parse(data); //This is the array you want
});
</code>```

...

```<code><?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');

    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array.
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo json_encode($data) //returning the array
}
</code>```

Body:
I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :

$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
                        });

Here is the method that is called :

<?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');

    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array.
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo $data; //returning the array
}

Thanks

Body:
Problem

You are trying to return am array. But as AJAX calls works on HTTP protocol, you can transfer only text, normally. So your ajaxmethod.php will print the array and the rendered page i.e. the text will be returned as it is displayed, not an array.

Solution

Convert the array into a JSON object using json_encode() (PHP) andreturn that. Then decode it on the page that made the ajax call, using JSON.parse() (JavaScript). This will give an array.

Code

$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
   var array = JSON.parse(data); //This is the array you want
});

...

<?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');

    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array.
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo json_encode($data) //returning the array
}


问:
Social Network PHP/MySQL Structure
I want to create a social media site. I'm just planning it out at the moment, i'm thinking first to log the user in by username/password combo, checking against a mysql db and seeing if they exist. Thats simple enough. But i'm asking is, like Facebook, for a "Bio" page, would you put stuff like "select from friends where user_id = $user_id", that sort of thing? So do i use the same user_id over the whole page for selecting comments, contact info, friends, pictures, likes, dislikes? Is this right or is this poor application structure?</p>

答:
I think you ahve a long way to go.

Please dont take this the wrong way but you seem to lack the required skills to manually build such a platform.

If you had it in you to build a social network site you would understand authentications systems down to a tee, but you seem to lack that.

What i would suggest is that you use a custom open source framework specifically built for social interactions such as facebook.

Here a few to get you started

Elgg - Open Source Social Networking Engine

SocialEngine (Paid)

Anahita Engine (NEW!!)

Title: Social Network PHP/MySQL Structure

ContentLicense: CC BY-SA 2.5


问:
Error no queue in vhost on application startup
I'm trying to start a Spring Boot application which has RabbitMQ configured by this configuration class:

```<code>@Configuration
public class RabbitConfig implements RabbitListenerConfigurer {

    public static final String AMQP_EXCHANGE_NAME = "test-queue";

    @Bean
    public Exchange accessExchange() {
        return new DirectExchange(AMQP_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(AMQP_EXCHANGE_NAME);
    }

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public MappingJackson2MessageConverter consumerJackson2MessageConverter() {
        return new MappingJackson2MessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public DefaultMessageHandlerMethodFactory messageHandlerMethodFactory() {
        DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
        factory.setMessageConverter(consumerJackson2MessageConverter());
        return factory;
    }

    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
        registrar.setMessageHandlerMethodFactory(messageHandlerMethodFactory());
    }
</code>```

But I'm getting the error no queue 'test-queue' in vhost '/':

```<code>Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'test-queue' in vhost '/', class-id=50, method-id=10)
    at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:509) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:340) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:162) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:109) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:643) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:47) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:581) ~[amqp-client-4.2.0.jar:4.2.0]
    ... 1 common frames omitted
</code>```

This problem only occurs when I have the following listener defined:

```<code>    @Transactional
    @RabbitListener(queues = RabbitConfig.AMQP_EXCHANGE_NAME)
    public void doSomething(TestDTO dto) {
        ...
    }
</code>```

It seems that I'm trying to consume from the queue, but the queue where not created. If I create the queue through the RabbitMQ Management interface, the error does not occurs.

Is there a way to automatically create this queue, so I do not get this error?

答:
You don't show your Queue bean. You also don't seem to have a RabbitAdmin in your configuration (required for auto declaration of queues, exchanges, bindings).

See Configuring the Broker.

Body:
I'm trying to start a Spring Boot application which has RabbitMQ configured by this configuration class:

@Configuration
public class RabbitConfig implements RabbitListenerConfigurer {

    public static final String AMQP_EXCHANGE_NAME = "test-queue";

    @Bean
    public Exchange accessExchange() {
        return new DirectExchange(AMQP_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(AMQP_EXCHANGE_NAME);
    }

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public MappingJackson2MessageConverter consumerJackson2MessageConverter() {
        return new MappingJackson2MessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public DefaultMessageHandlerMethodFactory messageHandlerMethodFactory() {
        DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
        factory.setMessageConverter(consumerJackson2MessageConverter());
        return factory;
    }

    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
        registrar.setMessageHandlerMethodFactory(messageHandlerMethodFactory());
    }

But I'm getting the error no queue 'test-queue' in vhost '/':

Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'test-queue' in vhost '/', class-id=50, method-id=10)
    at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:509) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:340) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:162) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:109) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:643) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:47) ~[amqp-client-4.2.0.jar:4.2.0]
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:581) ~[amqp-client-4.2.0.jar:4.2.0]
    ... 1 common frames omitted

This problem only occurs when I have the following listener defined:

    @Transactional
    @RabbitListener(queues = RabbitConfig.AMQP_EXCHANGE_NAME)
    public void doSomething(TestDTO dto) {
        ...
    }

It seems that I'm trying to consume from the queue, but the queue where not created. If I create the queue through the RabbitMQ Management interface, the error does not occurs.

Is there a way to automatically create this queue, so I do not get this error?

ContentLicense: CC BY-SA 4.0


问:
json.loads -> TypeError: the JSON object must be str, not 'dict'
I am using the Python (version: 3.4.4) Pyramid framework to receive a json request and convert the received json to a python object using json.loads. When using TestApp to unit test the app like listed below, it all works fine, however, when using through Apache mod_wsgi I do receive the following error in json.loads(...)

TypeError: the JSON object must be str, not 'dict'

Any idea why?

The view code:

```<code>@view_config(route_name='api.analysis', request_method='POST', renderer='json')
def fetch_my_info(request):
  data = json.loads(request.json_body, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
  ...
</code>```

The test code:

```<code>  self.testApp = TestApp(app)
  response = self.testApp.post_json('/v1/info/analysis', params={"id", "123"})
  ...
</code>```

答: request.json_body has already decoded the body into a python object for you. If you wish to decode it yourself then you should use the raw body via loads(request.body.decode(request.charset), ...).

Body:
I am using the Python (version: 3.4.4) Pyramid framework to receive a json request and convert the received json to a python object using json.loads. When using TestApp to unit test the app like listed below, it all works fine, however, when using through Apache mod_wsgi I do receive the following error in json.loads(...)

TypeError: the JSON object must be str, not 'dict'

Any idea why?

The view code:

@view_config(route_name='api.analysis', request_method='POST', renderer='json')
def fetch_my_info(request):
  data = json.loads(request.json_body, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
  ...

The test code:

  self.testApp = TestApp(app)
  response = self.testApp.post_json('/v1/info/analysis', params={"id", "123"})
  ...


问:
Node.js for lua?
I've been playing around with node.js (nodejs) for the past few day and it is fantastic. As far as I can tell, lua doesn't have a similar integration of libev and libio which let's one avoid almost any blocking calls and interact with the network and the filesystem in an asynchronous manner.

I'm slowly porting my java implementation to nodejs, but I'm shocked that luajit is much faster than v8 JavaScript AND uses far less memory!

I imagine writing my server in such an environment (very fast and responsive, very low memory usage, very expressive) will improve my project immensly.

Being new to lua, I'm just not sure if such a thing exists.  I'll appreciate any pointers.

Thanks

答:
Looks like the following is exactly what I was looking for:
LuaNode https://github.com/ignacio/LuaNode</p>

Title: Node.js for lua?


答:
It's not easy to determine what exactly you mean or you're having trouble with without code to look at. I'm including the T-SQL Code for you'll need to get one row per barcode and also how many duplicates exist per barcode for barcodes that are duplicated.

```<code>WITH ProductsCTE AS
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY Barcode ORDER BY Barcode) Instance, *
    FROM
        dbo.Products
)
SELECT * FROM ProductsCTE WHERE ProductsCTE.Instance = 1;
</code>```

The above code snippet will only get 1 row per unique barcode. So if you can load your products from that query you'll have no duplicates as far as the barcode is concerned.

For determining how many entries you have per barcode, consider the following code.

```<code>SELECT
    p.Barcode, COUNT(*) NumberOfEntries
FROM
    dbo.Products p
GROUP BY
    p.Barcode
HAVING -- You can leave the HAVING clause out if you want to include unique ones
    COUNT(*) > 1
</code>```

Title: sql select allColumns with (no duplicates One Colume) also return count

Body:
I need some help with the query,

I have a products Table.
I need to select all columns (No Duplicates for 'Barcode')
also I need to know how many duplicates were found for each 'barcode'...?

Heres What i have:

ID-----BarCode------Date------ProductType------Status------Serial ...etc.....

1------BarAA---------Jan1------Simple-------------Saleble------843573857

2------BarBB--------Jan2------Unqie---------------Saleble------87686585647

3------BarCC--------Jan9------Unqie---------------Saleble------456365677

4------BarCC--------Jan5------Unqie---------------Saleble------3415435437

5------BarCC--------Jan7------Unqie---------------Saleble------fdgsfdg4t

6------BarDD--------Jan6------Unqie---------------Saleble------435tergdf

7------BarDD--------Jan9------Unqie---------------Saleble------mgdnfdfsg

8------BarDD--------Jan4------Unqie---------------Saleble------sdfwr534ew

I need:

count----ID-----BarCode------Date------ProductType------Status------Serial ...etc.....

1---------1------BarAA---------Jan1------Simple-------------Saleble------843573857

1---------2------BarBB--------Jan2------Unqie---------------Saleble------87686585647

3---------3------BarCC--------Jan9------Unqie---------------Saleble------456365677

3---------6------BarDD--------Jan6------Unqie---------------Saleble------435tergdf

Body:
It's not easy to determine what exactly you mean or you're having trouble with without code to look at. I'm including the T-SQL Code for you'll need to get one row per barcode and also how many duplicates exist per barcode for barcodes that are duplicated.

WITH ProductsCTE AS
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY Barcode ORDER BY Barcode) Instance, *
    FROM
        dbo.Products
)
SELECT * FROM ProductsCTE WHERE ProductsCTE.Instance = 1;

The above code snippet will only get 1 row per unique barcode. So if you can load your products from that query you'll have no duplicates as far as the barcode is concerned.

For determining how many entries you have per barcode, consider the following code.

SELECT
    p.Barcode, COUNT(*) NumberOfEntries
FROM
    dbo.Products p
GROUP BY
    p.Barcode
HAVING -- You can leave the HAVING clause out if you want to include unique ones
    COUNT(*) > 1


问:
Can I change the High res icon after release
Can I change the application high res icon (512x512) after I published the app into PROD or ALPHA?

I haven't found any info on this so far in Android dev guides !

答:
Sure you can. You can change it at any time.
       android:label and android:logo attributes can be changed at any time from your manifest.xml

Also read this post.
Can I change my android app icon and name in later release


问:
Why shouldn't you use import all in ES6
So I recently started learning react and noticed that all the documentation has imports that look like else:

```<code>import { Apples, Bananas, Oranges } from 'fruits';
</code>```

But while studying react I found that this syntax works just as well:

```<code>import * as Fruits from 'fruits';
</code>```

My Question: Is there any performance loss or logical conflict with using the import all syntax?

If there is not then I will just keep using that syntax. I would rather be a little more verbose and not have to worry about making sure everything has been imported.

答:
It would be better to use the first way. At least for one thing: Always write explicitly what you want to use. It's a best practice in all framework / language.

If you have some tree-shaking, some unused module won't be loaded and everything should be good (like @zerkms said).
But it's in the best world case, even the best tree shaking isn't perfect and you could have some import still being imported even if you don't use them.
If your project is 'small' it should be ok. If in your project you load hundreds stuff, it could be a little bit different.

And when you will build your project, you will loose time with the tree-shaking analysis too.

So just because you don't want to "loose time by writing two words" you will loose time on every build and maybe have a performance impact

Title: Why shouldn't you use import all in ES6

Body:
So I recently started learning react and noticed that all the documentation has imports that look like else:

import { Apples, Bananas, Oranges } from 'fruits';

But while studying react I found that this syntax works just as well:

import * as Fruits from 'fruits';

My Question: Is there any performance loss or logical conflict with using the import all syntax?

If there is not then I will just keep using that syntax. I would rather be a little more verbose and not have to worry about making sure everything has been imported.


问:
Access Django Website from another computer on same network
As the title says I want to access my django website on a different computer on the same network.

Both are running windows 10 connected to the same network. The host is connect through wifi and the other through ethernet cable.

I've changed the allowed host to my ip address.

```<code>ALLOWED_HOSTS = ['71.89.113.52', 'localhost', '127.0.0.1']
</code>```

And ran the the server.

```<code>(VIRTEN) C:\Users\HP\Desktop\BBTennis\VIRTEN\src>python manage.py 0.0.0.0:8000
</code>```

But I still can't access it on the other computer. When I go to 71.89.113.52:8000 or 0.0.0.0:8000, I get the message, This site can't be reached.

If possible, please present an answer with every direction I should take such as how to configure my network settings or django changes I must make.

答:
check both are on same network

on PC1 windows go to cmd and type ipconfig and get IP-1 address

PC1 : python manage.py runserver 0.0.0.0:8000

go to other PC2 on same network and type IP-1_Address:8000

Body:
As the title says I want to access my django website on a different computer on the same network.

Both are running windows 10 connected to the same network. The host is connect through wifi and the other through ethernet cable.

I've changed the allowed host to my ip address.

ALLOWED_HOSTS = ['71.89.113.52', 'localhost', '127.0.0.1']

And ran the the server.

(VIRTEN) C:\Users\HP\Desktop\BBTennis\VIRTEN\src>python manage.py 0.0.0.0:8000

But I still can't access it on the other computer. When I go to 71.89.113.52:8000 or 0.0.0.0:8000, I get the message, This site can't be reached.

If possible, please present an answer with every direction I should take such as how to configure my network settings or django changes I must make.


问:
Can comments be used in JSON?
Can I use comments inside a JSON file? If so, how?</p>

答:
The Dojo Toolkit JavaScript toolkit (at least as of version 1.4), allows you to include comments in your JSON. The comments can be of /* */ format. Dojo Toolkit consumes the JSON via the dojo.xhrGet() call.

Other JavaScript toolkits may work similarly.

This can be helpful when experimenting with alternate data structures (or even data lists) before choosing a final option.

OwnerDisplayName: Michael Gundlach

Title: Can comments be used in JSON?

LastEditorDisplayName: Jeff Atwood


问:
R conditional subset gives odd output with no warnings
I'm using the following code to return a subset of data with the following conditions:

sample_id's contain "BLUE"

result_value field > result_limit (these two columns contain only numbers)

```<code>table1 <- subset(table1, grepl("*BLUE", sample_id) & (result_value > result_limit))
</code>```

At first I was getting a bad output (no warnings, but records that didn't follow the second condition), then I realized the result_value & result_limit columns were classified as "character", and not "numeric". It worked fine after reclassifying them as numeric. My question is, shouldn't R be returning a warning since I was performing a calculation on non-numeric fields before it returns a funky output? And does anyone know what odd things it might be doing when performing this test on character fields?

答:
Comparing character is posibble. For example</p>

```<code>> 'A' < 'a'
[1] FALSE
> 'a' < 'b'
[1] TRUE
> 'a' > 'b'
[1] FALSE
> '1' > '2'
[1] FALSE
> '1b' > '1a'
[1] TRUE
### check that
> '12311231' > '543242'
[1] FALSE
</code>```

Body:
I'm using the following code to return a subset of data with the following conditions:

sample_id's contain "BLUE"

result_value field > result_limit (these two columns contain only numbers)

table1 <- subset(table1, grepl("*BLUE", sample_id) & (result_value > result_limit))

At first I was getting a bad output (no warnings, but records that didn't follow the second condition), then I realized the result_value & result_limit columns were classified as "character", and not "numeric". It worked fine after reclassifying them as numeric. My question is, shouldn't R be returning a warning since I was performing a calculation on non-numeric fields before it returns a funky output? And does anyone know what odd things it might be doing when performing this test on character fields?

Body:
Comparing character is posibble. For example

> 'A' < 'a'
[1] FALSE
> 'a' < 'b'
[1] TRUE
> 'a' > 'b'
[1] FALSE
> '1' > '2'
[1] FALSE
> '1b' > '1a'
[1] TRUE
### check that
> '12311231' > '543242'
[1] FALSE


问:
Update Empty Table with Records from a View
I am trying to update an empty table I just created ([LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116] t1) with records from a view ([LA_Temp].[dbo].[vClaim] t2).  I know the update statement isn't working because of the join.  Since t1 is a new (empty) table, I won't return any results because of the join.  What is the best way to accomplish this task?  I know I am missing something simple.

```<code>Update [LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116] --empty table

Set [Claim_Sys_ICN] = t2.ClaimID,
Claim_Line_Number = ClaimLine,
MCO_Claim_Status = Case When ClaimStatus = 'PAID' Then 'P'
                    When ClaimStatus = 'ADJUCATED' Then 'A'
                    When ClaimStatus = 'DENIED' Then 'D'
                    When ClaimStatus = 'REVERSED' Then 'R'
                    When ClaimStatus = 'VOID' Then 'V' End,
Patient_Account_Number = CarrierMemID,
MCO_Paid_Date = PaidDate,
Paid_Provider_NPI = PayToNPI,
Procedure_Code = ProcCode,
Procedure_Code_Modifier_1 = Modifier,
Procedure_Code_Modifier_2 = Modifier2,
Procedure_Code_Modifier_3 = Modifier3,
Procedure_Code_Modifier_4 = Modifier4,
Service_Provider_NPI =  RenderingNPI,
HDR_Clm_Paid_Amount = AmountPaid

FROM [LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116] t1  --empty table

LEFT JOIN [LA_Temp].[dbo].[vClaim] t2 on --need records from this view
t1.[Claim_Sys_ICN] = t2.ClaimID

Where PaidDate Between '12/1/2016' and '12/31/2016'
</code>```

Same idea using INSERT INTO...

```<code>INSERT INTO [LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116]
([Claim_Sys_ICN], Claim_Line_Number,
MCO_Claim_Status, Patient_Account_Number, MCO_Paid_Date, Paid_Provider_NPI,
Procedure_Code, Procedure_Code_Modifier_1, Procedure_Code_Modifier_2,
Procedure_Code_Modifier_3, Procedure_Code_Modifier_4,
Service_Provider_NPI, HDR_Clm_Paid_Amount)

Select ClaimID, ClaimLine, Case When ClaimStatus = 'PAID' Then 'P'
                    When ClaimStatus = 'ADJUCATED' Then 'A'
                    When ClaimStatus = 'DENIED' Then 'D'
                    When ClaimStatus = 'REVERSED' Then 'R'
                    When ClaimStatus = 'VOID' Then 'V' End,
CarrierMemID, PaidDate, PayToNPI, ProcCode, Modifier, Modifier2, Modifier3,
Modifier4, RenderingNPI, AmountPaid

FROM [LA_Temp].[dbo].[vClaim]

Where PaidDate Between '12/1/2016' and '12/31/2016'
</code>```

答: Do an INSERT instead of an UPDATE.</p>

Body:
I am trying to update an empty table I just created ([LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116] t1) with records from a view ([LA_Temp].[dbo].[vClaim] t2).  I know the update statement isn't working because of the join.  Since t1 is a new (empty) table, I won't return any results because of the join.  What is the best way to accomplish this task?  I know I am missing something simple.

Update [LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116] --empty table

Set [Claim_Sys_ICN] = t2.ClaimID,
Claim_Line_Number = ClaimLine,
MCO_Claim_Status = Case When ClaimStatus = 'PAID' Then 'P'
                    When ClaimStatus = 'ADJUCATED' Then 'A'
                    When ClaimStatus = 'DENIED' Then 'D'
                    When ClaimStatus = 'REVERSED' Then 'R'
                    When ClaimStatus = 'VOID' Then 'V' End,
Patient_Account_Number = CarrierMemID,
MCO_Paid_Date = PaidDate,
Paid_Provider_NPI = PayToNPI,
Procedure_Code = ProcCode,
Procedure_Code_Modifier_1 = Modifier,
Procedure_Code_Modifier_2 = Modifier2,
Procedure_Code_Modifier_3 = Modifier3,
Procedure_Code_Modifier_4 = Modifier4,
Service_Provider_NPI =  RenderingNPI,
HDR_Clm_Paid_Amount = AmountPaid

FROM [LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116] t1  --empty table

LEFT JOIN [LA_Temp].[dbo].[vClaim] t2 on --need records from this view
t1.[Claim_Sys_ICN] = t2.ClaimID

Where PaidDate Between '12/1/2016' and '12/31/2016'

Same idea using INSERT INTO...

INSERT INTO [LA_Temp].[dbo].[LA_MCO_EQR_MED_201612_20171116]
([Claim_Sys_ICN], Claim_Line_Number,
MCO_Claim_Status, Patient_Account_Number, MCO_Paid_Date, Paid_Provider_NPI,
Procedure_Code, Procedure_Code_Modifier_1, Procedure_Code_Modifier_2,
Procedure_Code_Modifier_3, Procedure_Code_Modifier_4,
Service_Provider_NPI, HDR_Clm_Paid_Amount)

Select ClaimID, ClaimLine, Case When ClaimStatus = 'PAID' Then 'P'
                    When ClaimStatus = 'ADJUCATED' Then 'A'
                    When ClaimStatus = 'DENIED' Then 'D'
                    When ClaimStatus = 'REVERSED' Then 'R'
                    When ClaimStatus = 'VOID' Then 'V' End,
CarrierMemID, PaidDate, PayToNPI, ProcCode, Modifier, Modifier2, Modifier3,
Modifier4, RenderingNPI, AmountPaid

FROM [LA_Temp].[dbo].[vClaim]

Where PaidDate Between '12/1/2016' and '12/31/2016'

Body: Do an INSERT instead of an UPDATE.


问:
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex - Android Studio 3.0 stable
I made:

In "Settings"->"Android SDK"->"SDK Tools" Google Play services is checked and installed v.46

Removed folder /.gradle

"Clean Project"

"Rebuild Project

Error is:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code>```

Project build.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

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

App build.gradle

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

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.asanquran.mnaum.quranasaanurdutarjuma"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 3
        versionName "1.3"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-ads:11.4.2'
    compile 'com.github.barteksc:android-pdf-viewer:2.3.0'
    compile 'org.apache.commons:commons-io:1.3.2'
    compile 'com.google.firebase:firebase-ads:11.4.2'
    compile 'com.google.firebase:firebase-messaging:11.4.2'
    compile 'com.google.firebase:firebase-storage:11.4.2'
    apply plugin: 'com.google.gms.google-services'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
I got the same problem, adding sourceCompatibility and targetCompatibility to my build.gradle helped me:

```<code>android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}
</code>```

Body:
I made:

In "Settings"->"Android SDK"->"SDK Tools" Google Play services is checked and installed v.46

Removed folder /.gradle

"Clean Project"

"Rebuild Project

Error is:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Project build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

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

App build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.asanquran.mnaum.quranasaanurdutarjuma"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 3
        versionName "1.3"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'

    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-ads:11.4.2'
    compile 'com.github.barteksc:android-pdf-viewer:2.3.0'
    compile 'org.apache.commons:commons-io:1.3.2'
    compile 'com.google.firebase:firebase-ads:11.4.2'
    compile 'com.google.firebase:firebase-messaging:11.4.2'
    compile 'com.google.firebase:firebase-storage:11.4.2'
    apply plugin: 'com.google.gms.google-services'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Body:
I got the same problem, adding sourceCompatibility and targetCompatibility to my build.gradle helped me:

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}


问:
Objective-C How to get unicode character
I want to get unicode code point for a given unicode character in Objective-C. NSString said it internal use UTF-16 encoding and said,

The NSString class has two primitive methods—length and characterAtIndex:—that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0.

That seems assume characterAtIndex method is unicode aware. However it return unichar is a 16 bits unsigned int type.

```<code>- (unichar)characterAtIndex:(NSUInteger)index
</code>```

The questions are:

Q1: How it present unicode code point above UFFFF?

Q2: If Q1 make sense, is there method to get unicode code point for a given unicode character in Objective-C.

Thx.

答:
The short answer to "Q1: How it present unicode code point above UFFFF?" is: You need to be UTF16 aware and correctly handle Surrogate Code Points.  The info and links below should give you pointers and example code that allow you to do this.

The NSString documentation is correct.  However, while you said "NSString said it internal use UTF-16 encoding", it's more accurate to say that the public / abstract interface for NSString is UTF16 based.  The difference is that this leaves the internal representation of a string a private implementation detail, but the public methods such as characterAtIndex: and length are always in UTF16.

The reason for this is it tends to strike the best balance between older ASCII-centric and Unicode aware strings, largely due to the fact that Unicode is a strict superset of ASCII (ASCII uses 7 bits, for 128 characters, which are mapped to the first 128 Unicode Code Points).

To represent Unicode Code Points that are > U+FFFF, which obviously exceeds what can be represented in a single UTF16 Code Unit, UTF16 uses special Surrogate Code Points to form a Surrogate Pair, which when combined together form a Unicode Code Point > U+FFFF.  You can find details about this at:

Unicode UTF FAQ - What are surrogates?

Unicode UTF FAQ - What’s the algorithm to convert from UTF-16 to character codes?

Although the official Unicode UTF FAQ - How do I write a UTF converter? now recommends the use of International Components for Unicode, it used to recommend some code officially sanctioned and maintained by Unicode.  Although no longer directly available from Unicode.org, you can still find copies of the "no longer official" example code in various open-source projects: ConvertUTF.c and ConvertUTF.h.  If you need to roll your own, I'd strongly recommend examining this code first, as it is well tested.

Body:
I want to get unicode code point for a given unicode character in Objective-C. NSString said it internal use UTF-16 encoding and said,

The NSString class has two primitive methods—length and characterAtIndex:—that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0.

That seems assume characterAtIndex method is unicode aware. However it return unichar is a 16 bits unsigned int type.

- (unichar)characterAtIndex:(NSUInteger)index

The questions are:

Q1: How it present unicode code point above UFFFF?

Q2: If Q1 make sense, is there method to get unicode code point for a given unicode character in Objective-C.

Thx.


问:
libgit2sharp - Git - cannot push non-fastforwardable reference
I'm using libgit2sharp to push files to a repository once they have been generated.

```<code>using (var repo = new Repository(RepositoryPath))
{
    // Stage the file
    Commands.Stage(repo, "*");

    // Create the committer's signature and commit
    Signature author = new Signature("translator", "example.com", DateTime.Now);
    Signature committer = author;

    // Commit to the repository
    Commit commit = repo.Commit($"Resx files updated {DateTime.Now}", author, committer);

    Remote remote = repo.Network.Remotes["origin"];
    var options = new PushOptions
    {
        CredentialsProvider = (_url, _user, _cred) =>
           new UsernamePasswordCredentials
           {
               Username = _settings.GitUserName,
               Password = _settings.GitPassword
           }
     };
     repo.Network.Push(remote, @"refs/heads/master", options);
 }
</code>```

This has been working great for some time and pushing to repository without issue, however I am now getting the below error message for some files and the push does not occur for any files.

Error message (from server log):

```<code>Message: cannot push non-fastforwardable reference
StackTrace:  at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
   at LibGit2Sharp.Core.Proxy.git_remote_push(RemoteHandle remote, IEnumerable`1 refSpecs, GitPushOptions opts)
   at LibGit2Sharp.Network.Push(Remote remote, IEnumerable`1 pushRefSpecs, PushOptions pushOptions)
   at LibGit2Sharp.Network.Push(Remote remote, String pushRefSpec, PushOptions pushOptions)
   at Westwind.Globalization.Core.Utilities.DbResXConverter.SyncToGit(String resourceSet)
</code>```

I have searched for error but cannot find anything that covers this? Also as this repository is sat on a Azure web server I assume I would have run any Git commands via libgit2sharp C# code as I would not have permissions to run command line Git commands.

Any help appreciated on this one.

答:
If your changes are not fast-forwardable from the remote's branch, then that means that somebody else has updated the repository's branch.  You need to fetch from the remote, merge with the remote's branch, and then you can push.

Alternately, you can force push by prefixing your refspec with a + (eg, +refs/heads/master).

Body:
I'm using libgit2sharp to push files to a repository once they have been generated.

using (var repo = new Repository(RepositoryPath))
{
    // Stage the file
    Commands.Stage(repo, "*");

    // Create the committer's signature and commit
    Signature author = new Signature("translator", "example.com", DateTime.Now);
    Signature committer = author;

    // Commit to the repository
    Commit commit = repo.Commit($"Resx files updated {DateTime.Now}", author, committer);

    Remote remote = repo.Network.Remotes["origin"];
    var options = new PushOptions
    {
        CredentialsProvider = (_url, _user, _cred) =>
           new UsernamePasswordCredentials
           {
               Username = _settings.GitUserName,
               Password = _settings.GitPassword
           }
     };
     repo.Network.Push(remote, @"refs/heads/master", options);
 }

This has been working great for some time and pushing to repository without issue, however I am now getting the below error message for some files and the push does not occur for any files.

Error message (from server log):

Message: cannot push non-fastforwardable reference
StackTrace:  at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
   at LibGit2Sharp.Core.Proxy.git_remote_push(RemoteHandle remote, IEnumerable`1 refSpecs, GitPushOptions opts)
   at LibGit2Sharp.Network.Push(Remote remote, IEnumerable`1 pushRefSpecs, PushOptions pushOptions)
   at LibGit2Sharp.Network.Push(Remote remote, String pushRefSpec, PushOptions pushOptions)
   at Westwind.Globalization.Core.Utilities.DbResXConverter.SyncToGit(String resourceSet)

I have searched for error but cannot find anything that covers this? Also as this repository is sat on a Azure web server I assume I would have run any Git commands via libgit2sharp C# code as I would not have permissions to run command line Git commands.

Any help appreciated on this one.


问:
Is there a bokeh version of pandas autocorrelation plot method?
Let's say we have a time series object which is called "series". I know that its very easy to use autocorrelation_plot() method to plot Lag and Autocorrelation dimensions of series object.

Here is the code:

```<code>from matplotlib import pyplot
from pandas.tools.plotting import autocorrelation_plot
autocorrelation_plot(series)
pyplot.show()
</code>```

Here is the pandas plot:

Is there a way to get the same plot using bokeh server ?

答:
I am basically copying Ayberk's answer, but turning it into a function

```<code>def acf(series):
    n = len(series)
    data = np.asarray(series)
    mean = np.mean(data)
    c0 = np.sum((data - mean) ** 2) / float(n)
    def r(h):
        acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
        return round(acf_lag, 3)
    x = np.arange(n) # Avoiding lag 0 calculation
    acf_coeffs = pd.Series(map(r, x)).round(decimals = 3)
    acf_coeffs = acf_coeffs + 0
    return acf_coeffs

def significance(series):
    n = len(series)
    z95 = 1.959963984540054 / np.sqrt(n)
    z99 = 2.5758293035489004 / np.sqrt(n)
    return(z95,z99)

def bok_autocor(series):
    x = pd.Series(range(1, len(series)+1), dtype = float)
    z95, z99 = significance(series)
    y = acf(series)
    p = figure(title='Time Series Auto-Correlation', plot_width=1000,
               plot_height=500, x_axis_label="Lag", y_axis_label="Autocorrelation")
    p.line(x, z99, line_dash='dashed', line_color='grey')
    p.line(x, z95, line_color = 'grey')
    p.line(x, y=0.0, line_color='black')
    p.line(x, z99*-1, line_dash='dashed', line_color='grey')
    p.line(x, z95*-1, line_color = 'grey')
    p.line(x, y, line_width=2)
    return p

show(series.pipe(bok_autocor))
</code>```

I found the acf here, which states it is from the pandas autocorrelation_plot function, and looks close to what Ayberk used as well.

Body:
Let's say we have a time series object which is called "series". I know that its very easy to use autocorrelation_plot() method to plot Lag and Autocorrelation dimensions of series object.

Here is the code:

from matplotlib import pyplot
from pandas.tools.plotting import autocorrelation_plot
autocorrelation_plot(series)
pyplot.show()

Here is the pandas plot:

Is there a way to get the same plot using bokeh server ?

Body:
I am basically copying Ayberk's answer, but turning it into a function

def acf(series):
    n = len(series)
    data = np.asarray(series)
    mean = np.mean(data)
    c0 = np.sum((data - mean) ** 2) / float(n)
    def r(h):
        acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
        return round(acf_lag, 3)
    x = np.arange(n) # Avoiding lag 0 calculation
    acf_coeffs = pd.Series(map(r, x)).round(decimals = 3)
    acf_coeffs = acf_coeffs + 0
    return acf_coeffs

def significance(series):
    n = len(series)
    z95 = 1.959963984540054 / np.sqrt(n)
    z99 = 2.5758293035489004 / np.sqrt(n)
    return(z95,z99)

def bok_autocor(series):
    x = pd.Series(range(1, len(series)+1), dtype = float)
    z95, z99 = significance(series)
    y = acf(series)
    p = figure(title='Time Series Auto-Correlation', plot_width=1000,
               plot_height=500, x_axis_label="Lag", y_axis_label="Autocorrelation")
    p.line(x, z99, line_dash='dashed', line_color='grey')
    p.line(x, z95, line_color = 'grey')
    p.line(x, y=0.0, line_color='black')
    p.line(x, z99*-1, line_dash='dashed', line_color='grey')
    p.line(x, z95*-1, line_color = 'grey')
    p.line(x, y, line_width=2)
    return p

show(series.pipe(bok_autocor))

I found the acf here, which states it is from the pandas autocorrelation_plot function, and looks close to what Ayberk used as well.


问:
Convert CSV format as text in email body
I have a cron job which when run gives me a csv file which looks like below:

I have another cron job where I am trying to display the csv data directly in an email body and the output of that is as below:

As you can see above, the output from email is distorted and looks ugly. WHat changes should I make for the email format to be similar with the csv format?.

I am using the below bash commands in my cron :

```<code>EMAILBODY="$(${RUNDIR}/${DEV1} ${FILELOCATION} ${FILENAME})"

echo "$EMAILBODY" | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com
</code>```

I tried the below change to the script:

```<code>echo "$EMAILBODY" | column -s, -t | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com
</code>```

and now I see this in the email:

As you can notice, the format is little better than before. But how can I align the data perfectly with the headers?

答: I've used TAB delimited fields in email bodies, it makes it a bit more human readable. Personally though I like to send the actual csv file as an attachment so it can be opened and manipulated by a spreadsheet program. I'm usually not emailing the info to myself and the receiving end is usually just a basic Windows user. Optionally there is a great perl module that allows you to write a real excel file too, which can give some great looking results. Excel::Writer::XLSX</p>

Body:
I have a cron job which when run gives me a csv file which looks like below:

I have another cron job where I am trying to display the csv data directly in an email body and the output of that is as below:

As you can see above, the output from email is distorted and looks ugly. WHat changes should I make for the email format to be similar with the csv format?.

I am using the below bash commands in my cron :

EMAILBODY="$(${RUNDIR}/${DEV1} ${FILELOCATION} ${FILENAME})"

echo "$EMAILBODY" | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com

I tried the below change to the script:

echo "$EMAILBODY" | column -s, -t | mailx -r ${SENDER} -s "Alerts Email for $(date +%Y-%m-%d_%H:%M)" abcd@xyz.com

and now I see this in the email:

As you can notice, the format is little better than before. But how can I align the data perfectly with the headers?


问:
Angular ng build brakes the lazy loading
I have an app with the lazy loading configure and with ng serve is working but when i do ng build then stop working and im not receiving any error.

Is there any process im missing ? i even read the angular official docs and does not seem to be missing anything.

I install the app with angular CLI 'ng new project-x'. i have the minimum libraries.

Here is my package.json:

```<code>{
  "name": "single-boilerplate",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular-redux/store": "^6.5.7",
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "@ngx-translate/core": "^8.0.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "ng2-validation": "^4.2.0",
    "redux": "^3.7.2",
    "rxjs": "^5.4.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.0",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/es6-shim": "^0.31.35",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "^6.0.90",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}
</code>```

This is my main router :

```<code>export const AppRoutes: Routes = [
  {
    path: '',
    component: AppComponent,
    children: [
      { path: '', loadChildren: './components/dashboard/dashboard.module#DashboardModule' }
    ]
  },
  {
    path: '',
    component: AuthComponent,
    children: [
      { path: '', loadChildren: './components/auth/auth.module#AuthModule' }
    ]
  },
  {
    path: '**',
    redirectTo: '404'
  }
];
</code>```

I dont now what is the problem. Have this happend to anyone of you?

答:
Solution 1

Try deleting your package.lock.json (or yarn.lock.json) file, delete your node_modules folder, remove any reference to webpack in your package.json file (you don't appear to have one, but you can't have two versions of webpack installed just the one provided via the CLI), and then run npm install.

A way to check if two version of webpack are installed is by running npm ls webpack, but again you don't appear to have one unless it wasn't saved to your package.json.

I found this solution on Github, and it worked for me, and apparently a couple other posters.

Solution 2

It also appears that some people simply updated to a newer version of 4.x if the above doesn't work.

Body:
I have an app with the lazy loading configure and with ng serve is working but when i do ng build then stop working and im not receiving any error.

Is there any process im missing ? i even read the angular official docs and does not seem to be missing anything.

I install the app with angular CLI 'ng new project-x'. i have the minimum libraries.

Here is my package.json:

{
  "name": "single-boilerplate",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular-redux/store": "^6.5.7",
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "@ngx-translate/core": "^8.0.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "ng2-validation": "^4.2.0",
    "redux": "^3.7.2",
    "rxjs": "^5.4.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.0",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/es6-shim": "^0.31.35",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "^6.0.90",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}

This is my main router :

export const AppRoutes: Routes = [
  {
    path: '',
    component: AppComponent,
    children: [
      { path: '', loadChildren: './components/dashboard/dashboard.module#DashboardModule' }
    ]
  },
  {
    path: '',
    component: AuthComponent,
    children: [
      { path: '', loadChildren: './components/auth/auth.module#AuthModule' }
    ]
  },
  {
    path: '**',
    redirectTo: '404'
  }
];

I dont now what is the problem. Have this happend to anyone of you?


问:
How do I use a MD5 hash (or other binary data) as a key name?
I've been trying to use a MD5 hash as a key name on AppEngine, but the code I wrote raises a UnicodeDecodeError

```<code>from google.appengine.ext import db
import hashlib
key = db.Key.from_path('Post', hashlib.md5('thecakeisalie').digest())
</code>```

I don't want to use hexdigest() as that is not only a kludge, but an inferior one too (base64 would do a better job).

答:
An entity key in App Engine can have either an ID (a 4 byte integer), or a name (500 byte UTF-8 encoded string).

An MD5 digest is 16 bytes of binary data: too large for an integer, (likely to be) invalid UTF-8. Some form of encoding must be used.

If hexdigest() is too verbose at 32 bytes then try base64 at 24 bytes.

Whatever encoding scheme you use will ultimately be converted to UTF-8 by the datastore, so the following, which at first looks like an optimal encoding...

```<code>>>> u = hashlib.md5('thecakeisalie').digest().decode("iso-8859-1")
>>> len(u)
16
</code>```

...when encoded into it's final representation is two bytes longer than the base64 encoding:

```<code>>>> s = u.encode('utf-8')
>>> len(s)
26
</code>```

Body:
I've been trying to use a MD5 hash as a key name on AppEngine, but the code I wrote raises a UnicodeDecodeError

from google.appengine.ext import db
import hashlib
key = db.Key.from_path('Post', hashlib.md5('thecakeisalie').digest())

I don't want to use hexdigest() as that is not only a kludge, but an inferior one too (base64 would do a better job).

Body:
An entity key in App Engine can have either an ID (a 4 byte integer), or a name (500 byte UTF-8 encoded string).

An MD5 digest is 16 bytes of binary data: too large for an integer, (likely to be) invalid UTF-8. Some form of encoding must be used.

If hexdigest() is too verbose at 32 bytes then try base64 at 24 bytes.

Whatever encoding scheme you use will ultimately be converted to UTF-8 by the datastore, so the following, which at first looks like an optimal encoding...

>>> u = hashlib.md5('thecakeisalie').digest().decode("iso-8859-1")
>>> len(u)
16

...when encoded into it's final representation is two bytes longer than the base64 encoding:

>>> s = u.encode('utf-8')
>>> len(s)
26


问:
iOS 11 application crashes when trying to add attachment from camera
I have an application that crashes when the user tries to add an attachment from the camera (however it doesn't crash when they opt to load the attachment from their Photo Library).

Here's the method that gets called when an option (either Camera or Photo Library) is selected:

```<code>    public void AddMedia(UIImagePickerControllerSourceType type)
    {
        _imagePicker = new UIImagePickerController();

        // set our source to the photo library
        _imagePicker.SourceType = type;

        // set what media types
        _imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(type);

        _imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;

        _imagePicker.Canceled += (sender, evt) =>
        {
            Console.WriteLine("picker cancelled");
            _imagePicker.DismissViewController(false, () =>
                {
                });
        };

        //PresentModalViewController is depreciated in iOS6 so we use PresentViewController
        Parent.PresentViewController(_imagePicker, true, null);
    }
</code>```

And this is the line where it crashes:

```<code>        _imagePicker.SourceType = type;
</code>```

Why would it crash when setting it to Camera but not Photo Library? Does it have something to do with how the enum is ordered (Photo Library = 0, Camera = 1, Saved Photos Album = 2)?

答: Are you trying to reproduce it on simulator? Because you don't have an access to camera on it. </p>

Body:
I have an application that crashes when the user tries to add an attachment from the camera (however it doesn't crash when they opt to load the attachment from their Photo Library).

Here's the method that gets called when an option (either Camera or Photo Library) is selected:

    public void AddMedia(UIImagePickerControllerSourceType type)
    {
        _imagePicker = new UIImagePickerController();

        // set our source to the photo library
        _imagePicker.SourceType = type;

        // set what media types
        _imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(type);

        _imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;

        _imagePicker.Canceled += (sender, evt) =>
        {
            Console.WriteLine("picker cancelled");
            _imagePicker.DismissViewController(false, () =>
                {
                });
        };

        //PresentModalViewController is depreciated in iOS6 so we use PresentViewController
        Parent.PresentViewController(_imagePicker, true, null);
    }

And this is the line where it crashes:

        _imagePicker.SourceType = type;

Why would it crash when setting it to Camera but not Photo Library? Does it have something to do with how the enum is ordered (Photo Library = 0, Camera = 1, Saved Photos Album = 2)?


问:
Collect all values from nested array row of specific key
Need to create a list that consists of all values stored in the array row of a specific key (product_id). Currently, doing a print_r of my $bestsellers variable produces the following array:

```<code>Array
  (
    [0] => stdClass Object
        (
            [product_id] => 178
            [order_item_qty] => 9
        )

    [1] => stdClass Object
        (
            [product_id] => 233
            [order_item_qty] => 4
        )

    [2] => stdClass Object
        (
            [product_id] => 179
            [order_item_qty] => 1
        )
  )
</code>```

Other SO answers led me to try:

```<code>$ids = array_column($bestsellers, 'product_id');
</code>```

...but that produced an empty array, I guess because the row I’m trying to grab is nested in there? With that in mind I tried

```<code>foreach($bestsellers as $bestseller) {
    $ids = array_column($bestsellers, 'product_id');
}
</code>```

...which produced no result at all.
Hopefully someone can help clue me in as to where I’m going wrong. Thanks!

答:
For future reference, array_column will work for this in PHP 7, so you must be using PHP 5.

For PHP 7, your code

```<code>$ids = array_column($bestsellers, 'product_id');
</code>```

will do what you want it to.

See the difference here on 3v4l.org.

Body:
Need to create a list that consists of all values stored in the array row of a specific key (product_id). Currently, doing a print_r of my $bestsellers variable produces the following array:

Array
  (
    [0] => stdClass Object
        (
            [product_id] => 178
            [order_item_qty] => 9
        )

    [1] => stdClass Object
        (
            [product_id] => 233
            [order_item_qty] => 4
        )

    [2] => stdClass Object
        (
            [product_id] => 179
            [order_item_qty] => 1
        )
  )

Other SO answers led me to try:

$ids = array_column($bestsellers, 'product_id');

...but that produced an empty array, I guess because the row I’m trying to grab is nested in there? With that in mind I tried

foreach($bestsellers as $bestseller) {
    $ids = array_column($bestsellers, 'product_id');
}

...which produced no result at all.
Hopefully someone can help clue me in as to where I’m going wrong. Thanks!

Body:
For future reference, array_column will work for this in PHP 7, so you must be using PHP 5.

For PHP 7, your code

$ids = array_column($bestsellers, 'product_id');

will do what you want it to.

See the difference here on 3v4l.org.


问:
Is there a way to check for both `null` and `undefined`?
Since TypeScript is strongly-typed, simply using if () {} to check for null and undefined doesn't sound right.

Does TypeScript have any dedicated function or syntax sugar for this?

答:
If you want to pass tslint without setting strict-boolean-expressions to allow-null-union or allow-undefined-union, you need to use isNullOrUndefined from node's util module or roll your own:

```<code>// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword
</code>```

Not exactly syntactic sugar but useful when your tslint rules are strict.

Body:
If you want to pass tslint without setting strict-boolean-expressions to allow-null-union or allow-undefined-union, you need to use isNullOrUndefined from node's util module or roll your own:

// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword

Not exactly syntactic sugar but useful when your tslint rules are strict.


问:
How to get a browser alert message with angularjs and nodemailer
I am trying to get an alert with after sending an email with nodemailer and not just the json response.  Here is what I have so far:

app.js (nodejswith nodemailermodule):

```<code>transporter.sendMail(mailOptions, (error) => {
if (error) {
  res.sendStatus(500)
} else {
  res.sendStatus(200)
}
transporter.close();
});

});
</code>```

angularjs:

```<code>$http.post({
  url: '/contactUs',
  data: '',
}).then(
  function successCallback(response) {
    $scope.alert("Message Sent!!")
  },
  function errorCallback(response) {}
)
</code>```

答:
you'll need to just call alert("Message Sent") instead of $scope.alert("Message Sent").

If you want it to be angularized, you can inject $window and call $window.alert("Message Sent") which will make it easier on you if you're unit testing.

Body:
I am trying to get an alert with after sending an email with nodemailer and not just the json response.  Here is what I have so far:

app.js (nodejswith nodemailermodule):

transporter.sendMail(mailOptions, (error) => {
if (error) {
  res.sendStatus(500)
} else {
  res.sendStatus(200)
}
transporter.close();
});

});

angularjs:

$http.post({
  url: '/contactUs',
  data: '',
}).then(
  function successCallback(response) {
    $scope.alert("Message Sent!!")
  },
  function errorCallback(response) {}
)


问:
Dismiss keyboard in iOS
I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}
</code>```

and also setting a text field input as first responder:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    pressureInput.resignFirstResponder()
}
</code>```

I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.

答:
Did you tried to debug the program to see if the code stops in the function at all(with break point)? Usually this code should work...Check if those textFields are in the super view or in a child view and if they are maybe you should call  self.childView.endEditing(true).

If you really work with multiple textFields maybe you should try IQKeyboardManager library. I use it in all my projects. You can find it here: https://github.com/hackiftekhar/IQKeyboardManager. Simple to use and with good support. Just install it trough cocoa pods, put IQKeyboardManager.sharedManager().enable = true in the AppDelegate and you're ready to go. :)

Title: Dismiss keyboard in iOS

Body:
I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

and also setting a text field input as first responder:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    pressureInput.resignFirstResponder()
}

I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.


问:
Android app crashes when launched in debug mode
When I run in debug mode the app crashes, but when I just run it normally it works.
I think the problem happens when the debugger is attached.

Log:

```<code>A/art: art/runtime/jdwp/jdwp_event.cc:661] Check failed: Thread::Current() != GetDebugThread() (Thread::Current()=0x7f44a18400, GetDebugThread()=0x7f44a18400) Expected event thread
A/art: art/runtime/runtime.cc:422] Runtime aborting...
A/art: art/runtime/runtime.cc:422] Aborting thread:
A/art: art/runtime/runtime.cc:422] "JDWP" prio=5 tid=4 WaitingForDebuggerSend
A/art: art/runtime/runtime.cc:422]   | group="" sCount=0 dsCount=0 obj=0x12c60280 self=0x7f44a18400
A/art: art/runtime/runtime.cc:422]   | sysTid=24137 nice=0 cgrp=default sched=0/0 handle=0x7f4b904450
A/art: art/runtime/runtime.cc:422]   | state=R schedstat=( 132066712 16401043 106 ) utm=9 stm=2 core=3 HZ=100
A/art: art/runtime/runtime.cc:422]   | stack=0x7f4b80a000-0x7f4b80c000 stackSize=1005KB
A/art: art/runtime/runtime.cc:422]   | held mutexes= "abort lock"
A/art: art/runtime/runtime.cc:422]   native: #00 pc 000000000047e2cc  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+220)
A/art: art/runtime/runtime.cc:422]   native: #01 pc 000000000047e2c8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+216)
A/art: art/runtime/runtime.cc:422]   native: #02 pc 0000000000452434  /system/lib64/libart.so (_ZNK3art6Thread9DumpStackERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEbP12BacktraceMap+480)
A/art: art/runtime/runtime.cc:422]   native: #03 pc 00000000004403ac  /system/lib64/libart.so (_ZNK3art10AbortState10DumpThreadERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEPNS_6ThreadE+56)
A/art: art/runtime/runtime.cc:422]   native: #04 pc 0000000000440228  /system/lib64/libart.so (_ZNK3art10AbortState4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+668)
A/art: art/runtime/runtime.cc:422]   native: #05 pc 0000000000433bfc  /system/lib64/libart.so (_ZN3art7Runtime5AbortEPKc+148)
A/art: art/runtime/runtime.cc:422]   native: #06 pc 00000000000e597c  /system/lib64/libart.so (_ZN3art10LogMessageD2Ev+1592)
A/art: art/runtime/runtime.cc:422]   native: #07 pc 00000000002f8458  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState24AcquireJdwpTokenForEventEm+624)
A/art: art/runtime/runtime.cc:422]   native: #08 pc 00000000002f7b1c  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState29SendRequestAndPossiblySuspendEPNS0_9ExpandBufENS0_17JdwpSuspendPolicyEm+248)
A/art: art/runtime/runtime.cc:422]   native: #09 pc 00000000002fcb08  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState16PostClassPrepareEPNS_6mirror5ClassE+1380)
A/art: art/runtime/runtime.cc:422]   native: #10 pc 0000000000124a9c  /system/lib64/libart.so (_ZN3art11ClassLinker11DefineClassEPNS_6ThreadEPKcmNS_6HandleINS_6mirror11ClassLoaderEEERKNS_7DexFileERKNS9_8ClassDefE+804)
A/art: art/runtime/runtime.cc:422]   native: #11 pc 0000000000381d04  /system/lib64/libart.so (_ZN3artL25DexFile_defineClassNativeEP7_JNIEnvP7_jclassP8_jstringP8_jobjectS7_S7_+344)
A/art: art/runtime/runtime.cc:422]   native: #12 pc 00000000001dd40c  /system/framework/arm64/boot-core-libart.oat (???)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexFile.defineClassNative(Native method)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexFile.defineClass(DexFile.java:296)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:289)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexPathList.findClass(DexPathList.java:418)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:54)
A/art: art/runtime/runtime.cc:422]   at com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoader.findClass(IncrementalClassLoader.java:90)
A/art: art/runtime/runtime.cc:422]   at com.android.tools.fd.runtime.IncrementalClassLoader.findClass(IncrementalClassLoader.java:62)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:367)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:367)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
A/art: art/runtime/runtime.cc:422] Dumping all threads without appropriate locks held: thread list lock mutator lock
</code>```

答: Starting crashing only when starting with debugger.  Restarted Android Studio 2.3.2...kept crashing. Runs fine in Run mode.  I put in a Log.d() right after onCreate...and it cleared up the problem!  Go figure!</p>

Body:
When I run in debug mode the app crashes, but when I just run it normally it works.
I think the problem happens when the debugger is attached.

Log:

A/art: art/runtime/jdwp/jdwp_event.cc:661] Check failed: Thread::Current() != GetDebugThread() (Thread::Current()=0x7f44a18400, GetDebugThread()=0x7f44a18400) Expected event thread
A/art: art/runtime/runtime.cc:422] Runtime aborting...
A/art: art/runtime/runtime.cc:422] Aborting thread:
A/art: art/runtime/runtime.cc:422] "JDWP" prio=5 tid=4 WaitingForDebuggerSend
A/art: art/runtime/runtime.cc:422]   | group="" sCount=0 dsCount=0 obj=0x12c60280 self=0x7f44a18400
A/art: art/runtime/runtime.cc:422]   | sysTid=24137 nice=0 cgrp=default sched=0/0 handle=0x7f4b904450
A/art: art/runtime/runtime.cc:422]   | state=R schedstat=( 132066712 16401043 106 ) utm=9 stm=2 core=3 HZ=100
A/art: art/runtime/runtime.cc:422]   | stack=0x7f4b80a000-0x7f4b80c000 stackSize=1005KB
A/art: art/runtime/runtime.cc:422]   | held mutexes= "abort lock"
A/art: art/runtime/runtime.cc:422]   native: #00 pc 000000000047e2cc  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+220)
A/art: art/runtime/runtime.cc:422]   native: #01 pc 000000000047e2c8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+216)
A/art: art/runtime/runtime.cc:422]   native: #02 pc 0000000000452434  /system/lib64/libart.so (_ZNK3art6Thread9DumpStackERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEbP12BacktraceMap+480)
A/art: art/runtime/runtime.cc:422]   native: #03 pc 00000000004403ac  /system/lib64/libart.so (_ZNK3art10AbortState10DumpThreadERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEPNS_6ThreadE+56)
A/art: art/runtime/runtime.cc:422]   native: #04 pc 0000000000440228  /system/lib64/libart.so (_ZNK3art10AbortState4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEE+668)
A/art: art/runtime/runtime.cc:422]   native: #05 pc 0000000000433bfc  /system/lib64/libart.so (_ZN3art7Runtime5AbortEPKc+148)
A/art: art/runtime/runtime.cc:422]   native: #06 pc 00000000000e597c  /system/lib64/libart.so (_ZN3art10LogMessageD2Ev+1592)
A/art: art/runtime/runtime.cc:422]   native: #07 pc 00000000002f8458  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState24AcquireJdwpTokenForEventEm+624)
A/art: art/runtime/runtime.cc:422]   native: #08 pc 00000000002f7b1c  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState29SendRequestAndPossiblySuspendEPNS0_9ExpandBufENS0_17JdwpSuspendPolicyEm+248)
A/art: art/runtime/runtime.cc:422]   native: #09 pc 00000000002fcb08  /system/lib64/libart.so (_ZN3art4JDWP9JdwpState16PostClassPrepareEPNS_6mirror5ClassE+1380)
A/art: art/runtime/runtime.cc:422]   native: #10 pc 0000000000124a9c  /system/lib64/libart.so (_ZN3art11ClassLinker11DefineClassEPNS_6ThreadEPKcmNS_6HandleINS_6mirror11ClassLoaderEEERKNS_7DexFileERKNS9_8ClassDefE+804)
A/art: art/runtime/runtime.cc:422]   native: #11 pc 0000000000381d04  /system/lib64/libart.so (_ZN3artL25DexFile_defineClassNativeEP7_JNIEnvP7_jclassP8_jstringP8_jobjectS7_S7_+344)
A/art: art/runtime/runtime.cc:422]   native: #12 pc 00000000001dd40c  /system/framework/arm64/boot-core-libart.oat (???)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexFile.defineClassNative(Native method)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexFile.defineClass(DexFile.java:296)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:289)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.DexPathList.findClass(DexPathList.java:418)
A/art: art/runtime/runtime.cc:422]   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:54)
A/art: art/runtime/runtime.cc:422]   at com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoader.findClass(IncrementalClassLoader.java:90)
A/art: art/runtime/runtime.cc:422]   at com.android.tools.fd.runtime.IncrementalClassLoader.findClass(IncrementalClassLoader.java:62)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:367)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:367)
A/art: art/runtime/runtime.cc:422]   at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
A/art: art/runtime/runtime.cc:422] Dumping all threads without appropriate locks held: thread list lock mutator lock


问:
SQL Server Create table to autoconvert int -> decimal
I'm not sure if this is possible but here goes.

I have financial data stored in a csv format. The data unfortunately lacks any decimal points in the dollar fields. so $100.00 is stored as '00000010000'. Its also stored as a string. In my current setup I upload the csv file into a staging table with all columns set to varchar(x).

I know that if I try to insert this value into an integer column it will automatically convert it to 10000 of type integer, but that means I am missing my decimal place.

Is there anyway I can create a table such that inserting an integer stored as a string or integer automatically converts it to an decimal with 2 places behind the decimal????

EX: '000010000' -> 100.00

I know I can cast the column to a decimal and divide the existing value by 100.... but this table has 100+ columns with 60+ of them needing to be recast. This is also only table 1 of 6. I want to avoid creating commands to individually changing the relevant columns. Not all columns containing a number need the decimal treatment.

答:
Why not just a basic query? You have to do the math in two steps because '00000010000' is large to fit into a basic numeric. But by multiplying by 1 it will implicitly convert to an int and then it is simple to divide by 100. Notice it needs be 100.0 so it will implicitly convert it to a numeric and not an int. Here are a couple example values.</p>

```<code>select convert(numeric(9, 2), ('00000010000' * 1) / 100.0)
select convert(numeric(9, 2), ('00000010123' * 1) / 100.0)
</code>```

Body:
Why not just a basic query? You have to do the math in two steps because '00000010000' is large to fit into a basic numeric. But by multiplying by 1 it will implicitly convert to an int and then it is simple to divide by 100. Notice it needs be 100.0 so it will implicitly convert it to a numeric and not an int. Here are a couple example values.

select convert(numeric(9, 2), ('00000010000' * 1) / 100.0)
select convert(numeric(9, 2), ('00000010123' * 1) / 100.0)


问:
Compressing Guid based string to write on QR Code
I am developing a phonegap application in html5/javascript. I have a string of around 1000 characters comprising of guids in below format

1=0a0a8907-40b9-4e81-8c4d-d01af26efb78;2=cd4713339;3=Cjdnd;4=19120581-21e5-42b9-b85f-3b8c5b1206d9;5=hdhsfsdfsd;6=30a21580-48f3-40e8-87a3-fa6e39e6412f; ...............

I have to write this particular string into a QR code. Is there any working technique to compress this string and store in QR code. The QR generated by this string is too complex and is not easily read by the QR scanner of mobile phones. Pls suggest the approach to reduce the size of string to around 200-250 character which can be easily read.

Any help is appreciated.

答:
If you have access to a database already, can you create a table to support this?  If so, archive the value and use an ID for QR.

1) Simple schema: ID = bigint with Identity (1000,1) and set as primary key, Value = NVARCHAR(MAX).  Yes this is a bit overkill, so modify to taste.

2) Create a function to add your string value to the table and get the ID back as a string for the QR code.

3) Create another function to return the string value when passed a valid ID number.

Stays below the 200 character limit for a very long time.


问:
Convert serial printing to pdf
I have a lab measurement instrument that upon completing measurement, outputs the result as to a printer. The connection to printer is through an old fashion serial 25 pin port, which most modern printer does not have any longer. The supported driver from the measurement instrument is either Epson or IBM.

I have brought an adapter that converts the 25pins serial to usb.

Question:
In stead of printing to a printer, is it possible to print to my laptop? If yes, which software to use?

Thereafter, I will create a pdf of the print.

答:
I can't recommend a single integrated software product to solve your issue, but I can suggest an approach to devising your own solution.

I suggest breaking the problem into two phases:

Capture the output from the printer to a file via a terminal emulator connected to the virtual serial port. Ultimately, a serial connection just transmits a stream of bytes. A terminal emulator should be able to connect to the virtual serial port offered by the USB adapter, and give you an option to save the received data to a file. You will need to do some research to find a terminal emulator that will serve your needs.

Use a converter application to convert the printer data to PDF. Since it's a driver for an Epson printer, the data stream is most likely formatted as ESC/P, which was their common printer language in the days of serial ports (IBM printers used this language too). I expect the file you saved in step one to be a stream of ESC/P commands; you can probably find an application that can convert it to PDF (or perhaps convert it to Postscript, which can be converted to PDF). Off the top of my head, Ghostscript might do the job (but I have not used it in a while).

Ultimately this is old enough hardware that you will have to handcraft a solution. Hope this helps.

Title: Convert serial printing to pdf