问:
ISO 8601 DateTime representation
Is this a valid ISO 8601 representation of DateTime?

20170704T09:30:00+0530

i.e. whether a combination of both the basic and extended formats can be used? Or should it only be either of these:

20170704T093000+0530

  2017-07-04T09:30:00+05:30

答:
While ISO6801-2004 doesn't allow mixing basic and extended representations, there's no clause in the 2004 revision that would explicitly forbid that.

This question will be addressed in the next revision of ISO8601 [1] which finally includes a Backus-Naur Form definition of a valid timestamp syntax.

```<code>(* 4.3.2 Complete representations *)
dateTimeOfDayBasic = calendarDateBasic, "T", timeCompleteBasic,
                     [ "Z" | UTCoffsetBasic ] ;
dateTimeOfDayExt   = calendarDateExt, "T", timeCompleteExt,
                     [ "Z" | UTCoffsetExt ] ;
</code>```

[1] Draft 2016-10-26: https://www.loc.gov/standards/datetime/ISO_DIS%208601-1.pdf

Title: ISO 8601 DateTime representation

Body:
While ISO6801-2004 doesn't allow mixing basic and extended representations, there's no clause in the 2004 revision that would explicitly forbid that.

This question will be addressed in the next revision of ISO8601 [1] which finally includes a Backus-Naur Form definition of a valid timestamp syntax.

(* 4.3.2 Complete representations *)
dateTimeOfDayBasic = calendarDateBasic, "T", timeCompleteBasic,
                     [ "Z" | UTCoffsetBasic ] ;
dateTimeOfDayExt   = calendarDateExt, "T", timeCompleteExt,
                     [ "Z" | UTCoffsetExt ] ;

[1] Draft 2016-10-26: https://www.loc.gov/standards/datetime/ISO_DIS%208601-1.pdf


来源: stackexchange

问:
Triggering a jquery action when the users mark a Checkbox
im very new in javascript and jquery. I have this checkbox:

```<code><label for="editable">Editable </label><input name="editable" type="checkbox" id="edita"/>
</code>```

And this jquery action:

```<code>$('#slickbox1').toggle(400);
return false;
</code>```

I want to execute that action when the checkbox is checked. Thanks!

答:
You could try:

```<code>$('#edita').change(
function() {
    if ($(this).is(':checked')) {
       $('#slickbox1').toggle(400);
    }
});
</code>```

Although it's worth noting that running the toggle() method only when it's checked (assuming that it starts off un-checked) involves the user clicking the input once to show it, and then again to remove the check and again to re-check it so that it hides as a result of the toggle().

It might be worth considering:

```<code>$('#edita').change(
function() {
    if ($(this).is(':checked')) {
        // checked
        $('#slickbox1').show(400);
    }
    else {
        // un-checked
        $('#slickbox1').hide(400);
    }
});
</code>```

Which shows $('#slickbox1') if the check-box is checked, and hides it if not,

Or:

```<code>$('#edita').change(
function() {
       $('#slickbox1').toggle(400);
});
</code>```

Which toggles the $('#slickbox1') between show() and hide() when the input is checked and un-checked.

Edited to address the question raised by DomingoSL (the OP) in comments:

...can you please make an edit to see the procedure if now the triger is not a checkbox but a button?

There are two changes that need to be made to accommodate this:

a button has no change event, so it would have to use click() instead, and

a button has no :checked (or equivalent) state, so the if/else becomes redundant.

One way of doing it, though, and I'm assuming your element names remain the same since you've posted no information to the contrary, is:

```<code>$('#edita').click(
function(){
    $('#slickbox1').toggle(400);
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
im very new in javascript and jquery. I have this checkbox:

Editable <input name="editable" type="checkbox" id="edita"/>

And this jquery action:

$('#slickbox1').toggle(400);
return false;

I want to execute that action when the checkbox is checked. Thanks!

Body:
You could try:

$('#edita').change(
function() {
    if ($(this).is(':checked')) {
       $('#slickbox1').toggle(400);
    }
});

Although it's worth noting that running the toggle() method only when it's checked (assuming that it starts off un-checked) involves the user clicking the input once to show it, and then again to remove the check and again to re-check it so that it hides as a result of the toggle().

It might be worth considering:

$('#edita').change(
function() {
    if ($(this).is(':checked')) {
        // checked
        $('#slickbox1').show(400);
    }
    else {
        // un-checked
        $('#slickbox1').hide(400);
    }
});

Which shows $('#slickbox1') if the check-box is checked, and hides it if not,

Or:

$('#edita').change(
function() {
       $('#slickbox1').toggle(400);
});

Which toggles the $('#slickbox1') between show() and hide() when the input is checked and un-checked.

Edited to address the question raised by DomingoSL (the OP) in comments:

...can you please make an edit to see the procedure if now the triger is not a checkbox but a button?

There are two changes that need to be made to accommodate this:

a button has no change event, so it would have to use click() instead, and

a button has no :checked (or equivalent) state, so the if/else becomes redundant.

One way of doing it, though, and I'm assuming your element names remain the same since you've posted no information to the contrary, is:

$('#edita').click(
function(){
    $('#slickbox1').toggle(400);
});


问:
SQLALchemy lazy compile classes
i haven't found solution for this. Problem in very load compile (40 sec)
I have:

more then 1200 classes

300 enums

and some custom primitive classes for working

7 levels of polymorphic inherits

some itself relationship, may one-to-many and many-to-many in one class to itself

parents and childs may have somenamed relationship to one table

I undestand, that's big project, but in develop i need load ~100 classes.
Do the product exists that can do it or i need to create custom class map and custom factory?

答:
For perform this task i create only classes with inheritance and primary keys.

Steps is:

1) After that i wrote function who take one argument(class name) check if it already not loaded and create attributes, foreign_keys and relationship, somethink like class.attrib=Column(String)

2) Override definition __new__ for creating classes, __getattr__ for queries and maybe need __setattr__, i don't know

```<code>  def __new__(cls,*args,**kwargs):
    if cls.__name__ not in sl_loaded_classes: sl_load_function(cls.__name__)
    return super(MyCLA,cls).__new__(cls)

  def __getattr__(self,attr):
    if "MyClass" not in sl_loaded_classes: sl_load_function("NameType")
    if False: pass
    elif attr=="relation" and "RelatedClass" not in sl_loaded_classes:
      sl_load_function("RelatedClass")
      for sl_class in gc.get_objects():
        if isinstance(sl_class,self.__class__):
          config.session.refresh(sl_class)
    else: return config.Base.__getattr__(self, attr)
    return getattr(self,attr)
</code>```

And now it worked, not pefect (i can't deleted object, before load related classes), but it in process

ContentLicense: CC BY-SA 3.0

Title: SQLALchemy lazy compile classes

Body:
For perform this task i create only classes with inheritance and primary keys.

Steps is:

1) After that i wrote function who take one argument(class name) check if it already not loaded and create attributes, foreign_keys and relationship, somethink like class.attrib=Column(String)

2) Override definition __new__ for creating classes, __getattr__ for queries and maybe need __setattr__, i don't know

  def __new__(cls,*args,**kwargs):
    if cls.__name__ not in sl_loaded_classes: sl_load_function(cls.__name__)
    return super(MyCLA,cls).__new__(cls)

  def __getattr__(self,attr):
    if "MyClass" not in sl_loaded_classes: sl_load_function("NameType")
    if False: pass
    elif attr=="relation" and "RelatedClass" not in sl_loaded_classes:
      sl_load_function("RelatedClass")
      for sl_class in gc.get_objects():
        if isinstance(sl_class,self.__class__):
          config.session.refresh(sl_class)
    else: return config.Base.__getattr__(self, attr)
    return getattr(self,attr)

And now it worked, not pefect (i can't deleted object, before load related classes), but it in process


问:
Python Selenium : Unable to find text from web element
I have a test cases written in python selenium and when I try to get the text from a web element, it fails. I tried the following before get text on that web element to check if the code identifies the element but still fails

Find if element in the page(this line pass in the test case). It identifies that element and but fails to get the text

Find if element is visible (this line pass in the test case) - It identifies that element is visible and but fails to get the text

Find if element is enabled (this line pass in the test case) -It identifies that element is enabled and but fails to get the text

If I do sleep of 1 second. Then the text is extracted from the element. I don't want to give this sleep in my test case. Please tell me why it fails and what can i do other that sleep to get this element.

note -silmiarly i have drop down element for which the same happens.

please advise

答:
It seem that text is generated dynamically so you need to wait until target element contains any text:</p>

```<code>from selenium.webdriver.support.ui import WebDriverWait as wait

element = driver.find_element_by_xpath("//node")
text_content = wait(driver, 10).until(lambda driver: element.text)
</code>```

Body:
It seem that text is generated dynamically so you need to wait until target element contains any text:

from selenium.webdriver.support.ui import WebDriverWait as wait

element = driver.find_element_by_xpath("//node")
text_content = wait(driver, 10).until(lambda driver: element.text)


问:
How to share IORef state between two function invocations in Haskell when using IO?
I'm trying to learn Haskell and I'm playing around with IORef to which I try to save and find records. My code looks something like this (note that I've chosen "String" as IORef type in this example only for convienence and briefty, in my actual code I'm using a record. And also ignore that I'm using a Set instead of a Map, I will change that):

```<code>module MyTest where

import           Data.IORef
import           Data.Set
import           Data.Foldable          (find)

type State = (Set String)
type IORefState = IORef State

saveStringToState :: IO IORefState -> String -> IO String
saveStringToState stateIO string = do
  state <- stateIO
  atomicModifyIORef
    state
    (\oldStrings ->
       let updatedStrings = insert string oldStrings
       in (updatedStrings, updatedStrings))
  stringsState <- readIORef state :: IO State
  putStrLn ("### saved: " ++ show stringsState)
  return string

findStringInState :: IO IORefState -> String -> IO (Maybe String)
findStringInState stateIO soughtString = do
  state <- stateIO :: IO IORefState
  strings <- readIORef state :: IO State
  putStrLn ("Looking for " ++ soughtString ++ " in: " ++ show strings)
  return $ find (== soughtString) strings

doStuff =
  let stateIO = newIORef empty
  in do saveStringToState stateIO "string1"
        findStringInState stateIO "string1"
</code>```

What I want to achieve is to share the state (Set) between the two function calls so that findStringInState can return the String that I just inserted into the Set. But when I run the doStuff function I get this:

```<code>*MyTest> doStuff
### saved: fromList ["string1"]
Looking for string1 in: fromList []
Nothing
</code>```

I've probably misunderstood something since I thought the IORef should indeed be the container for my state.

Why is this not working?

What can I do to make it work?

答:
Seems that you confused IO IORefState with IORefState (without IO), more generally, IO a with a.

In your case, the value of IO IORefState is the action newIORef empty, which represents "an action that creates a fresh new IORef from scratch".

By contrast, IORefState (without IO) is the right, raw object that you should share among the functions that use it (saveStringToState, and findStringInState).

Then, both saveStringToState and findStringInState separately call newIORef empty, i.e. each of them create a different IORefState object, which cannot be affected by the other.

To fix, you must call newIORef empty (as an IO action using <-) in doStuff function and share the IORefState created by newIORef empty instead of IO IORefState:

```<code>  saveStringToState :: IORefState -> String -> IO String
  ...

  findStringInState :: IORefState -> String -> IO (Maybe String)
  ...

  let stateIO = newIORef empty
  in do ioRef <- stateIO
        saveStringToState ioRef "string1"
        findStringInState ioRef "string1"
  -- Or, more simply:
  do ioRef <- newIORef empty
     saveStringToState ioRef "string1"
     findStringInState ioRef "string1"
</code>```

In my opinion, the difference between IO a with a is similar to the difference between "a function object that returns a value typed as a (with some side effects)" and "just a raw value typed as a" in the other programming languages.

Body:
I'm trying to learn Haskell and I'm playing around with IORef to which I try to save and find records. My code looks something like this (note that I've chosen "String" as IORef type in this example only for convienence and briefty, in my actual code I'm using a record. And also ignore that I'm using a Set instead of a Map, I will change that):

module MyTest where

import           Data.IORef
import           Data.Set
import           Data.Foldable          (find)

type State = (Set String)
type IORefState = IORef State

saveStringToState :: IO IORefState -> String -> IO String
saveStringToState stateIO string = do
  state <- stateIO
  atomicModifyIORef
    state
    (\oldStrings ->
       let updatedStrings = insert string oldStrings
       in (updatedStrings, updatedStrings))
  stringsState <- readIORef state :: IO State
  putStrLn ("### saved: " ++ show stringsState)
  return string

findStringInState :: IO IORefState -> String -> IO (Maybe String)
findStringInState stateIO soughtString = do
  state <- stateIO :: IO IORefState
  strings <- readIORef state :: IO State
  putStrLn ("Looking for " ++ soughtString ++ " in: " ++ show strings)
  return $ find (== soughtString) strings

doStuff =
  let stateIO = newIORef empty
  in do saveStringToState stateIO "string1"
        findStringInState stateIO "string1"

What I want to achieve is to share the state (Set) between the two function calls so that findStringInState can return the String that I just inserted into the Set. But when I run the doStuff function I get this:

*MyTest> doStuff
### saved: fromList ["string1"]
Looking for string1 in: fromList []
Nothing

I've probably misunderstood something since I thought the IORef should indeed be the container for my state.

Why is this not working?

What can I do to make it work?

Body:
Seems that you confused IO IORefState with IORefState (without IO), more generally, IO a with a.

In your case, the value of IO IORefState is the action newIORef empty, which represents "an action that creates a fresh new IORef from scratch".

By contrast, IORefState (without IO) is the right, raw object that you should share among the functions that use it (saveStringToState, and findStringInState).

Then, both saveStringToState and findStringInState separately call newIORef empty, i.e. each of them create a different IORefState object, which cannot be affected by the other.

To fix, you must call newIORef empty (as an IO action using <-) in doStuff function and share the IORefState created by newIORef empty instead of IO IORefState:

  saveStringToState :: IORefState -> String -> IO String
  ...

  findStringInState :: IORefState -> String -> IO (Maybe String)
  ...

  let stateIO = newIORef empty
  in do ioRef <- stateIO
        saveStringToState ioRef "string1"
        findStringInState ioRef "string1"
  -- Or, more simply:
  do ioRef <- newIORef empty
     saveStringToState ioRef "string1"
     findStringInState ioRef "string1"

In my opinion, the difference between IO a with a is similar to the difference between "a function object that returns a value typed as a (with some side effects)" and "just a raw value typed as a" in the other programming languages.


问:
Why always include "v-else" template block?
I have two templates on components and one flag.

```<code><template v-if="mainPage">
    <div class="col-md-12">
        <h1>1 page</h1>
    </div>
</template>
<template v-else>
    <div class="col-md-12">
        <h1>2 page</h1>
    </div>
</template>
export default {
    data () {
        return {
            text : '',
            mainPage: true,
        }
    },
</code>```

but default include second template. why?

答:
First of all, when creating a vuejs you are only allowed one root element per component, so without the v-else part your component wouldnt work, unless you change template to div, and create one parent template:

If you don't want to use v-if you can just use v-show as:

```<code><template v-show="mainPage">
    <div class="col-md-12">
        <h1>1 page</h1>
    </div>
</template>
<template>
    <div class="col-md-12">
        <h1>2 page</h1>
    </div>
</template>
</code>```

This will not work for templates though. Because you can not have two templates in vuejs components

Body:
I have two templates on components and one flag.

<template v-if="mainPage">

1 page

</template>
<template v-else>

2 page

</template>
export default {
    data () {
        return {
            text : '',
            mainPage: true,
        }
    },

but default include second template. why?

Body:
First of all, when creating a vuejs you are only allowed one root element per component, so without the v-else part your component wouldnt work, unless you change template to div, and create one parent template:

If you don't want to use v-if you can just use v-show as:

<template v-show="mainPage">
    <div class="col-md-12">
        <h1>1 page</h1>
    </div>
</template>
<template>
    <div class="col-md-12">
        <h1>2 page</h1>
    </div>
</template>

This will not work for templates though. Because you can not have two templates in vuejs components


问:
Get/examine headers of some website in console

So, I want to send a GET request from my FFQuantum console and examine the response (the header) that I receive as response. I just want to check the fields, nothing more.

Now, when I run this script on this website (https://stackoverflow.com/), with this code:

```<code>var req = new XMLHttpRequest();
var web_adress = 'https://stackoverflow.com/';
req.open('GET', web_adress, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
</code>```

I get the header just right, but when I'm for example, on Google, then I get the error:

For results, I expect to see filled popup but I get the empty one. That is for when I'm on Google and trying to fetch the Stack's header.

What am I getting?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at https://stackoverflow.com/. (Reason: CORS
  header ‘Access-Control-Allow-Origin’ missing).

Is there a way to get the headers from StackOverflow when I'm on Googles pages?

答:
No, you can't. Is is because of security. Browser don't allow you to send requests across domains! To allow this action stackoverflow must return something like this:

```<code>Access-Control-Allow-Origin: https://google.com
</code>```

But there isn't this header in response. If you want to do something like this - try to use special browsers which do not use The Same Origin Policy or some other soft.
Phantomjs for example or nodejs  (if you want to do it with JS) or curl request etc.

But probaby you can do something like this:

```<code>google.com => yourdomain.com => stackoverflow.com
</code>```

Here you use your host like a proxy (remember that you need to set Access-Control-Allow-Origin: *)

The problem is in browser security =)

Body:
So, I want to send a GET request from my FFQuantum console and examine the response (the header) that I receive as response. I just want to check the fields, nothing more.

Now, when I run this script on this website (https://stackoverflow.com/), with this code:

var req = new XMLHttpRequest();
var web_adress = 'https://stackoverflow.com/';
req.open('GET', web_adress, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

I get the header just right, but when I'm for example, on Google, then I get the error:

For results, I expect to see filled popup but I get the empty one. That is for when I'm on Google and trying to fetch the Stack's header.

What am I getting?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at https://stackoverflow.com/. (Reason: CORS
  header ‘Access-Control-Allow-Origin’ missing).

Is there a way to get the headers from StackOverflow when I'm on Googles pages?

Body:
No, you can't. Is is because of security. Browser don't allow you to send requests across domains! To allow this action stackoverflow must return something like this:

Access-Control-Allow-Origin: https://google.com

But there isn't this header in response. If you want to do something like this - try to use special browsers which do not use The Same Origin Policy or some other soft.
Phantomjs for example or nodejs  (if you want to do it with JS) or curl request etc.

But probaby you can do something like this:

google.com => yourdomain.com => stackoverflow.com

Here you use your host like a proxy (remember that you need to set Access-Control-Allow-Origin: *)

The problem is in browser security =)


问:
Charts.js - Need to remove the data value from the Tooltip
Need to remove the data value from the Tooltip (The number in ''Varde 7: 50', Im trying to remove the '50').  Trying a ton of ways but cant figure it out yet.  This is the code I currently have.  It includes ways to link out from the pie chart which I need.

1) Need to remove the data value from the tooltip description.  So just the label with no data value.
2) Need each segment of the pie chart to link out to an external URL.

FYI-For some reason the snippet runs fine on my site, but not in the editor?  See working version at the bottom of the page: http://soccer.virnative.com/soccer/player-development-model

Please help!
Original code came from:
chart.js - link to other page when click on specific section in chart

var canvasP = document.getElementById("pieChart");
var ctxP = canvasP.getContext('2d');
var myPieChart = new Chart(ctxP, {
   type: 'pie',
   data: {
      labels: ["Värde 1", "Värde 2", "Värde 3", "Värde 4", "Värde 5", "Värde 6", "Värde 7"],
      datasets: [{
         data: [1, 5, 10, 20, 50, 70, 50],
         backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
         hoverBackgroundColor: ["#B2EBF2", "#FFCCBC", "#4DD0E1", "#FF8A65", "#00BCD4", "#FF5722", "#0097A7"]
      }]
   },
   options: {
      legend: {
         display: true,
         position: "right"
      }
   }
});

canvasP.onclick = function(e) {
   var slice = myPieChart.getElementAtEvent(e);
   if (!slice.length) return; // return if not clicked on slice
   var label = slice[0]._model.label;
   switch (label) {
      // add case for each label/slice
      case 'Värde 5':
         alert('clicked on slice 5');
         window.open('www.example.com/foo');
         break;
      case 'Värde 6':
         alert('clicked on slice 6');
         window.open('www.example.com/bar');
         break;
      // add rests ...
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="pieChart" width="400" height="400"></canvas></code>```

答:
You can control the label of the tooltip with it's callback.

If you just want to display the text of the label add this to your options:

```<code>tooltips: {
    callbacks: {
        label: function(tooltipItems, data) {
            return data.labels[tooltipItems.index];
        }
    }
}
</code>```

By the way: Your snippet is not working because you didn't include chart.js. I've copied your snippet and added my change below:

var canvasP = document.getElementById("pieChart");
var ctxP = canvasP.getContext('2d');
var myPieChart = new Chart(ctxP, {
   type: 'pie',
   data: {
      labels: ["Värde 1", "Värde 2", "Värde 3", "Värde 4", "Värde 5", "Värde 6", "Värde 7"],
      datasets: [{
         data: [1, 5, 10, 20, 50, 70, 50],
         backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
         hoverBackgroundColor: ["#B2EBF2", "#FFCCBC", "#4DD0E1", "#FF8A65", "#00BCD4", "#FF5722", "#0097A7"]
      }]
   },
   options: {
      legend: {
         display: true,
         position: "right"
      },
      tooltips: {
        callbacks: {
          label: function(tooltipItems, data) {
            return data.labels[tooltipItems.index];
          }
        }
      }
   }
});

canvasP.onclick = function(e) {
   var slice = myPieChart.getElementAtEvent(e);
   if (!slice.length) return; // return if not clicked on slice
   var label = slice[0]._model.label;
   switch (label) {
      // add case for each label/slice
      case 'Värde 5':
         alert('clicked on slice 5');
         window.open('www.example.com/foo');
         break;
      case 'Värde 6':
         alert('clicked on slice 6');
         window.open('www.example.com/bar');
         break;
      // add rests ...
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="pieChart" width="400" height="400"></canvas></code>```

Body:
Need to remove the data value from the Tooltip (The number in ''Varde 7: 50', Im trying to remove the '50').  Trying a ton of ways but cant figure it out yet.  This is the code I currently have.  It includes ways to link out from the pie chart which I need.

1) Need to remove the data value from the tooltip description.  So just the label with no data value.
2) Need each segment of the pie chart to link out to an external URL.

FYI-For some reason the snippet runs fine on my site, but not in the editor?  See working version at the bottom of the page: http://soccer.virnative.com/soccer/player-development-model

Please help!
Original code came from:
chart.js - link to other page when click on specific section in chart

var canvasP = document.getElementById("pieChart");
var ctxP = canvasP.getContext('2d');
var myPieChart = new Chart(ctxP, {
   type: 'pie',
   data: {
      labels: ["Värde 1", "Värde 2", "Värde 3", "Värde 4", "Värde 5", "Värde 6", "Värde 7"],
      datasets: [{
         data: [1, 5, 10, 20, 50, 70, 50],
         backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
         hoverBackgroundColor: ["#B2EBF2", "#FFCCBC", "#4DD0E1", "#FF8A65", "#00BCD4", "#FF5722", "#0097A7"]
      }]
   },
   options: {
      legend: {
         display: true,
         position: "right"
      }
   }
});

canvasP.onclick = function(e) {
   var slice = myPieChart.getElementAtEvent(e);
   if (!slice.length) return; // return if not clicked on slice
   var label = slice[0]._model.label;
   switch (label) {
      // add case for each label/slice
      case 'Värde 5':
         alert('clicked on slice 5');
         window.open('www.example.com/foo');
         break;
      case 'Värde 6':
         alert('clicked on slice 6');
         window.open('www.example.com/bar');
         break;
      // add rests ...
   }
}

<canvas id="pieChart" width="400" height="400"></canvas>

Body:
You can control the label of the tooltip with it's callback.

If you just want to display the text of the label add this to your options:

tooltips: {
    callbacks: {
        label: function(tooltipItems, data) {
            return data.labels[tooltipItems.index];
        }
    }
}

By the way: Your snippet is not working because you didn't include chart.js. I've copied your snippet and added my change below:

var canvasP = document.getElementById("pieChart");
var ctxP = canvasP.getContext('2d');
var myPieChart = new Chart(ctxP, {
   type: 'pie',
   data: {
      labels: ["Värde 1", "Värde 2", "Värde 3", "Värde 4", "Värde 5", "Värde 6", "Värde 7"],
      datasets: [{
         data: [1, 5, 10, 20, 50, 70, 50],
         backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
         hoverBackgroundColor: ["#B2EBF2", "#FFCCBC", "#4DD0E1", "#FF8A65", "#00BCD4", "#FF5722", "#0097A7"]
      }]
   },
   options: {
      legend: {
         display: true,
         position: "right"
      },
      tooltips: {
        callbacks: {
          label: function(tooltipItems, data) {
            return data.labels[tooltipItems.index];
          }
        }
      }
   }
});

canvasP.onclick = function(e) {
   var slice = myPieChart.getElementAtEvent(e);
   if (!slice.length) return; // return if not clicked on slice
   var label = slice[0]._model.label;
   switch (label) {
      // add case for each label/slice
      case 'Värde 5':
         alert('clicked on slice 5');
         window.open('www.example.com/foo');
         break;
      case 'Värde 6':
         alert('clicked on slice 6');
         window.open('www.example.com/bar');
         break;
      // add rests ...
   }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="pieChart" width="400" height="400"></canvas>

ContentLicense: CC BY-SA 4.0


问:
Uniqe constrain on condition psql
I required to implement unique constrain on psql table
i have columns,

1) date
2) employee
3) client_id
4) start_time

trying to add two constrain like,
1) check unique rule for date, employee, start_time, client_id this will simply work with unique constrain

BUT SECOND CONSTRAIN Is for condition where we already create entry with date,employee,start_time and client_id is False

-> so if someone try to create same entry we require to check constrain like,
 does any entry already exist with fields "date, employee_id,start_time" AND client_id= False

in SIMPLE words

1) check if all 4 fields exist with unique constrain        > display warning record exist

2) check if record with 3 fields and client_id = null exist > display warning record exist assign client_id

if anybody have little hint
it would be helpful

答:
I think you need partial indexes. One will cover case when client_id is provided and other will deal with NULL client_id.</p>

```<code>create table uni(val1 int, val2 text, val3 date, client_id int);

create unique index record_exists on uni(val1, val2, val3, client_id)
 where client_id is not null;

create unique index record_exists_assign_client_id on uni(val1, val2, val3)
 where client_id is null;

insert into uni values (1, 'test', current_date, 43), (2, 'test2', current_date, null);
--OK

insert into uni values (1, 'test', current_date, 43);
--duplicate key value violates unique constraint "record_exists"

insert into uni values (1, 'test', current_date, null);
--OK

insert into uni values (2, 'test2', current_date, null);
--duplicate key value violates unique constraint "record_exists_assign_client_id"
</code>```

Title: Uniqe constrain on condition psql

Body:
I think you need partial indexes. One will cover case when client_id is provided and other will deal with NULL client_id.

create table uni(val1 int, val2 text, val3 date, client_id int);

create unique index record_exists on uni(val1, val2, val3, client_id)
 where client_id is not null;

create unique index record_exists_assign_client_id on uni(val1, val2, val3)
 where client_id is null;

insert into uni values (1, 'test', current_date, 43), (2, 'test2', current_date, null);
--OK

insert into uni values (1, 'test', current_date, 43);
--duplicate key value violates unique constraint "record_exists"

insert into uni values (1, 'test', current_date, null);
--OK

insert into uni values (2, 'test2', current_date, null);
--duplicate key value violates unique constraint "record_exists_assign_client_id"


问:
how to change row height in FullCalendar?
this is my controller

```<code>      $calendar = Calendar::addEvents($events)
      ->setOptions([ //set fullcalendar options
          'firstDay' => 1,
          'height' => '200px',
          'themeSystem' => 'bootstrap3',
          'columnHeader' => false,
          'aspectRatio' => 1

      ]);
</code>```

I change the height of container but cell size remains with a scrolling bar

i want to change my calendar like this

答:
Replacing height with contentHeight should help change the size.

You might need more than 200px because it takes into account the whole calendars height rather than just one row. So if it was set to 1000, each section row would have a height of 162 or 329 if it was set to 2000.

So you'll just need to change:

```<code>'height' => '200px',
</code>```

to

```<code>'contentHeight' => 1300,
</code>```

You don't need to include the px.

Body:
this is my controller

      $calendar = Calendar::addEvents($events)
      ->setOptions([ //set fullcalendar options
          'firstDay' => 1,
          'height' => '200px',
          'themeSystem' => 'bootstrap3',
          'columnHeader' => false,
          'aspectRatio' => 1

      ]);

I change the height of container but cell size remains with a scrolling bar

i want to change my calendar like this

Body:
Replacing height with contentHeight should help change the size.

You might need more than 200px because it takes into account the whole calendars height rather than just one row. So if it was set to 1000, each section row would have a height of 162 or 329 if it was set to 2000.

So you'll just need to change:

'height' => '200px',

to

'contentHeight' => 1300,

You don't need to include the px.


问:
While running the application through "IIS Express" is not working in VS2017 Professional
I have opened the solution in Visual studio 2017 professional, I have built the solution and then I start running it through by clicking "IIS Express" but in IE browser opened and closed suddenly and showing error in VS2017 Professional.

答: You coul'd try to clean hidden .vs folder in your project path. Run clean solution.</p>


问:
GET with query string with Fetch in React Native
I am making a request like this:

```<code>fetch("https://api.parse.com/1/users", {
  method: "GET",
  headers: headers,
  body: body
})
</code>```

How do I pass query string parameters? Do I simply add them to the URL? I couldn't find an example in the docs.

答:
The accepted answer works, but if you have more params than one it doesn't generalize. I suggest the following approach, which also handles array parameters:</p>
```<code>let route = 'http://test.url.com/offices/search';
if (method == 'GET' && params) {
  const query = Object.keys(params)
    .map((k) => {
      if (Array.isArray(params[k])) {
        return params[k]
          .map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)
          .join('&');
      }

      return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
    })
    .join('&');

  route += `?${query}`;
}
</code>```

Body:
I am making a request like this:

fetch("https://api.parse.com/1/users", {
  method: "GET",
  headers: headers,
  body: body
})

How do I pass query string parameters? Do I simply add them to the URL? I couldn't find an example in the docs.

Body:
The accepted answer works, but if you have more params than one it doesn't generalize. I suggest the following approach, which also handles array parameters:

let route = 'http://test.url.com/offices/search';
if (method == 'GET' && params) {
  const query = Object.keys(params)
    .map((k) => {
      if (Array.isArray(params[k])) {
        return params[k]
          .map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)
          .join('&');
      }

      return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
    })
    .join('&');

  route += `?${query}`;
}


问:
aws s3 command responds with 403 forbidden
Trying to install AWS CodeDeploy agent on my EC2 instance

```<code>aws s3 cp s3://aws-codedeploy-ap-southeast-2/latest/install . --region ap-southeast-2
fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden
</code>```

The IAM Role for the instance has Policy Document

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
</code>```

and Trust relationship

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "codedeploy.ap-southeast-2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
</code>```

答:
That command is not correct. cpis used to upload something to S3, to download a file you could use curl or wget:

```<code>curl -O https://aws-codedeploy-ap-southeast-2.s3.amazonaws.com/latest/install
</code>```

or

```<code>wget https://aws-codedeploy-ap-southeast-2.s3.amazonaws.com/latest/install
</code>```

Body:
Trying to install AWS CodeDeploy agent on my EC2 instance

aws s3 cp s3://aws-codedeploy-ap-southeast-2/latest/install . --region ap-southeast-2
fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden

The IAM Role for the instance has Policy Document

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

and Trust relationship

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "codedeploy.ap-southeast-2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Body:
That command is not correct. cpis used to upload something to S3, to download a file you could use curl or wget:

curl -O https://aws-codedeploy-ap-southeast-2.s3.amazonaws.com/latest/install

or

wget https://aws-codedeploy-ap-southeast-2.s3.amazonaws.com/latest/install


问:
Persistence unit missing dependencies migrating from JBoss EAP 6.4 to 7.0
I have an application that must run on both JBoss EAP 6.4 and 7.0. The application uses EJB entity beans which are no longer supported on JBoss EAP 7 so the entity beans are being migrated to use JPA entities as described in the JBoss migration guide. The application deploys and works fine on 6.4 but fails to deploy with "missing dependencies" error on 7.0. I've seen alot of issues where the missing dependency was the datasource but that doesn't seem to be the case here. The datasource isn't mentioned at all in the missing dependencies error. I can see in the logs the persistence.xml file is being parsed and the jndi bindings added for the session beans before the deployment fails.

I have an EAR file that contains multiple war and ejb jar files. The application I'm having an issue with consists of an ejbModule.jar which contains the persistence.xml file and entity classes, and a webModule.war file with taglib classes that reference the entity classes contained in ejbModule.jar.

The structure of the EAR file is outlined below:

MyEAR.ear

 - ejbJar.jar

 - webApp1.war

 - webApp2.war

 - ejbModule.jar (contains persistence.xml and entity classes)

 -- META-INF/persistence.xml

 - webModule.jar (taglib classes have dependency on entity classes from ejbModule.jar)

 - META-INF

persistence.xml: (replaced class names, datasource name, persistence-unit name)

```<code><persistence version="2.0" xmlns:per="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="myPU">
    <class>org.MyEntity1</class>
    <class>org.MyEntity2</class>
    <jta-data-source>java:/MyDataSource</jta-data-source>
    <properties>
        <property name="jboss.entity.manager.jndi.name" value="java:/myPU"/>
        <property name="jboss.entity.manager.factory.jndi.name" value="java:/myPU"/>
    </properties>
</persistence-unit>
</code>```

It's difficult to post the error message as it's got hundreds of lines of "missing dependencies" for class names and application names that I can't share and by the time I replace them all I don't feel it would be of much use. But there are entries like:

"jboss.naming.context.java.comp.MyEAR.ejbModule.MyEntity1.InAppClientContainer is missing [jboss.naming.context.java.comp.MyEAR.ejbModule.MyEntity1]",

However there also entries like:

"jboss.deployment.subunit.\"MyEAR.ear\".\"webApp1.war\".component.\"org.taglib.MyTagLibClass\".START is missing [jboss.persistenceunit.\"MyEAT.ear/ejbModule.jar#myPU\"]"

I can see from the DEBUG logging for org.jboss.as.jpa that JBoss looks to be adding dependencies on the persistence unit for all taglib classes in all war files in the ear. Only the webModule.war needs to use the persistence unit.

2017-12-07 15:37:13,808 DEBUG [org.jboss.as.jpa] (MSC service thread 1-2) Adding dependency on PU service service jboss.persistenceunit."MyEAR.ear#myPU" for component org.taglib.MyTagLibClass

When I move the persistence.xml file to the META-INF directory of the EAR the application deploys and works fine on JBoss EAP 7.0. However, this isn't an ideal solution as the EAR file is built dynamically and could contain custom applications that I have no control over.
I've tried various other structures to try and get this working but haven't found anything else that works.

Any ideas how to get this working on JBoss EAP 7.0?

答:
There are unnecessary entries in your persistence.xml

You just need this

```<code><persistence version="2.0" xmlns:per="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="myPU">
    <jta-data-source>java:/MyDataSource</jta-data-source>
</persistence-unit>
</code>```

Because the entities will be found automatically relative to persistence.xml

Please try this and if doesn't help please post as much of the server.log as you can.

Another idea could be to ask the RedHat support as you use EAP I assume that you have subscriptions containing support.

Body:
I have an application that must run on both JBoss EAP 6.4 and 7.0. The application uses EJB entity beans which are no longer supported on JBoss EAP 7 so the entity beans are being migrated to use JPA entities as described in the JBoss migration guide. The application deploys and works fine on 6.4 but fails to deploy with "missing dependencies" error on 7.0. I've seen alot of issues where the missing dependency was the datasource but that doesn't seem to be the case here. The datasource isn't mentioned at all in the missing dependencies error. I can see in the logs the persistence.xml file is being parsed and the jndi bindings added for the session beans before the deployment fails.

I have an EAR file that contains multiple war and ejb jar files. The application I'm having an issue with consists of an ejbModule.jar which contains the persistence.xml file and entity classes, and a webModule.war file with taglib classes that reference the entity classes contained in ejbModule.jar.

The structure of the EAR file is outlined below:

MyEAR.ear

 - ejbJar.jar

 - webApp1.war

 - webApp2.war

 - ejbModule.jar (contains persistence.xml and entity classes)

 -- META-INF/persistence.xml

 - webModule.jar (taglib classes have dependency on entity classes from ejbModule.jar)

 - META-INF

persistence.xml: (replaced class names, datasource name, persistence-unit name)

<persistence version="2.0" xmlns:per="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="myPU">
    <class>org.MyEntity1</class>
    <class>org.MyEntity2</class>
    <jta-data-source>java:/MyDataSource</jta-data-source>
    <properties>
        <property name="jboss.entity.manager.jndi.name" value="java:/myPU"/>
        <property name="jboss.entity.manager.factory.jndi.name" value="java:/myPU"/>
    </properties>
</persistence-unit>

It's difficult to post the error message as it's got hundreds of lines of "missing dependencies" for class names and application names that I can't share and by the time I replace them all I don't feel it would be of much use. But there are entries like:

"jboss.naming.context.java.comp.MyEAR.ejbModule.MyEntity1.InAppClientContainer is missing [jboss.naming.context.java.comp.MyEAR.ejbModule.MyEntity1]",

However there also entries like:

"jboss.deployment.subunit.\"MyEAR.ear\".\"webApp1.war\".component.\"org.taglib.MyTagLibClass\".START is missing [jboss.persistenceunit.\"MyEAT.ear/ejbModule.jar#myPU\"]"

I can see from the DEBUG logging for org.jboss.as.jpa that JBoss looks to be adding dependencies on the persistence unit for all taglib classes in all war files in the ear. Only the webModule.war needs to use the persistence unit.

2017-12-07 15:37:13,808 DEBUG [org.jboss.as.jpa] (MSC service thread 1-2) Adding dependency on PU service service jboss.persistenceunit."MyEAR.ear#myPU" for component org.taglib.MyTagLibClass

When I move the persistence.xml file to the META-INF directory of the EAR the application deploys and works fine on JBoss EAP 7.0. However, this isn't an ideal solution as the EAR file is built dynamically and could contain custom applications that I have no control over.
I've tried various other structures to try and get this working but haven't found anything else that works.

Any ideas how to get this working on JBoss EAP 7.0?

Body:
There are unnecessary entries in your persistence.xml

You just need this

<persistence version="2.0" xmlns:per="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="myPU">
    <jta-data-source>java:/MyDataSource</jta-data-source>
</persistence-unit>

Because the entities will be found automatically relative to persistence.xml

Please try this and if doesn't help please post as much of the server.log as you can.

Another idea could be to ask the RedHat support as you use EAP I assume that you have subscriptions containing support.


问:
Good source of Crawler / Spider IP addresses
Where could I find comprehensive list of Crawler or Spider IP address. I need IPs from google yahoo microsoft and other search engines that regularly crawl my sites.

I do not want to disable them so keep robots.txt file out of the answers. The list is for filter that is doing statistical reporting on activity on each page.

Please post links to good sources that could be used. Paid or free.

答:
You probably don't want to do this by IP address. Most crawlers send a unique user agent string when they crawl your site and it's much more likely you want to use that to identify them. I don't know where you can find a good list of those though

EDIT: Actually this page I found with google seems to both answer your question a bit, and also give the user agents (which is still more likely a better approach)


问:
Switching from VS debugger to WinDbg
Given I have started a live debugging session by clicking the Play button in Visual Studio (F5) in order to launch the executable.

Say that I find an interesting situation which cannot be analyzed in Visual Studio but I know how to analyze it in WinDbg.

How would I detach Visual Studio and attach with WinDbg so that WinDbg is now the debugger?

I have tried:

detaching VS, but that will of course continue running the application, which I don't want

attaching WinDbg. Only one debugger can be attached. I'm not looking for a non-invasive attach of WinDbg.

I'd not like to create a crash dump in VS and then analyze that in WinDbg. I would prefer continuing the live debug session.

freezing the threads (interestingly they show up as unfrozen in a non-invasive WinDbg), but they will be unfrozen when detaching VS

答:
Here's how it worked for me:

Attach a WinDbg instance in non-invasive mode (F6)

Detach Visual Studio

Attach a new WinDbg instance in invasive mode (F6)

It will break automatically

Detach the non-invasive WinDbg (.detach)

Likewise you can transfer control back to Visual Studio:

Attach a WinDbg instance in non-invasive mode (F6)

Detach the invasive WinDbg (.detach)

Attach Visual Studio

Break in Visual Studio (press Pause)

Detach the non-invasive WinDbg (.detach)

Title: Switching from VS debugger to WinDbg


问:
Is it possible to selectively ignore service exception in Hystrix?
I have client API jar which internally makes external calls and throws single generic Service exception in case of issues. I have written hystrix  wrapper over the API calls. There are cases like "user not found" returning exception. Though the call was successful and service responded with valid response, the hystrix is treating it as a failure. I know that we can ignore the exception in Hystrix; but it will whitelist the only exception thrown by service calls. Is there a way to selectively ignore exception thrown by the service calls based on message in exception or http status code or something?</p>

答:
If the external service throw different exceptions in different cases, then you can probably ignore those exceptions like this </p>

```<code> @HystrixCommand(ignoreExceptions = {SomeException.class})
</code>```

<p>But if you have to ignore exceptions bases on error message then the best way to tackle this is put a try catch around your external call. And in the catch block check if it is one of those exceptions which needs to be ignored. If so don't do anything. If not rethrow this exception. Something like this will do. More info about HystrixBadRequestException </p>

```<code>@HystrixCommand(fallbackMethod = "fallBackMethod", groupKey = "CircuitBreaker", commandKey = "somekey", threadPoolKey = "somekey",
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"),
            @HystrixProperty(name = "execution.timeout.enabled", value = "false"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1200000"),
        },
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "30"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "180000")
        })
    public void someMethod(....){
             try {
               // Call external service
             } catch(Exception e) {
               if(exception to be ignored)
                 throw new HystrixBadRequestException("Some message", e);
               else
                  throw e
             }
    }
</code>```

Body:
If the external service throw different exceptions in different cases, then you can probably ignore those exceptions like this

 @HystrixCommand(ignoreExceptions = {SomeException.class})

But if you have to ignore exceptions bases on error message then the best way to tackle this is put a try catch around your external call. And in the catch block check if it is one of those exceptions which needs to be ignored. If so don't do anything. If not rethrow this exception. Something like this will do. More info about HystrixBadRequestException

@HystrixCommand(fallbackMethod = "fallBackMethod", groupKey = "CircuitBreaker", commandKey = "somekey", threadPoolKey = "somekey",
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"),
            @HystrixProperty(name = "execution.timeout.enabled", value = "false"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1200000"),
        },
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "30"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "180000")
        })
    public void someMethod(....){
             try {
               // Call external service
             } catch(Exception e) {
               if(exception to be ignored)
                 throw new HystrixBadRequestException("Some message", e);
               else
                  throw e
             }
    }


问:
Bottom TabLayout leaving space at bottom
I am facing a problem. I have a custom layout for toolbar and in my activity xml, I am including this toolbar. The structure of my activity is:

Toolbar layout on top using include tag.

The ViewPager

TabLayout at bottom to get bottom tabs.

The problem I am facing is that on some devices, it is coming out perfect but in a few devices (tested on moto G series devices) the bottom tab is leaving space.

Please Refer the Images below:

In Normal Phones when it shows expected UI

In MOTO G series

The xml code is following

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#efeded"
android:weightSum="11"
android:orientation="vertical">

<include layout="@layout/custom_tool_bar" />

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="10" />

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/BottomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#fff"
    android:layout_weight="1"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    />

</LinearLayout>
</code>```

答:
I found the problem why is it happening. I have used a library -  ResideMenu in my Activity and it has a function to detect whether the device has hardware Back and Menu buttons or the digital ones.

```<code>@Override
protected boolean fitSystemWindows(Rect insets) {

    int bottomPadding = viewActivity.getPaddingBottom() + insets.bottom;
    boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
    boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);

    if (!hasBackKey || !hasHomeKey) {//there's a navigation bar
        bottomPadding += getNavigationBarHeight();
    }

    this.setPadding(viewActivity.getPaddingLeft() + insets.left,
            viewActivity.getPaddingTop() + insets.top,
            viewActivity.getPaddingRight() + insets.right,
            bottomPadding);
    insets.left = insets.top = insets.right = insets.bottom = 0;
    return true;
}
</code>```

This is not working properly. For some devices it works fine but for some devices it's not able to determine the buttons. So in some devices it is going up leaving a space for digital buttons.
Anyways, I could not find a solution for this, tried a few StackOverflow but it didn't work out, please post if anyone finds something.

Body:
I am facing a problem. I have a custom layout for toolbar and in my activity xml, I am including this toolbar. The structure of my activity is:

Toolbar layout on top using include tag.

The ViewPager

TabLayout at bottom to get bottom tabs.

The problem I am facing is that on some devices, it is coming out perfect but in a few devices (tested on moto G series devices) the bottom tab is leaving space.

Please Refer the Images below:

In Normal Phones when it shows expected UI

In MOTO G series

The xml code is following

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#efeded"
android:weightSum="11"
android:orientation="vertical">

<include layout="@layout/custom_tool_bar" />

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="10" />

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/BottomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#fff"
    android:layout_weight="1"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    />

</LinearLayout>

Body:
I found the problem why is it happening. I have used a library -  ResideMenu in my Activity and it has a function to detect whether the device has hardware Back and Menu buttons or the digital ones.

@Override
protected boolean fitSystemWindows(Rect insets) {

    int bottomPadding = viewActivity.getPaddingBottom() + insets.bottom;
    boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
    boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);

    if (!hasBackKey || !hasHomeKey) {//there's a navigation bar
        bottomPadding += getNavigationBarHeight();
    }

    this.setPadding(viewActivity.getPaddingLeft() + insets.left,
            viewActivity.getPaddingTop() + insets.top,
            viewActivity.getPaddingRight() + insets.right,
            bottomPadding);
    insets.left = insets.top = insets.right = insets.bottom = 0;
    return true;
}

This is not working properly. For some devices it works fine but for some devices it's not able to determine the buttons. So in some devices it is going up leaving a space for digital buttons.
Anyways, I could not find a solution for this, tried a few StackOverflow but it didn't work out, please post if anyone finds something.


问:
How to trigger SelectIndexChanged event to VListBox?
Somebody know the VListBox?
It is fast to load item to the listbox.

But I can't get the SelectIndexChanged Event be triggered by set SelectIndex.
Somebody know how to trigger that event by winapi or something else?
VlistBox source code is in the page above.

答:
does the event get fired when you click on the item with a mouse?

if so then it may be by design.  also if you are selecting it via code then a better way is not "how to manually trigger the event".  consider refactoring the event handling code into a new DoSelectionChanged() method and have the code that calls SelectIndex() call that.  in this way the "meaty" stuff that normally would be in an event callback can be used by other methods, not just the callback.

hope that helps


问:
How to determine which element triggered accordion collapsed event
I have an accordion that I fill dynamically using JQuery.
I would like to start a script specific to each element on trigger.
I figured easily out how to check for a collapse :

```<code><script>
  $('#accordion').on('show.bs.collapse', function () {
       alert($(this).text());
});
</script>
</code>```

However, in $(this), I have all the accordion and not only the element that collapsed. I can't check for a specific ID as I don't know it

答:
Don't use 'this' but rather use the 'event' parameter from the function like this:</p>

```<code><script>
    $('#accordion').on('show.bs.collapse', function (event) { // Note the 'event' parameter

        // event.target is the collapsed element
        alert(event.target);

        // You can use this element to get the id like this: $(event.target).attr('id')
    });
</script>
</code>```

Body:
I have an accordion that I fill dynamically using JQuery.
I would like to start a script specific to each element on trigger.
I figured easily out how to check for a collapse :

However, in $(this), I have all the accordion and not only the element that collapsed. I can't check for a specific ID as I don't know it

Body:
Don't use 'this' but rather use the 'event' parameter from the function like this:

<script>
    $('#accordion').on('show.bs.collapse', function (event) { // Note the 'event' parameter

        // event.target is the collapsed element
        alert(event.target);

        // You can use this element to get the id like this: $(event.target).attr('id')
    });
</script>


问:
How exactly do I get the pretty print in Tensorflow while printing variable type?
In the ipython I have been trying the following statement.

W1 = tf.Variable(tf.random_normal([3, 3, 1, 2], stddev=0.01))
```

<p>This Means, I m creating 2 filters of each size 3*3 with 1 channel.
When this W1 is printed, I am getting something like</p>

<pre class="lang-py prettyprint-override"><code>print W1
<tf.Variable 'Variable_4:0' shape=(3, 3, 1, 2) dtype=float32_ref>
</code>```

Is there any possibility of getting sort of pretty print that displays entire matrix?

答:
This line is a definition of the tensorflow variable, i.e. a node in computational graph:

W1 = tf.Variable(tf.random_normal([3, 3, 1, 2], stddev=0.01))
```

<p>You have provided the initial value, but you can't access it until the session is started and the initializer is run. Here's how you do all this:</p>

<pre class="lang-py prettyprint-override"><code>with tf.Session() as sess:
    sess.run(W1.initializer)
    print(W1.eval())  # another way: sess.run(W1)
</code>```

... which outputs something like:

[[[[-0.00224525  0.00417244]]
  [[ 0.00627046 -0.01300699]]
  [[ 0.01755865 -0.01225026]]]
 [[[-0.01875982  0.00103016]]
  [[-0.01131416 -0.00079146]]
  [[-0.00957317  0.00036654]]]
 [[[ 0.00464012  0.0016774 ]]
  [[-0.00546181 -0.00818472]]
  [[ 0.01199017  0.00849589]]]]
```

Body:
In the ipython I have been trying the following statement.

W1 = tf.Variable(tf.random_normal([3, 3, 1, 2], stddev=0.01))

This Means, I m creating 2 filters of each size 3*3 with 1 channel.
When this W1 is printed, I am getting something like

print W1
<tf.Variable 'Variable_4:0' shape=(3, 3, 1, 2) dtype=float32_ref>

Is there any possibility of getting sort of pretty print that displays entire matrix?

Body:
This line is a definition of the tensorflow variable, i.e. a node in computational graph:

W1 = tf.Variable(tf.random_normal([3, 3, 1, 2], stddev=0.01))

You have provided the initial value, but you can't access it until the session is started and the initializer is run. Here's how you do all this:

with tf.Session() as sess:
    sess.run(W1.initializer)
    print(W1.eval())  # another way: sess.run(W1)

... which outputs something like:

[[[[-0.00224525  0.00417244]]
  [[ 0.00627046 -0.01300699]]
  [[ 0.01755865 -0.01225026]]]
 [[[-0.01875982  0.00103016]]
  [[-0.01131416 -0.00079146]]
  [[-0.00957317  0.00036654]]]
 [[[ 0.00464012  0.0016774 ]]
  [[-0.00546181 -0.00818472]]
  [[ 0.01199017  0.00849589]]]]


问:
Zoom functionality using Qt
Current implementation, zooms towards the center of View so items present in the top left corner or the current mouse pointer is not visible when we Zoom it.

I want zoom functionality based on the current mouse pointer so items present on the current mouse pointer zoom towards the center of the view.

Code for Zoom base don center of view area

```<code>void csGuiView::wheelEvent(QWheelEvent *event)
{

    if ((event->modifiers()&Qt::ControlModifier) == Qt::ControlModifier
        && event->angleDelta().x() == 0)
    {
    QPoint  pos  = event->pos();
    QPointF posf = this->mapToScene(pos);

    double angle = event->angleDelta().y();

    double scalingFactor;

    if(angle > 0)
    {
        scalingFactor = 1 + ( angle / 360 * 0.1);
    }else if (angle < 0)
    {
        scalingFactor = 1 - ( -angle / 360 * 0.1);
    } else
    {
        scalingFactor = 1;
    }

    m_pvtData->m_scale = scalingFactor;

    this->scale(scalingFactor, scalingFactor);

    double w = this->viewport()->width();
    double h = this->viewport()->height();

    double wf = this->mapToScene(QPoint(w-1, 0)).x()
            - this->mapToScene(QPoint(0,0)).x();
    double hf = this->mapToScene(QPoint(0, h-1)).y()
            - this->mapToScene(QPoint(0,0)).y();

    double lf = posf.x() - pos.x() * wf / w;
    double tf = posf.y() - pos.y() * hf / h;

    /* try to set viewport properly */
    this->ensureVisible(lf, tf, wf, hf, 0, 0);

    QPointF newPos = this->mapToScene(pos);

    this->ensureVisible(QRectF(QPointF(lf, tf) - newPos + posf,
                               QSizeF(wf, hf)), 0, 0);

    }

    if ((event->modifiers()&Qt::ControlModifier) != Qt::ControlModifier) {
    QGraphicsView::wheelEvent(event);
    }

    event->accept();
}
</code>```

答:
To zoom always centered at mouse pointer – the position of mouse pointer just has to become the origin of scaling.

It sounds that simple but I struggled a bit to prepare a demonstration. (I'm not that good in linear algebra, sorry.) However, I finally got it running.

My sample code testQWidget-Zoom.cc:

```<code>#include <vector>
#include <QtWidgets>

// class for widget to demonstrate zooming
class Canvas: public QWidget {
  // types:
  private:
    struct Geo {
      QRectF rect; QColor color;
      Geo(const QRectF &rect, const QColor &color):
        rect(rect), color(color)
      { }
    };
  // variables:
  private:
    bool _initDone : 1; // flag: true ... sample geo created
    std::vector<Geo> _scene; // contents to render
    QMatrix _mat; // view matrix
  // methods:
  public:
    // constructor.
    Canvas(): QWidget(), _initDone(false) { }
    // destructor.
    virtual ~Canvas() = default;
    // disabled:
    Canvas(const Canvas&) = delete;
    Canvas& operator=(const Canvas&) = delete;
  private:
    // initializes sample geo
    void init()
    {
      if (_initDone) return;
      _initDone = true;
      // build scene (with NDC i.e. view x/y range: [-1, 1])
      _scene.emplace_back(Geo(QRectF(-1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u)));
      _scene.emplace_back(Geo(QRectF(-0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u)));
      // get initial scaling
      const int wView = width(), hView = height();
      _mat.scale(wView / 2, hView / 2);
      _mat.translate(1, 1);
    }
  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      init();
      // render
      QPainter qPainter(this);
#if 0 // This scales line width as well:
      qPainter.setMatrix(_mat);
      for (const Geo &geo : _scene) {
        qPainter.setPen(geo.color);
        qPainter.drawRect(geo.rect);
      }
#else // This transforms only coordinates:
      for (const Geo &geo : _scene) {
        qPainter.setPen(geo.color);
        QRectF rect(geo.rect.topLeft() * _mat, geo.rect.bottomRight() * _mat);
        qPainter.drawRect(rect);
      }
#endif // 0
    }
    virtual void wheelEvent(QWheelEvent *pQEvent) override
    {
      //qDebug() << "Wheel Event:"
      //qDebug() << "mouse pos:" << pQEvent->pos();
      // pos() -> virtual canvas
      bool matInvOK = false;
      QMatrix matInv = _mat.inverted(&matInvOK);
      if (!matInvOK) {
        qDebug() << "View matrix not invertible!";
        return;
      }
      QPointF posNDC
        = QPointF(pQEvent->pos().x(), pQEvent->pos().y()) * matInv;
      //qDebug() << "mouse pos (NDC):" << posNDC;
      float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
      //qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
      //qDebug() << "scale factor:" << delta;
      _mat.translate(posNDC.x(), posNDC.y()); // origin to spot
      _mat.scale(delta, delta); // scale
      _mat.translate(-posNDC.x(), -posNDC.y()); // spot to origin
      update();
      pQEvent->accept();
    }
};

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  Canvas canvas;
  canvas.resize(512, 512);
  canvas.show();
  // runtime loop
  return app.exec();
}
</code>```

and these three lines are the actual interesting ones (in Canvas::wheelEvent()):

```<code>      _mat.translate(posNDC.x(), posNDC.y()); // origin to spot
      _mat.scale(delta, delta); // scale
      _mat.translate(-posNDC.x(), -posNDC.y()); // spot to origin
</code>```

And this is how it looks:

The first image is a snapshot of the application just after starting it.

Then I pointed into the center of the red rectangle and turned the wheel slightly. The red rectangle grew around the mouse pointer as intended.

1st Update:

And, this is the updated version which uses screen coordinates directly (instead of converting everything to NDCs):

```<code>#include <vector>
#include <QtWidgets>

// class for widget to demonstrate zooming
class Canvas: public QWidget {
  // types:
  private:
    struct Geo {
      QRectF rect; QColor color;
      Geo(const QRectF &rect, const QColor &color):
        rect(rect), color(color)
      { }
    };
  // variables:
  private:
    bool _initDone : 1; // flag: true ... sample geo created
    std::vector<Geo> _scene; // contents to render
    QMatrix _mat; // view matrix
  // methods:
  public:
    // constructor.
    Canvas(): QWidget(), _initDone(false) { }
    // destructor.
    virtual ~Canvas() = default;
    // disabled:
    Canvas(const Canvas&) = delete;
    Canvas& operator=(const Canvas&) = delete;
  private:
    // initializes sample geo
    void init()
    {
      if (_initDone) return;
      _initDone = true;
      const int wView = width(), hView = height();
      // build scene (with NDC i.e. view x/y range: [-1, 1])
      _scene.emplace_back(Geo(QRectF(-1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u)));
      _scene.emplace_back(Geo(QRectF(-0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u)));
      // scale geometry to screen coordinates
      QMatrix mat;
      mat.scale(wView / 2, hView / 2);
      mat.translate(1, 1);
      for (Geo &geo : _scene) {
        geo.rect = QRectF(geo.rect.topLeft() * mat, geo.rect.bottomRight() * mat);
      }
    }
  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      init();
      // render
      QPainter qPainter(this);
      qPainter.setMatrix(_mat);
      for (const Geo &geo : _scene) {
        qPainter.setPen(geo.color);
        qPainter.drawRect(geo.rect);
      }
    }
    virtual void wheelEvent(QWheelEvent *pQEvent) override
    {
      //qDebug() << "Wheel Event:";
      //qDebug() << "mouse pos:" << pQEvent->pos();
      float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
      //qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
      //qDebug() << "scale factor:" << delta;
      _mat.translate(pQEvent->pos().x(), pQEvent->pos().y()); // origin to spot
      _mat.scale(delta, delta); // scale
      _mat.translate(-pQEvent->pos().x(), -pQEvent->pos().y()); // spot to origin
      update();
      pQEvent->accept();
    }
};

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  Canvas canvas;
  canvas.resize(256, 256);
  canvas.show();
  // runtime loop
  return app.exec();
}
</code>```

The relevant three lines didn't change much – the mouse coordinates are applied directly to transformation.

Btw. I changed the rendering – it now scales line width as well as I used

```<code>      qPainter.setMatrix(_mat);
</code>```

in Canvas::paintEvent() instead of transforming all points "manually".

The snapshot shows the application after I pointed into the center of the blue rectangle and turned the mouse wheel:

2nd Update:

The suggested matrix manipulation works in a QGraphicsView as well:

```<code>#include <QtWidgets>

// class for widget to demonstrate zooming
class Canvas: public QGraphicsView {
  // methods:
  public:
    // constructor.
    Canvas() = default;
    // destructor.
    virtual ~Canvas() = default;
    // disabled:
    Canvas(const Canvas&) = delete;
    Canvas& operator=(const Canvas&) = delete;

  protected:

    virtual void wheelEvent(QWheelEvent *pQEvent) override
    {
      //qDebug() << "Wheel Event:";
      // pos() -> virtual canvas
      QPointF pos = mapToScene(pQEvent->pos());
      //qDebug() << "mouse pos:" << pos;
      // scale from wheel angle
      float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
      //qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
      //qDebug() << "scale factor:" << delta;
      // modify transform matrix
      QTransform xform = transform();
      xform.translate(pos.x(), pos.y()); // origin to spot
      xform.scale(delta, delta); // scale
      xform.translate(-pos.x(), -pos.y()); // spot to origin
      setTransform(xform);
      //qDebug() << "transform:" << xform;
      // force update
      update();
      pQEvent->accept();
    }
};

QRectF toScr(QWidget *pQWidget, float x, float y, float w, float h)
{
  const int wView = pQWidget->width(), hView = pQWidget->height();
  const int s = wView < hView ? wView : hView;
  return QRectF(
    (0.5f * x + 0.5f) * s, (0.5f * y + 0.5f) * s,
    0.5f * w * s, 0.5f * h * s);
}

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  // setup GUI
  Canvas canvas;
  canvas.setTransformationAnchor(QGraphicsView::NoAnchor);
  canvas.resize(256, 256);
  canvas.show();
  // prepare scene
  QGraphicsScene qGScene;
  qGScene.addRect(toScr(canvas.viewport(), -1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u));
  qGScene.addRect(toScr(canvas.viewport(), -0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u));
  qGScene.addRect(toScr(canvas.viewport(), -0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u));
  qGScene.addRect(toScr(canvas.viewport(), -0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu));
  qGScene.addRect(toScr(canvas.viewport(), 0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu));
  qGScene.addRect(toScr(canvas.viewport(), 0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u));
  canvas.setScene(&qGScene);
  // runtime loop
  return app.exec();
}
</code>```

Using a QGraphicsView simplifies code as no rendering code is needed – it's already built-in.

As I have not (yet) much experience with QGraphicsView, another issue hit me quite hard: The QGraphicsView is able to fix the view position automati[cg]ally after a transformation has been applied. In my case, this was rather counter-productive as obviously my transformation and the QGraphicsView seemed to "pull" in opposite directions.

Hence, I've learnt my lesson of the day:  QGrapicsView::setTransformationAnchor(QGraphicsView::NoAnchor)
is necessary to switch off this (in my case not-intended) auto-centering.

The other detail I find worth to notice is QGraphicsView::mapToScene() which can be used to conveniently convert widget coordinates (e.g. mouse coordinates) to scene space.

Title: Zoom functionality using Qt

Body:
Current implementation, zooms towards the center of View so items present in the top left corner or the current mouse pointer is not visible when we Zoom it.

I want zoom functionality based on the current mouse pointer so items present on the current mouse pointer zoom towards the center of the view.

Code for Zoom base don center of view area

void csGuiView::wheelEvent(QWheelEvent *event)
{

    if ((event->modifiers()&Qt::ControlModifier) == Qt::ControlModifier
        && event->angleDelta().x() == 0)
    {
    QPoint  pos  = event->pos();
    QPointF posf = this->mapToScene(pos);

    double angle = event->angleDelta().y();

    double scalingFactor;

    if(angle > 0)
    {
        scalingFactor = 1 + ( angle / 360 * 0.1);
    }else if (angle < 0)
    {
        scalingFactor = 1 - ( -angle / 360 * 0.1);
    } else
    {
        scalingFactor = 1;
    }

    m_pvtData->m_scale = scalingFactor;

    this->scale(scalingFactor, scalingFactor);

    double w = this->viewport()->width();
    double h = this->viewport()->height();

    double wf = this->mapToScene(QPoint(w-1, 0)).x()
            - this->mapToScene(QPoint(0,0)).x();
    double hf = this->mapToScene(QPoint(0, h-1)).y()
            - this->mapToScene(QPoint(0,0)).y();

    double lf = posf.x() - pos.x() * wf / w;
    double tf = posf.y() - pos.y() * hf / h;

    /* try to set viewport properly */
    this->ensureVisible(lf, tf, wf, hf, 0, 0);

    QPointF newPos = this->mapToScene(pos);

    this->ensureVisible(QRectF(QPointF(lf, tf) - newPos + posf,
                               QSizeF(wf, hf)), 0, 0);

    }

    if ((event->modifiers()&Qt::ControlModifier) != Qt::ControlModifier) {
    QGraphicsView::wheelEvent(event);
    }

    event->accept();
}

Body:
To zoom always centered at mouse pointer – the position of mouse pointer just has to become the origin of scaling.

It sounds that simple but I struggled a bit to prepare a demonstration. (I'm not that good in linear algebra, sorry.) However, I finally got it running.

My sample code testQWidget-Zoom.cc:

#include <vector>
#include <QtWidgets>

// class for widget to demonstrate zooming
class Canvas: public QWidget {
  // types:
  private:
    struct Geo {
      QRectF rect; QColor color;
      Geo(const QRectF &rect, const QColor &color):
        rect(rect), color(color)
      { }
    };
  // variables:
  private:
    bool _initDone : 1; // flag: true ... sample geo created
    std::vector<Geo> _scene; // contents to render
    QMatrix _mat; // view matrix
  // methods:
  public:
    // constructor.
    Canvas(): QWidget(), _initDone(false) { }
    // destructor.
    virtual ~Canvas() = default;
    // disabled:
    Canvas(const Canvas&) = delete;
    Canvas& operator=(const Canvas&) = delete;
  private:
    // initializes sample geo
    void init()
    {
      if (_initDone) return;
      _initDone = true;
      // build scene (with NDC i.e. view x/y range: [-1, 1])
      _scene.emplace_back(Geo(QRectF(-1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u)));
      _scene.emplace_back(Geo(QRectF(-0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u)));
      // get initial scaling
      const int wView = width(), hView = height();
      _mat.scale(wView / 2, hView / 2);
      _mat.translate(1, 1);
    }
  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      init();
      // render
      QPainter qPainter(this);
#if 0 // This scales line width as well:
      qPainter.setMatrix(_mat);
      for (const Geo &geo : _scene) {
        qPainter.setPen(geo.color);
        qPainter.drawRect(geo.rect);
      }
#else // This transforms only coordinates:
      for (const Geo &geo : _scene) {
        qPainter.setPen(geo.color);
        QRectF rect(geo.rect.topLeft() * _mat, geo.rect.bottomRight() * _mat);
        qPainter.drawRect(rect);
      }
#endif // 0
    }
    virtual void wheelEvent(QWheelEvent *pQEvent) override
    {
      //qDebug() << "Wheel Event:"
      //qDebug() << "mouse pos:" << pQEvent->pos();
      // pos() -> virtual canvas
      bool matInvOK = false;
      QMatrix matInv = _mat.inverted(&matInvOK);
      if (!matInvOK) {
        qDebug() << "View matrix not invertible!";
        return;
      }
      QPointF posNDC
        = QPointF(pQEvent->pos().x(), pQEvent->pos().y()) * matInv;
      //qDebug() << "mouse pos (NDC):" << posNDC;
      float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
      //qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
      //qDebug() << "scale factor:" << delta;
      _mat.translate(posNDC.x(), posNDC.y()); // origin to spot
      _mat.scale(delta, delta); // scale
      _mat.translate(-posNDC.x(), -posNDC.y()); // spot to origin
      update();
      pQEvent->accept();
    }
};

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  Canvas canvas;
  canvas.resize(512, 512);
  canvas.show();
  // runtime loop
  return app.exec();
}

and these three lines are the actual interesting ones (in Canvas::wheelEvent()):

      _mat.translate(posNDC.x(), posNDC.y()); // origin to spot
      _mat.scale(delta, delta); // scale
      _mat.translate(-posNDC.x(), -posNDC.y()); // spot to origin

And this is how it looks:

The first image is a snapshot of the application just after starting it.

Then I pointed into the center of the red rectangle and turned the wheel slightly. The red rectangle grew around the mouse pointer as intended.

1st Update:

And, this is the updated version which uses screen coordinates directly (instead of converting everything to NDCs):

#include <vector>
#include <QtWidgets>

// class for widget to demonstrate zooming
class Canvas: public QWidget {
  // types:
  private:
    struct Geo {
      QRectF rect; QColor color;
      Geo(const QRectF &rect, const QColor &color):
        rect(rect), color(color)
      { }
    };
  // variables:
  private:
    bool _initDone : 1; // flag: true ... sample geo created
    std::vector<Geo> _scene; // contents to render
    QMatrix _mat; // view matrix
  // methods:
  public:
    // constructor.
    Canvas(): QWidget(), _initDone(false) { }
    // destructor.
    virtual ~Canvas() = default;
    // disabled:
    Canvas(const Canvas&) = delete;
    Canvas& operator=(const Canvas&) = delete;
  private:
    // initializes sample geo
    void init()
    {
      if (_initDone) return;
      _initDone = true;
      const int wView = width(), hView = height();
      // build scene (with NDC i.e. view x/y range: [-1, 1])
      _scene.emplace_back(Geo(QRectF(-1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u)));
      _scene.emplace_back(Geo(QRectF(-0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u)));
      _scene.emplace_back(Geo(QRectF(-0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu)));
      _scene.emplace_back(Geo(QRectF(0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u)));
      // scale geometry to screen coordinates
      QMatrix mat;
      mat.scale(wView / 2, hView / 2);
      mat.translate(1, 1);
      for (Geo &geo : _scene) {
        geo.rect = QRectF(geo.rect.topLeft() * mat, geo.rect.bottomRight() * mat);
      }
    }
  protected:
    virtual void paintEvent(QPaintEvent *pQEvent) override
    {
      init();
      // render
      QPainter qPainter(this);
      qPainter.setMatrix(_mat);
      for (const Geo &geo : _scene) {
        qPainter.setPen(geo.color);
        qPainter.drawRect(geo.rect);
      }
    }
    virtual void wheelEvent(QWheelEvent *pQEvent) override
    {
      //qDebug() << "Wheel Event:";
      //qDebug() << "mouse pos:" << pQEvent->pos();
      float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
      //qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
      //qDebug() << "scale factor:" << delta;
      _mat.translate(pQEvent->pos().x(), pQEvent->pos().y()); // origin to spot
      _mat.scale(delta, delta); // scale
      _mat.translate(-pQEvent->pos().x(), -pQEvent->pos().y()); // spot to origin
      update();
      pQEvent->accept();
    }
};

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  Canvas canvas;
  canvas.resize(256, 256);
  canvas.show();
  // runtime loop
  return app.exec();
}

The relevant three lines didn't change much – the mouse coordinates are applied directly to transformation.

Btw. I changed the rendering – it now scales line width as well as I used

      qPainter.setMatrix(_mat);

in Canvas::paintEvent() instead of transforming all points "manually".

The snapshot shows the application after I pointed into the center of the blue rectangle and turned the mouse wheel:

2nd Update:

The suggested matrix manipulation works in a QGraphicsView as well:

#include <QtWidgets>

// class for widget to demonstrate zooming
class Canvas: public QGraphicsView {
  // methods:
  public:
    // constructor.
    Canvas() = default;
    // destructor.
    virtual ~Canvas() = default;
    // disabled:
    Canvas(const Canvas&) = delete;
    Canvas& operator=(const Canvas&) = delete;

  protected:

    virtual void wheelEvent(QWheelEvent *pQEvent) override
    {
      //qDebug() << "Wheel Event:";
      // pos() -> virtual canvas
      QPointF pos = mapToScene(pQEvent->pos());
      //qDebug() << "mouse pos:" << pos;
      // scale from wheel angle
      float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
      //qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
      //qDebug() << "scale factor:" << delta;
      // modify transform matrix
      QTransform xform = transform();
      xform.translate(pos.x(), pos.y()); // origin to spot
      xform.scale(delta, delta); // scale
      xform.translate(-pos.x(), -pos.y()); // spot to origin
      setTransform(xform);
      //qDebug() << "transform:" << xform;
      // force update
      update();
      pQEvent->accept();
    }
};

QRectF toScr(QWidget *pQWidget, float x, float y, float w, float h)
{
  const int wView = pQWidget->width(), hView = pQWidget->height();
  const int s = wView < hView ? wView : hView;
  return QRectF(
    (0.5f * x + 0.5f) * s, (0.5f * y + 0.5f) * s,
    0.5f * w * s, 0.5f * h * s);
}

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  // setup GUI
  Canvas canvas;
  canvas.setTransformationAnchor(QGraphicsView::NoAnchor);
  canvas.resize(256, 256);
  canvas.show();
  // prepare scene
  QGraphicsScene qGScene;
  qGScene.addRect(toScr(canvas.viewport(), -1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u));
  qGScene.addRect(toScr(canvas.viewport(), -0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u));
  qGScene.addRect(toScr(canvas.viewport(), -0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u));
  qGScene.addRect(toScr(canvas.viewport(), -0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu));
  qGScene.addRect(toScr(canvas.viewport(), 0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu));
  qGScene.addRect(toScr(canvas.viewport(), 0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u));
  canvas.setScene(&qGScene);
  // runtime loop
  return app.exec();
}

Using a QGraphicsView simplifies code as no rendering code is needed – it's already built-in.

As I have not (yet) much experience with QGraphicsView, another issue hit me quite hard: The QGraphicsView is able to fix the view position automati[cg]ally after a transformation has been applied. In my case, this was rather counter-productive as obviously my transformation and the QGraphicsView seemed to "pull" in opposite directions.

Hence, I've learnt my lesson of the day:  QGrapicsView::setTransformationAnchor(QGraphicsView::NoAnchor)
is necessary to switch off this (in my case not-intended) auto-centering.

The other detail I find worth to notice is QGraphicsView::mapToScene() which can be used to conveniently convert widget coordinates (e.g. mouse coordinates) to scene space.


问:
Jasper exception occurring while trying to include a jsp page with dynamic URL
Please look at the following code snippet and let me know what's wrong with that as I'm getting the below errors when trying to run it.

```<code>org.apache.jasper.JasperException: The jsp:param action must not be used outside the jsp:include, jsp:forward, or jsp:params elements

org.apache.jasper.JasperException: Expecting "jsp:param" standard action with "name" and "value" attributes
</code>```

Here's the code I'm trying to execute

```<code><%
    String contextRoot = request.getContextPath();
    String stdInfoViewURL = contextRoot.concat("jsp/student/ViewStudentDetails.jsp"):
%>

<html><body>

<jsp:include page="<%=stdInfoViewURL%>" flush="true">

    <jsp:param name="studentId" value="ABC123" />
    <jsp:param name="studentName" value="MARK TAYLOR" />

</jsp:include>

</body></html>
</code>```

I tried even declaring the java objects in following manner too. But no luck.

```<code><%!
    String contextRoot = request.getContextPath();
    String stdInfoViewURL = contextRoot.concat("jsp/student/ViewStudentDetails.jsp"):
%>
</code>```

答:
Omit the contextRoot from your stdInfoViewURL and just do

String stdInfoViewURL = "/jsp/student/ViewStudentDetails.jsp":

Body:
Please look at the following code snippet and let me know what's wrong with that as I'm getting the below errors when trying to run it.

org.apache.jasper.JasperException: The jsp:param action must not be used outside the jsp:include, jsp:forward, or jsp:params elements

org.apache.jasper.JasperException: Expecting "jsp:param" standard action with "name" and "value" attributes

Here's the code I'm trying to execute

<%
    String contextRoot = request.getContextPath();
    String stdInfoViewURL = contextRoot.concat("jsp/student/ViewStudentDetails.jsp"):
%>

<jsp:include page="<%=stdInfoViewURL%>" flush="true">

    <jsp:param name="studentId" value="ABC123" />
    <jsp:param name="studentName" value="MARK TAYLOR" />

</jsp:include>

I tried even declaring the java objects in following manner too. But no luck.

<%!
    String contextRoot = request.getContextPath();
    String stdInfoViewURL = contextRoot.concat("jsp/student/ViewStudentDetails.jsp"):
%>


问:
Save a file interactively?
Using tk_choose.files or file.choose I am able to select a file interactively. Is there an analogous function wherein I can allow a user to interactively decide where to save the output of a write.table?

答:
@Chase - this works in OS X (Eclipse and StatET). At least, I tried writing a data.frame (df) as a CSV file:</p>

```<code>write.csv(x = df, file = file.choose())
</code>```

Title: Save a file interactively?

Body:
@Chase - this works in OS X (Eclipse and StatET). At least, I tried writing a data.frame (df) as a CSV file:

write.csv(x = df, file = file.choose())


问:
java program is not able to read a string
```<code>import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}
</code>```

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

答:
Replace this lines as</p>

```<code>double d1 = Double.parseDouble(scan.nextLine());
</code>```

Body:
import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

Body:
Replace this lines as

double d1 = Double.parseDouble(scan.nextLine());


答:
Pass the Event Object thru the callback and use e.target instead of this. I replaced the alarm() with console.log() so look at the left hand corner and you'll see each .collapse report its #id on show.bs.collapse event.

Demo

$('.collapse').on('show.bs.collapse', function(e) {
  console.log(e.target.id);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapse::before {
  content: attr(id)
}

.collapse {
  font-size: 20px;
  background: rgba(0, 0, 0, .3);
  border: 3px ridge blue;
}

.as-console-wrapper {
  max-width: 30%;
  margin-left: 70%
}</code>```

<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet'>

COL0

COL1

COL2

```

Title: How to determine which element triggered accordion collapsed event

Body:
Pass the Event Object thru the callback and use e.target instead of this. I replaced the alarm() with console.log() so look at the left hand corner and you'll see each .collapse report its #id on show.bs.collapse event.

Demo

$('.collapse').on('show.bs.collapse', function(e) {
  console.log(e.target.id);
});

.collapse::before {
  content: attr(id)
}

.collapse {
  font-size: 20px;
  background: rgba(0, 0, 0, .3);
  border: 3px ridge blue;
}

.as-console-wrapper {
  max-width: 30%;
  margin-left: 70%
}

<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet'>

<div class='btn btn-primary' data-toggle="collapse" data-target="#col0">COL0</div>

<div class='btn btn-primary' data-toggle="collapse" data-target="#col1">COL1</div>

<div class='btn btn-primary' data-toggle="collapse" data-target="#col2">COL2</div>
<hr>
<div id='col0' class="collapse panel-collapse">
  <div class='panel-body'></div>
</div>

<div id='col1' class="collapse panel-collapse">
  <div class='panel-body'></div>
</div>

<div id='col2' class="collapse panel-collapse">
  <div class='panel-body'></div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>


问:
ActiveMQ-cpp Broker URI with PrefetchPolicy has no effect
I am using activemq-cpp 3.7.0 with VS 2010 to build a client, the server is ActiveMQ 5.8. I have created a message consumer using code similar to the following, based on the CMS configurations mentioned here. ConnClass is a ExceptionListener and a MessageListener. I only want to consume a single message before calling cms::Session::commit().

```<code>void ConnClass::setup()
{

    // Create a ConnectionFactory
    std::tr1::shared_ptr<ConnectionFactory> connectionFactory(
        ConnectionFactory::createCMSConnectionFactory(
            "tcp://localhost:61616?cms.PrefetchPolicy.queuePrefetch=1");

    // Create a Connection
    m_connection = std::tr1::shared_ptr<cms::Connection>(
        connectionFactory->createConnection());

    m_connection->start();
    m_connection->setExceptionListener(this);

    // Create a Session
    m_session = std::tr1::shared_ptr<cms::Session>(
        m_connection->createSession(Session::SESSION_TRANSACTED));

    // Create the destination (Queue)
    m_destination = std::tr1::shared_ptr<cms::Destination>(
        m_session->createQueue("myqueue?consumer.prefetchSize=1"));

    // Create a MessageConsumer from the Session to the Queue
    m_consumer = std::tr1::shared_ptr<cms::MessageConsumer>(
        m_session->createConsumer( m_destination.get() ));

    m_consumer->setMessageListener( this );

}

void ConnClass::onMessage( const Message* message )
{
    // read message code ...
    // schedule a processing event for
    // another thread that calls m_session->commit() when done
}
</code>```

The problem is I am receiving multiple messages instead of one message before calling m_session->commit() -- I know this because the commit() call is triggered by user input. How can I ensure onMessage() is only called once before each call to commit()?

答:
Yes, I find this too. However, when I use the Destination URI option ( "consumer.prefetchSize=15" , http://activemq.apache.org/cms/configuring.html#Configuring-DestinationURIParameters ) for the asynchronous consumer, It works well.

BTW, I just use the latest ActiveMQ-CPP v3.9.4 by Tim , and ActiveMQ v5.12.1 on CentOS 7.

Thanks!

Body:
I am using activemq-cpp 3.7.0 with VS 2010 to build a client, the server is ActiveMQ 5.8. I have created a message consumer using code similar to the following, based on the CMS configurations mentioned here. ConnClass is a ExceptionListener and a MessageListener. I only want to consume a single message before calling cms::Session::commit().

void ConnClass::setup()
{

    // Create a ConnectionFactory
    std::tr1::shared_ptr<ConnectionFactory> connectionFactory(
        ConnectionFactory::createCMSConnectionFactory(
            "tcp://localhost:61616?cms.PrefetchPolicy.queuePrefetch=1");

    // Create a Connection
    m_connection = std::tr1::shared_ptr<cms::Connection>(
        connectionFactory->createConnection());

    m_connection->start();
    m_connection->setExceptionListener(this);

    // Create a Session
    m_session = std::tr1::shared_ptr<cms::Session>(
        m_connection->createSession(Session::SESSION_TRANSACTED));

    // Create the destination (Queue)
    m_destination = std::tr1::shared_ptr<cms::Destination>(
        m_session->createQueue("myqueue?consumer.prefetchSize=1"));

    // Create a MessageConsumer from the Session to the Queue
    m_consumer = std::tr1::shared_ptr<cms::MessageConsumer>(
        m_session->createConsumer( m_destination.get() ));

    m_consumer->setMessageListener( this );

}

void ConnClass::onMessage( const Message* message )
{
    // read message code ...
    // schedule a processing event for
    // another thread that calls m_session->commit() when done
}

The problem is I am receiving multiple messages instead of one message before calling m_session->commit() -- I know this because the commit() call is triggered by user input. How can I ensure onMessage() is only called once before each call to commit()?