问:
How can I run script automatically after Docker container startup
I'm using Search Guard plugin to secure an elasticsearch cluster composed of multiple nodes.
Here is my Dockerfile:

```<code>#!/bin/sh
FROM docker.elastic.co/elasticsearch/elasticsearch:5.6.3

USER root

# Install search guard
RUN bin/elasticsearch-plugin install --batch com.floragunn:search-guard-5:5.6.3-16 \
    && chmod +x \
        plugins/search-guard-5/tools/hash.sh \
        plugins/search-guard-5/tools/sgadmin.sh \
        bin/init_sg.sh \
    && chown -R elasticsearch:elasticsearch /usr/share/elasticsearch

USER elasticsearch
</code>```

To initialize SearchGuard (create internal users and assign roles). I need to run the script init_sg.sh after the container startup.
Here is the problem: Unless elasticsearch is running, the script will not initialize any security index.

The script's content is :

```<code>sleep 10
plugins/search-guard-5/tools/sgadmin.sh -cd config/ -ts config/truststore.jks -ks config/kirk-keystore.jks -nhnv -icl
</code>```

Now, I just run the script manually after the container startup but since I'm running it on Kubernetes.. Pods may get killed or fail and get recreated automatically for some reason. In this case, the plugin have to be initialized automatically after the container startup!

So how to accomplish this? Any help or hint would be really appreciated.

答:
Not sure this will solves your problem, but its worth check my repo'sDockerfile

I have created a simple run.sh file copied to docker image and in the Dockerfile I wrote CMD ["run.sh"]. In the same way define whatever you want in run.sh and write CMD ["run.sh"]. You can find another example like below

Dockerfile

```<code>FROM java:8

RUN apt-get update && apt-get install stress-ng -y
ADD target/restapp.jar /restapp.jar
COPY dockerrun.sh /usr/local/bin/dockerrun.sh
RUN chmod +x /usr/local/bin/dockerrun.sh
CMD ["dockerrun.sh"]
</code>```

dockerrun.sh

```<code>#!/bin/sh
java -Dserver.port=8095 -jar /restapp.jar &
hostname="hostname: `hostname`"
nohup stress-ng --vm 4 &
while true; do
  sleep 1000
done
</code>```

Body:
I'm using Search Guard plugin to secure an elasticsearch cluster composed of multiple nodes.
Here is my Dockerfile:

#!/bin/sh
FROM docker.elastic.co/elasticsearch/elasticsearch:5.6.3

USER root

# Install search guard
RUN bin/elasticsearch-plugin install --batch com.floragunn:search-guard-5:5.6.3-16 \
    && chmod +x \
        plugins/search-guard-5/tools/hash.sh \
        plugins/search-guard-5/tools/sgadmin.sh \
        bin/init_sg.sh \
    && chown -R elasticsearch:elasticsearch /usr/share/elasticsearch

USER elasticsearch

To initialize SearchGuard (create internal users and assign roles). I need to run the script init_sg.sh after the container startup.
Here is the problem: Unless elasticsearch is running, the script will not initialize any security index.

The script's content is :

sleep 10
plugins/search-guard-5/tools/sgadmin.sh -cd config/ -ts config/truststore.jks -ks config/kirk-keystore.jks -nhnv -icl

Now, I just run the script manually after the container startup but since I'm running it on Kubernetes.. Pods may get killed or fail and get recreated automatically for some reason. In this case, the plugin have to be initialized automatically after the container startup!

So how to accomplish this? Any help or hint would be really appreciated.

Body:
Not sure this will solves your problem, but its worth check my repo'sDockerfile

I have created a simple run.sh file copied to docker image and in the Dockerfile I wrote CMD ["run.sh"]. In the same way define whatever you want in run.sh and write CMD ["run.sh"]. You can find another example like below

Dockerfile

FROM java:8

RUN apt-get update && apt-get install stress-ng -y
ADD target/restapp.jar /restapp.jar
COPY dockerrun.sh /usr/local/bin/dockerrun.sh
RUN chmod +x /usr/local/bin/dockerrun.sh
CMD ["dockerrun.sh"]

dockerrun.sh

#!/bin/sh
java -Dserver.port=8095 -jar /restapp.jar &
hostname="hostname: `hostname`"
nohup stress-ng --vm 4 &
while true; do
  sleep 1000
done


来源: stackexchange

问:
How to authenticate the express API to allow only logged In user
say for example in express.js if I'm having the api like this. I need to allow access to api only for logged in users.

Let me know how to authenticate it by JWT.

Refer my code which was hosted in glitch.

答:
You could try using passportjs.

It works well with express and has configurations for multiple types of authentication mechanisms such as Google, Facebook and Twitter. You can also configure it to work with a simple username password authentication method

Here is a good tutorial by JonathanMH on exactly what you are asking for

ContentLicense: CC BY-SA 3.0


问:
Option Strict Intellisense errors but compiles fine
I have just got a new work PC and am moving a solution from VS15 to 17.

When I edit existing source files, I get a bunch of errors relating to option strict, which include:

```<code>Option Strict On requires all variable declarations to have an 'As' clause
Option Strict On disallows implicit conversions from 'Object' to 'Integer'
Option Strict prohibits operands of type Object for operator '-'
Option Strict On disallows late binding
</code>```

In addition to this, I am getting errors about System classes not being found, for example Attribute, NotImplementedException, etc.

Option Strict is turned off for all solutions in the project.

The errors relating to Object to Integer are caused by i variables within loops, where the for line also has an error about late binding being disallowed.

I have tried deleting the vs folder within the solution but it made no difference.

The project compiles without issue. How can I fix the Intellisense errors?

答:
I think that there is a problem with the .suo files (or sqlite3 files) and VB.NET in Visual Studio 15.5.

Deleting .suo file manually or even the full .vs project subfolder doesn't solve it.

You need to open the solution, go to My Project -> Properties -> References.

You'll see that the Imported Namespaces in the bottom are all unchecked.

Scroll to System and enable it (mouse double click or space).

You'll probably receive an exception "Index was outside the bounds of array". Just ignore it but the intellisense problem should be solved now.

You have to do it for every VB.NET project is loaded with the solution.

It is the only workaround I found. I hope that they will fix it in the next release.

Another workaround: Disable Parallel Project Initialization

I found another workaround in the Visual Studio Feedback page (https://developercommunity.visualstudio.com/content/problem/160241/errors-reported-when-none-exist.html). Credits to Peter van den Berge.

Uncheck option "Allow parallel project initialization" (Tools > Options > Projects and Solutions > General). Reopen the solution.

Body:
I have just got a new work PC and am moving a solution from VS15 to 17.

When I edit existing source files, I get a bunch of errors relating to option strict, which include:

Option Strict On requires all variable declarations to have an 'As' clause
Option Strict On disallows implicit conversions from 'Object' to 'Integer'
Option Strict prohibits operands of type Object for operator '-'
Option Strict On disallows late binding

In addition to this, I am getting errors about System classes not being found, for example Attribute, NotImplementedException, etc.

Option Strict is turned off for all solutions in the project.

The errors relating to Object to Integer are caused by i variables within loops, where the for line also has an error about late binding being disallowed.

I have tried deleting the vs folder within the solution but it made no difference.

The project compiles without issue. How can I fix the Intellisense errors?


问:
Stick TextView on the top once it is scrolled to the top of the visible area
I'm working on this nestedscrollview for a while now. It contains a single child RelativeLayout. Here's the pseudo code.

```<code><NestedScrollView>
    <RelativeLayout>
         <TextView />  //text A
         <CalendaerView />
         <TextView /> //id = date_string //shows a date string
         <RecyclerView /> //list of events
    <RelativeLayout>
</NestedScrollView>
</code>```

The idea is while performing a scroll downwards, the entire view should scroll as normal, but once the date string TextView reaches top of the visible area, it has to stay on the top for further scroll down. However, when it is scrolled upwards, I should be able to see CalendarView and text A.

I tried scroll listener for nestedscrollview and created another textview outside nestedscrollview and changed the visibility.

```<code><RelativeLayout>
   <TextView /> //to mimic date string
  <NestedScrollView>
    <RelativeLayout>
       <TextView />  //text A
       <CalendaerView />
       <TextView /> //id = date_string //shows a date string
       <RecyclerView /> //list of events
   <RelativeLayout>
  </NestedScrollView>
</RelativeLayout>
</code>```

Here's the scroll listener logic

```<code>public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
      if (isDone && scrollY < oldScrollY) {
          //scroll up
          int firstVisibleItem = ((LinearLayoutManager) mRecycler.getLayoutManager())
                        .findFirstVisibleItemPosition();
                if(0 == firstVisibleItem) {
                    textA.setVisibility(View.VISIBLE);
                    calendarView.setVisibility(View.VISIBLE);
                    dateString.setVisibility(View.VISIBLE);
                    dateStringCopy.setVisibility(View.GONE);
                }
            }

            if (scrollY > oldScrollY) {
                //scroll down
                int dateTop = dateString.getTop();
                //check if datestring reaches the top of screen
                if(0 >= dateTop - scrollY) {
                    isDone = false;
                    textA.setVisibility(View.GONE);
                    calendarView.setVisibility(View.GONE);
                    dateString.setVisibility(View.GONE);
                    dateStringCopy.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isDone = true;
                        }
                    }, 50);
                }
            }
        }
</code>```

In reality, the experience is not very smooth as it involves changing visibility of views. Has anyone got any better way to solve this?

答:
Try this simple Github library project.

https://github.com/amarjain07/StickyScrollView

Body:
I'm working on this nestedscrollview for a while now. It contains a single child RelativeLayout. Here's the pseudo code.

<NestedScrollView>
    <RelativeLayout>
         <TextView />  //text A
         <CalendaerView />
         <TextView /> //id = date_string //shows a date string
         <RecyclerView /> //list of events
    <RelativeLayout>
</NestedScrollView>

The idea is while performing a scroll downwards, the entire view should scroll as normal, but once the date string TextView reaches top of the visible area, it has to stay on the top for further scroll down. However, when it is scrolled upwards, I should be able to see CalendarView and text A.

I tried scroll listener for nestedscrollview and created another textview outside nestedscrollview and changed the visibility.

<RelativeLayout>
   <TextView /> //to mimic date string
  <NestedScrollView>
    <RelativeLayout>
       <TextView />  //text A
       <CalendaerView />
       <TextView /> //id = date_string //shows a date string
       <RecyclerView /> //list of events
   <RelativeLayout>
  </NestedScrollView>
</RelativeLayout>

Here's the scroll listener logic

public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
      if (isDone && scrollY < oldScrollY) {
          //scroll up
          int firstVisibleItem = ((LinearLayoutManager) mRecycler.getLayoutManager())
                        .findFirstVisibleItemPosition();
                if(0 == firstVisibleItem) {
                    textA.setVisibility(View.VISIBLE);
                    calendarView.setVisibility(View.VISIBLE);
                    dateString.setVisibility(View.VISIBLE);
                    dateStringCopy.setVisibility(View.GONE);
                }
            }

            if (scrollY > oldScrollY) {
                //scroll down
                int dateTop = dateString.getTop();
                //check if datestring reaches the top of screen
                if(0 >= dateTop - scrollY) {
                    isDone = false;
                    textA.setVisibility(View.GONE);
                    calendarView.setVisibility(View.GONE);
                    dateString.setVisibility(View.GONE);
                    dateStringCopy.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isDone = true;
                        }
                    }, 50);
                }
            }
        }

In reality, the experience is not very smooth as it involves changing visibility of views. Has anyone got any better way to solve this?


问:
No log4j2 configuration file found. Using default configuration: logging only errors to the console
```<code>$ java -Dlog4j.configuration=file:///path/to/your/log4j2.xml -jar /path/to/your/jar_file.jar
</code>```

Written to the console, you get

```<code>ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
</code>```

But, it also looks like the configuration file has been found and was not parsable:

```<code>    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document root element "Configuration", must match DOCTYPE root "null".
    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document is invalid: no grammar found.
    log4j:ERROR DOM element is - not a <log4j:configuration> element.
    log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code>```

答:
I have solve this problem by configuring the build path. Here are the steps that I followed:
In eclipse.

create a folder and save the logj4 file in it.

Write click in the folder created and go to Build path.

Click on Add folder

Choose the folder created.

Click ok and Apply and close.

Now you should be able to run

Body:
$ java -Dlog4j.configuration=file:///path/to/your/log4j2.xml -jar /path/to/your/jar_file.jar

Written to the console, you get

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

But, it also looks like the configuration file has been found and was not parsable:

    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document root element "Configuration", must match DOCTYPE root "null".
    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document is invalid: no grammar found.
    log4j:ERROR DOM element is - not a <log4j:configuration> element.
    log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.


问:
opendialog.onhint crash
I have checked 100% I am closing all handles on a file I recently created. But when I call "opendialog.execute;" the dialog pop up as usual but on the mouse over hint of a recently created file the entire thing crashes with a out of bounds error.

I know this is not any of my out of bounds as if I open the file without causing a (onhint) event there is no problem and hardcoding a list of filenames for testing showed that there was nothing wrong with opening or saving a file. Its purely on the onhint event of the open dialog. Like I said if I am quick or I use arrow keys there is nothing wrong with my program.

Whats more interesting is that it doesnt even happen 100% of the time about 70% which has led to me thinking I have fixed it several time if not only for a short amount of time. Does anyone know what could be happening? And if not how can I disable the onhint event?

as aked for the code not that helps at all

```<code>OpenDialog.execute;    // crashes here
if fileexists(form1.OpenDialog.FileName) then
  form1.Address.Text:=form1.OpenDialog.FileName;
</code>```

and the error
link text

EDIT: ok i have some new information a new instance of opendialog still has the same issues. and more interestingly i seem to have solved the 30% issue its on hint of a file with a double tag for example "test.jpg.enc" the thing is its fine with it the first time it runs, and it only crashes on hint of these encoded files, but only if i have encoded that file white the applicatuion has benn open. for example if i encode it,, then try to decode and it crashes.. i can run it again and decode it fine,, but there is no problem with decoding and then encoding in one instance of the aplication.

答:
First -- it is almost never necessary to refer to "form1.xxx" in your code, /especially/ if you are writing code in a method of Form1.  I'd remove those references.

Then, I'd create as simple an application as possible -- a form, a TOpenDialog, and a button, and I'd try to write as little code as possible to open the file in question.  If that works, try to figure out what the difference is between your simple app and your real app.  If it fails, edit your question above with /all/ the code for the simple program that fails.

OwnerDisplayName: Arthur

ContentLicense: CC BY-SA 2.5

Title: opendialog.onhint crash

Body:
I have checked 100% I am closing all handles on a file I recently created. But when I call "opendialog.execute;" the dialog pop up as usual but on the mouse over hint of a recently created file the entire thing crashes with a out of bounds error.

I know this is not any of my out of bounds as if I open the file without causing a (onhint) event there is no problem and hardcoding a list of filenames for testing showed that there was nothing wrong with opening or saving a file. Its purely on the onhint event of the open dialog. Like I said if I am quick or I use arrow keys there is nothing wrong with my program.

Whats more interesting is that it doesnt even happen 100% of the time about 70% which has led to me thinking I have fixed it several time if not only for a short amount of time. Does anyone know what could be happening? And if not how can I disable the onhint event?

as aked for the code not that helps at all

OpenDialog.execute;    // crashes here
if fileexists(form1.OpenDialog.FileName) then
  form1.Address.Text:=form1.OpenDialog.FileName;

and the error
link text

EDIT: ok i have some new information a new instance of opendialog still has the same issues. and more interestingly i seem to have solved the 30% issue its on hint of a file with a double tag for example "test.jpg.enc" the thing is its fine with it the first time it runs, and it only crashes on hint of these encoded files, but only if i have encoded that file white the applicatuion has benn open. for example if i encode it,, then try to decode and it crashes.. i can run it again and decode it fine,, but there is no problem with decoding and then encoding in one instance of the aplication.

LastEditorDisplayName: Arthur

OwnerDisplayName: Nick Hodges


问:
Ng-if inside ng-template does not work
I created a component and I am trying to make the component's template dynamic, that is, for some condition the parent tag should be a div, otherwise it should be an anchor tag.

I have been trying to use ng-if but somehow it wont work. Here is a code snippet. For some reason, even if the ng-if is true, the nested div (.testDiv .testThumbnail) will be undefined and this will break my component.

I cannot understand why it doesn't find the component even if the ng-if is true. I am new to Angular JS, so maybe I am missing something here? Or there is a better way to dynamically create the component's parent tags according to some condition.

function myCardController($window) {
   var element = angular.element(document.querySelector('.testDiv .testThumbnail'));//is undefined
}

angular.module('myApp').component('myCard', {
 templateUrl: 'testTemplate', ,
 controller: ["$window", myCardController],
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/ng-template" id="testTemplate">
  <div ng-if="true"
       class="testDiv">
       <div role="img" class="testThumbnail"></div>
  </div>
  same content
</script></code>```

答:
You probably miss to add ng-app or ng-controller directive. Use following HTML as your template:

```<code><div ng-controller = "myCardController">
  <div ng-if="show"
       class="testDiv">
       <div role="img" class="testThumbnail"></div>
  </div>
  <a ng-if="!show" class="tesstDiv">same content</a>
</div>
</code>```

Update your JS code as like:

```<code>function myCardController($window) {
   var element = angular.element(document.querySelector('.testDiv .testThumbnail'));//is undefined
   $scope.show = true;
}

angular.module('myApp').component('myCard', {
    templateUrl: 'testTemplate.html', ,
    controller: ["$window", myCardController],
});
</code>```

You also can use ng-app="myApp" in your body tag.

Title: Ng-if inside ng-template does not work

Body:
You probably miss to add ng-app or ng-controller directive. Use following HTML as your template:

<div ng-controller = "myCardController">
  <div ng-if="show"
       class="testDiv">
       <div role="img" class="testThumbnail"></div>
  </div>
  <a ng-if="!show" class="tesstDiv">same content</a>
</div>

Update your JS code as like:

function myCardController($window) {
   var element = angular.element(document.querySelector('.testDiv .testThumbnail'));//is undefined
   $scope.show = true;
}

angular.module('myApp').component('myCard', {
    templateUrl: 'testTemplate.html', ,
    controller: ["$window", myCardController],
});

You also can use ng-app="myApp" in your body tag.


问:
How to set the height of panel screen header in Feathers UI?
I created a PanelScreen from feathers.controls. However, I feel like I can only change the width of its header, How can I change the height of its header?

for example:

```<code>var layout:PanelScreen=new PanelScreen;
layout.title = 'mm';
this.addChild(layout);
layout.validate();
layout.width = 100; // it works
layout.height = 100; // it doesn't work
</code>```

答:
you need to change the panel's headerFactory like this

panel.headerFactory = function():Header
{
    var header:Header = new Header();
    header.height = 100;
    return header;
};
```

ContentLicense: CC BY-SA 4.0

Body:
I created a PanelScreen from feathers.controls. However, I feel like I can only change the width of its header, How can I change the height of its header?

for example:

var layout:PanelScreen=new PanelScreen;
layout.title = 'mm';
this.addChild(layout);
layout.validate();
layout.width = 100; // it works
layout.height = 100; // it doesn't work


问:
Jquery autocomplete from json data
i have country related data stored as json. i want to show country name from that json array. i use jquery autocomplete. this is my code which i tried but not working. give me some hint that where is the mistake.

```<code><input type="text" class="form-control" id="plugins" name="plugins" />

var myData =[
    {"name": "Afghanistan"},
    {"name": "Åland Islands"},
    {"name": "Albania"},
    {"name": "Algeria"},
    {"name": "American Samoa"},
    {"name": "Bahamas"},
    {"name": "Bahrain"},
    {"name": "Bangladesh"},
    {"name": "Barbados"},
    {"name": "Belarus"},
    {"name": "Belgium"},
    {"name": "Belize"},
    {"name": "Benin"},
    {"name": "Cambodia"},
    {"name": "Cameroon"},
    {"name": "Canada"},
    {"name": "Cape Verde"},
    {"name": "Cayman Islands"},
    {"name": "Viet Nam"},
    {"name": "Virgin Islands, British"},
    {"name": "Virgin Islands, U.S."},
    {"name": "Wallis and Futuna"},
    {"name": "Western Sahara"},
    {"name": "Yemen"},
    {"name": "Zambia"},
    {"name": "Zimbabwe"}
]

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.indexOf(req.term) != -1) {
          results.push(v);
          return;
        }
      });
      resp(results);
    }
  });
});
</code>```

here is jsfiddle version https://jsfiddle.net/urtkxo46/2/

this is working version of jsfiddle https://jsfiddle.net/durga598/urtkxo46/5/

答:
In your result array you need to push results.push(v.name); to match case insensitive use toLowerCase() , so it will match all the values properly.
You need to use source an array or string or a function returns object with key: label and value .

/*var myData = [{
  label: "xxx",
  value: "9997515744"
}, {
  label: "abc",
  value: "9619054073"
}, {
  label: "asd",
  value: "9323135708"
}];*/

var myData =[
 {"name": "Afghanistan"},
 {"name": "Åland Islands"},
 {"name": "Albania"},
 {"name": "Algeria"},
 {"name": "American Samoa"},
 {"name": "Bahamas"},
 {"name": "Bahrain"},
 {"name": "Bangladesh"},
 {"name": "Barbados"},
 {"name": "Belarus"},
 {"name": "Belgium"},
 {"name": "Belize"},
 {"name": "Benin"},
 {"name": "Cambodia"},
 {"name": "Cameroon"},
 {"name": "Canada"},
 {"name": "Cape Verde"},
 {"name": "Cayman Islands"},
 {"name": "Viet Nam"},
 {"name": "Virgin Islands, British"},
 {"name": "Virgin Islands, U.S."},
 {"name": "Wallis and Futuna"},
 {"name": "Western Sahara"},
 {"name": "Yemen"},
 {"name": "Zambia"},
 {"name": "Zimbabwe"}
]

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        if (v.name.toLowerCase().startsWith(req.term.toLowerCase())) {
          results.push(v.name);
          return;
        }
      });
      //console.log(results)
      resp(results);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" class="form-control" id="plugins" name="plugins" /></code>```

Title: Jquery autocomplete from json data

Body:
i have country related data stored as json. i want to show country name from that json array. i use jquery autocomplete. this is my code which i tried but not working. give me some hint that where is the mistake.

<input type="text" class="form-control" id="plugins" name="plugins" />

var myData =[
    {"name": "Afghanistan"},
    {"name": "Åland Islands"},
    {"name": "Albania"},
    {"name": "Algeria"},
    {"name": "American Samoa"},
    {"name": "Bahamas"},
    {"name": "Bahrain"},
    {"name": "Bangladesh"},
    {"name": "Barbados"},
    {"name": "Belarus"},
    {"name": "Belgium"},
    {"name": "Belize"},
    {"name": "Benin"},
    {"name": "Cambodia"},
    {"name": "Cameroon"},
    {"name": "Canada"},
    {"name": "Cape Verde"},
    {"name": "Cayman Islands"},
    {"name": "Viet Nam"},
    {"name": "Virgin Islands, British"},
    {"name": "Virgin Islands, U.S."},
    {"name": "Wallis and Futuna"},
    {"name": "Western Sahara"},
    {"name": "Yemen"},
    {"name": "Zambia"},
    {"name": "Zimbabwe"}
]

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.indexOf(req.term) != -1) {
          results.push(v);
          return;
        }
      });
      resp(results);
    }
  });
});

here is jsfiddle version https://jsfiddle.net/urtkxo46/2/

this is working version of jsfiddle https://jsfiddle.net/durga598/urtkxo46/5/

Body:
In your result array you need to push results.push(v.name); to match case insensitive use toLowerCase() , so it will match all the values properly.
You need to use source an array or string or a function returns object with key: label and value .

/*var myData = [{
  label: "xxx",
  value: "9997515744"
}, {
  label: "abc",
  value: "9619054073"
}, {
  label: "asd",
  value: "9323135708"
}];*/

var myData =[
 {"name": "Afghanistan"},
 {"name": "Åland Islands"},
 {"name": "Albania"},
 {"name": "Algeria"},
 {"name": "American Samoa"},
 {"name": "Bahamas"},
 {"name": "Bahrain"},
 {"name": "Bangladesh"},
 {"name": "Barbados"},
 {"name": "Belarus"},
 {"name": "Belgium"},
 {"name": "Belize"},
 {"name": "Benin"},
 {"name": "Cambodia"},
 {"name": "Cameroon"},
 {"name": "Canada"},
 {"name": "Cape Verde"},
 {"name": "Cayman Islands"},
 {"name": "Viet Nam"},
 {"name": "Virgin Islands, British"},
 {"name": "Virgin Islands, U.S."},
 {"name": "Wallis and Futuna"},
 {"name": "Western Sahara"},
 {"name": "Yemen"},
 {"name": "Zambia"},
 {"name": "Zimbabwe"}
]

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        if (v.name.toLowerCase().startsWith(req.term.toLowerCase())) {
          results.push(v.name);
          return;
        }
      });
      //console.log(results)
      resp(results);
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" class="form-control" id="plugins" name="plugins" />


问:
Is there a better way to design the Message model?
Is there a better way to design the Message model ?

I have a Message model:

```<code>class Message(models.Model):
    """
    message
    """
    title = models.CharField(max_length=64, help_text="title")
    content = models.CharField(max_length=1024, help_text="content")

    is_read = models.BooleanField(default=False, help_text="whether message is read")

    create_user = models.ForeignKey(User, related_name="messages",help_text="creator")
    receive_user = models.CharField(max_length=1024, help_text="receive users' id")

    def __str__(self):
        return self.title
    def __unicode__(self):
        return self.title
</code>```

You see, I use models.CharField to store the users' id, so I can know the users who should receive this row message.

I don't know whether this design type is good. or is there a better way to do that?

I have considered use ManyToMany Field, but I think if user is too many, the admin create one message will create as many as users count, so I think this is not a good idea.

答:
So it actually depends on your needs in which direction I would change your message Model.

General Changes

Based on the guess: you don't ever need an index on the content field

I would change the content to a TextField (alse because the length of 1024 is already to large for a propper index on mysql for example) https://docs.djangoproject.com/en/1.11/ref/databases/#textfield-limitations here some more infos about this topic.

I would pbly increase the size of the title field just because it seems convenient to me.

1. Simple -> One User to One User

The single read field indicates a one to one message:

I would change the Receiver to also be a Foreign key and adapt the related names of the sender and receiver field to represent these connections to something like sent-messages and received-messages.

Like @sebastian-fleck already suggested I'd also change the read field to a datetime field, it only changes your querysets from filter(read=True) to filter(read__isnull=False) to get the same results and you could create a property representing the read as boolean for conveniance, e.g.

```<code>@property
def read(self):
    return bool(self.read_datetime)  # assumed read as a datetime is read_datetime
</code>```

2. More Complex: One User to Multiple User

This can get a lot more complex, here the least complex solution I could think of.

Conditions:
- there are only messages and no conversation like strukture
- a message should have a read status for every receiver

(I removed descriptions for an easier overview and changed the models according to my opinions from before, this is based on my experience and the business needs I assumed from your example and answers)

```<code>@python_2_unicode_compatible
class Message(models.Model):
    title = models.CharField(max_length=160)
    content = models.TextField()

    create_user = models.ForeignKey(User, related_name="sent-messages")
    receive_users = models.ManyToManyField(User, through=MessageReceiver)

    def __str__(self):
        return 'Message: %s' % self.title

@python_2_unicode_compatible
class MessageReceiver(models.Model):
    is_read = models.Datetime(null=True, blank=True)
    receiver = models.ForeignKey(User)
    message = models.ForeignKey(Message)
</code>```

This structure is using the power of ManyToMany with a custom through Model, check this out, it very mighty: https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ManyToManyField.through.

tldr: we want every receiver to have a read status, so we modeled this in a separate object

Longer version: we utilize the power of a custom ManyToMany through model to have a separate read status for every receiver. This means we need to change some parts of our code to work for the many to many structure, e.g. if we want to know if a message was read by all receivers:

```<code>def did_all_receiver_read_the_message(message)
    unread_count = my_message.receive_users.filter(is_read__isnull=True).count()
    if unread_count > 0:
        return True
    return False
</code>```

if we want to know if a specific user read a specific message:

```<code>def did_user_read_this_message(user, message)
    receiver = message.receive_users.get(receiver=user)
    return bool(receiver.is_read)
</code>```

3. Conversations + Messages + Participants

This is something that would exceed my time limit but some short hints:

Conversation holds everything together

Message is written by a Participant and holds a created timestamp

Participant allows access to a conversation and links a User to the Conversation object

the Participant holds a last_read timestamp with can be used to calculate if a message was read or not using the messages created timestamps (-> annoyingly complex part & milliseconds are important)

Everything else pbly would need to be adapted to your specific business needs. This scenario is pbly the most flexible but it's a lot of work (based on personal experience) and adds quite a bit of complexity to your architecture - I only recommend this if it's really really needed ^^.

Disclaimer:

This could be an overall structure, most design decisions I made for the examples are based on assumptions, I could only mentioned some or the text would to long, but feel free to ask.

Please excuse any typos and errors, I didn't had the chance to run the code.

Body:
Is there a better way to design the Message model ?

I have a Message model:

class Message(models.Model):
    """
    message
    """
    title = models.CharField(max_length=64, help_text="title")
    content = models.CharField(max_length=1024, help_text="content")

    is_read = models.BooleanField(default=False, help_text="whether message is read")

    create_user = models.ForeignKey(User, related_name="messages",help_text="creator")
    receive_user = models.CharField(max_length=1024, help_text="receive users' id")

    def __str__(self):
        return self.title
    def __unicode__(self):
        return self.title

You see, I use models.CharField to store the users' id, so I can know the users who should receive this row message.

I don't know whether this design type is good. or is there a better way to do that?

I have considered use ManyToMany Field, but I think if user is too many, the admin create one message will create as many as users count, so I think this is not a good idea.

Body:
So it actually depends on your needs in which direction I would change your message Model.

General Changes

Based on the guess: you don't ever need an index on the content field

I would change the content to a TextField (alse because the length of 1024 is already to large for a propper index on mysql for example) https://docs.djangoproject.com/en/1.11/ref/databases/#textfield-limitations here some more infos about this topic.

I would pbly increase the size of the title field just because it seems convenient to me.

1. Simple -> One User to One User

The single read field indicates a one to one message:

I would change the Receiver to also be a Foreign key and adapt the related names of the sender and receiver field to represent these connections to something like sent-messages and received-messages.

Like @sebastian-fleck already suggested I'd also change the read field to a datetime field, it only changes your querysets from filter(read=True) to filter(read__isnull=False) to get the same results and you could create a property representing the read as boolean for conveniance, e.g.

@property
def read(self):
    return bool(self.read_datetime)  # assumed read as a datetime is read_datetime

2. More Complex: One User to Multiple User

This can get a lot more complex, here the least complex solution I could think of.

Conditions:
- there are only messages and no conversation like strukture
- a message should have a read status for every receiver

(I removed descriptions for an easier overview and changed the models according to my opinions from before, this is based on my experience and the business needs I assumed from your example and answers)

@python_2_unicode_compatible
class Message(models.Model):
    title = models.CharField(max_length=160)
    content = models.TextField()

    create_user = models.ForeignKey(User, related_name="sent-messages")
    receive_users = models.ManyToManyField(User, through=MessageReceiver)

    def __str__(self):
        return 'Message: %s' % self.title

@python_2_unicode_compatible
class MessageReceiver(models.Model):
    is_read = models.Datetime(null=True, blank=True)
    receiver = models.ForeignKey(User)
    message = models.ForeignKey(Message)

This structure is using the power of ManyToMany with a custom through Model, check this out, it very mighty: https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ManyToManyField.through.

tldr: we want every receiver to have a read status, so we modeled this in a separate object

Longer version: we utilize the power of a custom ManyToMany through model to have a separate read status for every receiver. This means we need to change some parts of our code to work for the many to many structure, e.g. if we want to know if a message was read by all receivers:

def did_all_receiver_read_the_message(message)
    unread_count = my_message.receive_users.filter(is_read__isnull=True).count()
    if unread_count > 0:
        return True
    return False

if we want to know if a specific user read a specific message:

def did_user_read_this_message(user, message)
    receiver = message.receive_users.get(receiver=user)
    return bool(receiver.is_read)

3. Conversations + Messages + Participants

This is something that would exceed my time limit but some short hints:

Conversation holds everything together

Message is written by a Participant and holds a created timestamp

Participant allows access to a conversation and links a User to the Conversation object

the Participant holds a last_read timestamp with can be used to calculate if a message was read or not using the messages created timestamps (-> annoyingly complex part & milliseconds are important)

Everything else pbly would need to be adapted to your specific business needs. This scenario is pbly the most flexible but it's a lot of work (based on personal experience) and adds quite a bit of complexity to your architecture - I only recommend this if it's really really needed ^^.

Disclaimer:

This could be an overall structure, most design decisions I made for the examples are based on assumptions, I could only mentioned some or the text would to long, but feel free to ask.

Please excuse any typos and errors, I didn't had the chance to run the code.


问:
How to store an image in a JavaScript variable and render it to the web page?
I am trying to put a small .jpg file inside a JavaScript variable so that it can be rendered to the web page. I do not want to store the path to the image, but the actual image itself.

Even though I think this should be possible, I don't exactly know how to go about this. I would like all processing to be client-side.

答:
Always the contrarian:</p>

```<code>var img = new Image();
img.src = 'whatever.jpg';
</code>```

Body:
Always the contrarian:

var img = new Image();
img.src = 'whatever.jpg';


问:
UICollectionView's cellForItemAtIndexPath is not being called
Only my second time using UICollectionView's and perhaps I have bitten off more than I can chew but nevertheless:

I am implementing a UICollectionView (myCollectionView) that uses custom UICollectionViewCell's that I have subclassed.  The subclassed cells (FullReceiptCell) contain UITableView's and are the size of the viewcontroller.  I am trying to allow for horizontal scrolling between the FullReceiptCells.

The subclassed UICollectionViewController that contains myCollectionView is being pushed on to a nav controller stack.  Currently, myCollectionView loas and horizontal scrolling is enabled.  However, no cells are visible.  I have confirmed that

```<code>- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
</code>```

has run and is returning an integer greater than 0.  I have also confirmed that myCollectionView's delegate and datasource are properly set in IB to the subclassed UICollectionViewController.

The method where the cells are to be loaded:

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
</code>```

is not being called.

Here is where I push the UICollectionViewController and my viewDidLoad method within that controller (NOTE: initWithBill is an override of the normal initializer):

In the prior ViewControllers .m file:

```<code>FullReceiptViewController *test = [[FullReceiptViewController alloc] initWithBill:currentBill];
test.title = @"Review";
[self.navigationController pushViewController:test animated:YES];
</code>```

In FullReceiptViewController.m:

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.myCollectionView registerClass:[FullReceiptCell class] forCellWithReuseIdentifier:@"FullReceiptCellIdentifier"];
    self.myCollectionView.pagingEnabled = YES;
    // Setup flowlayout

    self.myCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    [self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)];
    [self.myCollectionViewFlowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.myCollectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.myCollectionViewFlowLayout.minimumLineSpacing = 0;
    self.myCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    [self.myCollectionView setCollectionViewLayout:myCollectionViewFlowLayout];
    //testing to see if the collection view is loading
    self.myCollectionView.backgroundColor = [UIColor colorWithWhite:0.25f alpha:1.0f];
</code>```

Any clue as to why it is not being called?

答: In my case the collection view was not fully visible in its parent view due to wrong auto layout constraints. So fixing the constraints made the collection view all visible and cellForItemAtIndexPath was called.</p>

Body:
Only my second time using UICollectionView's and perhaps I have bitten off more than I can chew but nevertheless:

I am implementing a UICollectionView (myCollectionView) that uses custom UICollectionViewCell's that I have subclassed.  The subclassed cells (FullReceiptCell) contain UITableView's and are the size of the viewcontroller.  I am trying to allow for horizontal scrolling between the FullReceiptCells.

The subclassed UICollectionViewController that contains myCollectionView is being pushed on to a nav controller stack.  Currently, myCollectionView loas and horizontal scrolling is enabled.  However, no cells are visible.  I have confirmed that

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

has run and is returning an integer greater than 0.  I have also confirmed that myCollectionView's delegate and datasource are properly set in IB to the subclassed UICollectionViewController.

The method where the cells are to be loaded:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

is not being called.

Here is where I push the UICollectionViewController and my viewDidLoad method within that controller (NOTE: initWithBill is an override of the normal initializer):

In the prior ViewControllers .m file:

FullReceiptViewController *test = [[FullReceiptViewController alloc] initWithBill:currentBill];
test.title = @"Review";
[self.navigationController pushViewController:test animated:YES];

In FullReceiptViewController.m:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.myCollectionView registerClass:[FullReceiptCell class] forCellWithReuseIdentifier:@"FullReceiptCellIdentifier"];
    self.myCollectionView.pagingEnabled = YES;
    // Setup flowlayout

    self.myCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    [self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)];
    [self.myCollectionViewFlowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.myCollectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.myCollectionViewFlowLayout.minimumLineSpacing = 0;
    self.myCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    [self.myCollectionView setCollectionViewLayout:myCollectionViewFlowLayout];
    //testing to see if the collection view is loading
    self.myCollectionView.backgroundColor = [UIColor colorWithWhite:0.25f alpha:1.0f];

Any clue as to why it is not being called?


问:
Navbar not doing the same behavior in Chrome and Firefox
i'm doing a website, and even if my code is a little dirty(With some "inline css" that i'm going to remove), it's nearly finished.
My major problem here is that my collapsing navbar is acting very well in chrome, but not in firefox when I resize exactly the same way.
Here is the site : http://www.castegnaro-exterieur.fr/
Let me show you with images:

And here with Chrome there is absolutely no problem

I would like someone to help me correcting this flaw, I think Chrome and Firefox got maybe some differences, like my font-weight is not working too in the title, you can see it bold in Chrome and not bold in firefox even it's the same code of course.
Sorry for my poor english I hope you get my problem, and can help me understand these browsers differences, you can link me some good article if you wish too :).

答:
The box-model is different between Firefox and Chrome. Chrome uses one that is similar to IE. Refer to this article: CSS Box Model Differences.

I am guessing that this is the root cause of the issues you are seeing.


问:
CSS to fit image to container when image is smaller than the container
I have the following CSS code which works fine to fit an image to its container while keeping the image size ratio.

```<code>img { /* ASSUMING THE IMAGE IS WIDER THAN 150PX OR HIGHER THAN 100PX */
    max-height: 100%;
    max-width: 100%;
}
div.mydiv1 {
    width: 150px;
    height: 100px;
    background-color:red;
}
</code>```

However, if the image is both shorter and narrower than the container, it does stretch to fit (keeping size ratio). Is there a way to do this?

Here a fiddle... http://jsfiddle.net/many_tentacles/uz3e7/

答:
Use object-fit: cover on the  element:

```<code>img { object-fit: cover; }
</code>```

Body:
I have the following CSS code which works fine to fit an image to its container while keeping the image size ratio.

img { /* ASSUMING THE IMAGE IS WIDER THAN 150PX OR HIGHER THAN 100PX */
    max-height: 100%;
    max-width: 100%;
}
div.mydiv1 {
    width: 150px;
    height: 100px;
    background-color:red;
}

However, if the image is both shorter and narrower than the container, it does stretch to fit (keeping size ratio). Is there a way to do this?

Here a fiddle... http://jsfiddle.net/many_tentacles/uz3e7/

Body:
Use object-fit: cover on the <img> element:

img { object-fit: cover; }


问:
Playing RTP stream from embedded device using sockets
I'm writing an application on an embedded device which receives an RTP stream which carries G.729, PCM or H.264. The packets arrive to my application as a char* to the RTP packet. I would like to be able to see or listen to the stream (as a test), but on this device I don't have player. I thought I may forward this stream to a socket and play the RTP stream somewhere else, like on a Linux machine running a player. Would this be possible? I don't have RTSP, only RTP. Is VLC, for instance, a possible way to do this? Can I simply send the RTP packets to the socket to play them on the other side?
Thanks!</p>

答: You can forward RTP packets over a UDP socket.</p>


问:
How to authenticate against a mongod instance in sharded cluster after security has been enabled?
I am working with a mongo cluster with 3 shards. Each shard replica-set in turn has 3 members. Security is enabled and I created users with clusteradmin, useradmin etc. roles, also many users whose access confined to particular databases.
But now I have a problem when I am trying to collect storage engine (wired tiger in our case) stats. For that I need to directly connect to individual mongodb node in each replica-set and issue db.serverStatus() command. But, authentication is failing with all the users with clusteradmin, useradmin etc. privileges.
How can I directly connect and authenticate (bypassing mongos) to a mongod node in the cluster and collect stats.</p>

答:
You can connect to individual instance with regular mongo command, e.g.

```<code>mongo mongodb://host_name:port/db_name --authenticationDatabase admin --username ... --password ...
</code>```

Tested with dbAdmin role, db.serverStatus() works fine. clusterAdmin and userAdmin roles are not quite suitable for the job.

Body:
You can connect to individual instance with regular mongo command, e.g.

mongo mongodb://host_name:port/db_name --authenticationDatabase admin --username ... --password ...

Tested with dbAdmin role, db.serverStatus() works fine. clusterAdmin and userAdmin roles are not quite suitable for the job.


问:
java synchronization with executor framework
What's wrong with this code?

```<code>public class SimpleThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 2000; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        WorkerThread obj = new WorkerThread();
        System.out.println(obj.getCount());
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private String command;
    private volatile static int count;
    public WorkerThread(){
    }
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        try {
            synchronized (this) {
                processCommand();
            }

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

    private void processCommand() throws InterruptedException {
        count++;
        System.out.println("count " + count);
        //Thread.sleep(500);
    }

    @Override
    public String toString(){
        return this.command;
    }

    public int getCount(){
        return count;
    }
}
</code>```

I am trying to get the result of count as 2000 and that too at end... What's wrong with my code??

How can I make sure that the count is always incremented in correct order??

When should I use volatile or synchronized block or both??

答: as @Keppil mentioned, you can not use synchronized (this) . because in this case every thread works on different object but as per your requirement you need to increment variable under same object. and this is what i found wrong with your code. please use synchronized (WorkerThread.class) to achieve result you want. in this way every thread will work in synchronized way only. and yes you can remove volatile keyword for your requirement.

Body:
What's wrong with this code?

public class SimpleThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 2000; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        WorkerThread obj = new WorkerThread();
        System.out.println(obj.getCount());
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private String command;
    private volatile static int count;
    public WorkerThread(){
    }
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        try {
            synchronized (this) {
                processCommand();
            }

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

    private void processCommand() throws InterruptedException {
        count++;
        System.out.println("count " + count);
        //Thread.sleep(500);
    }

    @Override
    public String toString(){
        return this.command;
    }

    public int getCount(){
        return count;
    }
}

I am trying to get the result of count as 2000 and that too at end... What's wrong with my code??

How can I make sure that the count is always incremented in correct order??

When should I use volatile or synchronized block or both??


问:
remove an elements ability to open a modal after first click
I have a square that opens like a door when you click it. I also have a data attribute attached to it, which opens a modal. So basically the door opens and reveals a modal.

What I want, is to show the animation, open the modal ONCE, then disable it.

```<code>$(document).on("click", function(){
    $('.door_1').addClass('doorOpen');
});
</code>```

```

Adding the doorOpen class is what triggers the door opening animation. So is there a way to remove the data-attribute after the initial click?

答:
You can create an animation with setTimeOut like below:

```<code>$('.door_1').addClass('doorOpen');
setTimeout(function () {
  $('#modal-1').modal('hide');
  $('.door_1').removeClass('doorOpen');
}, 1000);
</code>```

This will close the modal after 1 second or 1000 milliseconds.

Body:
I have a square that opens like a door when you click it. I also have a data attribute attached to it, which opens a modal. So basically the door opens and reveals a modal.

What I want, is to show the animation, open the modal ONCE, then disable it.

$(document).on("click", function(){
    $('.door_1').addClass('doorOpen');
});

Adding the doorOpen class is what triggers the door opening animation. So is there a way to remove the data-attribute after the initial click?

Body:
You can create an animation with setTimeOut like below:

$('.door_1').addClass('doorOpen');
setTimeout(function () {
  $('#modal-1').modal('hide');
  $('.door_1').removeClass('doorOpen');
}, 1000);

This will close the modal after 1 second or 1000 milliseconds.


问:
App developed in Xcode for native iOS
We have our native iOS app developed in Xcode and now software developer is saying that we should upgrade our code to Xcode 9 as we may face issue with the new release on the App Store if we continue using Xcode for development. I would like to know if this is a fact, since I am not from iOS development and I don't know if this is a fact.

Any help in this regarding or a pointer to documentation would be appreciated.

答:
Yes, your developer is absolutely right.

General Suggestion: Your project/app source code should be compatible with latest technological upgrades.

Why should you move your app development on Xcode 9?

Here are several useful stack over flow discussions (questions and answers), explaining, new changes with Xcode 9.

Xcode 9 Release Notes

iPhone-X interface support - Safe Area of Xcode 9

Swift 4 - Code migration from Swift 2.x to Swift 4

Face-Id Authentication (If you have used biometric authentication)

Facebook integration IOS 11 & FBSDKShareDialog not working on IOS11

Navigation Controller and Navigation Bars

Title: App developed in Xcode for native iOS


问:
How to show custom dialog at Center Vertical
See the screen shot the dialog is not showing center vertically and unexpected margin

I have tried many example but no one solve this.
please refer to screen shot so you will understand very easy,what my problem is.
"As you see - Dialog appear with unexpected margin"

i have also try this

Window window = dialog.getWindow();
                  window.setLayout(AppBarLayout.LayoutParams.WRAP_CONTENT,
                  AppBarLayout.LayoutParams.WRAP_CONTENT);
                  window.setGravity(Gravity.CENTER);

java code is -

```<code>final Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.dialogforgot_password);
            final EditText et_emailforgot = (EditText)dialog.findViewById(R.id.et_EnterMail);
            final Button bt_SubmitForgotPass = (Button)dialog.findViewById(R.id.bt_SubmitForgotButton);
            final TextView ForgotHeading = (TextView)dialog.findViewById(R.id.tv_forgotpasswordHeading);
            final TextView PleaseEnterurMail = (TextView)dialog.findViewById(R.id.tv_Enteruremail);
            et_emailforgot.setTypeface(Lato_Regular);
            PleaseEnterurMail.setTypeface(Lato_Regular);
            ForgotHeading.setTypeface(Lato_Bold);
            bt_SubmitForgotPass.setTypeface(Lato_Bold);
            dialog.show();
</code>```

and my XML file is as Follows:

```<code><RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_windowcorner"
>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/rounded_headingcorner"
    android:layout_alignParentTop="true"
    android:id="@+id/RLForgot">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Forgot Password"
        android:textColor="#ffffff"
        android:textSize="16dp"
        android:id="@+id/tv_forgotpasswordHeading"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please Enter Your Registered Email id"
        android:textColor="#000000"
        android:textSize="17dp"
        android:layout_marginRight="22dp"
        android:layout_marginLeft="22dp"
        android:id="@+id/tv_Enteruremail"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/RLForgot"
        android:layout_marginTop="20dp"
        android:textAlignment="center"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:id="@+id/et_EnterMail"
        android:hint="Enter Your Email Id Here"
        android:singleLine="true"
        android:background="@drawable/custom_spinner_background"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="40dp"
        android:layout_below="@+id/tv_Enteruremail"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="Submit"
        android:background="@drawable/signin_btn"
        android:textColor="@color/signinlogcolor"
        style="?android:attr/borderlessButtonStyle"
        android:id="@+id/bt_SubmitForgotButton"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="10dp"
        android:layout_below="@+id/et_EnterMail"
        android:layout_centerHorizontal="true" />
        </RelativeLayout>
</code>```

答:
what my problem is. "As you see - Dialog appear with unexpected margin"

it is called Dialog title  Use dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
 to remove title from Dialog like below code

Try this

```<code>final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialogforgot_password);
</code>```

Body:
See the screen shot the dialog is not showing center vertically and unexpected margin

I have tried many example but no one solve this.
please refer to screen shot so you will understand very easy,what my problem is.
"As you see - Dialog appear with unexpected margin"

i have also try this

Window window = dialog.getWindow();
                  window.setLayout(AppBarLayout.LayoutParams.WRAP_CONTENT,
                  AppBarLayout.LayoutParams.WRAP_CONTENT);
                  window.setGravity(Gravity.CENTER);

java code is -

final Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.dialogforgot_password);
            final EditText et_emailforgot = (EditText)dialog.findViewById(R.id.et_EnterMail);
            final Button bt_SubmitForgotPass = (Button)dialog.findViewById(R.id.bt_SubmitForgotButton);
            final TextView ForgotHeading = (TextView)dialog.findViewById(R.id.tv_forgotpasswordHeading);
            final TextView PleaseEnterurMail = (TextView)dialog.findViewById(R.id.tv_Enteruremail);
            et_emailforgot.setTypeface(Lato_Regular);
            PleaseEnterurMail.setTypeface(Lato_Regular);
            ForgotHeading.setTypeface(Lato_Bold);
            bt_SubmitForgotPass.setTypeface(Lato_Bold);
            dialog.show();

and my XML file is as Follows:

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_windowcorner"
>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/rounded_headingcorner"
    android:layout_alignParentTop="true"
    android:id="@+id/RLForgot">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Forgot Password"
        android:textColor="#ffffff"
        android:textSize="16dp"
        android:id="@+id/tv_forgotpasswordHeading"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please Enter Your Registered Email id"
        android:textColor="#000000"
        android:textSize="17dp"
        android:layout_marginRight="22dp"
        android:layout_marginLeft="22dp"
        android:id="@+id/tv_Enteruremail"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/RLForgot"
        android:layout_marginTop="20dp"
        android:textAlignment="center"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:id="@+id/et_EnterMail"
        android:hint="Enter Your Email Id Here"
        android:singleLine="true"
        android:background="@drawable/custom_spinner_background"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="40dp"
        android:layout_below="@+id/tv_Enteruremail"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="Submit"
        android:background="@drawable/signin_btn"
        android:textColor="@color/signinlogcolor"
        style="?android:attr/borderlessButtonStyle"
        android:id="@+id/bt_SubmitForgotButton"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="10dp"
        android:layout_below="@+id/et_EnterMail"
        android:layout_centerHorizontal="true" />
        </RelativeLayout>

Body:
what my problem is. "As you see - Dialog appear with unexpected margin"

it is called Dialog title  Use dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
 to remove title from Dialog like below code

Try this

final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialogforgot_password);


问:
CSS Different Class
I need change a color for this element

```<code><div class="box download">
    <div class="box-inner-block">
        <a href="" target="_blank" rel="noopener">Plugin Windows</a>
    </div>
</div>
</code>```

I call a from CSS with:

```<code>.download.box-inner-block a {
    color: white!important;
}
</code>```

But it does not work, why? I need this color only for the element in .box-inner-block inside .download.

答:
Is this what you are looking for as understood in your question ?

If so you need to carefully watch how you indent and construct your css.

As you can see in my snippet I added a space between:
.download .box-inner-block a
in order to make that work.

You can also remove !important from you css as it will not be useful in that case. If you need it, don't forget to add a space bewtween white and !important

.download {
    background-color: black;
}

.download .box-inner-block a {
    color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box download">
  <div class="box-inner-block">
    Plugin Windows
  </div>
</div></code>```

Title: CSS Different Class

Body:
I need change a color for this element

        Plugin Windows

I call a from CSS with:

.download.box-inner-block a {
    color: white!important;
}

But it does not work, why? I need this color only for the element in .box-inner-block inside .download.

Body:
Is this what you are looking for as understood in your question ?

If so you need to carefully watch how you indent and construct your css.

As you can see in my snippet I added a space between:
.download .box-inner-block a
in order to make that work.

You can also remove !important from you css as it will not be useful in that case. If you need it, don't forget to add a space bewtween white and !important

.download {
    background-color: black;
}

.download .box-inner-block a {
    color: white;
}

<div class="box download">
  <div class="box-inner-block">
    <a href="" target="_blank" rel="noopener">Plugin Windows</a>
  </div>
</div>


问:
PHP: How to check if image file exists?
I need to see if a specific image exists on my cdn.

I've tried the following and it doesn't work:

```<code>if (file_exists(http://www.example.com/images/$filename)) {
    echo "The file exists";
} else {
    echo "The file does not exist";
}
</code>```

Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...

答:
If you are using curl, you can try the following script:

```<code>function checkRemoteFile($url)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url);
 // don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
    return true;
}
else
{
    return false;
}
</code>```

}

Reference URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/

Title: PHP: How to check if image file exists?

Body:
I need to see if a specific image exists on my cdn.

I've tried the following and it doesn't work:

if (file_exists(http://www.example.com/images/$filename)) {
    echo "The file exists";
} else {
    echo "The file does not exist";
}

Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...

Body:
If you are using curl, you can try the following script:

function checkRemoteFile($url)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url);
 // don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
    return true;
}
else
{
    return false;
}

}

Reference URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/


问:
Force SSL on Apache, with Auth and Canonical redirect
I've read some posts on how to redirect to SSL, also some on how to make sure a site is using the www subdomain / canonical name, and some on how to set up Basic Auth. Here is what I have in my .htaccess file right now:

```
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteEngine on
RewriteCond %{HTTP_HOST} !(^www\.site\.com*)$
RewriteRule (.*) https://www.site.com$1 [R=301,L]

AuthName "Locked"
AuthUserFile "/home/.htpasswd"
AuthType Basic
require valid-user
```

It works fairly well, but I'd like to optimize it. My questions include:

How do I avoid double authentication? When I access the site w.o. SSL I have to authenticate, and then I am redirected to SSL and have to authenticate again. Can I just be redirected and then authenticated?

It looks like the first rule is pretty awesome because I could use it on any site without modifying it. Can rule #2 be rewritten to be site-independent? ie: it will force www to be used on any site no matter what the domain name is (with a better written rule)? answered here

How would I do the reverse of number 3 with a rule that would work on any site to force the site not to use www, ie redirect to site.com from www.site.com? answered here

答:
For #1:

Set the Auth instructions only on the VirtualHost which is listening on *:443. You should have 2 VirtualHosts, one listening on port 80 and one on port 443. Using AuthType Basic on  non-SSL communication is a big issue, username and password are just base64 encoded, so it's in clear on every requests (even images or css) that are used on your http server!

Body:
I've read some posts on how to redirect to SSL, also some on how to make sure a site is using the www subdomain / canonical name, and some on how to set up Basic Auth. Here is what I have in my .htaccess file right now:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteEngine on
RewriteCond %{HTTP_HOST} !(^www\.site\.com*)$
RewriteRule (.*) https://www.site.com$1 [R=301,L]

AuthName "Locked"
AuthUserFile "/home/.htpasswd"
AuthType Basic
require valid-user

It works fairly well, but I'd like to optimize it. My questions include:

How do I avoid double authentication? When I access the site w.o. SSL I have to authenticate, and then I am redirected to SSL and have to authenticate again. Can I just be redirected and then authenticated?

It looks like the first rule is pretty awesome because I could use it on any site without modifying it. Can rule #2 be rewritten to be site-independent? ie: it will force www to be used on any site no matter what the domain name is (with a better written rule)? answered here

How would I do the reverse of number 3 with a rule that would work on any site to force the site not to use www, ie redirect to site.com from www.site.com? answered here


问:
How to make a Hello World application without HTML tags?
I'm used to PHP and I wanted to make a totally empty asp.net page "Hello World" (in the source code) I.E. not "
Hello World
" I want to totally strip it all out (and possibly manipulate the headers) so the view source is Hello World.

This is because I am writing an asp.net throughput environment (basically a triangulation server, to facilitate network security) that effectively redirects so I want to have no outputs that I don't accurately control.

Incidentally this also includes response headers as well. Full Control basically.

This is what I have so far

答:
What you use is the DOM explorer not the source code. Right click on the page and select View source. I bet the tags aren't there.

Headers can be displayed in the network tab. Just click on the page request in the network tab and you will see details like headers.


答:
This is example how to open only once the modal..

We first watch for event hidden.bs.modal on modal, that happens when modal is closed, and then we only need to removing data-toggle attr from button that initiates the modal!
All events for bootstrap modal are documented here: https://getbootstrap.com/docs/3.3/javascript/#modals-events

// after modal is closed, remove attached events
$('#myModal').on('hidden.bs.modal', function (e) {
  $('button').attr('data-toggle', '');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        Some Lorem Ipsum ..
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div></code>```

Title: remove an elements ability to open a modal after first click

Body:
This is example how to open only once the modal..

We first watch for event hidden.bs.modal on modal, that happens when modal is closed, and then we only need to removing data-toggle attr from button that initiates the modal!
All events for bootstrap modal are documented here: https://getbootstrap.com/docs/3.3/javascript/#modals-events

// after modal is closed, remove attached events
$('#myModal').on('hidden.bs.modal', function (e) {
  $('button').attr('data-toggle', '');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        Some Lorem Ipsum ..
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


答:
There isn't any unexpected margin in your dialog

Your dialog is already aligned center vertically. Because you have the title bar, it seems off.

Put

```<code>dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

after the dialog initialization

Title: How to show custom dialog at Center Vertical

Body:
There isn't any unexpected margin in your dialog

Your dialog is already aligned center vertically. Because you have the title bar, it seems off.

Put

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

after the dialog initialization


问:
Complex filter between 2 objects and a boolean
I have this array burgerActions :

```<code>[
  {
    statusId: 2,
    label: 'Accept'
  },
  {
    statusId: 3,
    label: 'Reject'
  },
  {
    label: 'Consult'
  },
  {
    label: 'Transfer'
  }
]
</code>```

and this object status which can be either :

```<code>{
  "label": "Accept",
  "id": 2
}
</code>```

or :

```<code>{
  "label": "Reject",
  "id": 3
}
</code>```

In a first case you have to create a new array from burgerActions array where the statusId is not equivalent to the id of the status object that we have (we can only have one status object of the 2 cases that I listed).
For that I used the filter method :

```<code>const result =  burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id
})
</code>```

In the second case I need a complex conditioning adding with boolean

```<code>const statusRef = recommendation.recipient
</code>```

In a first case I want if statusRef is false filter the last object in the burgerAction ({label: 'Transfer'}) but not in the case if statusRef is true.
I need a method that does this type of filter without using the if () conditions because there are several cases to handle.

答:
If you want to filter the objects that doesn't have the same statusId as in the recommendation.status.id and if recommendation.recipient === true filter the ones that doesn't have statusId, you can use this condition in the filter callback function:

```<code>element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
</code>```

Where && recommendation.recipient ? element.statusId != null : true means that if recommendation.recipient is true filter elements with a statusId.

Here's how should be your code:

```<code>var recommendation = {
  status: {
    "label": "Pending",
    "id": 1
  },
  recipient: true
};

const result = burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});
</code>```

Demo:

var burgerActions = [{
    statusId: 2,
    label: 'Accept'
  },
  {
    statusId: 3,
    label: 'Reject'
  },
  {
    label: 'Consult'
  },
  {
    statusId: 1,
    label: 'Transfer'
  }
];

var recommendation = {
  status: {
    "label": "Pending",
    "id": 1
  },
  recipient: true
};

const result = burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});

console.log(result);```

Body:
I have this array burgerActions :

[
  {
    statusId: 2,
    label: 'Accept'
  },
  {
    statusId: 3,
    label: 'Reject'
  },
  {
    label: 'Consult'
  },
  {
    label: 'Transfer'
  }
]

and this object status which can be either :

{
  "label": "Accept",
  "id": 2
}

or :

{
  "label": "Reject",
  "id": 3
}

In a first case you have to create a new array from burgerActions array where the statusId is not equivalent to the id of the status object that we have (we can only have one status object of the 2 cases that I listed).
For that I used the filter method :

const result =  burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id
})

In the second case I need a complex conditioning adding with boolean

const statusRef = recommendation.recipient

In a first case I want if statusRef is false filter the last object in the burgerAction ({label: 'Transfer'}) but not in the case if statusRef is true.
I need a method that does this type of filter without using the if () conditions because there are several cases to handle.

Body:
If you want to filter the objects that doesn't have the same statusId as in the recommendation.status.id and if recommendation.recipient === true filter the ones that doesn't have statusId, you can use this condition in the filter callback function:

element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;

Where && recommendation.recipient ? element.statusId != null : true means that if recommendation.recipient is true filter elements with a statusId.

Here's how should be your code:

var recommendation = {
  status: {
    "label": "Pending",
    "id": 1
  },
  recipient: true
};

const result = burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});

Demo:

var burgerActions = [{
    statusId: 2,
    label: 'Accept'
  },
  {
    statusId: 3,
    label: 'Reject'
  },
  {
    label: 'Consult'
  },
  {
    statusId: 1,
    label: 'Transfer'
  }
];

var recommendation = {
  status: {
    "label": "Pending",
    "id": 1
  },
  recipient: true
};

const result = burgerActions.filter((element) => {
  return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});

console.log(result);


问:
How to prevent hangs on SocketInputStream.socketRead0 in Java?
Performing millions of HTTP requests with different Java libraries gives me threads hung on:

java.net.SocketInputStream.socketRead0()

which is a native function.

I tried to set up the Apache Http Client and RequestConfig to have timeouts on  (I hope) everythig that is possible but still, I have (probably infinite) hangs on socketRead0. How to get rid of them?

The hung ratio is about ~1 per 10000 requests (to 10000 different hosts) and it can last probably forever (I've confirmed thread hung as still valid after 10 hours).

JDK 1.8 on Windows 7.

My HttpClient factory:

```<code>SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(false)
            .setSoLinger(1)
            .setSoReuseAddress(true)
            .setSoTimeout(5000)
            .setTcpNoDelay(true).build();

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableAutomaticRetries();
    builder.disableContentCompression();
    builder.disableCookieManagement();
    builder.disableRedirectHandling();
    builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    builder.setDefaultSocketConfig(socketConfig);

    return HttpClientBuilder.create().build();
</code>```

My RequestConfig factory:

```<code>    HttpGet request = new HttpGet(url);

    RequestConfig config = RequestConfig.custom()
            .setCircularRedirectsAllowed(false)
            .setConnectionRequestTimeout(8000)
            .setConnectTimeout(4000)
            .setMaxRedirects(1)
            .setRedirectsEnabled(true)
            .setSocketTimeout(5000)
            .setStaleConnectionCheckEnabled(true).build();
    request.setConfig(config);

    return new HttpGet(url);
</code>```

OpenJDK socketRead0 source

Note: Actually I have a "trick": I can schedule .getConnectionManager().shutdown() in other Thread with a cancellation of the Future if request finished properly. But, it is deprecated and also it kills whole HttpClient, not just that single request.

答:
I bumped into the same issue using apache common http client.

There's a pretty simple workaround (which doesn't require shutting the connection manager down):

In order to reproduce it, one needs to execute the request from the question in a new thread paying attention to details:

run request in separate thread, close request and release it's connection in a different thread, interrupt hanging thread

don't run EntityUtils.consumeQuietly(response.getEntity()) in finally block (because it hangs on 'dead' connection)

First, add the interface

```<code>interface RequestDisposer {
    void dispose();
}
</code>```

Execute an HTTP request in a new thread

```<code>final AtomicReference<RequestDisposer> requestDisposer = new AtomicReference<>(null);

final Thread thread = new Thread(() -> {
    final HttpGet request = new HttpGet("http://my.url");
    final RequestDisposer disposer = () -> {
        request.abort();
        request.releaseConnection();
    };
    requestDiposer.set(disposer);

    try (final CloseableHttpResponse response = httpClient.execute(request))) {
        ...
    } finally {
      disposer.dispose();
    }
};)
thread.start()
</code>```

Call dispose() in the main thread to close hanging connection

```<code>requestDisposer.get().dispose(); // better check if it's not null first
thread.interrupt();
thread.join();
</code>```

That fixed the issue for me.

My stacktrace looked like this:

```<code>java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:139)
at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:155)
at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:284)
at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:253)
at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:227)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:186)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
</code>```

To whom it might be interesting, it easily reproducable, interrupt the thread without aborting request and releasing connection (ratio is about 1/100).
Windows 10, version 10.0.
jdk8.151-x64.

Body:
Performing millions of HTTP requests with different Java libraries gives me threads hung on:

java.net.SocketInputStream.socketRead0()

which is a native function.

I tried to set up the Apache Http Client and RequestConfig to have timeouts on  (I hope) everythig that is possible but still, I have (probably infinite) hangs on socketRead0. How to get rid of them?

The hung ratio is about ~1 per 10000 requests (to 10000 different hosts) and it can last probably forever (I've confirmed thread hung as still valid after 10 hours).

JDK 1.8 on Windows 7.

My HttpClient factory:

SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(false)
            .setSoLinger(1)
            .setSoReuseAddress(true)
            .setSoTimeout(5000)
            .setTcpNoDelay(true).build();

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableAutomaticRetries();
    builder.disableContentCompression();
    builder.disableCookieManagement();
    builder.disableRedirectHandling();
    builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    builder.setDefaultSocketConfig(socketConfig);

    return HttpClientBuilder.create().build();

My RequestConfig factory:

    HttpGet request = new HttpGet(url);

    RequestConfig config = RequestConfig.custom()
            .setCircularRedirectsAllowed(false)
            .setConnectionRequestTimeout(8000)
            .setConnectTimeout(4000)
            .setMaxRedirects(1)
            .setRedirectsEnabled(true)
            .setSocketTimeout(5000)
            .setStaleConnectionCheckEnabled(true).build();
    request.setConfig(config);

    return new HttpGet(url);

OpenJDK socketRead0 source

Note: Actually I have a "trick": I can schedule .getConnectionManager().shutdown() in other Thread with a cancellation of the Future if request finished properly. But, it is deprecated and also it kills whole HttpClient, not just that single request.

Body:
I bumped into the same issue using apache common http client.

There's a pretty simple workaround (which doesn't require shutting the connection manager down):

In order to reproduce it, one needs to execute the request from the question in a new thread paying attention to details:

run request in separate thread, close request and release it's connection in a different thread, interrupt hanging thread

don't run EntityUtils.consumeQuietly(response.getEntity()) in finally block (because it hangs on 'dead' connection)

First, add the interface

interface RequestDisposer {
    void dispose();
}

Execute an HTTP request in a new thread

final AtomicReference<RequestDisposer> requestDisposer = new AtomicReference<>(null);

final Thread thread = new Thread(() -> {
    final HttpGet request = new HttpGet("http://my.url");
    final RequestDisposer disposer = () -> {
        request.abort();
        request.releaseConnection();
    };
    requestDiposer.set(disposer);

    try (final CloseableHttpResponse response = httpClient.execute(request))) {
        ...
    } finally {
      disposer.dispose();
    }
};)
thread.start()

Call dispose() in the main thread to close hanging connection

requestDisposer.get().dispose(); // better check if it's not null first
thread.interrupt();
thread.join();

That fixed the issue for me.

My stacktrace looked like this:

java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:139)
at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:155)
at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:284)
at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:253)
at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:227)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:186)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)

To whom it might be interesting, it easily reproducable, interrupt the thread without aborting request and releasing connection (ratio is about 1/100).
Windows 10, version 10.0.
jdk8.151-x64.


问:
Video Streaming, allow streaming only through the Player and prevent download
I m working on a video streaming application. The application is ready and working well. In the final check I m visualizing a scenario where a valid user can download the video rather than playing at player.

I want to prevent the download and allow streaming via player. I m not worried about screen capture and other methods.

Thanks

答:
You need a streaming server like red5
http://red5.org/
you cannot disallow stream download without a true streaming server.
you can host you video on a streaming service too ( no server set up , but a fee according to the bandwith ).</p>


问:
Return matched value in any() list in string
I've the following script

```<code>#Tails every new line created in this file
for line in tailer.follow(open("my/path/chatlog.html")):
    #If the new line has the word "TURN" on it, continue
    if("TURN" in line):
        #IF any of the names in the list characterNames is in the new line, execute the function parseCharacter passing the matched "name"
        if any(name in line.lower() for name in characterNames):
            parseCharacter(charactersPath + name + ".xml")
</code>```

That "name" in the last line is what I need to match the matched name in the line. I tried to check the any() documentation but couldn't find a solution.

Thanks in advance.

答:
Change this:

```<code>if any(name in line.lower() for name in characterNames):
    parseCharacter(charactersPath + name + ".xml")
</code>```

To this:

```<code>try:
    bingo = next(name for name in characterNames if name in line.lower()):
except StopIteration:  # none found
    # break \ continue ?
else:
    parseCharacter(charactersPath + bingo + ".xml")
</code>```

any() goes though the iterator trying to find any value that returns True but does not tell you which one it was.

next() will only return the next value that returns True. The catch here is that there might be multiple that do so. Do not use next if you want to get them all.

Finally, note that next() can also take a default argument in case nothing is found. You might wanna use that. If you do, you do not need the except part. It is handled internally.

Body:
I've the following script

#Tails every new line created in this file
for line in tailer.follow(open("my/path/chatlog.html")):
    #If the new line has the word "TURN" on it, continue
    if("TURN" in line):
        #IF any of the names in the list characterNames is in the new line, execute the function parseCharacter passing the matched "name"
        if any(name in line.lower() for name in characterNames):
            parseCharacter(charactersPath + name + ".xml")

That "name" in the last line is what I need to match the matched name in the line. I tried to check the any() documentation but couldn't find a solution.

Thanks in advance.

Body:
Change this:

if any(name in line.lower() for name in characterNames):
    parseCharacter(charactersPath + name + ".xml")

To this:

try:
    bingo = next(name for name in characterNames if name in line.lower()):
except StopIteration:  # none found
    # break \ continue ?
else:
    parseCharacter(charactersPath + bingo + ".xml")

any() goes though the iterator trying to find any value that returns True but does not tell you which one it was.

next() will only return the next value that returns True. The catch here is that there might be multiple that do so. Do not use next if you want to get them all.

Finally, note that next() can also take a default argument in case nothing is found. You might wanna use that. If you do, you do not need the except part. It is handled internally.