问:
ElasticSearch nested bool queries
I'm using ElasticSearch 5.6. I have following JSON document.

```<code>    {
          "cards": [{
                        "tag_categories": [
                            {
                                "is_sensitive": true,
                                "category": "Users",
                                "tags": [
                                    {
                                        "is_selected": true,
                                        "name": "user1"
                                    },
                                    {
                                        "is_selected": true,
                                        "name": "user2"
                                    },
                                    {
                                        "is_selected": false,
                                        "name": "user3"
                                    }
                                ]
                            }
                        ],
                        "risk": "medium",
                        "position": 1,
                        "placement": 4,
                        "title": "test title",

                    }, ...]
       }
</code>```

I want to return this document if all the given users names and corresponding is_selected value is true.

This is my query.

```<code>{
  "_source": {
    "excludes": ["cards.pages"]
  },
  "query": {
    "bool": {
      "must": [{
        "match": {
          "_all": "hello world"
    }
  }],
  "filter": [{
      "nested": {
        "path": "cards.tag_categories.tags",
        "query": {
          "bool": {
            "must": [
                {
                "bool": {
                  "must": [
                    {
                      "match": {
                        "cards.tag_categories.tags.name": "user2"
                      }
                    },
                    {
                      "match": {
                        "cards.tag_categories.tags.is_selected": true
                      }
                    }

                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {
                      "match": {
                        "cards.tag_categories.tags.name": "user1"
                      }
                    },
                    {
                      "match": {
                        "cards.tag_categories.tags.is_selected": true
                      }
                    }

                  ]
                }
              }

            ]
          }
        }
      }
    },
    {
      "term": {
        "name.keyword": "hello name"
      }
    },
    {
      "term": {
        "title.keyword": "hello title"
      }
    }

  ]
   }
  }
}
</code>```

I have added two child bool queries to match each set of user name and is_selected values. Parent bool query will get the AND and return the document if true.

In the above example query the document should be returned as user1 and user2 match the condition. But it doesn't happen.

If I compare a single user with his is_selected value the document returns. eg: user1.

I will be thankful if anyone can show me where I've made the mistake.

答:
I added separate nested blocks and it worked! </p>

```<code>{
  "_source": {
  "excludes": ["cards.pages"]
 },
 "query": {
"bool": {
  "must": [{
    "match": {
      "_all": "hello world"
    }
  }],
  "filter": [
    {
      "nested": {
        "path": "cards.tag_categories.tags",
        "query": {
          "bool": {
            "must": [
                {
                  "term": {
                    "cards.tag_categories.tags.name.keyword": "user1"
                  }
                },
                {
                  "term": {
                    "cards.tag_categories.tags.is_selected": true
                  }
                }

            ]
          }
        }
      }
    },
    {
      "nested": {
        "path": "cards.tag_categories.tags",
        "query": {
          "bool": {
            "must": [
                {
                  "term": {
                    "cards.tag_categories.tags.name.keyword": "user2"
                  }
                },
                {
                  "term": {
                    "cards.tag_categories.tags.is_selected": true
                  }
                }

            ]
          }
        }
      }
    },

    {
      "term": {
        "name.keyword": "hello name"
      }
    },
    {
      "term": {
        "title.keyword": "hello title"
      }
    }

  ]
}
</code>```

<p>}
}</p>

Title: ElasticSearch nested bool queries

Body:
I'm using ElasticSearch 5.6. I have following JSON document.

    {
          "cards": [{
                        "tag_categories": [
                            {
                                "is_sensitive": true,
                                "category": "Users",
                                "tags": [
                                    {
                                        "is_selected": true,
                                        "name": "user1"
                                    },
                                    {
                                        "is_selected": true,
                                        "name": "user2"
                                    },
                                    {
                                        "is_selected": false,
                                        "name": "user3"
                                    }
                                ]
                            }
                        ],
                        "risk": "medium",
                        "position": 1,
                        "placement": 4,
                        "title": "test title",

                    }, ...]
       }

I want to return this document if all the given users names and corresponding is_selected value is true.

This is my query.

{
  "_source": {
    "excludes": ["cards.pages"]
  },
  "query": {
    "bool": {
      "must": [{
        "match": {
          "_all": "hello world"
    }
  }],
  "filter": [{
      "nested": {
        "path": "cards.tag_categories.tags",
        "query": {
          "bool": {
            "must": [
                {
                "bool": {
                  "must": [
                    {
                      "match": {
                        "cards.tag_categories.tags.name": "user2"
                      }
                    },
                    {
                      "match": {
                        "cards.tag_categories.tags.is_selected": true
                      }
                    }

                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {
                      "match": {
                        "cards.tag_categories.tags.name": "user1"
                      }
                    },
                    {
                      "match": {
                        "cards.tag_categories.tags.is_selected": true
                      }
                    }

                  ]
                }
              }

            ]
          }
        }
      }
    },
    {
      "term": {
        "name.keyword": "hello name"
      }
    },
    {
      "term": {
        "title.keyword": "hello title"
      }
    }

  ]
   }
  }
}

I have added two child bool queries to match each set of user name and is_selected values. Parent bool query will get the AND and return the document if true.

In the above example query the document should be returned as user1 and user2 match the condition. But it doesn't happen.

If I compare a single user with his is_selected value the document returns. eg: user1.

I will be thankful if anyone can show me where I've made the mistake.

Body:
I added separate nested blocks and it worked!

{
  "_source": {
  "excludes": ["cards.pages"]
 },
 "query": {
"bool": {
  "must": [{
    "match": {
      "_all": "hello world"
    }
  }],
  "filter": [
    {
      "nested": {
        "path": "cards.tag_categories.tags",
        "query": {
          "bool": {
            "must": [
                {
                  "term": {
                    "cards.tag_categories.tags.name.keyword": "user1"
                  }
                },
                {
                  "term": {
                    "cards.tag_categories.tags.is_selected": true
                  }
                }

            ]
          }
        }
      }
    },
    {
      "nested": {
        "path": "cards.tag_categories.tags",
        "query": {
          "bool": {
            "must": [
                {
                  "term": {
                    "cards.tag_categories.tags.name.keyword": "user2"
                  }
                },
                {
                  "term": {
                    "cards.tag_categories.tags.is_selected": true
                  }
                }

            ]
          }
        }
      }
    },

    {
      "term": {
        "name.keyword": "hello name"
      }
    },
    {
      "term": {
        "title.keyword": "hello title"
      }
    }

  ]
}

}
}


来源: stackexchange

问:
Express: Do not send response to request
Is it somehow possible in Express to not respond at all? I don’t want to send a 4xx or 5xx in a specific case, but just show the “server did not respond” error (in Chrome it’s the ERR_EMPTY_RESPONSE).

```<code>router.get('/noresponse', (req, res, next) => {
  res.end(); // this will send an empty page with a 200 status
});
</code>```

To clarify: I want a behavior similar to NGINX when “sending” a 444 status. (which does not actually send a 444 to the client, but cancels the request)

答:
For the sake of completeness, here’s a snippet which does what I was initially aiming for:

```<code>router.get('/noresponse', (req, res, next) => {
  res.destroy(null);
});
</code>```

However as I find no documentation about its implications and I do not want to work against any best practices I’ll go for a 4xx response instead.

ContentLicense: CC BY-SA 3.0

Body:
Is it somehow possible in Express to not respond at all? I don’t want to send a 4xx or 5xx in a specific case, but just show the “server did not respond” error (in Chrome it’s the ERR_EMPTY_RESPONSE).

router.get('/noresponse', (req, res, next) => {
  res.end(); // this will send an empty page with a 200 status
});

To clarify: I want a behavior similar to NGINX when “sending” a 444 status. (which does not actually send a 444 to the client, but cancels the request)

Body:
For the sake of completeness, here’s a snippet which does what I was initially aiming for:

router.get('/noresponse', (req, res, next) => {
  res.destroy(null);
});

However as I find no documentation about its implications and I do not want to work against any best practices I’ll go for a 4xx response instead.


问:
Django data logging front end - phidgets
What would the best method be to use Django for creating an application similar to say OpenNMS or any comparable network management tool?

The Django app needs to be constantly polling 1 or more devices, with each device having 1 or more analog and digital inputs.

Basically, how do you integrate the necessary polling functions into a django app, so that when the device(s) sensor(s) are polled, the resulting value is stored in the Django ORM so that the user can then pull up graphs, charts, etc of the data it is logging?

Is Django not the right base for something like this?  The embedded devices I am polling has python APIs to set events handlers or just poll the objects current reading if needed.
(http://www.phidgets.com)

The end goal is that this Django site resides on the PhidgetSBC and can then be easily accessed and controlled via the network.  The polling and storing of the sensor values needs to be running 24/7, unless specifically disabled by the web user via a "device admin area" on the Django site for instance.

I am not worried about charting, controlling devices on the output pins, etc at this time as getting the data into the database reliably is top priority.  I don't think the current python package I created is going to port over to Django well, so I would rather start from scratch and start it right.

Thanks

答:
How you handle data logging really depends on how you want to present the data. However, unless you are only interested in a real time display (i.e. no charting), whatever code which is responsible for the logging will have to run outside the HTTP request/response cycle, and therefore outside of Django.

Probably the most straightforward approach would be to write a separate python script that would run in the background, which would periodically poll the phidget API and dump the data into the DB. A potential major problem with this approach is that the sensor configuration is essentially hard-coded - if you wish to add or remove a sensor, you'll have to change the python script. This may or may not be important to your application.

In order to better integrate the data retrieved by the script into Django, you might create a few models like this:

```<code>class Device(models.Model):
    """A sensor"""
    name = models.CharField(max_length=20)
    ...

class DataPoint(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=10) # whatever is appropriate
    timestamp = models.DateTimeField()
    device = models.ForiegnKey(Device)
</code>```

When you run syncdb, you can see the table names that will be created. It should be something like:

```<code>appname_device
appname_data_point
</code>```

Your background script would then create records in the appname_data_point table, which would then be accessible via the Django ORM.

ContentLicense: CC BY-SA 2.5

Body:
How you handle data logging really depends on how you want to present the data. However, unless you are only interested in a real time display (i.e. no charting), whatever code which is responsible for the logging will have to run outside the HTTP request/response cycle, and therefore outside of Django.

Probably the most straightforward approach would be to write a separate python script that would run in the background, which would periodically poll the phidget API and dump the data into the DB. A potential major problem with this approach is that the sensor configuration is essentially hard-coded - if you wish to add or remove a sensor, you'll have to change the python script. This may or may not be important to your application.

In order to better integrate the data retrieved by the script into Django, you might create a few models like this:

class Device(models.Model):
    """A sensor"""
    name = models.CharField(max_length=20)
    ...

class DataPoint(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=10) # whatever is appropriate
    timestamp = models.DateTimeField()
    device = models.ForiegnKey(Device)

When you run syncdb, you can see the table names that will be created. It should be something like:

appname_device
appname_data_point

Your background script would then create records in the appname_data_point table, which would then be accessible via the Django ORM.


问:
Tooltips not working on IE10
I want to show tooltips on parts of an image. I have this technique where it puts a invisible div on the image with absolute positioning.

```<code><!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<meta http-equiv="X-UA-Compatible" content="IE=10" >
</head>

<body>

    <div style="position:relative;">
        <img src="http://blog.caranddriver.com/wp-content/uploads/2016/11/BMW-M2-lead.jpg"/>
        <div title="HELLO" style="position:absolute; width:100px; height:100px; top:0; left:0;"></div>
    </div>

</body>

</html>
</code>```

but when I hover over, the tooltip does not show.

Does anyone know what's wrong? This same code works on chrome 59.

Thanks

答:
this code seems to be ok on Explorer, Chrome, Firefox and Edge.
img tag has a different behaviour of div tag in Explorer.

<!DOCTYPE html>

        <title>Title of the document</title>
        <meta http-equiv="X-UA-Compatible" content="IE=10">

 ```

Title: Tooltips not working on IE10

Body:
I want to show tooltips on parts of an image. I have this technique where it puts a invisible div on the image with absolute positioning.

<!DOCTYPE html>

<title>Title of the document</title>
<meta http-equiv="X-UA-Compatible" content="IE=10" >

but when I hover over, the tooltip does not show.

Does anyone know what's wrong? This same code works on chrome 59.

Thanks

Body:
this code seems to be ok on Explorer, Chrome, Firefox and Edge.
img tag has a different behaviour of div tag in Explorer.

<!DOCTYPE html>
<html>
    <head>
        <title>Title of the document</title>
        <meta http-equiv="X-UA-Compatible" content="IE=10">
    </head>
    <body>
        <div style="position:relative;">
            <img src="http://blog.caranddriver.com/wp-content/uploads/2016/11/BMW-M2-lead.jpg"/>
            <img style="position:absolute; width:100px; height:100px; top:0; left:0; border-width: 0px;" src="javascript:void(0)" title="Test" alt="">
        </div>
    </body>
</html>


问:
MIDI messages confusion [Python]
I'm trying to get the start and stop times of all the notes from a MIDI file for a piano. From my understanding, there are note_on and note_off events with delta time in ticks, which I can use to get the start and stop times. However, what I'm confused with is with the time variable. When I just have a simple program such as

```<code>for msg in mid:
    print(msg.dict())
</code>```

I get outputs such as:

```<code>{'note': 60, 'velocity': 61, 'type': 'note_on', 'channel': 0, 'time': 0.0016891895833333333}
{'note': 64, 'velocity': 57, 'type': 'note_on', 'channel': 0, 'time': 0.20270275}
{'note': 67, 'velocity': 56, 'type': 'note_on', 'channel': 0, 'time': 0.20270275}
{'note': 67, 'velocity': 0, 'type': 'note_on', 'channel': 0, 'time': 0.20270275}
{'note': 72, 'velocity': 60, 'type': 'note_on', 'channel': 0, 'time': 0}
{'type': 'set_tempo', 'tempo': 794702, 'time': 0.20101356041666665}
</code>```

From my understanding, this means that the notes have delta times that are all less than 1 tick, which seems completely wrong to me. However, what I like is that doing it this way has the note_on, note_off, and set_tempo events in the order that they occur. When I instead do

```<code>mid.print_tracks()
</code>```

I get an output such as:

```<code><meta message set_tempo tempo=794702 time=480>
<meta message set_tempo tempo=810811 time=120>
<meta message set_tempo tempo=800000 time=960>
<meta message set_tempo tempo=810811 time=360>
...
=== Track 1
<meta message midi_port port=0 time=0>
<meta message track_name name=u'Piano right' time=0>
<message program_change channel=0 program=0 time=0>
<message control_change channel=0 control=7 value=100 time=0>
<message control_change channel=0 control=10 value=64 time=0>
<message control_change channel=0 control=91 value=127 time=0>
<meta message text text=u'bdca426d104a26ac9dcb070447587523' time=0>
<message note_on channel=0 note=67 velocity=56 time=241>
<message note_on channel=0 note=67 velocity=0 time=120>
</code>```

The time element in the messages make more sense to me, as they all have 100+ ticks, but the ordering is by track, and so all the tempo changes are printed at once, then all the note events for the right hand, and then all the note events for the left hand (etc). Is it possible to get the best of both worlds, where I can get a list of the MIDI events based on time with the time attribute being the 100+ numbers that I get from print_tracks()?

答:
The documentation says:

The time attribute is used in several different ways:

inside a track, it is delta time in ticks. This must be an integer.

in messages yielded from play(), it is delta time in seconds (time elapsed since the last yielded message)

Delta times are relative to the previous message in the same track, so you have to add them up separately for each track.

Title: MIDI messages confusion [Python]

Body:
I'm trying to get the start and stop times of all the notes from a MIDI file for a piano. From my understanding, there are note_on and note_off events with delta time in ticks, which I can use to get the start and stop times. However, what I'm confused with is with the time variable. When I just have a simple program such as

for msg in mid:
    print(msg.dict())

I get outputs such as:

{'note': 60, 'velocity': 61, 'type': 'note_on', 'channel': 0, 'time': 0.0016891895833333333}
{'note': 64, 'velocity': 57, 'type': 'note_on', 'channel': 0, 'time': 0.20270275}
{'note': 67, 'velocity': 56, 'type': 'note_on', 'channel': 0, 'time': 0.20270275}
{'note': 67, 'velocity': 0, 'type': 'note_on', 'channel': 0, 'time': 0.20270275}
{'note': 72, 'velocity': 60, 'type': 'note_on', 'channel': 0, 'time': 0}
{'type': 'set_tempo', 'tempo': 794702, 'time': 0.20101356041666665}

From my understanding, this means that the notes have delta times that are all less than 1 tick, which seems completely wrong to me. However, what I like is that doing it this way has the note_on, note_off, and set_tempo events in the order that they occur. When I instead do

mid.print_tracks()

I get an output such as:

<meta message set_tempo tempo=794702 time=480>
<meta message set_tempo tempo=810811 time=120>
<meta message set_tempo tempo=800000 time=960>
<meta message set_tempo tempo=810811 time=360>
...
=== Track 1
<meta message midi_port port=0 time=0>
<meta message track_name name=u'Piano right' time=0>
<message program_change channel=0 program=0 time=0>
<message control_change channel=0 control=7 value=100 time=0>
<message control_change channel=0 control=10 value=64 time=0>
<message control_change channel=0 control=91 value=127 time=0>
<meta message text text=u'bdca426d104a26ac9dcb070447587523' time=0>
<message note_on channel=0 note=67 velocity=56 time=241>
<message note_on channel=0 note=67 velocity=0 time=120>

The time element in the messages make more sense to me, as they all have 100+ ticks, but the ordering is by track, and so all the tempo changes are printed at once, then all the note events for the right hand, and then all the note events for the left hand (etc). Is it possible to get the best of both worlds, where I can get a list of the MIDI events based on time with the time attribute being the 100+ numbers that I get from print_tracks()?


问:
I want to save a image from remote URL to local system in PHP
this is my PHP code

```<code><?php
$return = array();
$img_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$imageUrl = $img_url;
$dd = pathinfo($imageUrl);
$pic_name=  $dd['basename'];

@$rawImage = file_get_contents($imageUrl);

if($rawImage)
{
    file_put_contents("C:/xampp/htdocs/get_img/".$pic_name,$rawImage);

    echo 'Image Saved';
}
else
{

echo 'Error Occured';
}

?>
</code>```

but for this URL from google images, this code is giving me this.

"Warning: file_put_contents(C:/xampp/htdocs/get_img/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS): failed to open stream: Resource temporarily unavailable in C:\xampp\htdocs\get_img\get1.php on line 12"

how can i save this image?

答:
Just sanitize the filename before trying to create the file. Just create an MD5 string from the pic url.</p>

```<code>file_put_contents("C:/xampp/htdocs/get_img/".md5($pic_name),$rawImage);
</code>```

Body:
this is my PHP code

<?php
$return = array();
$img_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS";
$imageUrl = $img_url;
$dd = pathinfo($imageUrl);
$pic_name=  $dd['basename'];

@$rawImage = file_get_contents($imageUrl);

if($rawImage)
{
    file_put_contents("C:/xampp/htdocs/get_img/".$pic_name,$rawImage);

    echo 'Image Saved';
}
else
{

echo 'Error Occured';
}

?>

but for this URL from google images, this code is giving me this.

"Warning: file_put_contents(C:/xampp/htdocs/get_img/images?q=tbn:ANd9GcRriYVsmTPMn-8zkAKAtTzghAwUeQwaqmZCJTc127h7-WFYIpNS): failed to open stream: Resource temporarily unavailable in C:\xampp\htdocs\get_img\get1.php on line 12"

how can i save this image?

Body:
Just sanitize the filename before trying to create the file. Just create an MD5 string from the pic url.

file_put_contents("C:/xampp/htdocs/get_img/".md5($pic_name),$rawImage);


问:
java.net.SocketTimeoutException when sending video using OkhttpClient 3.2 and Retrofit 2
I using OkhttpClient to send a video with 15 seconds long to the server using OkhttpClient 3.2 and Retrofit2,sometimes it work fine but sometimes I get the error below,which is very inconsistent.

java.net.SocketTimeoutException: timeout

Here is my code for sending the video up to server

```<code>private void sendVideoToServer( final String videoFilePath,final String api_key)
    {
        File videoFile = new File(videoFilePath);
        RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
        MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        VideoInterface videoInterface = retrofit.create(VideoInterface.class);
        Call<ResultObject> serverCom = videoInterface.sendVideoToServer(vFile);

        serverCom.enqueue(new Callback<ResultObject>() {
            @Override
            public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
                ResultObject result = response.body();
                if(!TextUtils.isEmpty(result.getSuccess())){
                    Log.d("video Result " , result.getSuccess());
                }
            }

            @Override
            public void onFailure(Call<ResultObject> call, Throwable t) {
               Log.d("video error",t.toString());
            }
        });
    }
</code>```

After reading some question,I tried to set the connection timeout to the OkhttpClient like below,but still cant solve the problem.

```<code>OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                });
builder.connectTimeout(5, TimeUnit.MINUTES)
       .writeTimeout(5, TimeUnit.MINUTES)
       .readTimeout(5, TimeUnit.MINUTES);
OkHttpClient httpClient = builder.build();
</code>```

I totally dont know what was doing wrong in this part,somebody please give me some guidance. Tq

答:
try passing actual file object</p>

```<code>  file = new File(tasks.getImageUrl());
            requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
 body =  MultipartBody.Part.createFormData("file", file.getName(), requestFile);

 sendVideo(body);
</code>```

Body:
I using OkhttpClient to send a video with 15 seconds long to the server using OkhttpClient 3.2 and Retrofit2,sometimes it work fine but sometimes I get the error below,which is very inconsistent.

java.net.SocketTimeoutException: timeout

Here is my code for sending the video up to server

private void sendVideoToServer( final String videoFilePath,final String api_key)
    {
        File videoFile = new File(videoFilePath);
        RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
        MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        VideoInterface videoInterface = retrofit.create(VideoInterface.class);
        Call<ResultObject> serverCom = videoInterface.sendVideoToServer(vFile);

        serverCom.enqueue(new Callback<ResultObject>() {
            @Override
            public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
                ResultObject result = response.body();
                if(!TextUtils.isEmpty(result.getSuccess())){
                    Log.d("video Result " , result.getSuccess());
                }
            }

            @Override
            public void onFailure(Call<ResultObject> call, Throwable t) {
               Log.d("video error",t.toString());
            }
        });
    }

After reading some question,I tried to set the connection timeout to the OkhttpClient like below,but still cant solve the problem.

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                });
builder.connectTimeout(5, TimeUnit.MINUTES)
       .writeTimeout(5, TimeUnit.MINUTES)
       .readTimeout(5, TimeUnit.MINUTES);
OkHttpClient httpClient = builder.build();

I totally dont know what was doing wrong in this part,somebody please give me some guidance. Tq

Body:
try passing actual file object

  file = new File(tasks.getImageUrl());
            requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
 body =  MultipartBody.Part.createFormData("file", file.getName(), requestFile);

 sendVideo(body);


问:
How can I test what my readme.md file will look like before committing to github?
I am writing a readme for my github project in the .md format. Is there a way can I test what my readme.md file will look like before committing to github?   </p>

答:
SublimeText 2/3

Install package: Markdown Preview

Options:

Preview in browser.

Export to html.

Copy to clipboard.


问:
How to compare Character for empty space
I need to check if a Character is a space, how do you do that?</p>

```<code>for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}
</code>```

答:
Use NSCharacterSet to check for white space, including \n, \t, etc.</p>

```<code>NSCharacterSet.whitespaces.contains(val.unicodeScalars.first!)
</code>```

Body:
I need to check if a Character is a space, how do you do that?

for (index, val) in (self.textField.text?.enumerated())! {
  if val == " " { // How?
    if index % 2 == 0 {
      // ...
    }
  }
}

Body:
Use NSCharacterSet to check for white space, including \n, \t, etc.

NSCharacterSet.whitespaces.contains(val.unicodeScalars.first!)


问:
BASH: Find number in text -> variable
I need little help from the community:

I have these two lines in a large text file:

```<code>Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS
</code>```

How I can find, extract and assign the numbers to variables?

```<code>clients=42
active=4
</code>```

SED, AWK, GREP? Which one should I use?

答:
you can use awk

```<code>$ set -- $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print c,a}' file)
$ echo $1
42
$ echo $2
4
</code>```

assign $1, $2 to appropriate variable names as desired

if you can directly assign using declare

```<code>$ declare $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print "client="c;print "active="a}' file)
$ echo $client
42
$ echo $active
4
</code>```

Title: BASH: Find number in text -> variable

Body:
I need little help from the community:

I have these two lines in a large text file:

Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS

How I can find, extract and assign the numbers to variables?

clients=42
active=4

SED, AWK, GREP? Which one should I use?

Body:
you can use awk

$ set -- $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print c,a}' file)
$ echo $1
42
$ echo $2
4

assign $1, $2 to appropriate variable names as desired

if you can directly assign using declare

$ declare $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print "client="c;print "active="a}' file)
$ echo $client
42
$ echo $active
4


问:
Why does the insert function and concatenation do this?
```<code>x = [4, 5, 6]
li = [1, 2, 3, 7]
li.insert(3,x)
x+=li
print(x)
</code>```

The output is:

```<code>[4, 5, 6, 1, 2, 3, [...], 7]
</code>```

I'm new to python/coding and I don't know what these ellipses are but when I do other code it starts getting weird. Wasn't sure what to ask since I have no clue what's going on. Thank you!

答:
you're inserting a list inside your list, probably not what you want.

Then when doing this

```<code>x+=li
</code>```

the representation of the list then shows an ellipsis because you're referencing the list from itself (x is referenced in li already)

To insert several items at once in a list in-place you could use slice assignment:

```<code>>>> x = [4, 5, 6]
>>> li = [1, 2, 3, 7]
>>> li[3:3] = x
>>> li
[1, 2, 3, 4, 5, 6, 7]
</code>```

Body:
x = [4, 5, 6]
li = [1, 2, 3, 7]
li.insert(3,x)
x+=li
print(x)

The output is:

[4, 5, 6, 1, 2, 3, [...], 7]

I'm new to python/coding and I don't know what these ellipses are but when I do other code it starts getting weird. Wasn't sure what to ask since I have no clue what's going on. Thank you!

Body:
you're inserting a list inside your list, probably not what you want.

Then when doing this

x+=li

the representation of the list then shows an ellipsis because you're referencing the list from itself (x is referenced in li already)

To insert several items at once in a list in-place you could use slice assignment:

>>> x = [4, 5, 6]
>>> li = [1, 2, 3, 7]
>>> li[3:3] = x
>>> li
[1, 2, 3, 4, 5, 6, 7]


问:
Gradle DSL method not found:'compile' error(31, 0)
I just added a design support in app/build.gradle file. when I synced the file, there was an error. Can anyone tell me what I am doing wrong?

Thiis is my app/build.gradle file

```<code>apply plugin: 'com.android.application'
android{
       complieSdkVersion 26
       buildToolsVersion "26.0.0"
       defaultConfig{
                 application "sun.example.test"
                 minSdkVersion  15
                 targetSdkVersion  26
                 versionCode  1
                 versionName "1.0"
                 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'
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:design:${supportLibVersion}'

}
</code>```

答:
The issue is here:

```<code> androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',{
        exclude group" 'com.android.support', module: 'support-annotations'
        })
</code>```

Pay attention to the {} and group:
Use:

```<code> androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2'){
        exclude group: 'com.android.support', module: 'support-annotations'
        }
</code>```

Body:
I just added a design support in app/build.gradle file. when I synced the file, there was an error. Can anyone tell me what I am doing wrong?

Thiis is my app/build.gradle file

apply plugin: 'com.android.application'
android{
       complieSdkVersion 26
       buildToolsVersion "26.0.0"
       defaultConfig{
                 application "sun.example.test"
                 minSdkVersion  15
                 targetSdkVersion  26
                 versionCode  1
                 versionName "1.0"
                 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'
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:design:${supportLibVersion}'

}

Body:
The issue is here:

 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',{
        exclude group" 'com.android.support', module: 'support-annotations'
        })

Pay attention to the {} and group:
Use:

 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2'){
        exclude group: 'com.android.support', module: 'support-annotations'
        }


问:
Programmatically created document set item is always a folder
I have a problem by creating a list item programmatically. The szenario:

2 Lists (Changes-CustomDocSet Lib, Risks-Custom Task List) with custom content types and fields

The new/edit form of the Changes List includes a DataGrid witch shows the items of the Risks list

All items, i created manually in the Risk list are shown. Now I can add additional items from the new/edit form of the Changes list using the Add button. I can insert but the item is not shown in the grid.

Risk items within new form of changes list:

Why? If i look into my Risk list, I can see the inserted item, but it is not a item, it is shown as folder type.

Add new risk item:

This is my implementation to add the item:

```<code>SPListItem item = list.Items.Add();
item["ChangeReference"] = "1";
item[SPBuiltInFieldId.Title] = title.Text;
item["Title"] = title.Text;
item["Risk"] = risk.Text;
item["Probability"] = probability.Text;
item.Update();
</code>```

The List Definition only has my custom content type:

```<code><List xmlns:ows="Microsoft SharePoint" Title="Risks" FolderCreation="FALSE" Direction="$Resources:Direction;" EnableContentTypes="TRUE" Url="Lists\Risks" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
  <MetaData>
    <ContentTypes>
      <ContentTypeRef ID="0x0108009007F1B9465C48F2AE80B77CC58A4AA7" />
    </ContentTypes>
...
</code>```

The manually created item can be found within list.Items, the programmitcally created item are always created in list.folders, but I don't know why and how to change that? I need normal items, not folders.

Manually vs. prog items:

Any idears?

UPDATE:

I already try to set the CT, without success. I now use a standard task list without custom content type, but it always created a folder instead an item.

While debugging, everything looks fine:

Debugging item creation

答:
Looks like your content type is not getting set whenever you add a list item.

Assuming that your content type name is Example Content Type, you can try the below code. Modify it as per your content type name:

```<code>SPContentType spctExampleContentType = list.ContentTypes["Example Content Type"];

SPListItem item = list.Items.Add();
item["ChangeReference"] = "1";
item[SPBuiltInFieldId.Title] = title.Text;
item["Title"] = title.Text;
item["Risk"] = risk.Text;
item["Probability"] = probability.Text;
spliNewItem["ContentTypeId"] = spctExampleContentType.Id;
item.Update();
</code>```

Body:
I have a problem by creating a list item programmatically. The szenario:

2 Lists (Changes-CustomDocSet Lib, Risks-Custom Task List) with custom content types and fields

The new/edit form of the Changes List includes a DataGrid witch shows the items of the Risks list

All items, i created manually in the Risk list are shown. Now I can add additional items from the new/edit form of the Changes list using the Add button. I can insert but the item is not shown in the grid.

Risk items within new form of changes list:

Why? If i look into my Risk list, I can see the inserted item, but it is not a item, it is shown as folder type.

Add new risk item:

This is my implementation to add the item:

SPListItem item = list.Items.Add();
item["ChangeReference"] = "1";
item[SPBuiltInFieldId.Title] = title.Text;
item["Title"] = title.Text;
item["Risk"] = risk.Text;
item["Probability"] = probability.Text;
item.Update();

The List Definition only has my custom content type:

<List xmlns:ows="Microsoft SharePoint" Title="Risks" FolderCreation="FALSE" Direction="$Resources:Direction;" EnableContentTypes="TRUE" Url="Lists\Risks" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
  <MetaData>
    <ContentTypes>
      <ContentTypeRef ID="0x0108009007F1B9465C48F2AE80B77CC58A4AA7" />
    </ContentTypes>
...

The manually created item can be found within list.Items, the programmitcally created item are always created in list.folders, but I don't know why and how to change that? I need normal items, not folders.

Manually vs. prog items:

Any idears?

UPDATE:

I already try to set the CT, without success. I now use a standard task list without custom content type, but it always created a folder instead an item.

While debugging, everything looks fine:

Debugging item creation

Body:
Looks like your content type is not getting set whenever you add a list item.

Assuming that your content type name is Example Content Type, you can try the below code. Modify it as per your content type name:

SPContentType spctExampleContentType = list.ContentTypes["Example Content Type"];

SPListItem item = list.Items.Add();
item["ChangeReference"] = "1";
item[SPBuiltInFieldId.Title] = title.Text;
item["Title"] = title.Text;
item["Risk"] = risk.Text;
item["Probability"] = probability.Text;
spliNewItem["ContentTypeId"] = spctExampleContentType.Id;
item.Update();


问:
traceroute mac in mininet
In mininet I want to find out through which switches ping goes. For example from PC1 (h1) to PC3 (h3). I already tried:

```<code>h1 traceroute mac ip h3
</code>```

or

```<code>11:00:00:00:00:00 traceroute mac 33:00:00:00:00:00
</code>```

But it didnt work. "Normal" traceroute (h1 traceroute h2) is working (only destination address is in output). But I need to find out the path of ping.

答:
Traceroute only works with L3, so its not possible to find route.
So i use flow-tables in switches, where is shown through which port the path goes.

For example, if I want to know the path of mac address: 66:00:00:00:00 a look at the output port. And thanks to ryu gui topology is easy to find way.

Title: traceroute mac in mininet

Body:
In mininet I want to find out through which switches ping goes. For example from PC1 (h1) to PC3 (h3). I already tried:

h1 traceroute mac ip h3

or

11:00:00:00:00:00 traceroute mac 33:00:00:00:00:00

But it didnt work. "Normal" traceroute (h1 traceroute h2) is working (only destination address is in output). But I need to find out the path of ping.


问:
Android edittext - choose contact's phone number (with auto completion)
Is there a way to put a EditText element in which i could choose contact's phone number from my contacts list. Just as in generic android sms app. (Auto-complete when typing phone number or contact name!).

答:
Have you checked out Android's Auto Complete example at : http://developer.android.com/resources/tutorials/views/hello-autocomplete.html

maybe you can tweak this example to add your contact list.


问:
Moment js. How to convert the current time to a different time zone
For example current time (Timezone +2) time 11:00 how to get this time for (Time zone +9). Need to use moment js.

答:
You can set moment().utcOffset(9); and with a given date just do moment(givenDate).utcOffset(9);

Please see momentjs.com/docs/


问:
get git commit SHA within Jenkins pipeline with JGit
I have a Jenkins with the Github organization plugin that scans my organization and build all the branches/PRs of all the repositories within the organization that have a Jenkinsfile.

It works great, but I would like to retrieve for each build the commit SHA, in order to tag Docker images with both the branch name and the commit SHA.

Getting the branch name works great with env.BRANCH_NAME, however I cannot find any way to get the commit SHA.

The catch is that we are using JGit, so I cannot use git log to retrieve it.

I tried having a look at what is contained in the ENV using sh 'printenv', but there's nothing of any use there.

I also tried the following:

```<code>def checkoutResults = checkout scm
echo 'checkout results: ' + checkoutResults
</code>```

but this yields the following result:

```<code>checkout results: [:]
</code>```

Even though I cannot get the revision from my pipeline, Jenkins is getting it alright, as I can see in the logs:

```<code>...
Obtained Jenkinsfile from 98062e5f651ca698f4303c3bb8d20665ce491294
...
Checking out Revision 98062e5f651ca698f4303c3bb8d20665ce491294 (docker)
</code>```

I am running the following versions:

Jenkins 2.73.3

Git plugin plugin 3.3.0

Pipeline: SCM Step plugin 2.6

Would appreciate any help in retrieving the commit SHA / revision in this particular situation.

答:
I created a small groovy function

```<code>def getCommitSha(){
    return sh(returnStdout: true, script: 'git rev-parse HEAD')
}
</code>```

you can add it to your pipeline , or to your shared library if you are using one ( if not it's a good time to start ... :-)  )

Body:
I have a Jenkins with the Github organization plugin that scans my organization and build all the branches/PRs of all the repositories within the organization that have a Jenkinsfile.

It works great, but I would like to retrieve for each build the commit SHA, in order to tag Docker images with both the branch name and the commit SHA.

Getting the branch name works great with env.BRANCH_NAME, however I cannot find any way to get the commit SHA.

The catch is that we are using JGit, so I cannot use git log to retrieve it.

I tried having a look at what is contained in the ENV using sh 'printenv', but there's nothing of any use there.

I also tried the following:

def checkoutResults = checkout scm
echo 'checkout results: ' + checkoutResults

but this yields the following result:

checkout results: [:]

Even though I cannot get the revision from my pipeline, Jenkins is getting it alright, as I can see in the logs:

...
Obtained Jenkinsfile from 98062e5f651ca698f4303c3bb8d20665ce491294
...
Checking out Revision 98062e5f651ca698f4303c3bb8d20665ce491294 (docker)

I am running the following versions:

Jenkins 2.73.3

Git plugin plugin 3.3.0

Pipeline: SCM Step plugin 2.6

Would appreciate any help in retrieving the commit SHA / revision in this particular situation.

Body:
I created a small groovy function

def getCommitSha(){
    return sh(returnStdout: true, script: 'git rev-parse HEAD')
}

you can add it to your pipeline , or to your shared library if you are using one ( if not it's a good time to start ... :-)  )


问:
Need insight on how to build javascript fetch API
I am creating a web app with django rest framework as backend and react as frontend. The react app i generated from create-react-app. To make api call, i use fetch Api. I see some repetition in my api call that need to a reafactor. But i know which pattern is better here.

Here is the code:

Api.js

```<code>let _options = {headers: new Headers({'Content-Type': 'application/json'})}

const _url = {
  'users': '/api/users/',
  'obtain-token': '/api/obtain-token/',
  'verify-token': '/api/verify-token/',
  'refresh-token': '/api/refresh-token/'
}

const _fetch = (request) => {
  return fetch(request)
    .then(res => {
      if ( ! res.ok) {
        let err = {
          'status': res.status,
          'statusText': res.statusText,
          'data': {}
        }
        return res.json().then(
          data => {
            err.data = data
            return Promise.reject(new Error(JSON.stringify(err)))
          },
          () => Promise.reject(new Error(JSON.stringify(err)))
        )
      }

      return res.json()
    })
    .catch(err => {
      return Promise.reject(err)
    })
}

export const obtainToken = (username, password) => {
  const credential = {username, password}

  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify(credential)

  const request = new Request(_url['obtain-token'], options)

  return _fetch(request)
}

export const verifyToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['verify-token'], options)

  return _fetch(request)
}

export const refreshToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['refresh-token'], options)

  return _fetch(request)
}

export const getUser = (username, token='') => {
  let options = _options
  options.method = 'GET'
  if (token) options.headers.append('Authorization', `JWT ${token}`)

  const request = new Request(`${_url['users']}/${username}`, options)

  return _fetch(request)
}
</code>```

What i like from this code is, when i need to request a resource, i just run a function with needed parameter without knowing it is get or post or else, and i dont need to pass header configuration and url.

```<code>// example api call
let token = '4346h9r7yt47t9...'

verifyToken(token)
  .then(data => {
    // server response json available here

    token = data.token
  })
  .catch(err => {
    // handle network error and bad response here

    console.log(err)
  })
</code>```

Im follwing @challenger solution. And manage to get it shorter with this:

```<code>// Change _build function name to makeRequest and export it
const makeRequest = (name, _url='', body=undefined, headers={}) => {
  let [method, url] = source[name]
  let options = {
     headers: new Headers({
       'Content-Type': 'application/json',
       ...headers,
     })
   }
  options.method = method
  if (body) options.body = JSON.stringify(body)
  return _fetch(url+_url, options)
}

export default makeRequest
</code>```

But, of course to call this function i need to supply the appended url, and a custom header if needed. But as this project goes it's proved that appended url (use by user detail resource) and costum header (use by resource that need authentication) is needed.

答:
```<code>let source = {
  'getUser': ['GET', '/api/users/'],
  'obtain-token': ['POST','/api/obtain-token/'],
  'verify-token': ['POST','/api/verify-token/'],
  'refresh-token':['POST', '/api/refresh-token/']
}

let _build = (name, _url, body, headers) => {
  let [method, url] = source[name]
  let options = {
     headers: new Headers({
       'Content-Type': 'application/json',
       ...headers,
     })
   }
  options.method = method
  if (body) options.body = JSON.stringify(body)
  return new Request(url+_url, options)
}
</code>```

and then

```<code>export const obtainToken = (username, password) => {
  const credential = {username, password}
  const request = _build('obtainToken','', credential, {})
  return _fetch(request)
}
export const verifyToken = (token) => {
  const request = _build('verifyToken', '',{token}, {})
  return _fetch(request)
}

export const refreshToken = (token) => {
  const request = _build('refreshToken', '', {token}, {})
  return _fetch(request)
}
export const getUser = (username, token='') => {
  let headers = {'Authorization': `JWT ${token}`}

  const request = _build('getUser',`/${username}`, undefined, headers)
  return _fetch(request)
}
</code>```

even more, instead of...

```<code>return new Request(url+_url, options)
</code>```

in the _build function you can replace it with

```<code>return _fetch(new Request(url+_url, options))
</code>```

which allows you to have this:

```<code>   export const obtainToken = (username, password) => {
      const credential = {username, password}
      return _build('obtainToken','', credential, {})
    }
    export const verifyToken = (token) => {
      return _build('verifyToken', '',{token}, {})
    }

    export const refreshToken = (token) => {
      retun _build('refreshToken', '', {token}, {})
    }

    export const getUser = (username, token='') => {
      let headers = {'Authorization': `JWT ${token}`}
      return _build('getUser',`/${username}`, undefined, headers)
    }
</code>```

Body:
I am creating a web app with django rest framework as backend and react as frontend. The react app i generated from create-react-app. To make api call, i use fetch Api. I see some repetition in my api call that need to a reafactor. But i know which pattern is better here.

Here is the code:

Api.js

let _options = {headers: new Headers({'Content-Type': 'application/json'})}

const _url = {
  'users': '/api/users/',
  'obtain-token': '/api/obtain-token/',
  'verify-token': '/api/verify-token/',
  'refresh-token': '/api/refresh-token/'
}

const _fetch = (request) => {
  return fetch(request)
    .then(res => {
      if ( ! res.ok) {
        let err = {
          'status': res.status,
          'statusText': res.statusText,
          'data': {}
        }
        return res.json().then(
          data => {
            err.data = data
            return Promise.reject(new Error(JSON.stringify(err)))
          },
          () => Promise.reject(new Error(JSON.stringify(err)))
        )
      }

      return res.json()
    })
    .catch(err => {
      return Promise.reject(err)
    })
}

export const obtainToken = (username, password) => {
  const credential = {username, password}

  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify(credential)

  const request = new Request(_url['obtain-token'], options)

  return _fetch(request)
}

export const verifyToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['verify-token'], options)

  return _fetch(request)
}

export const refreshToken = (token) => {
  let options = _options
  options.method = 'POST'
  options.body = JSON.stringify({token})

  const request = new Request(_url['refresh-token'], options)

  return _fetch(request)
}

export const getUser = (username, token='') => {
  let options = _options
  options.method = 'GET'
  if (token) options.headers.append('Authorization', `JWT ${token}`)

  const request = new Request(`${_url['users']}/${username}`, options)

  return _fetch(request)
}

What i like from this code is, when i need to request a resource, i just run a function with needed parameter without knowing it is get or post or else, and i dont need to pass header configuration and url.

// example api call
let token = '4346h9r7yt47t9...'

verifyToken(token)
  .then(data => {
    // server response json available here

    token = data.token
  })
  .catch(err => {
    // handle network error and bad response here

    console.log(err)
  })

Im follwing @challenger solution. And manage to get it shorter with this:

// Change _build function name to makeRequest and export it
const makeRequest = (name, _url='', body=undefined, headers={}) => {
  let [method, url] = source[name]
  let options = {
     headers: new Headers({
       'Content-Type': 'application/json',
       ...headers,
     })
   }
  options.method = method
  if (body) options.body = JSON.stringify(body)
  return _fetch(url+_url, options)
}

export default makeRequest

But, of course to call this function i need to supply the appended url, and a custom header if needed. But as this project goes it's proved that appended url (use by user detail resource) and costum header (use by resource that need authentication) is needed.

Body:
let source = {
  'getUser': ['GET', '/api/users/'],
  'obtain-token': ['POST','/api/obtain-token/'],
  'verify-token': ['POST','/api/verify-token/'],
  'refresh-token':['POST', '/api/refresh-token/']
}

let _build = (name, _url, body, headers) => {
  let [method, url] = source[name]
  let options = {
     headers: new Headers({
       'Content-Type': 'application/json',
       ...headers,
     })
   }
  options.method = method
  if (body) options.body = JSON.stringify(body)
  return new Request(url+_url, options)
}

and then

export const obtainToken = (username, password) => {
  const credential = {username, password}
  const request = _build('obtainToken','', credential, {})
  return _fetch(request)
}
export const verifyToken = (token) => {
  const request = _build('verifyToken', '',{token}, {})
  return _fetch(request)
}

export const refreshToken = (token) => {
  const request = _build('refreshToken', '', {token}, {})
  return _fetch(request)
}
export const getUser = (username, token='') => {
  let headers = {'Authorization': `JWT ${token}`}

  const request = _build('getUser',`/${username}`, undefined, headers)
  return _fetch(request)
}

even more, instead of...

return new Request(url+_url, options)

in the _build function you can replace it with

return _fetch(new Request(url+_url, options))

which allows you to have this:

   export const obtainToken = (username, password) => {
      const credential = {username, password}
      return _build('obtainToken','', credential, {})
    }
    export const verifyToken = (token) => {
      return _build('verifyToken', '',{token}, {})
    }

    export const refreshToken = (token) => {
      retun _build('refreshToken', '', {token}, {})
    }

    export const getUser = (username, token='') => {
      let headers = {'Authorization': `JWT ${token}`}
      return _build('getUser',`/${username}`, undefined, headers)
    }


问:
What is "metrics" in Keras?
It is not yet clear for me what metrics are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the model? Why we can have multiple metrics in one model? And more importantly what is the mechanics behind all this?
Any scientific reference is also appreciated.

model.compile(loss='mean_squared_error',
              optimizer='sgd',
              metrics=['mae', 'acc'])
```

答:
Reference: Keras Metrics Documentation

As given in the documentation page of keras metrics, a metric judges the performance of your model. The metrics argument in the compile method holds the list of metrics that needs to be evaluated by the model during its training and testing phases.
Metrics like:

binary_accuracy

categorical_accuracy

sparse_categorical_accuracy

top_k_categorical_accuracy and

sparse_top_k_categorical_accuracy

are the available metric functions that are supplied in the metrics parameter when the model is compiled.

Metric functions are customizable as well. When multiple metrics need to be evaluated it is passed in the form of a dictionary or a list.

One important resource you should refer for diving deep into metrics can be found here

Title: What is "metrics" in Keras?


问:
How to create a Spinner in PHP?
I have problem and I hope you help me, please.

I have a code:

```<code>$a = 'A B C D E';
$b = '{A|a|AA}{B|b|BB} {E|e|EEE}';
</code>```

And I want to use $b to random display $a like this:

```<code>A b C D EE

AA B C D e

A b C D EEE ...
</code>```

This mean:

A replace to A,  a or AA

B replace to B, b or BB

and

E replace to E, e or EEE

I hope you understand and help me, thankyou so much!!! <3

答:
If you are not wedded to the format of $b, you could use arrays for substitutes, and pick a random item to replace.

```<code>$placeholders = 'A B C D E';
$substitutes  = [
        'A' => ['A','a','AA'],
        'B' => ['B','b','BB'],
        'E' => ['E','e','EE','EEE'],
];
$replacements = [];
foreach($substitutes as $key => $choices) {
    $random_key = array_rand($choices);
    $replacements[$key] = $choices[$random_key];
}
$spun = str_replace(
    array_keys($replacements),
    array_values($replacements),
    $placeholders
);
echo $spun;
</code>```

Example output:

```<code>AA b C D EE
</code>```

Alternatively (if your substitutes are uniform):

```<code>function substitute($character) {
    $random = rand(0,2);
    $string = $random
        ? str_repeat($character, $random)
        : strtolower($character);
    return $string;
}

$spun = implode(
    ' ',
    array_map(
        'substitute',
        ['A','B','C','D','E']
    )
);
echo $spun;
</code>```

But the above will substitute for C and D also.  You could easily adapt for exclusions.

Title: How to create a Spinner in PHP?

Body:
I have problem and I hope you help me, please.

I have a code:

$a = 'A B C D E';
$b = '{A|a|AA}{B|b|BB} {E|e|EEE}';

And I want to use $b to random display $a like this:

A b C D EE

AA B C D e

A b C D EEE ...

This mean:

A replace to A,  a or AA

B replace to B, b or BB

and

E replace to E, e or EEE

I hope you understand and help me, thankyou so much!!! <3

Body:
If you are not wedded to the format of $b, you could use arrays for substitutes, and pick a random item to replace.

$placeholders = 'A B C D E';
$substitutes  = [
        'A' => ['A','a','AA'],
        'B' => ['B','b','BB'],
        'E' => ['E','e','EE','EEE'],
];
$replacements = [];
foreach($substitutes as $key => $choices) {
    $random_key = array_rand($choices);
    $replacements[$key] = $choices[$random_key];
}
$spun = str_replace(
    array_keys($replacements),
    array_values($replacements),
    $placeholders
);
echo $spun;

Example output:

AA b C D EE

Alternatively (if your substitutes are uniform):

function substitute($character) {
    $random = rand(0,2);
    $string = $random
        ? str_repeat($character, $random)
        : strtolower($character);
    return $string;
}

$spun = implode(
    ' ',
    array_map(
        'substitute',
        ['A','B','C','D','E']
    )
);
echo $spun;

But the above will substitute for C and D also.  You could easily adapt for exclusions.


问:
Why does my Tkinter window background not change?
I've a small program with a feature to change the background color of a different window than the frame I use to ask for the background color. (I hope you understand this.) The program is written in Python with the Tkinter library.

Every time I click Enable in the window it changes the color of the background in the second window but not to the color I choose.

Where is the problem?

```<code>def Options():
def OptionButton():
    c= wert.get()
    if c == 1:
        fenster.config(background="red")
    elif c == 2:
        fenster.config(background="blue")
    else:
        fenster.config(background="yellow")

    global usermod
    usermod= tkinter.Entry.get(opEntry)

    fenster.update()
    option.destroy()

def close():
    option.destroy()

option=tkinter.Tk()
option.title("Options")
option.config(background="white")

#Backgroundframe
bgFrame= tkinter.Frame(option)
bgFrame.grid(row=0, column=0, padx=10, pady=20)

info3=tkinter.Label(bgFrame,text="Hintergrund im Menü")
info3.grid(row=1,column=0,padx=10, pady=20)

#2 Radiobutton

global wert
wert = tkinter.StringVar()

knopfA=tkinter.Radiobutton(bgFrame,text="Red", variable=wert,value="1")
knopfB=tkinter.Radiobutton(bgFrame,text="Blue", variable=wert, value="2")
knopfC=tkinter.Radiobutton(bgFrame,text="green", variable=wert,value="3")

knopfA.grid(column=0,row=2)
knopfB.grid(column=0,row=3)
knopfC.grid(column=0,row=4)

knopfA.select()

#OptionFrame
opFrame = tkinter.Frame(option)
opFrame.grid(row=0, column=1,padx=10,pady=20)

#Optionbutton
oplabel=tkinter.Label(opFrame,text="Value User Mode")
oplabel.grid(row=1,column=0,padx=10,pady=2)

opEntry=tkinter.Entry(opFrame,width=12)
opEntry.grid(row=2,column=0,padx=10,pady=2)

#OptionButtonFrame
btFrame=tkinter.Frame(option)
btFrame.grid(row=3,column=0,padx=10,pady=20)

opbutton=tkinter.Button(btFrame,text="Enable", command = lambda:OptionButton())
opbutton.grid(row=1, column=0,padx=10,pady=2)

clbutton=tkinter.Button(btFrame,text="close",command=lambda:close())
clbutton.grid(row=2, column=0,padx=10,pady=2)

option.mainloop()
</code>```

答: Instead of declaring wert as a StringVar, you should declare it as IntVar because in your function OptionButton you're making the comparaison between a string and an int so it always entering in the else part so your background is always yellow.</p>

Body:
I've a small program with a feature to change the background color of a different window than the frame I use to ask for the background color. (I hope you understand this.) The program is written in Python with the Tkinter library.

Every time I click Enable in the window it changes the color of the background in the second window but not to the color I choose.

Where is the problem?

def Options():
def OptionButton():
    c= wert.get()
    if c == 1:
        fenster.config(background="red")
    elif c == 2:
        fenster.config(background="blue")
    else:
        fenster.config(background="yellow")

    global usermod
    usermod= tkinter.Entry.get(opEntry)

    fenster.update()
    option.destroy()

def close():
    option.destroy()

option=tkinter.Tk()
option.title("Options")
option.config(background="white")

#Backgroundframe
bgFrame= tkinter.Frame(option)
bgFrame.grid(row=0, column=0, padx=10, pady=20)

info3=tkinter.Label(bgFrame,text="Hintergrund im Menü")
info3.grid(row=1,column=0,padx=10, pady=20)

#2 Radiobutton

global wert
wert = tkinter.StringVar()

knopfA=tkinter.Radiobutton(bgFrame,text="Red", variable=wert,value="1")
knopfB=tkinter.Radiobutton(bgFrame,text="Blue", variable=wert, value="2")
knopfC=tkinter.Radiobutton(bgFrame,text="green", variable=wert,value="3")

knopfA.grid(column=0,row=2)
knopfB.grid(column=0,row=3)
knopfC.grid(column=0,row=4)

knopfA.select()

#OptionFrame
opFrame = tkinter.Frame(option)
opFrame.grid(row=0, column=1,padx=10,pady=20)

#Optionbutton
oplabel=tkinter.Label(opFrame,text="Value User Mode")
oplabel.grid(row=1,column=0,padx=10,pady=2)

opEntry=tkinter.Entry(opFrame,width=12)
opEntry.grid(row=2,column=0,padx=10,pady=2)

#OptionButtonFrame
btFrame=tkinter.Frame(option)
btFrame.grid(row=3,column=0,padx=10,pady=20)

opbutton=tkinter.Button(btFrame,text="Enable", command = lambda:OptionButton())
opbutton.grid(row=1, column=0,padx=10,pady=2)

clbutton=tkinter.Button(btFrame,text="close",command=lambda:close())
clbutton.grid(row=2, column=0,padx=10,pady=2)

option.mainloop()


问:
What happens if Var args method also exists with overloaded methods exists in a Java method
Here is a program with method overloading done.

```<code>package com.tests;
public class BasicClass {

    public void getMe(Object a) {
        System.out.println("getMe 1");
    }

    public void getMe(Object a, Object b) {
        System.out.println("getMe 2");
    }

    public void getMe(Object a, Object b, Object c) {
        System.out.println("getMe 3");
    }

    public void getMe(Object a, Object b, Object c, Object d) {
        System.out.println("getMe 4");
    }

    public void getMe(Object... parms) {
        System.out.println("getMe 5");
    }
}
</code>```

What is the exact benefit do we get with this type of polymorphism..?

答: You get one more object in case of var args - which is an array implicitly. These concerns of creating more objects like this are valid only when your library truly cares about this. For example jdk-9 methods like Set.of has overloaded methods that take up to 10 different arguments - without the need to create one extra array object.

Body:
Here is a program with method overloading done.

package com.tests;
public class BasicClass {

    public void getMe(Object a) {
        System.out.println("getMe 1");
    }

    public void getMe(Object a, Object b) {
        System.out.println("getMe 2");
    }

    public void getMe(Object a, Object b, Object c) {
        System.out.println("getMe 3");
    }

    public void getMe(Object a, Object b, Object c, Object d) {
        System.out.println("getMe 4");
    }

    public void getMe(Object... parms) {
        System.out.println("getMe 5");
    }
}

What is the exact benefit do we get with this type of polymorphism..?


问:
Can I specify an XML schema/xsd when deserializing?
I'm trying to deserialize XML from an external service, so I have no control over the output XML I receive.

The service's XML is a little strange. It doesn't specify a schema, it references itself. For example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE response>
<response>
 // blah blah
</response>
</code>```

I can use VS's built in tools to create an XSD file for it, but when deserializing, is it possible to specify a local XSD file? Instead of using the non-existent one in the DOCTYPE tag?

答:
You might need to specify to not use an XmlResolver when loading the XML document. See Ignore DOCTYPE .dtd, but .dtd file must still exist

You can easily specify the .xsd file. Use an XmlReaderSettings object when you load the document.  Note that if your program is a web service, your .xsd might need to reside under the Windows directory.  For a hint at it, including pain on 64 bit Windows, see MSI Installer, 64 bit OS, write to \windows\system32\inetsrv folder

Body:
I'm trying to deserialize XML from an external service, so I have no control over the output XML I receive.

The service's XML is a little strange. It doesn't specify a schema, it references itself. For example:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE response>
<response>
 // blah blah
</response>

I can use VS's built in tools to create an XSD file for it, but when deserializing, is it possible to specify a local XSD file? Instead of using the non-existent one in the DOCTYPE tag?


问:
ng-repeat filter on json object
I have a complex JSON structure as below:

My JSON object  is like -

```<code>$scope.data = {
    "Test 1": [
      {
          "paperName": "Physics Test",
          "lkExamTypePk": 1,
          "paperPK": "20",
          "lkExamType": 2
      }
    ],
    "Test 2": [
      {
          "paperName": "Maths Test",
          "lkExamTypePk": 2,
          "paperPK": "23",
          "lkExamType": 3
      }
    ]
}
</code>```

I am using this json to display in my html page and want to search key which is Test 1, Test 2, etc:

```<code><input ng-model="filter.key" />
<table>
    <tr ng-repeat="(key,val) in controllerName.data | filter:filter.key">
        <td>
            {{key}}
        </td>
    </tr>
</table>
</code>```

But the problem is that filter works on array and on the values of JSON and I am getting error of not an array.

Error which I'm getting at the console

Error: [filter:notarray]

答:
I think you problem is in how you refer your variabile. As I can see you are declaring your data array into $scope variabile with

```<code>$scope.data = { ... }
</code>```

Then you try to access it referring to your controller with

```<code>controllerName.data
</code>```

You can follow 2 different approaches, but you can't mix them.

1) $scope variabile

If you want to work into $scope, in your controller you must declare your variabile as follow:

```<code>$scope.data = { ... }
</code>```

then into html you must refer to it like this (without controllerName):

```<code><tr ng-repeat="(key,val) in data | filter:filter.key">
</code>```

2) controller scope

If you want to work into controller's scope, in your controller you must declare your variabile as follow:

```<code>this.data = { ... }
</code>```

then into html you can refer to it like this:

```<code><tr ng-repeat="(key,val) in controllerName.data | filter:filter.key">
</code>```

Hint

Generally a good practice, when you receive an error referring to a variable, is to print your variable's data into html to check that you are referring well to it, something like:

```<code>```{{ data | json }}```
</code>```

Try with array instead of object

You can try using an array intead of a json object, as suggested by the error, something like this:

```<code>$scope.data = [
    "Test 1": [{
      "paperName": "Physics Test",
      "lkExamTypePk": 1,
      "paperPK": "20",
      "lkExamType": 2
    }],
    "Test 2": [{
      "paperName": "Maths Test",
      "lkExamTypePk": 2,
      "paperPK": "23",
      "lkExamType": 3
    }]
  ]
</code>```

Title: ng-repeat filter on json object

Body:
I have a complex JSON structure as below:

My JSON object  is like -

$scope.data = {
    "Test 1": [
      {
          "paperName": "Physics Test",
          "lkExamTypePk": 1,
          "paperPK": "20",
          "lkExamType": 2
      }
    ],
    "Test 2": [
      {
          "paperName": "Maths Test",
          "lkExamTypePk": 2,
          "paperPK": "23",
          "lkExamType": 3
      }
    ]
}

I am using this json to display in my html page and want to search key which is Test 1, Test 2, etc:

<input ng-model="filter.key" />

            {{key}}

But the problem is that filter works on array and on the values of JSON and I am getting error of not an array.

Error which I'm getting at the console

Error: [filter:notarray]

Body:
I think you problem is in how you refer your variabile. As I can see you are declaring your data array into $scope variabile with

$scope.data = { ... }

Then you try to access it referring to your controller with

controllerName.data

You can follow 2 different approaches, but you can't mix them.

1) $scope variabile

If you want to work into $scope, in your controller you must declare your variabile as follow:

$scope.data = { ... }

then into html you must refer to it like this (without controllerName):

<tr ng-repeat="(key,val) in data | filter:filter.key">

2) controller scope

If you want to work into controller's scope, in your controller you must declare your variabile as follow:

this.data = { ... }

then into html you can refer to it like this:

<tr ng-repeat="(key,val) in controllerName.data | filter:filter.key">

Hint

Generally a good practice, when you receive an error referring to a variable, is to print your variable's data into html to check that you are referring well to it, something like:

<pre>{{ data | json }}</pre>

Try with array instead of object

You can try using an array intead of a json object, as suggested by the error, something like this:

$scope.data = [
    "Test 1": [{
      "paperName": "Physics Test",
      "lkExamTypePk": 1,
      "paperPK": "20",
      "lkExamType": 2
    }],
    "Test 2": [{
      "paperName": "Maths Test",
      "lkExamTypePk": 2,
      "paperPK": "23",
      "lkExamType": 3
    }]
  ]


问:
Typo3 RealURL tx_news 403 error on detail page with banner link
I have problems with my RealURL Configuration and can't find a solution. I have included banners in my site, but on the news detail pages the link does not work, creating a 403 error. So there has to be something wrong with my RealURL configuration:

```<code>'fixedPostVars' => array(
    'newsDetailConfiguration' => array(
        array(
            'GETvar' => 'tx_news_pi1[news]',
            'lookUpTable' => array(
                'table' => 'tx_news_domain_model_news',
                'id_field' => 'uid',
                'alias_field' => 'title',
                'addWhereClause' => ' AND NOT deleted',
                'useUniqueCache' => 1,
                'useUniqueCache_conf' => array(
                    'strtolower' => 1,
                    'spaceCharacter' => '-'
                ),
                'languageGetVar' => 'L',
                'languageExceptionUids' => '',
                'languageField' => 'sys_language_uid',
                'transOrigPointerField' => 'l10n_parent',
                'autoUpdate' => 1,
                'expireDays' => 180,
            )
        )
    ),
    '18' => 'newsDetailConfiguration',
</code>```

The link when clicking on the banner looks like this:
/detail/?type=9002&tx_sfbanners_pi1[banner]=4&tx_sfbanners_pi1[action]=click&tx_sfbanners_pi1[controller]=Banner&cHash=5ab32cd1edb0529752985d5e30dfd8be

Thanks for your help!

答: The parameters of EXT:news are missing and need to be added when you create the link of the banner</p>

Body:
I have problems with my RealURL Configuration and can't find a solution. I have included banners in my site, but on the news detail pages the link does not work, creating a 403 error. So there has to be something wrong with my RealURL configuration:

'fixedPostVars' => array(
    'newsDetailConfiguration' => array(
        array(
            'GETvar' => 'tx_news_pi1[news]',
            'lookUpTable' => array(
                'table' => 'tx_news_domain_model_news',
                'id_field' => 'uid',
                'alias_field' => 'title',
                'addWhereClause' => ' AND NOT deleted',
                'useUniqueCache' => 1,
                'useUniqueCache_conf' => array(
                    'strtolower' => 1,
                    'spaceCharacter' => '-'
                ),
                'languageGetVar' => 'L',
                'languageExceptionUids' => '',
                'languageField' => 'sys_language_uid',
                'transOrigPointerField' => 'l10n_parent',
                'autoUpdate' => 1,
                'expireDays' => 180,
            )
        )
    ),
    '18' => 'newsDetailConfiguration',

The link when clicking on the banner looks like this:
/detail/?type=9002&tx_sfbanners_pi1[banner]=4&tx_sfbanners_pi1[action]=click&tx_sfbanners_pi1[controller]=Banner&cHash=5ab32cd1edb0529752985d5e30dfd8be

Thanks for your help!


问:
Laravel many to many fetching data from another table
I am a laravel greenhorn and I am going nuts. Well, maybe I am starring too long on that project.
I'm stucked in the following situation:

I am building a "diary" for enterprises. My tables from my database are below.

My target is, that only users within the same enterprise can see the reports related to their enterprise. So in my reportController I have following lines in my index method:

```<code>$enterpriseId = Auth::user()->enterprise_id;
$enterpriseProjects = Enterprise::find($enterpriseId)->projects()->get();
$enterprises = Enterprise::find($enterpriseId);
foreach ($enterprises->projects as $key => $pivotTableProject) {
      $reports = Report::where('project_id', $pivotTableProject->pivot->project_id)->get();
}

return view('reports.index')->with('reports', $reports);
</code>```

As expected I get only one entry from my database. How can I fetch all for the same enterprise? If I put the reports in an array I get this (with dd):

```<code>array:2 [▼
  0 => Collection {#250 ▼
    #items: array:1 [▶]
  }
  1 => Collection {#239 ▼
    #items: array:1 [▶]
  }
]
</code>```

But I need a collection with one array and the reports inside there.
Can anyone help a desperated laravel newbie?

Thanks in advance.
Image of database part here

答:
Finally I solved the problem yesterday with these lines: In my ReportController
$usersEnterpriseId = Auth::user()->enterprise_id; $enterprises = Enterprise::find($usersEnterpriseId);
foreach ($enterprises->projects as $pivotTableProject) {
   $reports[] = Report::where('project_id', $pivotTableProject->pivot->project_id)->get();
}

And in my view I am showing the results via 2 foreach-loops (of course not the best solution, but it works for me). Thanks for your help @HasilT. You pushed me into the right direction.

Body:
I am a laravel greenhorn and I am going nuts. Well, maybe I am starring too long on that project.
I'm stucked in the following situation:

I am building a "diary" for enterprises. My tables from my database are below.

My target is, that only users within the same enterprise can see the reports related to their enterprise. So in my reportController I have following lines in my index method:

$enterpriseId = Auth::user()->enterprise_id;
$enterpriseProjects = Enterprise::find($enterpriseId)->projects()->get();
$enterprises = Enterprise::find($enterpriseId);
foreach ($enterprises->projects as $key => $pivotTableProject) {
      $reports = Report::where('project_id', $pivotTableProject->pivot->project_id)->get();
}

return view('reports.index')->with('reports', $reports);

As expected I get only one entry from my database. How can I fetch all for the same enterprise? If I put the reports in an array I get this (with dd):

array:2 [▼
  0 => Collection {#250 ▼
    #items: array:1 [▶]
  }
  1 => Collection {#239 ▼
    #items: array:1 [▶]
  }
]

But I need a collection with one array and the reports inside there.
Can anyone help a desperated laravel newbie?

Thanks in advance.
Image of database part here


问:
Do subclasses ALWAYS need to implement a designated initializer in Objective-C?
Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?

The Apple's documentation for NSObject's init method provides some discussion:

"Every class must guarantee that the
init method either returns a fully
functional instance of the class or
raises an exception. Subclasses should
override the init method to add
class-specific initialization code."

"If a subclass does any initialization
of its own, it must define its own
designated initializer. This method
should begin by sending a message to
super to invoke the designated
initializer of its superclass."

However, nothing is specified for the case when a subclass needs no extra initialization code.

The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.

Explanatory Code:

```<code>@interface ClassA : NSObject {
  NSInteger x;
  NSInteger y;
}

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;

@end

@implementation ClassA

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super init]) {
    x = initX;
    y = initY;
  }
  return self;
}
@end

@interface ClassB : ClassA {
  //no extra variables
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;

@end

@implementation ClassB

/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
//  with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super initWithX:initX Y:initY]) {
    /* Don't need class-specific initialization code */
  }
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}

@end
</code>```

答:
The answer is in your question:

"If a subclass does any initialization of its own, it must define its own designated initializer. This method should begin by sending a message to super to invoke the designated initializer of its superclass."

If you don't need to do any extra initialization, there's no need to override (or create your own) designated initializer. The method lookup for initWithX:Y: will simply use the superclass implementation.

Body:
Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?

The Apple's documentation for NSObject's init method provides some discussion:

"Every class must guarantee that the
init method either returns a fully
functional instance of the class or
raises an exception. Subclasses should
override the init method to add
class-specific initialization code."

"If a subclass does any initialization
of its own, it must define its own
designated initializer. This method
should begin by sending a message to
super to invoke the designated
initializer of its superclass."

However, nothing is specified for the case when a subclass needs no extra initialization code.

The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.

Explanatory Code:

@interface ClassA : NSObject {
  NSInteger x;
  NSInteger y;
}

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;

@end

@implementation ClassA

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super init]) {
    x = initX;
    y = initY;
  }
  return self;
}
@end

@interface ClassB : ClassA {
  //no extra variables
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;

@end

@implementation ClassB

/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
//  with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super initWithX:initX Y:initY]) {
    /* Don't need class-specific initialization code */
  }
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}

@end


问:
how to check item in a list contains in python
I have 2 lists,

```<code>my_list = ['on@3','one',"$", "lo#"]
spl = ["@","$"]
</code>```

I am trying to get the items in 'my_list' which contains any of the items in spl.

I tried

```<code>out_list = [item for item in my_list if item.contains("!".join(spl))]
</code>```

but this gives error.

My expected output is

```<code>out_list = ["on@3","$"]
</code>```

答:
No such method as item.contains. There's item.__contains__, but you don't need to call that directly.

You want to check if any of the items in spl is contained in the item, use the builtin any:

```<code>lst = [item for item in my_list if any(x in item for x in spl)]
# ...                           if any(item.__contains__(x) for x in spl)]
print(lst)
# ['on@3', '$']
</code>```

Body:
I have 2 lists,

my_list = ['on@3','one',"$", "lo#"]
spl = ["@","$"]

I am trying to get the items in 'my_list' which contains any of the items in spl.

I tried

out_list = [item for item in my_list if item.contains("!".join(spl))]

but this gives error.

My expected output is

out_list = ["on@3","$"]

Body:
No such method as item.contains. There's item.__contains__, but you don't need to call that directly.

You want to check if any of the items in spl is contained in the item, use the builtin any:

lst = [item for item in my_list if any(x in item for x in spl)]
# ...                           if any(item.__contains__(x) for x in spl)]
print(lst)
# ['on@3', '$']


问:
Website icon (rel=icon) not appearing in chrome for android
I have this code on every page of my website.

```<code><link rel="icon" sizes="192x192" href="http://compesh.com/assets/graphics/touch-icon-chrome.png" />
</code>```

Yet when I go to my website on Chrome for Android and tap "Add to home screen" my icon never shows up in the dialog. My image is of the correct size and exists.

What is going on?

I have used this documentation from Google.

Update

My website is http://compesh.com
Look at the page source and see if I've made any mistakes.

It works in Firefox for Android but not Chrome for Android and Chrome for Windows. I see this in Firefox WebIDE

2nd Update
Firefox for Windows is not showing my favicon image in the tab. Instead it is showing the wrong image and scaling it down to 16x16 pixels, instead of using my 16x16 favicon I specified in my web page.

答:
hey try this one just go to https://www.favicon-generator.org
and choose your file and click on create favicon.

Now Download the rar file and extract where your project file is and then copy below code

```<code><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
</code>```

now refresh the browser or try in another browser

Body:
I have this code on every page of my website.

<link rel="icon" sizes="192x192" href="http://compesh.com/assets/graphics/touch-icon-chrome.png" />

Yet when I go to my website on Chrome for Android and tap "Add to home screen" my icon never shows up in the dialog. My image is of the correct size and exists.

What is going on?

I have used this documentation from Google.

Update

My website is http://compesh.com
Look at the page source and see if I've made any mistakes.

It works in Firefox for Android but not Chrome for Android and Chrome for Windows. I see this in Firefox WebIDE

2nd Update
Firefox for Windows is not showing my favicon image in the tab. Instead it is showing the wrong image and scaling it down to 16x16 pixels, instead of using my 16x16 favicon I specified in my web page.

Body:
hey try this one just go to https://www.favicon-generator.org
and choose your file and click on create favicon.

Now Download the rar file and extract where your project file is and then copy below code

<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

now refresh the browser or try in another browser


问:
When I run "tf.nn.dynamic_rnn", I got TypeError: Expected int32, got list containing Tensors of type '_Message' instead
I trying to convert following code to tensorflow 1.2 but I hard understand how to fixed it. Thanks for your any replying.

```<code>out_gt, controller_final_state_gt = tf.nn.dynamic_rnn(
cell=cell_with_ground_truth,
inputs=rnn_inputs_with_ground_truth,
sequence_length=[SEQ_LEN]*BATCH_SIZE,
initial_state=controller_initial_state_gt,
dtype=tf.float32,
swap_memory=True,
time_major=False)
</code>```

All Input Variables:

```<code>cell_with_ground_truth:<__main__.SamplingRNNCell object at 0x7f3f88383250>
rnn_inputs_with_ground_truth:(<tf.Tensor 'dropout/mul:0' shape=(4, 10, 128) dtype=float32>, <tf.Tensor 'div:0' shape=(4, 10, 3) dtype=float32>)
[SEQ_LEN]:[10]
BATCH_SIZE:4
controller_initial_state_gt:(<tf.Tensor 'Identity_3:0' shape=(4, 3) dtype=float32>, LSTMStateTuple(c=<tf.Tensor 'Identity_4:0' shape=(4, 32) dtype=float32>, h=<tf.Tensor 'Identity_5:0' shape=(4, 32) dtype=float32>))
</code>```

Error Messgae:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-1911ca77ee35> in <module>()
     53         out_gt, controller_final_state_gt = tf.nn.dynamic_rnn(cell=cell_with_ground_truth, inputs=rnn_inputs_with_ground_truth,
     54                           sequence_length=[SEQ_LEN]*BATCH_SIZE, initial_state=controller_initial_state_gt, dtype=tf.float32,
---> 55                           swap_memory=True, time_major=False)
     56
     57     with tf.variable_scope("predictor", reuse=True):

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.pyc in dynamic_rnn(cell, inputs, sequence_length, initial_state, dtype, parallel_iterations, swap_memory, time_major, scope)
    572         swap_memory=swap_memory,
    573         sequence_length=sequence_length,
--> 574         dtype=dtype)
    575
    576     # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].
</code>```

.
.

```<code>/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.pyc in _AssertCompatible(values, dtype)
    300     else:
    301       raise TypeError("Expected %s, got %s of type '%s' instead." %
--> 302                       (dtype.name, repr(mismatch), type(mismatch).__name__))
    303
    304

TypeError: Expected int32, got list containing Tensors of type '_Message' instead.
</code>```

答:
I resolved this problem.

This is because cell_with_ground_truth object is come from one SamplingRNNCell function

In here, I found one line:
context = tf.concat(1, [prev_output, visual_feats]),

For TF 1.4, it should be fixed like this:
context = tf.concat([prev_output, visual_feats], 1),

same with this solution

Body:
I trying to convert following code to tensorflow 1.2 but I hard understand how to fixed it. Thanks for your any replying.

out_gt, controller_final_state_gt = tf.nn.dynamic_rnn(
cell=cell_with_ground_truth,
inputs=rnn_inputs_with_ground_truth,
sequence_length=[SEQ_LEN]*BATCH_SIZE,
initial_state=controller_initial_state_gt,
dtype=tf.float32,
swap_memory=True,
time_major=False)

All Input Variables:

cell_with_ground_truth:<__main__.SamplingRNNCell object at 0x7f3f88383250>
rnn_inputs_with_ground_truth:(<tf.Tensor 'dropout/mul:0' shape=(4, 10, 128) dtype=float32>, <tf.Tensor 'div:0' shape=(4, 10, 3) dtype=float32>)
[SEQ_LEN]:[10]
BATCH_SIZE:4
controller_initial_state_gt:(<tf.Tensor 'Identity_3:0' shape=(4, 3) dtype=float32>, LSTMStateTuple(c=<tf.Tensor 'Identity_4:0' shape=(4, 32) dtype=float32>, h=<tf.Tensor 'Identity_5:0' shape=(4, 32) dtype=float32>))

Error Messgae:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-1911ca77ee35> in <module>()
     53         out_gt, controller_final_state_gt = tf.nn.dynamic_rnn(cell=cell_with_ground_truth, inputs=rnn_inputs_with_ground_truth,
     54                           sequence_length=[SEQ_LEN]*BATCH_SIZE, initial_state=controller_initial_state_gt, dtype=tf.float32,
---> 55                           swap_memory=True, time_major=False)
     56
     57     with tf.variable_scope("predictor", reuse=True):

/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.pyc in dynamic_rnn(cell, inputs, sequence_length, initial_state, dtype, parallel_iterations, swap_memory, time_major, scope)
    572         swap_memory=swap_memory,
    573         sequence_length=sequence_length,
--> 574         dtype=dtype)
    575
    576     # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].

.
.

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.pyc in _AssertCompatible(values, dtype)
    300     else:
    301       raise TypeError("Expected %s, got %s of type '%s' instead." %
--> 302                       (dtype.name, repr(mismatch), type(mismatch).__name__))
    303
    304

TypeError: Expected int32, got list containing Tensors of type '_Message' instead.


问:
Reduce Application Size
In my last update my application size was 36 MB when i uploaded on app store. Then i added some pods files like Firebase Database ,storage and JSQMessagesViewController in my project after that when i uploaded my application its size increased and it become 101 MB. I'm shocked that how it is increased so and why? How can i reduced this size like about 40 MB? I have also used Bridge Header File in my project because firebase chat code is in swift and my project is in objective C.

答:
You can export an archive to an ipa from the organizer. Then rename the ipa file to .zip and extract it.

From there, you'll be able to see what component is taking how much space.

This is the file structure for my app that has been extracted

Title: Reduce Application Size