问:
Filter element if checkboxes are check or not JavaScript
I got a problem with my code. I coded a search bar which filter checkboxes by their name and I coded a function which only display the checkboxes selected. But there is a conflict.

Everytime I click on "Selected" everything is passing to a display : none;

So I tried to wrap my search bar into some div but it's not working as I imagined. I know that .parent() is the problem because it impacts the parent of my search bar, but I need it to hide the elements not selected so I don't succeed in solving it.

Here is the snippet to understand what I mean. Update it in your answer to let me see what was wrong.

Hope you guys will be able to help me.

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  width: 100vw;
  white-space: normal;
  height: 75px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}</code>```

All | Selected | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>

</form>
<textarea id="t" style="display: none;"></textarea>```

答:
Change the function OnlySelecteds() to this:

```<code>function OnlySelecteds() {
  $("input").closest('label').show();
  $("input:not(:checked)").closest('label').hide();
}
</code>```

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input").closest('label').show();
  $("input:not(:checked)").closest('label').hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}
function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  width: 100vw;
  white-space: normal;
  height: 75px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}</code>```

All | Selected | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>

</form>
<textarea id="t" style="display: none;"></textarea>```

Body:
I got a problem with my code. I coded a search bar which filter checkboxes by their name and I coded a function which only display the checkboxes selected. But there is a conflict.

Everytime I click on "Selected" everything is passing to a display : none;

So I tried to wrap my search bar into some div but it's not working as I imagined. I know that .parent() is the problem because it impacts the parent of my search bar, but I need it to hide the elements not selected so I don't succeed in solving it.

Here is the snippet to understand what I mean. Update it in your answer to let me see what was wrong.

Hope you guys will be able to help me.

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input:not(:checked)").parent().hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
  }
}

* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  width: 100vw;
  white-space: normal;
  height: 75px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}

All | Selected | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>

</form>
<textarea id="t" style="display: none;"></textarea>

Body:
Change the function OnlySelecteds() to this:

function OnlySelecteds() {
  $("input").closest('label').show();
  $("input:not(:checked)").closest('label').hide();
}

function All() {
  $("input").parent().show();
}

function OnlySelecteds() {
  $("input").closest('label').show();
  $("input:not(:checked)").closest('label').hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }

}
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}
function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains(' + $('#SearchBar').val() + ')').show();
  }
}

* {
  box-sizing: border-box;
}

#data {
  padding: 5px;
  width: 100vw;
}

.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  width: 100vw;
  white-space: normal;
  height: 75px;
}

.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}

label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<span onclick="All()">All</span> | <span onclick="OnlySelecteds()">Selected</span> | <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
<form>
  <div id="data">
    <div class="multiselect">
      <div id="c_b">
        <div id="checkboxes">
        </div>
      </div>
    </div>
  </div>
</form>
<textarea id="t" style="display: none;"></textarea>


来源: stackexchange

问:
yFiles Graphsource alternative(js or python) for "DAGs" or "networks"
yFiles have this graph, I'm very interesting in applying something similar in a python/JS environment.
http://live.yworks.com/yfiles-for-html/1.3/demos/databinding/demo.yfiles.binding.interactivegraphsource/index.html

It has to be JS or Python.
 Do notice is not a tree-structure, as it has interconnectivity, as the possibity multiple parent nodes. So it is more of DAG - Directec Acyclic Graf or network graf.

I can't seem to find anything that is as simple and symmetric as this module.

I've lookup DAG's and networks for python and js, but can't seem to find anything similar.

答:
I ended up using https://github.com/cpettitt/dagre-d3

It is great. Has two weaknesses:

Bad integration with IE and you cannot make it collabsible (what I know of)

ContentLicense: CC BY-SA 3.0


问:
Finding the value of a particular index in a Python list
I have a simple python program.

```<code>from nltk.tokenize import word_tokenize

negation ='no','not','never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')
sentence = 'loss money'

if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
list2 for word in word_tokenize(sentence))[-1:])not in negation :
  print 'sad'
else:
  print 'not sad'
</code>```

This make error which is

```<code>TypeError: 'bool' object has no attribute '__getitem__'
</code>```

What I need here, I want to check if any word in the sentence is in the list2. If yes, then want to check its before index value is in the negation list or not. if yes it should be "not sad".

For an example "I miss him" should sad, "I not miss him" should be not sad.

Can anyone help me !

答:
You didn't write the second part of your if well.
You first look at any(word in list2 for word in word_tokenize(sentence)) which returns a boolean. Then you try to extract the last element of this boolean ([-1]) which return an error.

No need to use nltk library here, you can do it with just .split():

```<code>negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
    if any(word in list2 for word in sentence.split()) and not any(word in negation for word in sentence.split()):
        print 'sad'
    else:
        print 'not sad'

l = ['loss money', 'I miss him', 'I not miss him']
for e in l:
    f(e)
# Outputs: sad / sad / not sad
</code>```

edit New version to take into account @Baldrickk good remark.
I took two more cases into consideration. It prints 'happy' if no words belong to list2. If several words belongs to list2, it checks every previous words and not just the first one.

```<code>negation = {'no', 'not', 'never'}
list2 = {'miss', 'loss', 'gone', 'give up', 'lost'}

def f(sentence):
    s = sentence.split()
    l = [s.index(word) for word in s if word in list2]
    # Will returns list of indices (of sentence) where word is in list2
    if len(l) > 0:
        for e in l:
            # Check previous word
            if s[e-1] not in negation:
                print 'sad'
            else:
                print 'not sad'
    else:
        print 'happy'

l = ['loss money', 'I miss him', 'I not miss him', 'happy new year', 'I am not here I am gone']
for e in l:
    f(e)
# sad / sad / not sad / happy / sad
</code>```

Body:
I have a simple python program.

from nltk.tokenize import word_tokenize

negation ='no','not','never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')
sentence = 'loss money'

if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
list2 for word in word_tokenize(sentence))[-1:])not in negation :
  print 'sad'
else:
  print 'not sad'

This make error which is

TypeError: 'bool' object has no attribute '__getitem__'

What I need here, I want to check if any word in the sentence is in the list2. If yes, then want to check its before index value is in the negation list or not. if yes it should be "not sad".

For an example "I miss him" should sad, "I not miss him" should be not sad.

Can anyone help me !

Body:
You didn't write the second part of your if well.
You first look at any(word in list2 for word in word_tokenize(sentence)) which returns a boolean. Then you try to extract the last element of this boolean ([-1]) which return an error.

No need to use nltk library here, you can do it with just .split():

negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
    if any(word in list2 for word in sentence.split()) and not any(word in negation for word in sentence.split()):
        print 'sad'
    else:
        print 'not sad'

l = ['loss money', 'I miss him', 'I not miss him']
for e in l:
    f(e)
# Outputs: sad / sad / not sad

edit New version to take into account @Baldrickk good remark.
I took two more cases into consideration. It prints 'happy' if no words belong to list2. If several words belongs to list2, it checks every previous words and not just the first one.

negation = {'no', 'not', 'never'}
list2 = {'miss', 'loss', 'gone', 'give up', 'lost'}

def f(sentence):
    s = sentence.split()
    l = [s.index(word) for word in s if word in list2]
    # Will returns list of indices (of sentence) where word is in list2
    if len(l) > 0:
        for e in l:
            # Check previous word
            if s[e-1] not in negation:
                print 'sad'
            else:
                print 'not sad'
    else:
        print 'happy'

l = ['loss money', 'I miss him', 'I not miss him', 'happy new year', 'I am not here I am gone']
for e in l:
    f(e)
# sad / sad / not sad / happy / sad


问:
Why DataGrid doesn't lose focus with ToolBar-Click?
I have a ToolBar with a Button and a DataGrid and a separate Button.

When I edit a cell (EditMode) and then click the "separate" Button, the cell leaves EditMode and commit the changes.

But when I click the Button on the within the ToolBar, the cell doesn't leave EditMode and doesn't commit its changes.

How can I force the cell to commit its changes when I click the ToolBar Button?

XAML:

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataContextSample" Height="543.538" Width="733.463"
        xmlns:self="clr-namespace:WpfApplication1">
    <DockPanel Margin="15">
        <ToolBar DockPanel.Dock="Top" Height="40">
            <Button Width="150" Height="20">ToolBarBUtton</Button>
        </ToolBar>
        <Button DockPanel.Dock="Top" Height="20" Width="150">Button</Button>
        <DataGrid DockPanel.Dock="Top" Name="DataGridJobConfigurations" ItemsSource="{Binding}"  VerticalScrollBarVisibility="Auto">
        </DataGrid>
    </DockPanel>
</Window>
</code>```

C#:

```<code>namespace WpfApplication1
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();

            List<Data> dataList = new List<Data>();

            dataList.Add(new Data(1));
            dataList.Add(new Data(2));
            dataList.Add(new Data(3));
            dataList.Add(new Data(4));

            this.DataContext = dataList;
        }
    }

    class Data {
        public Data(int i) {
            Number = i;
        }
        public int Number { get; set; }
    }
}
</code>```

答:
You could set the attached FocusManager.IsFocusScope property of the Toolbar to false:

```<code><ToolBar DockPanel.Dock="Top" Height="40" FocusManager.IsFocusScope="False">
    <Button Width="150" Height="20">ToolBarBUtton</Button>
</ToolBar>
</code>```

Body:
I have a ToolBar with a Button and a DataGrid and a separate Button.

When I edit a cell (EditMode) and then click the "separate" Button, the cell leaves EditMode and commit the changes.

But when I click the Button on the within the ToolBar, the cell doesn't leave EditMode and doesn't commit its changes.

How can I force the cell to commit its changes when I click the ToolBar Button?

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataContextSample" Height="543.538" Width="733.463"
        xmlns:self="clr-namespace:WpfApplication1">
    <DockPanel Margin="15">
        <ToolBar DockPanel.Dock="Top" Height="40">
            <Button Width="150" Height="20">ToolBarBUtton</Button>
        </ToolBar>
        <Button DockPanel.Dock="Top" Height="20" Width="150">Button</Button>
        <DataGrid DockPanel.Dock="Top" Name="DataGridJobConfigurations" ItemsSource="{Binding}"  VerticalScrollBarVisibility="Auto">
        </DataGrid>
    </DockPanel>
</Window>

C#:

namespace WpfApplication1
{
    ///
    /// Interaktionslogik für MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();

            List<Data> dataList = new List<Data>();

            dataList.Add(new Data(1));
            dataList.Add(new Data(2));
            dataList.Add(new Data(3));
            dataList.Add(new Data(4));

            this.DataContext = dataList;
        }
    }

    class Data {
        public Data(int i) {
            Number = i;
        }
        public int Number { get; set; }
    }
}

Body:
You could set the attached FocusManager.IsFocusScope property of the Toolbar to false:

<ToolBar DockPanel.Dock="Top" Height="40" FocusManager.IsFocusScope="False">
    <Button Width="150" Height="20">ToolBarBUtton</Button>
</ToolBar>


问:
Hide translation key on page load angular
I am using Angular-translate in combination with partial-loader,i want to hide translate key on page load.
 in app.js

```<code>       var app = angular.module('myapp', [
          'ngRoute',
          'appRoutes',
          'pascalprecht.translate',
          'angularTranslate',
          'indexCtrl'
        ]);

    angular.module('angularTranslateApp', ['pascalprecht.translate']).config(function($translateProvider) {
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'translation/{lang}/{part}.json'
        });
 $translateProvider.preferredLanguage('en-US');
</code>```

index.js

```<code>angular.module('indexCtrl', []).controller('indexController',
  function($scope, $translate, $translatePartialLoader) {

    $translatePartialLoader.addPart('test');
    $translate.refresh();

});
</code>```

test.json

```<code>{
"testkey":"testval"
}
</code>```

HTML

```<code>{{ "testkey" || translate }}
</code>```

so on page load its showing testkey for few seconds,i dont want to show this,how to acheive this. i have already used translate-cloak but its not working

答:
can you please try that on resolve of that page in routeconfig</p>

```<code>    resolve: {
           translatePartialLoader: ['$translate', '$translatePartialLoader', function($translate, $translatePartialLoader) {
                $translatePartialLoader.addPart('test');
                return $translate.refresh();
           }]
    }
</code>```

Body:
I am using Angular-translate in combination with partial-loader,i want to hide translate key on page load.
 in app.js

       var app = angular.module('myapp', [
          'ngRoute',
          'appRoutes',
          'pascalprecht.translate',
          'angularTranslate',
          'indexCtrl'
        ]);

    angular.module('angularTranslateApp', ['pascalprecht.translate']).config(function($translateProvider) {
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'translation/{lang}/{part}.json'
        });
 $translateProvider.preferredLanguage('en-US');

index.js

angular.module('indexCtrl', []).controller('indexController',
  function($scope, $translate, $translatePartialLoader) {

    $translatePartialLoader.addPart('test');
    $translate.refresh();

});

test.json

{
"testkey":"testval"
}

HTML

{{ "testkey" || translate }}

so on page load its showing testkey for few seconds,i dont want to show this,how to acheive this. i have already used translate-cloak but its not working

Body:
can you please try that on resolve of that page in routeconfig

    resolve: {
           translatePartialLoader: ['$translate', '$translatePartialLoader', function($translate, $translatePartialLoader) {
                $translatePartialLoader.addPart('test');
                return $translate.refresh();
           }]
    }


问:
Multiple websites with one IP: settings with proxy server and proxy cache (flask, uwsgi, nginx)
I want to allow my nginx server to server multiple subdomains.
Each site is served by a flask + uwsgi, listening to own ports.

All sites have many endpoints with same name, and responses are cached in different zones: I want to serve the correct cache (or correct site) from the proxy server.

I read https://askubuntu.com/questions/766352/multiple-websites-on-nginx-one-ip : in my configuration I keep having domain2 redirected to domain1.
I cannot find proper configuration for listening to uwsgi and have the proxy server serve the correct site.

How to properly set the ports and proxy_cache on the proxy_server to allow nginx serve two flask sites from a single server?

Below is my set current setup:

configuration domain_1

```<code>server {
    server_name www.domain1.com;
    return 301 $scheme://domain1.com$request_uri;
}

server {
    listen 8000 default_server;
    server_name domain1.com;

    root /var/www/example_site_1;

    # common locations for all sites
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/example_site_1/domain1.sock;
    }

    # API
    location /api {
        include uwsgi_params;
        uwsgi_param UWSGI_SCRIPT wsgi;
        uwsgi_pass unix:/var/www/example_site_1/domain1.sock;
    }
}

# Set cache directory for site

proxy_cache_path /tmp/nginx/domain1 levels=1:2 keys_zone=my_zone_domain_1:10m max_size=50m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

# Virtualhost/server configuration
server {
    listen  80  default_server;
    server_name domain1;

    root /var/www/domain1;

    ## how to serve proxy_cache if locations of domain_1 and domain_2 are the same ?

    location / {
        proxy_cache my_zone_domain_1;
        add_header X-Proxy-Cache $upstream_cache_status;
        include proxy_params;
        proxy_pass http://domain1.com:8000;
    }

    location /api {
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_cache my_zone_domain_1;
        proxy_pass http://domain1.com:8000/api;
    }

}
</code>```

configuration domain_2

```<code>server {
    server_name www.domain2.com;
    return 301 $scheme://domain2.com$request_uri;
}

server {
    listen 3000;
    server_name domain2.com;

    root /var/www/example_site_2;

    # common locations for all sites
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/example_site_2/domain2.sock;
    }

    # API
    location /api {
        include uwsgi_params;
        uwsgi_param UWSGI_SCRIPT wsgi;
        uwsgi_pass unix:/var/www/example_site_2/domain2.sock;
    }
}

# Set cache directory for site

proxy_cache_path /tmp/nginx/domain2 levels=1:2 keys_zone=my_zone_domain_2:10m max_size=50m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

# Virtualhost/server configuration
server {

    # I tried listening on other ports than 80, but kept having redirects on domain_1

    listen  80;
    server_name domain2;

    root /var/www/domain2;

    ## how to serve proxy_cache if locations of domain_1 and domain_2 are the same ?

    location / {
        proxy_cache my_zone_domain_2;
        add_header X-Proxy-Cache $upstream_cache_status;
        include proxy_params;
        proxy_pass http://domain2.com:3000;
    }

    location /api {
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_cache my_zone_domain_2;
        proxy_pass http://domain2.com:3000/api;
    }

}
</code>```

答:
I found the culprit was Uwsgi : it was loaded from usr/bin folder, and not from virtual environment folder of my app.

Maybe virtualenv folder was corrupted: when I tried to re-install uwsgi (pip install uwsgi), it kept saying requirements satisfied until I noticed that which uwsgi was not loaded from virtualenv.

I had to remove and reinstall virtualenv folder with uwsgi and python modules.

Now applications were running (answer to the question), but proxy_server configuration has to be further adjusted in my case.

The following may be useful for people making use of url_for() directives in flask: url_for() directive routes to an absolute path, which may conflict with the nginx proxy.

Example: nginx proxy server listens on domains2.com on port 80, proxy_pass /path location to http://domain2.com:3000; if flask is redirecting a route to /path (with url_for()), the resulting url will be http://domain2.com:3000/path (because it follows the port specified in absolute path) instead of http://domain2.com/path (the url of the proxy).

Add proxy_set_header Host $http_host; to /path location to allow nginx proxy follow the correct redirect of your flask application.

Body:
I want to allow my nginx server to server multiple subdomains.
Each site is served by a flask + uwsgi, listening to own ports.

All sites have many endpoints with same name, and responses are cached in different zones: I want to serve the correct cache (or correct site) from the proxy server.

I read https://askubuntu.com/questions/766352/multiple-websites-on-nginx-one-ip : in my configuration I keep having domain2 redirected to domain1.
I cannot find proper configuration for listening to uwsgi and have the proxy server serve the correct site.

How to properly set the ports and proxy_cache on the proxy_server to allow nginx serve two flask sites from a single server?

Below is my set current setup:

configuration domain_1

server {
    server_name www.domain1.com;
    return 301 $scheme://domain1.com$request_uri;
}

server {
    listen 8000 default_server;
    server_name domain1.com;

    root /var/www/example_site_1;

    # common locations for all sites
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/example_site_1/domain1.sock;
    }

    # API
    location /api {
        include uwsgi_params;
        uwsgi_param UWSGI_SCRIPT wsgi;
        uwsgi_pass unix:/var/www/example_site_1/domain1.sock;
    }
}

# Set cache directory for site

proxy_cache_path /tmp/nginx/domain1 levels=1:2 keys_zone=my_zone_domain_1:10m max_size=50m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

# Virtualhost/server configuration
server {
    listen  80  default_server;
    server_name domain1;

    root /var/www/domain1;

    ## how to serve proxy_cache if locations of domain_1 and domain_2 are the same ?

    location / {
        proxy_cache my_zone_domain_1;
        add_header X-Proxy-Cache $upstream_cache_status;
        include proxy_params;
        proxy_pass http://domain1.com:8000;
    }

    location /api {
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_cache my_zone_domain_1;
        proxy_pass http://domain1.com:8000/api;
    }

}

configuration domain_2

server {
    server_name www.domain2.com;
    return 301 $scheme://domain2.com$request_uri;
}

server {
    listen 3000;
    server_name domain2.com;

    root /var/www/example_site_2;

    # common locations for all sites
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/example_site_2/domain2.sock;
    }

    # API
    location /api {
        include uwsgi_params;
        uwsgi_param UWSGI_SCRIPT wsgi;
        uwsgi_pass unix:/var/www/example_site_2/domain2.sock;
    }
}

# Set cache directory for site

proxy_cache_path /tmp/nginx/domain2 levels=1:2 keys_zone=my_zone_domain_2:10m max_size=50m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

# Virtualhost/server configuration
server {

    # I tried listening on other ports than 80, but kept having redirects on domain_1

    listen  80;
    server_name domain2;

    root /var/www/domain2;

    ## how to serve proxy_cache if locations of domain_1 and domain_2 are the same ?

    location / {
        proxy_cache my_zone_domain_2;
        add_header X-Proxy-Cache $upstream_cache_status;
        include proxy_params;
        proxy_pass http://domain2.com:3000;
    }

    location /api {
        add_header X-Proxy-Cache $upstream_cache_status;
        proxy_cache my_zone_domain_2;
        proxy_pass http://domain2.com:3000/api;
    }

}


问:
Get URL As Shown In Address Bar
I'm using some URL rewriting, on top of the URL rewriting that Wordpress does natively.

The basic idea is that I use a category page with an address that appears like it belongs somewhere else, so /blog/type/kids is the true category in WP. I rewrite this with a .htaccess file in /kids/ to make the category look like its actually a page called /kids/programs with this code in the kids folder:

```<code>RewriteEngine on
RewriteRule ^programs$ /blog/type/kids/ [P]
</code>```

This happens in two different locations in the site, but the both load the same WP page behind the scenes. This all works fine.

What I need to do now, is set a variable based on which location it is being loaded from, to ensure that the navigation highlights the proper section of the site, and shows the proper subnav. The problem is that I can't access the new, rewritten URL that the user sees.

Ideally, I'm looking for something like this:

```<code>if(strpos($_SERVER['PHP_SELF'],'kids//programs')) {
    $top_nav_item_id = 'kids';
} else {
    $top_nav_item_id = 'programs';
    $subnav_item_id = 'kids';
}
</code>```

PHP_SELF resolves to /blog/index.php and REQUEST_URI shows /blog/type/kids. So neither are showing me the /kids/programs location that is truly being displayed.

Any ideas how to get this? Maybe WP has a built in tag for this?

Cheers!

答:
Returns the current url:</p>

```<code><?php
   function curPageURL() {
     $pageURL = 'http';
     if (@$_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }
     return $pageURL;
    }
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Get URL As Shown In Address Bar

Body:
I'm using some URL rewriting, on top of the URL rewriting that Wordpress does natively.

The basic idea is that I use a category page with an address that appears like it belongs somewhere else, so /blog/type/kids is the true category in WP. I rewrite this with a .htaccess file in /kids/ to make the category look like its actually a page called /kids/programs with this code in the kids folder:

RewriteEngine on
RewriteRule ^programs$ /blog/type/kids/ [P]

This happens in two different locations in the site, but the both load the same WP page behind the scenes. This all works fine.

What I need to do now, is set a variable based on which location it is being loaded from, to ensure that the navigation highlights the proper section of the site, and shows the proper subnav. The problem is that I can't access the new, rewritten URL that the user sees.

Ideally, I'm looking for something like this:

if(strpos($_SERVER['PHP_SELF'],'kids//programs')) {
    $top_nav_item_id = 'kids';
} else {
    $top_nav_item_id = 'programs';
    $subnav_item_id = 'kids';
}

PHP_SELF resolves to /blog/index.php and REQUEST_URI shows /blog/type/kids. So neither are showing me the /kids/programs location that is truly being displayed.

Any ideas how to get this? Maybe WP has a built in tag for this?

Cheers!

Body:
Returns the current url:

<?php
   function curPageURL() {
     $pageURL = 'http';
     if (@$_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }
     return $pageURL;
    }
?>


问:
Extracting sub arrays from a two dimensional array for each element and displaying them in a table using KnockoutJS
I have used below code in PHP to extract data from MySQL :

```<code><?php
require("connect.php");
$sql = "SELECT `inn_lay_list`, `inner_layer` FROM `da_customer_auto_inner`
where `mpcode` = 'qf017'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)) {
    $data1 = $row['inn_lay_list'];
    $data2 = $row['inner_layer'];
}

$parts1 = explode(';',$data1);
$parts2 = explode(';',$data2);
$layer_cnt = count($parts1);
$array_inner = array_chunk($parts2, 8);

echo json_encode($parts1);
echo json_encode($array_inner);

mysqli_close($conn);
?>
</code>```

I obtained the result as:

["001","011","021","031"]

[["1","2","3","4","5","6","7","8"], ["11","12","13","14","15","16","17","18"], ["21","22","23","24","25","26","27","28"],[31","32","33","34","35","36","37","38"]]

Here for each element in first array there is a sub array in the second array(two dimensional array).
Now I want to display this in HTML page using a table. I am trying to use KnockoutJS “foreach” option with a named template:

```<code><script>
function MyViewModel() {
    this.layer = [{
        name: "<?=@$parts1[0]?>",
        layer_data: "<?=@$array_inner[0]?>"
    },
    {
        name: "<?=@$parts1[1]?>",
        layer_data: "<?=@$array_inner[1]?>"
    },
    {
        name: "<?=@$parts1[2]?>",
        layer_data: "<?=@$array_inner[2]?>"
    },
    {
        name: "<?=@$parts1[3]?>",
        layer_data: "<?=@$array_inner[3]?>"
    }]
}
ko.applyBindings(new MyViewModel());
</script>

<table class="table table-bordered">
    <thead>
    <tr>
      <td>Layer</td>
      <td>P2P</td>
      <td>P2T</td>
      <td>T2T</td>
      <td>Track Width</td>
      <td>PTH To Cu</td>
      <td>NPTH To Cu</td>
      <td>PTH AR</td>
      <td>Via AR</td>
    </tr>
    </thead>
    <tbody data-bind="template:{name:'layer-template', foreach:layer}">
    </tbody>
</table>
<script type="text/html" id="layer-template">
<tr>
    <td data-bind="text: name"></td>
    <td data-bind="text: layer_data[0]"></td>
    <td data-bind="text: layer_data[1]"></td>
    <td data-bind="text: layer_data[2]"></td>
    <td data-bind="text: layer_data[3]"></td>
    <td data-bind="text: layer_data[4]"></td>
    <td data-bind="text: layer_data[5]"></td>
    <td data-bind="text: layer_data[6]"></td>
    <td data-bind="text: layer_data[7]"></td>
</tr>
</script>
</code>```

I want my output as below :

答:
Simple do this:</p>

```<code>$array=[[1,2,3], [4,5,6], [7,8,9]];
print_r($array[0]);

If you want read all:
foreach($array as $arr){
print_r($arr);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have used below code in PHP to extract data from MySQL :

<?php
require("connect.php");
$sql = "SELECT `inn_lay_list`, `inner_layer` FROM `da_customer_auto_inner`
where `mpcode` = 'qf017'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)) {
    $data1 = $row['inn_lay_list'];
    $data2 = $row['inner_layer'];
}

$parts1 = explode(';',$data1);
$parts2 = explode(';',$data2);
$layer_cnt = count($parts1);
$array_inner = array_chunk($parts2, 8);

echo json_encode($parts1);
echo json_encode($array_inner);

mysqli_close($conn);
?>

I obtained the result as:

["001","011","021","031"]

[["1","2","3","4","5","6","7","8"], ["11","12","13","14","15","16","17","18"], ["21","22","23","24","25","26","27","28"],[31","32","33","34","35","36","37","38"]]

Here for each element in first array there is a sub array in the second array(two dimensional array).
Now I want to display this in HTML page using a table. I am trying to use KnockoutJS “foreach” option with a named template:

      Layer
      P2P
      P2T
      T2T
      Track Width
      PTH To Cu
      NPTH To Cu
      PTH AR
      Via AR

I want my output as below :

Body:
Simple do this:

$array=[[1,2,3], [4,5,6], [7,8,9]];
print_r($array[0]);

If you want read all:
foreach($array as $arr){
print_r($arr);
}


问:
Using checkbox value inside conditional statements in JavaScript
I'm doing a questionnaire/survey using HTML. I need to get the value of the checkbox that is being checked. The questions on the next page(L2) will be based on the questions that is only checked on the checkbox when i click "submit".

I have a problem in getting and storing the value of the checkbox and using it later for an IF else-If else statement. Read a lot of online materials but I can't see any light from this. Any help will do... here is the code of the plain checkbox.

```<code><html>
    <head>
    </head>
    <body>
        <script>
            var vg = document.getElementId("VideoGame").checked;
            var te = document.getElementId("Text").checked;
            var an = document.getElementId("Animals").checked;
            var sp = document.getElementId("Sports").checked;
            var lo = document.getElementId("Logo").checked;
        </script>
        <form action="L2.html">
            Check the box if applicable: <br>
            <input type="checkbox" name="Q1" id="VideoGame"> The image is a Video Game.
            <br>
            <input type="checkbox" name="Q1" id="Text"> The image contains text. <br>
            <input type="checkbox" name="Q1" id="Animals"> The image is about animals.
            <br>
            <input type="checkbox" name="Q1" id="Sports"> The image is about sports.
            <br>
            <input type="checkbox" name="Q1" id="Logo"> The image contains a logo. <br>
            <input type="submit" value="NEXT">
        </form>
    </body>
</html>
</code>```

答:
You can simply add onclick to every input-element:

```<code><input type="checkbox" name="Q1" id="VideoGame" onclick="refreshValues()" />
</code>```

The refreshValues()-function can look like this:

```<code>function refreshValues() {
    var vg = document.getElementId("VideoGame").checked;
    var te = document.getElementId("Text").checked;
    var an = document.getElementId("Animals").checked;
    var sp = document.getElementId("Sports").checked;
    var lo = document.getElementId("Logo").checked;
}
</code>```

Body:
I'm doing a questionnaire/survey using HTML. I need to get the value of the checkbox that is being checked. The questions on the next page(L2) will be based on the questions that is only checked on the checkbox when i click "submit".

I have a problem in getting and storing the value of the checkbox and using it later for an IF else-If else statement. Read a lot of online materials but I can't see any light from this. Any help will do... here is the code of the plain checkbox.

        <form action="L2.html">
            Check the box if applicable:

            <input type="checkbox" name="Q1" id="VideoGame"> The image is a Video Game.

            <input type="checkbox" name="Q1" id="Text"> The image contains text.

            <input type="checkbox" name="Q1" id="Animals"> The image is about animals.

            <input type="checkbox" name="Q1" id="Sports"> The image is about sports.

            <input type="checkbox" name="Q1" id="Logo"> The image contains a logo.

            <input type="submit" value="NEXT">
        </form>

Body:
You can simply add onclick to every input-element:

<input type="checkbox" name="Q1" id="VideoGame" onclick="refreshValues()" />

The refreshValues()-function can look like this:

function refreshValues() {
    var vg = document.getElementId("VideoGame").checked;
    var te = document.getElementId("Text").checked;
    var an = document.getElementId("Animals").checked;
    var sp = document.getElementId("Sports").checked;
    var lo = document.getElementId("Logo").checked;
}


问:
Changing the domain name causes my image to not load in Wordpress
I have recently changed my wordpress installation a bit. I have configred IIS to have the website run as an application under a common domain name i have for multiple website.

So the main website name is www.example.com

The application is configured as www.example.com/sitename

Now i can access the site as www.example.com/sitename but all the images on the site have the src as "/wp-content/uploads/image.jpg" which causes the links to be broken as they point to www.example.com/wp-content.... instead of www.example.com/sitename/wp-content . how can i fix this.

I have tried the following.

Change the wp_options table. Set SiteURL and home to  http://www.example.com/sitename

Changed the Wp-Config.php file with the following parameters.

define( 'WP_ALLOW_MULTISITE', true );

define('MULTISITE', false);

define('SUBDOMAIN_INSTALL', false);

define('DOMAIN_CURRENT_SITE', 'www.abs-projects.co.uk/absuk');

define('WP_HOME','http://www.abs-projects.co.uk/absuk');

define('WP_SITEURL','http://www.abs-projects.co.uk/absuk');

define('PATH_CURRENT_SITE', '/');

答:
ensure that you have set the siteurl and home options in the {tableprefix}_options table to the new URL in your database without an ending /. if that doesn't do it, your theme will need to be updated. precede each path to an image with

```<code><?php echo home_url(); ?>/wp-content/uploads/image.jpg
</code>```

alternatively, since you have constants in your wp-config.php file,

```<code><?php echo WP_HOME; ?>/wp-content/uploads/image.jpg
</code>```

Body:
ensure that you have set the siteurl and home options in the {tableprefix}_options table to the new URL in your database without an ending /. if that doesn't do it, your theme will need to be updated. precede each path to an image with

<?php echo home_url(); ?>/wp-content/uploads/image.jpg

alternatively, since you have constants in your wp-config.php file,

<?php echo WP_HOME; ?>/wp-content/uploads/image.jpg


问:
How to get the total number of weeks in the current year?
I got below code on stackoverflow which return total number of week in current year, but it is hardcoded which'll not work on 2014 and 2016. How I get total number of week in current year dynamically???

```<code>Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.DAY_OF_MONTH, 31);

int ordinalDay = cal.get(Calendar.DAY_OF_YEAR);
int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Sunday = 0
int numberOfWeeks = (ordinalDay - weekDay + 10) / 7;
System.out.println(numberOfWeeks);
</code>```

I did like this just check it is current method?

```<code>     Calendar cal = Calendar.getInstance();
     int year = cal.get(Calendar.YEAR);
     cal.set(Calendar.YEAR, year);
     cal.set(Calendar.MONTH, Calendar.DECEMBER);
     cal.set(Calendar.DAY_OF_MONTH, 31);

     int ordinalDay = cal.get(Calendar.DAY_OF_YEAR);
     int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Sunday = 0
     int numberOfWeeks = (ordinalDay - weekDay + 10) / 7;
     System.out.println(numberOfWeeks);
</code>```

答:
Why not to use getActualMaximum property of Calendar ?

```<code>private int getWeeksCount(final int year, final Locale locale)
{
    Calendar calendar = Calendar.getInstance(locale);
    calendar.set(Calendar.YEAR, year);

    int totalWeekNumber = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
    return totalWeekNumber;
}
</code>```

Body:
I got below code on stackoverflow which return total number of week in current year, but it is hardcoded which'll not work on 2014 and 2016. How I get total number of week in current year dynamically???

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.DAY_OF_MONTH, 31);

int ordinalDay = cal.get(Calendar.DAY_OF_YEAR);
int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Sunday = 0
int numberOfWeeks = (ordinalDay - weekDay + 10) / 7;
System.out.println(numberOfWeeks);

I did like this just check it is current method?

     Calendar cal = Calendar.getInstance();
     int year = cal.get(Calendar.YEAR);
     cal.set(Calendar.YEAR, year);
     cal.set(Calendar.MONTH, Calendar.DECEMBER);
     cal.set(Calendar.DAY_OF_MONTH, 31);

     int ordinalDay = cal.get(Calendar.DAY_OF_YEAR);
     int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; // Sunday = 0
     int numberOfWeeks = (ordinalDay - weekDay + 10) / 7;
     System.out.println(numberOfWeeks);

Body:
Why not to use getActualMaximum property of Calendar ?

private int getWeeksCount(final int year, final Locale locale)
{
    Calendar calendar = Calendar.getInstance(locale);
    calendar.set(Calendar.YEAR, year);

    int totalWeekNumber = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
    return totalWeekNumber;
}


问:
how to convert xml response to class object in c#?
Hi i am going for the xml response to convert as a class object in c#.i have get the xml from the sql side and call the one utility and get the xml and go for the convert in class object but with my code not return null in the class. any one know where is my problem then please let me know.

Here is my xml data :

```<code><Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>
</code>```

this is my class in c#:

```<code>        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }
</code>```

this is my method in c#:

```<code>    public string xmldata()
    {
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class
            }
        return null;
    }
</code>```

答:
There is no <UserList> that wraps them, so this isn't an xml-array. Instead, use:

```<code>[XmlElement("User")]
public User[] ListUsers { get; set; }
</code>```

or better: List<User> instead of User[]; personally I'd have:

```<code>[XmlElement("User")]
public List<User> Users {get; } = new List<User>();
</code>```

(but that also requires that you renaming the root type to something else)

On User, it isn't a root, so [XmlRoot] is redundant; and [XmlElement] is the default and assumed automatically, so you can remove all of the [XmlElement] from User too.

To show it all working just fine:

```<code>using System;
using System.IO;
using System.Xml.Serialization;

public class Users
{
    public class User
    {
        public int UserId { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string ProfileImage { get; set; }
        public string Name { get; set; }
        public int FeedId { get; set; }
        public string Description { get; set; }
        public string Interest { get; set; }
        public int InterestId { get; set; }
    }

    [XmlElement("User")]
    public User[] ListUsers { get; set; }
}
static class Program
{
    static void Main()
    {
        var ser = new XmlSerializer(typeof(Users));
        using (var sr = new StringReader(xml))
        {
            var obj = (Users)ser.Deserialize(sr);
            Console.WriteLine(obj.ListUsers.Length); // 2
        }
    }

    const string xml = @"<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>";

}
</code>```

Body:
Hi i am going for the xml response to convert as a class object in c#.i have get the xml from the sql side and call the one utility and get the xml and go for the convert in class object but with my code not return null in the class. any one know where is my problem then please let me know.

Here is my xml data :

<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>

this is my class in c#:

        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }

this is my method in c#:

    public string xmldata()
    {
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class
            }
        return null;
    }

Body:
There is no <UserList> that wraps them, so this isn't an xml-array. Instead, use:

[XmlElement("User")]
public User[] ListUsers { get; set; }

or better: List<User> instead of User[]; personally I'd have:

[XmlElement("User")]
public List<User> Users {get; } = new List<User>();

(but that also requires that you renaming the root type to something else)

On User, it isn't a root, so [XmlRoot] is redundant; and [XmlElement] is the default and assumed automatically, so you can remove all of the [XmlElement] from User too.

To show it all working just fine:

using System;
using System.IO;
using System.Xml.Serialization;

public class Users
{
    public class User
    {
        public int UserId { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string ProfileImage { get; set; }
        public string Name { get; set; }
        public int FeedId { get; set; }
        public string Description { get; set; }
        public string Interest { get; set; }
        public int InterestId { get; set; }
    }

    [XmlElement("User")]
    public User[] ListUsers { get; set; }
}
static class Program
{
    static void Main()
    {
        var ser = new XmlSerializer(typeof(Users));
        using (var sr = new StringReader(xml))
        {
            var obj = (Users)ser.Deserialize(sr);
            Console.WriteLine(obj.ListUsers.Length); // 2
        }
    }

    const string xml = @"<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>";

}


问:
Correctness of using std::atomic<bool> in combination with std::mutex
I have written a shared priority queue class.

To signal to stop serving data I use method Cancel(), which sets a sign done to false and application is not allowed to write / read any data from the queue. I am not sure about using std::atomic<bool> in combination with std::mutex and std::condition_variable. I am not sure, if my solution is thread safe or race condition can happen:

The original version of Enqueue method is:

```<code>std::deque<T> deque;
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> done;

SharedPriorityQueue() : done(false)
{
}

~SharedPriorityQueue()
{
    Cancel();
}

void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    std::lock_guard<std::mutex> lock(mtx);
    deque.push_back(item);
    cv.notify_one();
}
</code>```

However, can be the variable done (atomic bool) separated from the locking mechanism by mutex?

To cancel the queue I use this construction:

```<code>void Cancel()
{
    if (done)
    {
        return;
    }
    done = true;

    cv.notify_all();
}
</code>```

What is the best solution of the designs bellow?

```<code>// A)
void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    {
        std::lock_guard<std::mutex> lock(mtx); // lock is released before notify call
        deque.push_back(item);
    }
    cv.notify_one();
}

// B)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is atomic bool and protected by the lock along with data (deque)
        if (done) // atomic bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}

// C)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is NOT atomic bool and is protected by the lock along with data (deque)
        if (done) // simple bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}
</code>```

Waiting staff:

```<code>bool Dequeue(T& item)
{
    std::unique_lock<std::mutex> lock(mtx);
    while (!done && deque.empty())
    {
        cv.wait(lock);
    }

    if (!deque.empty())
    {
        item = deque.front();
        deque.pop_front();
    }

    if (done)
    {
        return false;
    }
    return true;
}
</code>```

答:
The normal / most frequent case is probably that the queue is ready (not done), whereas done state is likely used during termination only. It may make little sense to optimize for the done case by using an atomic.

You need to understand what you are optimizing for and use a profiler.

Body:
I have written a shared priority queue class.

To signal to stop serving data I use method Cancel(), which sets a sign done to false and application is not allowed to write / read any data from the queue. I am not sure about using std::atomic<bool> in combination with std::mutex and std::condition_variable. I am not sure, if my solution is thread safe or race condition can happen:

The original version of Enqueue method is:

std::deque<T> deque;
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> done;

SharedPriorityQueue() : done(false)
{
}

~SharedPriorityQueue()
{
    Cancel();
}

void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    std::lock_guard<std::mutex> lock(mtx);
    deque.push_back(item);
    cv.notify_one();
}

However, can be the variable done (atomic bool) separated from the locking mechanism by mutex?

To cancel the queue I use this construction:

void Cancel()
{
    if (done)
    {
        return;
    }
    done = true;

    cv.notify_all();
}

What is the best solution of the designs bellow?

// A)
void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    {
        std::lock_guard<std::mutex> lock(mtx); // lock is released before notify call
        deque.push_back(item);
    }
    cv.notify_one();
}

// B)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is atomic bool and protected by the lock along with data (deque)
        if (done) // atomic bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}

// C)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is NOT atomic bool and is protected by the lock along with data (deque)
        if (done) // simple bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}

Waiting staff:

bool Dequeue(T& item)
{
    std::unique_lock<std::mutex> lock(mtx);
    while (!done && deque.empty())
    {
        cv.wait(lock);
    }

    if (!deque.empty())
    {
        item = deque.front();
        deque.pop_front();
    }

    if (done)
    {
        return false;
    }
    return true;
}


问:
My app is getting crashed on UIDocumentPickerViewController
I am working on file sharing on my iOS App, I am new to UIDocumentPickerViewController. I do not know why my app is crashing.

```<code>UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.image"] inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
</code>```

App is crashing on the highlighted lines.

Has anyone done this previously? I want to do the same like the attachment below

答:
swift 3.0 you can select all document.

```<code>let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import)

    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)
</code>```

Body:
I am working on file sharing on my iOS App, I am new to UIDocumentPickerViewController. I do not know why my app is crashing.

UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.image"] inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];

App is crashing on the highlighted lines.

Has anyone done this previously? I want to do the same like the attachment below

Body:
swift 3.0 you can select all document.

let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import)

    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)


问:
MySQL using "-" as different
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

```<code>delete from <table> where id - 145;
</code>```

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

答:
```<code>delete from <table> where id - 145;
</code>```

will work fine if id is 146 as 146-145=1 and mysql return true for 1 and false for 0;

Hope this solve your doubt.

Title: MySQL using "-" as different

Body:
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

delete from
 where id - 145;

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

Body:
delete from <table> where id - 145;

will work fine if id is 146 as 146-145=1 and mysql return true for 1 and false for 0;

Hope this solve your doubt.


问:
WKWebView goes to about:blank page after appearing
I have a WKWebView and it has a randomly occuring bug when I leave the WebView ViewController to another "native" ViewController and come back, it shows nothing but a white screen. I debugged with Safari and find that the WKWebView shows a page "about:blank" with an empty head and body tag as content.

The phenomena occurs completely at random. Sometimes I leave the WKWebView 3 times, sometimes I do it over 100 times until the white screen appears.

It doesn´t fire any of the WKNavigationDelegate's Callbacks for the "about:blank" page. My logs are the same then if the WebView works normal. We have no idea what`s going on. Anyone experienced similar behaviour?

答:
I have never experienced similar behavior however, I can think of a solution. How about you save in a variable the last page visited and reload it on viewWillAppear if _wkWebView.URL is the blank page?

Also maybe the delegate is being deallocated, make sure you reassign the delegate on viewWillAppear


问:
Chart.js: Is it possible to get the label of a dataset in a stacked bargraph on clicking it?
I'm trying to get the name of the label associated with the dataset in a stacked bar graph when that particular dataset's stack is clicked on.

This is my code:

```<code>    var dataPack1 = [100, 200, 300, 400, 500];
    var dataPack2 = [150, 450, 350, 250, 150];
    var dates = ["May 1", "May 2", "May 3", "May 4", "May 5"];
    var bar_chart = new Chart(bar_ctx, {
        type: 'bar',
        data: {
            labels: dates,
            datasets: [
            {
                label: 'Bowser',
                data: dataPack1,
                backgroundColor: "grey"
            },
            {
                label: 'Mario',
                data: dataPack2,
                backgroundColor: "maroon"
            },
            ]
        },
        options: {
            scales: {
              xAxes: [{
                stacked: true,
                gridLines: { display: false },
                }],
              yAxes: [{
                stacked: true
                }],
            }, // scales
            onClick: function(evt, element) {
              //var val = element.something such that val is assigned 'Bowser'
            }
        } // options
       }
    );
</code>```

Now, when I click on say, 500, I want a variable, val to get assigned 'Bowser'. Is that possible?

Here is the jsfiddle for it.

答:
You can use the prototype method .getElementAtEvent(e) to get the element clicked on like so

```<code>onClick: function(evt, element) {
  var activePoints = bar_chart.getElementAtEvent(evt);
  console.log(activePoints[0]._model.datasetLabel);
}
</code>```

JSFiddle

Or you can attach it as an event handler on the chart element

```<code>bar_ctx.onclick = function(evt) {
  var activePoints = bar_chart.getElementAtEvent(evt);
  console.log(activePoints[0]._model.datasetLabel);
};
</code>```

JSFiddle

Body:
I'm trying to get the name of the label associated with the dataset in a stacked bar graph when that particular dataset's stack is clicked on.

This is my code:

    var dataPack1 = [100, 200, 300, 400, 500];
    var dataPack2 = [150, 450, 350, 250, 150];
    var dates = ["May 1", "May 2", "May 3", "May 4", "May 5"];
    var bar_chart = new Chart(bar_ctx, {
        type: 'bar',
        data: {
            labels: dates,
            datasets: [
            {
                label: 'Bowser',
                data: dataPack1,
                backgroundColor: "grey"
            },
            {
                label: 'Mario',
                data: dataPack2,
                backgroundColor: "maroon"
            },
            ]
        },
        options: {
            scales: {
              xAxes: [{
                stacked: true,
                gridLines: { display: false },
                }],
              yAxes: [{
                stacked: true
                }],
            }, // scales
            onClick: function(evt, element) {
              //var val = element.something such that val is assigned 'Bowser'
            }
        } // options
       }
    );

Now, when I click on say, 500, I want a variable, val to get assigned 'Bowser'. Is that possible?

Here is the jsfiddle for it.

Body:
You can use the prototype method .getElementAtEvent(e) to get the element clicked on like so

onClick: function(evt, element) {
  var activePoints = bar_chart.getElementAtEvent(evt);
  console.log(activePoints[0]._model.datasetLabel);
}

JSFiddle

Or you can attach it as an event handler on the chart element

bar_ctx.onclick = function(evt) {
  var activePoints = bar_chart.getElementAtEvent(evt);
  console.log(activePoints[0]._model.datasetLabel);
};

JSFiddle


问:
Ruby mailer with sidekiq into Rails 5.x app : ArgumentError
I'm trying to migrate from rails 4.x to rails 5.x

gemfile.lock:

- rails (5.0.2)

- sidekiq_mailer (0.0.8)

- sidekiq (5.0.0)

- actionmailer (= 5.0.2)

For mailing stuff, when I try the following :
$>UserMailer.password_reset(account_to_reset).deliver_later
(which previously worked like a charm)

I got this error :

ArgumentError: wrong number of arguments (given 2, expected 0)

with (the full and only) following backtrace :

from /Users/nathangouy/.rvm/gems/ruby-2.4.1/gems/actionmailer-5.0.2/lib/action_mailer/base.rb:582:in 'initialize'
    from /Users/nathangouy/.rvm/gems/ruby-2.4.1/gems/sidekiq_mailer-0.0.8/lib/sidekiq_mailer/proxy.rb:11:in 'new'
    from /Users/nathangouy/.rvm/gems/ruby-2.4.1/gems/sidekiq_mailer-0.0.8/lib/sidekiq_mailer/proxy.rb:11:in 'actual_message'
    from /Users/nathangouy/.rvm/gems/ruby-2.4.1/gems/sidekiq_mailer-0.0.8/lib/sidekiq_mailer/proxy.rb:28:in 'method_missing'

I try a lot of things and wasn't able to find any similar issue on sidekiq or actionmailer

答: Ok I found the problem, the thing is that sidekiq_mailer isn't maintained by the sidekiq author (I missed this crucial info), and then it's not usable for now with sidekiq/rails 5.x</p>


答:
I would consider storing the data in either LocalStorage or SessionStorage and then retrieve it on the next page with localStorage.set('key', 'item') and localStorage.get('key');

https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
https://developer.mozilla.org/en/docs/Web/API/Window/sessionstorage

And if you need to store an object with multiple inputs consider using JSON stringify.

Storing Objects in HTML5 localStorage

Title: Using checkbox value inside conditional statements in JavaScript


问:
How to send/receive Message to/from particular ibm mq queue using JMS
Currently I am using ‘onMessage’ to listen dedicated queue for message.

Now new requirement is,
1.  different vendor will put msg on single queue, and  I have to differentiate the msg by vendor and store into oracle db.
2.  Second requirement is to send back msg on single queue so particular vendor will pick up.

I am new to this.
Any response is appreciated.

答:
1) Ask your vendor to set a property, say "Vendor Name", on the message. Then you can use that property to differentiate by vendor. If property can not be set on a message, then you will have to parse the message payload and update database accordingly.

2) Ask your vendor to set JMSReplyTo property on the message they are putting in the queue. You can then use the value of the JMSReplyTo to send a reply back to vendor. Also you need to take the JMSMessageID of the vendor's message and set it as JMSCorrelationID of the reply message your application is sending. This way your vendor can correlate the request message with the reply message you sent.

Hope this helps.


问:
Getting expression text
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:</p>

```<code>public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"
</code>```

答:
My first thought was to use expression.Body.ToString() and tweak that a bit, but you would still need to deal with Unary (convert) etc. Assuming this is for logging and you want more control, the below can be used for formatting as wanted (e.g. if you want Child->Name for display purposes, string.Join("->",..) can be used). It may not be complete, but should you find any unsupported types, they should be easy to add.

PS: this post was generated before the question was closed. Just noticed it was reopend and submitting it now, but I haven't checked if particulars have been changed.

```<code>public string GetName(Expression e, out Expression parent)
{
    if(e is MemberExpression  m){ //property or field
        parent = m.Expression;
        return m.Member.Name;
    }
    else if(e is MethodCallExpression mc){
        string args = string.Join(",", mc.Arguments.SelectMany(GetExpressionParts));
        if(mc.Method.IsSpecialName){ //for indexers, not sure this is a safe check...
            return $"{GetName(mc.Object, out parent)}[{args}]";
        }
        else{ //other method calls
            parent = mc.Object;
            return $"{mc.Method.Name}({args})";
        }
    }
    else if(e is ConstantExpression c){ //constant value
        parent = null;
        return c.Value?.ToString() ?? "null";
    }
    else if(e is UnaryExpression u){ //convert
        parent=  u.Operand;
        return null;
    }
    else{
        parent =null;
        return e.ToString();
    }
}

public IEnumerable<string> GetExpressionParts(Expression e){
    var list = new List<string>();
    while(e!=null && !(e is ParameterExpression)){
        var name = GetName(e,out e);
        if(name!=null)list.Add(name);
    }
    list.Reverse();
    return list;
}

public string GetExpressionText<T>(Expression<Func<T, object>> expression) => string.Join(".", GetExpressionParts(expression.Body));
</code>```

Title: Getting expression text

Body:
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:

public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"

Body:
My first thought was to use expression.Body.ToString() and tweak that a bit, but you would still need to deal with Unary (convert) etc. Assuming this is for logging and you want more control, the below can be used for formatting as wanted (e.g. if you want Child->Name for display purposes, string.Join("->",..) can be used). It may not be complete, but should you find any unsupported types, they should be easy to add.

PS: this post was generated before the question was closed. Just noticed it was reopend and submitting it now, but I haven't checked if particulars have been changed.

public string GetName(Expression e, out Expression parent)
{
    if(e is MemberExpression  m){ //property or field
        parent = m.Expression;
        return m.Member.Name;
    }
    else if(e is MethodCallExpression mc){
        string args = string.Join(",", mc.Arguments.SelectMany(GetExpressionParts));
        if(mc.Method.IsSpecialName){ //for indexers, not sure this is a safe check...
            return $"{GetName(mc.Object, out parent)}[{args}]";
        }
        else{ //other method calls
            parent = mc.Object;
            return $"{mc.Method.Name}({args})";
        }
    }
    else if(e is ConstantExpression c){ //constant value
        parent = null;
        return c.Value?.ToString() ?? "null";
    }
    else if(e is UnaryExpression u){ //convert
        parent=  u.Operand;
        return null;
    }
    else{
        parent =null;
        return e.ToString();
    }
}

public IEnumerable<string> GetExpressionParts(Expression e){
    var list = new List<string>();
    while(e!=null && !(e is ParameterExpression)){
        var name = GetName(e,out e);
        if(name!=null)list.Add(name);
    }
    list.Reverse();
    return list;
}

public string GetExpressionText<T>(Expression<Func<T, object>> expression) => string.Join(".", GetExpressionParts(expression.Body));


问:
What would cause an HTML5 canvas toBlob to create an incomplete image?
I have the following javascript produce images from a canvas and upload them to a server.

```<code>var can = document.createElement('canvas');
can.width = 600;
can.height = 600;
var ctx = can.getContext('2d');
ctx.fillRect(0, 0, can.width, can.height);
ctx.fillText("Julia", can.width/2, can.height/2);
can.toBlob(uploadImage, "image/jpg", 0.9);

function uploadImage(jpeg) {
  var data = new FormData();
  data.append('image', jpeg, 'image.jpg');
  ...
}
</code>```

Every so often, the result looks like the above, only partially drawn. Multiple canvases are processed and uploaded serially, only moving on in the completion of the ajax (in the ... part), so only one at a time.

Have you seen this happen? If so, where in this process should I debug further? Maybe a setting or something in the context object?

Edit

The upload is an ajax post with a promise resolved only on the success branch. It actually uses angular's $http service:

```<code>$http({method: 'POST', url: '...', data: data}).then(function(response) {
    // callback that processes and uploads the next image
});
</code>```

答:
try to rearrange your logic a little,, you are getting racing condition with uploading process and when the image is created, they have to be callback in callback sorta ..

```<code>// ...
ctx.fillText("Julia", can.width / 2, can.height / 2);
can.toBlob(function(blob) {
    var newImg = document.createElement('img'),
        url = URL.createObjectURL(blob);
    newImg.onload = function() {
        // no longer need to read the blob so it's revoked
        URL.revokeObjectURL(url);
        newImg.src = url;
        // we have image out of canvas and now do the upload of newImg
        // $http || $.ajax call goes here
    };
});
</code>```

of if you want to submit image data URL try something like,,

```<code>// ...
ctx.fillText("Julia", can.width / 2, can.height / 2);
can.toBlob(function(blob) {
    var reader = new window.FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = function() {
                base64data = reader.result;
        // we have image in base64 and now do the upload of base64data
        // $http || $.ajax call goes here
    }
});
</code>```

hth, k

Body:
I have the following javascript produce images from a canvas and upload them to a server.

var can = document.createElement('canvas');
can.width = 600;
can.height = 600;
var ctx = can.getContext('2d');
ctx.fillRect(0, 0, can.width, can.height);
ctx.fillText("Julia", can.width/2, can.height/2);
can.toBlob(uploadImage, "image/jpg", 0.9);

function uploadImage(jpeg) {
  var data = new FormData();
  data.append('image', jpeg, 'image.jpg');
  ...
}

Every so often, the result looks like the above, only partially drawn. Multiple canvases are processed and uploaded serially, only moving on in the completion of the ajax (in the ... part), so only one at a time.

Have you seen this happen? If so, where in this process should I debug further? Maybe a setting or something in the context object?

Edit

The upload is an ajax post with a promise resolved only on the success branch. It actually uses angular's $http service:

$http({method: 'POST', url: '...', data: data}).then(function(response) {
    // callback that processes and uploads the next image
});

Body:
try to rearrange your logic a little,, you are getting racing condition with uploading process and when the image is created, they have to be callback in callback sorta ..

// ...
ctx.fillText("Julia", can.width / 2, can.height / 2);
can.toBlob(function(blob) {
    var newImg = document.createElement('img'),
        url = URL.createObjectURL(blob);
    newImg.onload = function() {
        // no longer need to read the blob so it's revoked
        URL.revokeObjectURL(url);
        newImg.src = url;
        // we have image out of canvas and now do the upload of newImg
        // $http || $.ajax call goes here
    };
});

of if you want to submit image data URL try something like,,

// ...
ctx.fillText("Julia", can.width / 2, can.height / 2);
can.toBlob(function(blob) {
    var reader = new window.FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = function() {
                base64data = reader.result;
        // we have image in base64 and now do the upload of base64data
        // $http || $.ajax call goes here
    }
});

hth, k


问:
Finding the value of a particular index in a Python list
I have a simple python program.

```<code>from nltk.tokenize import word_tokenize

negation ='no','not','never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')
sentence = 'loss money'

if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
list2 for word in word_tokenize(sentence))[-1:])not in negation :
  print 'sad'
else:
  print 'not sad'
</code>```

This make error which is

```<code>TypeError: 'bool' object has no attribute '__getitem__'
</code>```

What I need here, I want to check if any word in the sentence is in the list2. If yes, then want to check its before index value is in the negation list or not. if yes it should be "not sad".

For an example "I miss him" should sad, "I not miss him" should be not sad.

Can anyone help me !

答:
You have a number of problems here, for starters:

If you are going to be looking through sets of words, use sets, not lists. e.g. negations={'no','not','never'}

'give up' will never be found as a token in a sentence.

any() returns a boolean (see this question) for how it works.

listobj[-1:] returns the slice of the list with only the last element

you are not trying to extract items from a list or container, as any() returns a boolean, you are trying to treat a boolean as a container.  This is what is causing the error you can see.

I suggest you break down your problem into more logical steps rather than jumping straight into list comprehensions / generators.

Where you want to access items in a list based on the position of others, I recommend starting with a indexed for loop:

```<code>for index, value in enumerate(var):
    last_word=var[index-1] if index > 0 else None
</code>```

And do operations like word tokenisation only once, no need to keep doing it over and over.

Example solution:

```<code>def sad_sentence(sentence):
    wordlist=sentence.split()
    negations={'no','not','never'}
    negphrases={'miss','loss','gone','give up','lost'}

    for index, word in enumerate(wordlist):
        last_word=wordlist[index-1] if index > 0 else None
        if word in negphrases:
            if last_word in negations:
                print 'not sad'
            else:
                print 'sad'
            break;
        print 'not sad'
</code>```

This results in:

```<code>>>> sad_sentence("I am not gone")
not sad
>>> sad_sentence("I am not here I am gone")
sad
>>>
</code>```

Body:
I have a simple python program.

from nltk.tokenize import word_tokenize

negation ='no','not','never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')
sentence = 'loss money'

if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
list2 for word in word_tokenize(sentence))[-1:])not in negation :
  print 'sad'
else:
  print 'not sad'

This make error which is

TypeError: 'bool' object has no attribute '__getitem__'

What I need here, I want to check if any word in the sentence is in the list2. If yes, then want to check its before index value is in the negation list or not. if yes it should be "not sad".

For an example "I miss him" should sad, "I not miss him" should be not sad.

Can anyone help me !

Body:
You have a number of problems here, for starters:

If you are going to be looking through sets of words, use sets, not lists. e.g. negations={'no','not','never'}

'give up' will never be found as a token in a sentence.

any() returns a boolean (see this question) for how it works.

listobj[-1:] returns the slice of the list with only the last element

you are not trying to extract items from a list or container, as any() returns a boolean, you are trying to treat a boolean as a container.  This is what is causing the error you can see.

I suggest you break down your problem into more logical steps rather than jumping straight into list comprehensions / generators.

Where you want to access items in a list based on the position of others, I recommend starting with a indexed for loop:

for index, value in enumerate(var):
    last_word=var[index-1] if index > 0 else None

And do operations like word tokenisation only once, no need to keep doing it over and over.

Example solution:

def sad_sentence(sentence):
    wordlist=sentence.split()
    negations={'no','not','never'}
    negphrases={'miss','loss','gone','give up','lost'}

    for index, word in enumerate(wordlist):
        last_word=wordlist[index-1] if index > 0 else None
        if word in negphrases:
            if last_word in negations:
                print 'not sad'
            else:
                print 'sad'
            break;
        print 'not sad'

This results in:

>>> sad_sentence("I am not gone")
not sad
>>> sad_sentence("I am not here I am gone")
sad
>>>


问:
Fetching of mails in third party iPhone application
I am trying to fetch all my gmail account mails in my iphone app. Is there any third party API which provides me some help on this. I am trying to use pop3 but not found success. Mail sending from third party app without using iphone default library is succeed using SMTP. Can we do such kind of thing for fetching mails also.

Thanks in advance.

答: I would recommend looking into this.</p>

Body: I would recommend looking into this.


问:
Dealing with SVN merge issues
After trying a merge through different branches, I'm facing the following problems

Tortoise SVN sees some conflicts

Trying to solve the conflicts by editing them shows some empty files

There is no file marked as 'in conflict' but they contains this kind of text
<<<<<<< .working ======= >>>>>> .merge-right.r12532

As a solution I'd like to have an extra check through an external comparison tool but I need a way to find every file modified by the merge. Have you got suggestions?

答:
I don't know if this is what you are looking.

File :-

you can do right click-> TortoiseSVN->Diff later.

Folder :-

right click the folder -> TortoiseSVN->Repository Browse then right click the folder and use the Mark for comparison option.

use revision graph TortoiseSVN->Revision Graph.

Title: Dealing with SVN merge issues


问:
Removing list of vms in vagrant cache
I'm not looking for this answer, because my question is different.

When I type vagrant global-status I get a list of vms, but some of those directories and VMs have been deleted along with the Vagrantfiles.

But when i type vagrant destroy [machineid], I get the following error, which I am looking to resolve. Please advise.

```<code>The working directory for Vagrant doesn't exist! This is the
specified working directory:

/Users/steven/projects/php/vagrant-laravel
</code>```

答:
Use vagrant box remove -f [name]

It works. Guaranteed!

Title: Removing list of vms in vagrant cache

Body:
I'm not looking for this answer, because my question is different.

When I type vagrant global-status I get a list of vms, but some of those directories and VMs have been deleted along with the Vagrantfiles.

But when i type vagrant destroy [machineid], I get the following error, which I am looking to resolve. Please advise.

The working directory for Vagrant doesn't exist! This is the
specified working directory:

/Users/steven/projects/php/vagrant-laravel


问:
Redirect http requests to https in wildfly 10
This is my standalone-full.xml configuration with ssl configured

security realm .

```<code>      <security-realm name="SslRealm">
            <server-identities>
            <ssl>
            <keystore path="D:\ncm.keystore" alias="ncm" keystore-password="*****" />
            </ssl>
            </server-identities>
        </security-realm>
</code>```

Subsystem

```<code> <server name="default-server">
            <http-listener name="default" socket-binding="http" redirect-socket="https"/>
            <https-listener name="default-ssl" socket-binding="https" security-realm="SslRealm"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
            </host>
        </server>
</code>```

Socket Binding

```<code>   <socket-binding name="http" port="${jboss.http.port:8080}"/>
    <socket-binding name="https" port="${jboss.https.port:8443}"/>
</code>```

How to redirect to https:///localhost:8443/myApp when user hits http://localhost:8080/myApp

答:
I tried

```<code><rewrite name="http-to-https" redirect="true" target="https://my.website.com:443/Web/"/>
</code>```

As you can see without %U

It redirects all HTTP traffic to HTTPS

Body:
This is my standalone-full.xml configuration with ssl configured

security realm .

      <security-realm name="SslRealm">
            <server-identities>
            <ssl>
            <keystore path="D:\ncm.keystore" alias="ncm" keystore-password="*****" />
            </ssl>
            </server-identities>
        </security-realm>

Subsystem

 <server name="default-server">
            <http-listener name="default" socket-binding="http" redirect-socket="https"/>
            <https-listener name="default-ssl" socket-binding="https" security-realm="SslRealm"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
            </host>
        </server>

Socket Binding

   <socket-binding name="http" port="${jboss.http.port:8080}"/>
    <socket-binding name="https" port="${jboss.https.port:8443}"/>

How to redirect to https:///localhost:8443/myApp when user hits http://localhost:8080/myApp

Body:
I tried

<rewrite name="http-to-https" redirect="true" target="https://my.website.com:443/Web/"/>

As you can see without %U

It redirects all HTTP traffic to HTTPS