问:
AngularJs: controller is called twice by using $routeProvider
Module routes:

```<code>var switchModule = angular.module('switchModule', []);

switchModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/build-content', {templateUrl: 'build-content.html', controller: BuildInfoController});
}]);
</code>```

Controller:

```<code>function BuildInfoController($http, $scope){
    alert("hello");
}
</code>```

Html:

```<code><html ng-app="switchModule">
...
<body>
    <ul>
        <li><a href="#build-content"/></a></li>
    </ul>
    <div class="ng-view"></div>
</body>
...
</code>```

Each time when i click the hyperlink '', the 'BuildInfoController' will be called twice. Am i missing something here?

答:
I had declaration of SomeController for each view partial in a single state.
That caused duplicate event firing.

```<code> .state('chat', {
            url: '/',
            views: {
                'content@': {
                    templateUrl: 'views/chat_wv1.html',
                    controller: 'ChatController'
                },
                'form@': {
                    templateUrl: 'views/chat_wv_placeholder.html',
                    controller: 'ViewController'
                },
                'sidePanel@': {
                     templateUrl: 'views/sidePanel_wv.html'
                     /* removing this part solved my issue*/
                     /*controller: 'ChatController'*/
                }

            }
        })
</code>```

Hope this helps some  one else.

Body:
Module routes:

var switchModule = angular.module('switchModule', []);

switchModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/build-content', {templateUrl: 'build-content.html', controller: BuildInfoController});
}]);

Controller:

function BuildInfoController($http, $scope){
    alert("hello");
}

Html:

...

...

Each time when i click the hyperlink '', the 'BuildInfoController' will be called twice. Am i missing something here?

Body:
I had declaration of SomeController for each view partial in a single state.
That caused duplicate event firing.

 .state('chat', {
            url: '/',
            views: {
                'content@': {
                    templateUrl: 'views/chat_wv1.html',
                    controller: 'ChatController'
                },
                'form@': {
                    templateUrl: 'views/chat_wv_placeholder.html',
                    controller: 'ViewController'
                },
                'sidePanel@': {
                     templateUrl: 'views/sidePanel_wv.html'
                     /* removing this part solved my issue*/
                     /*controller: 'ChatController'*/
                }

            }
        })

Hope this helps some  one else.


来源: stackexchange

问:
How to get selected item on Jcalendar
I load my jCalendar to Calendar then I used the day for the index but problem every month's days different so I can't select. When I click 21, I'm selecting 10.</p>

```<code>   Calendar cal = Calendar.getInstance();

   cal.setTime(jCalendar1.getDate());
   int day = cal.get(Calendar.DAY_OF_MONTH);

   JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
   Component compo[] = jpanel.getComponents();
   compo[day].setBackground(Color.red);
</code>```

答:
```<code>public class CalendarTest2 extends JFrame {
    private static final long serialVersionUID = 1L;

    public CalendarTest2() {
        Calendar cal = Calendar.getInstance();
        JCalendar jCalendar1 = new JCalendar();
        cal.setTime(jCalendar1.getDate());
        int dayToBeSelected = cal.get(Calendar.DAY_OF_MONTH);
        dayToBeSelected = 21;

        JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
        Component compo[] = jpanel.getComponents();
        for (Component comp : compo) {
            if (!(comp instanceof JButton))
                continue;

            JButton btn = (JButton) comp;
            if (btn.getText().equals(String.valueOf(dayToBeSelected)))
                comp.setBackground(Color.red);
        }
        add(jpanel);
    }

    public static void main(String[] args) {
        CalendarTest2 test = new CalendarTest2();
        test.setVisible(true);
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.setSize(800, 800);
    }
}
</code>```

Instead of accessing the 'button to be selected' through index,
try to access the button through the text(day number) written on it.
The reason is, calendar of a month is displayed using 49 buttons arranged in 7x7 fashion .
So for ex) index 0 will always point to 'Sunday' button.

ContentLicense: CC BY-SA 3.0

Title: How to get selected item on Jcalendar

Body:
I load my jCalendar to Calendar then I used the day for the index but problem every month's days different so I can't select. When I click 21, I'm selecting 10.

   Calendar cal = Calendar.getInstance();

   cal.setTime(jCalendar1.getDate());
   int day = cal.get(Calendar.DAY_OF_MONTH);

   JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
   Component compo[] = jpanel.getComponents();
   compo[day].setBackground(Color.red);

Body:
public class CalendarTest2 extends JFrame {
    private static final long serialVersionUID = 1L;

    public CalendarTest2() {
        Calendar cal = Calendar.getInstance();
        JCalendar jCalendar1 = new JCalendar();
        cal.setTime(jCalendar1.getDate());
        int dayToBeSelected = cal.get(Calendar.DAY_OF_MONTH);
        dayToBeSelected = 21;

        JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
        Component compo[] = jpanel.getComponents();
        for (Component comp : compo) {
            if (!(comp instanceof JButton))
                continue;

            JButton btn = (JButton) comp;
            if (btn.getText().equals(String.valueOf(dayToBeSelected)))
                comp.setBackground(Color.red);
        }
        add(jpanel);
    }

    public static void main(String[] args) {
        CalendarTest2 test = new CalendarTest2();
        test.setVisible(true);
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.setSize(800, 800);
    }
}

Instead of accessing the 'button to be selected' through index,
try to access the button through the text(day number) written on it.
The reason is, calendar of a month is displayed using 49 buttons arranged in 7x7 fashion .
So for ex) index 0 will always point to 'Sunday' button.


问:
codeigniter -> having trouble loading multiple libraries/classes
Ok, so in my base controller (page.php) I have the following code which works fine:

```<code>   $this->load->library('Siteclass');
   $mysite = new site_model();
</code>```

The siteclass library references a model named site_model and instantiates based on data received from that model. All is good.

Now I want to load another library so that I can instantiate another object as well. So I add this to page.php:

```<code> $this->load->library('Memberclass');
 $mysite = new member_model();
</code>```

But now I get the following error:

```<code> Message: Undefined property: Memberclass::$site_model
 Filename: libraries/Loader.php
 Line Number: 1035
</code>```

From what I can tell, it seems that the loader class, when being applied to the Memberclass, is somehow still referencing the site_model instead of the member_model. I've checked my code and I am definitely calling the correct files.

Here's what Siteclass.php looks like:

```<code> if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 class Siteclass extends Controller {
    function __construct() {
        parent::Controller();
        $this->load->model('Site_model');
        $data = $this->Site_model->load_site_data();
        // etc etc
</code>```

and here's what Memberclass.php looks like:

```<code>if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Memberclass extends Controller {
function __construct() {
        parent::Controller();
    $this->load->model('Member_model');
        $data = $this->Member_model->load_member_data();
        // etc etc
</code>```

Thanks in advance for any help!

Gary

答:
I think you're confused about how MVC works in CodeIgniter. Why are you using the loader class to create a controller? Why are you creating a stand-alone instance of your model outside of your controller class?

In CodeIgniter, your URLs represent paths to your controllers' methods. That means that your "base controller" should automatically be instantiated if you go to:

www.example.com/memberclass

Or perhaps more to the point, if you have a link like this:

www.example.com/page

You should have a file in your /application/controllers directory called page.php which looks like this:

```<code>if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Page extends Controller {
    function __construct() {
        parent::Controller();
        // etc etc
</code>```

Furthermore, unless you're loading data from your model to be used every single time you call this controller, you'll want to put your model calls inside a non-constructor method of this class. Something like:

```<code>class Page extends Controller {
    function __construct() {
        parent::Controller();
    }

    function index() {
        $this->load->model('Member_model');
        $data = $this->Member_model->load_member_data();
        $this->load->view('myview', array('data'=>$data));
    }
}
</code>```

So again...not entirely sure what context you're doing this all in, but it seems like you're not standing firmly within the framework. There's basically no reason you should be using the loader class to load controllers, and furthermore there's no reason you should be creating stand-alone instances of model classes using PHP's new keyword.

ContentLicense: CC BY-SA 2.5

Body:
Ok, so in my base controller (page.php) I have the following code which works fine:

   $this->load->library('Siteclass');
   $mysite = new site_model();

The siteclass library references a model named site_model and instantiates based on data received from that model. All is good.

Now I want to load another library so that I can instantiate another object as well. So I add this to page.php:

 $this->load->library('Memberclass');
 $mysite = new member_model();

But now I get the following error:

 Message: Undefined property: Memberclass::$site_model
 Filename: libraries/Loader.php
 Line Number: 1035

From what I can tell, it seems that the loader class, when being applied to the Memberclass, is somehow still referencing the site_model instead of the member_model. I've checked my code and I am definitely calling the correct files.

Here's what Siteclass.php looks like:

 if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 class Siteclass extends Controller {
    function __construct() {
        parent::Controller();
        $this->load->model('Site_model');
        $data = $this->Site_model->load_site_data();
        // etc etc

and here's what Memberclass.php looks like:

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Memberclass extends Controller {
function __construct() {
        parent::Controller();
    $this->load->model('Member_model');
        $data = $this->Member_model->load_member_data();
        // etc etc

Thanks in advance for any help!

Gary

Body:
I think you're confused about how MVC works in CodeIgniter. Why are you using the loader class to create a controller? Why are you creating a stand-alone instance of your model outside of your controller class?

In CodeIgniter, your URLs represent paths to your controllers' methods. That means that your "base controller" should automatically be instantiated if you go to:

www.example.com/memberclass

Or perhaps more to the point, if you have a link like this:

www.example.com/page

You should have a file in your /application/controllers directory called page.php which looks like this:

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Page extends Controller {
    function __construct() {
        parent::Controller();
        // etc etc

Furthermore, unless you're loading data from your model to be used every single time you call this controller, you'll want to put your model calls inside a non-constructor method of this class. Something like:

class Page extends Controller {
    function __construct() {
        parent::Controller();
    }

    function index() {
        $this->load->model('Member_model');
        $data = $this->Member_model->load_member_data();
        $this->load->view('myview', array('data'=>$data));
    }
}

So again...not entirely sure what context you're doing this all in, but it seems like you're not standing firmly within the framework. There's basically no reason you should be using the loader class to load controllers, and furthermore there's no reason you should be creating stand-alone instances of model classes using PHP's new keyword.


问:
jQuery UI Autocomplete - menu disappears on hover
I'm trying to use jQuery UI Autocomplete to bring up a list of names of people in a MySQL Database. The basic function is working - when you type in two or more letters a list of possible names is displayed - but when I hover the mouse over the list or press the down key to access the list, it disappears (2 screenshots below may help to explain this).

What this means is that the Autocomplete becomes pointless as I can't actually access the list! If anyone can help I'd be most appreciative! Screenshots and code are posted below.

Type in the first few characters and the menu appears

But hover the mouse or press the 'down' key and it disappears before a selection can be made

HTML:

```<code>  <div id="chooseaccount">
  Choose Account to Edit
  <div id="iechooseaccountlabel" class="labeldiv">
    <!--[if IE]>
     Enter Student Name
    <![endif]-->
   </div>

  <input type="text" class="inputs" id="editname" placeholder="Enter Student Name" />

  </div>
</code>```

jQuery:

```<code>$(document).ready(function(){

$("#editname").autocomplete({
 source: "names.php",
 minLength: 2,
});

});
</code>```

PHP:

```<code><?php

$mysqli = new mysqli('********', '********', '**********', '*********');
$text = $mysqli->real_escape_string($_GET['term']);

$query = "SELECT name FROM users WHERE name LIKE '%$text%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .=  ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;

?>
</code>```

答:
I had same problem and I did not use the jquery UI twice, my jquery UI was part of jquery DataTable.
My problem was solved with following code
Note: with this code we need to write code to close the UL when we do not click on UL

$(".gettingContactList").autocomplete({
     source:this.contactList,
     /*following focus function was written because when mouse
     was being hovered over the menu, the menu was disappearing*/
    focus:function(e,ui) {
      $(e.toElement).parents().show()
    }
})```

Body:
I'm trying to use jQuery UI Autocomplete to bring up a list of names of people in a MySQL Database. The basic function is working - when you type in two or more letters a list of possible names is displayed - but when I hover the mouse over the list or press the down key to access the list, it disappears (2 screenshots below may help to explain this).

What this means is that the Autocomplete becomes pointless as I can't actually access the list! If anyone can help I'd be most appreciative! Screenshots and code are posted below.

Type in the first few characters and the menu appears

But hover the mouse or press the 'down' key and it disappears before a selection can be made

HTML:

  Choose Account to Edit

  <input type="text" class="inputs" id="editname" placeholder="Enter Student Name" />

jQuery:

$(document).ready(function(){

$("#editname").autocomplete({
 source: "names.php",
 minLength: 2,
});

});

PHP:

<?php

$mysqli = new mysqli('********', '********', '**********', '*********');
$text = $mysqli->real_escape_string($_GET['term']);

$query = "SELECT name FROM users WHERE name LIKE '%$text%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .=  ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;

?>


问:
Numpy's float32 and float comparisons
Continuing from Difference between Python float and numpy float32:

```<code>import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)
</code>```

Prints:

```<code><class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True
</code>```

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

```<code>print(repr(float_32), repr(a))
# 58682.758 58682.7578125
</code>```

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

```<code>print(repr(float(float_32)))
</code>```

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

答:
The numbers compare equal because 58682.7578125 can be exactly represented in both 32 and 64 bit floating point. Let's take a close look at the binary representation:

```<code>32 bit:  01000111011001010011101011000010
sign    :  0
exponent:  10001110
fraction:  11001010011101011000010

64 bit:  0100000011101100101001110101100001000000000000000000000000000000
sign    :  0
exponent:  10000001110
fraction:  1100101001110101100001000000000000000000000000000000
</code>```

They have the same sign, the same exponent, and the same fraction - the extra bits in the 64 bit representation are filled with zeros.

No matter which way they are cast, they will compare equal. If you try a different number such as  58682.7578124 you will see that the representations differ at the binary level; 32 bit looses more precision and they won't compare equal.

(It's also easy to see in the binary representation that a float32 can be upcast to a float64 without any loss of information. That is what numpy is supposed to do before comparing both.)

```<code>import numpy as np

a = 58682.7578125
f32 = np.float32(a)
f64 = np.float64(a)

u32 = np.array(a, dtype=np.float32).view(dtype=np.uint32)
u64 = np.array(a, dtype=np.float64).view(dtype=np.uint64)

b32 = bin(u32)[2:]
b32 = '0' * (32-len(b32)) + b32  # add leading 0s
print('32 bit: ', b32)
print('sign    : ', b32[0])
print('exponent: ', b32[1:9])
print('fraction: ', b32[9:])
print()

b64 = bin(u64)[2:]
b64 = '0' * (64-len(b64)) + b64  # add leading 0s
print('64 bit: ', b64)
print('sign    : ', b64[0])
print('exponent: ', b64[1:12])
print('fraction: ', b64[12:])
</code>```

Title: Numpy's float32 and float comparisons

Body:
Continuing from Difference between Python float and numpy float32:

import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)

Prints:

<class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

print(repr(float_32), repr(a))
# 58682.758 58682.7578125

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

print(repr(float(float_32)))

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

Body:
The numbers compare equal because 58682.7578125 can be exactly represented in both 32 and 64 bit floating point. Let's take a close look at the binary representation:

32 bit:  01000111011001010011101011000010
sign    :  0
exponent:  10001110
fraction:  11001010011101011000010

64 bit:  0100000011101100101001110101100001000000000000000000000000000000
sign    :  0
exponent:  10000001110
fraction:  1100101001110101100001000000000000000000000000000000

They have the same sign, the same exponent, and the same fraction - the extra bits in the 64 bit representation are filled with zeros.

No matter which way they are cast, they will compare equal. If you try a different number such as  58682.7578124 you will see that the representations differ at the binary level; 32 bit looses more precision and they won't compare equal.

(It's also easy to see in the binary representation that a float32 can be upcast to a float64 without any loss of information. That is what numpy is supposed to do before comparing both.)

import numpy as np

a = 58682.7578125
f32 = np.float32(a)
f64 = np.float64(a)

u32 = np.array(a, dtype=np.float32).view(dtype=np.uint32)
u64 = np.array(a, dtype=np.float64).view(dtype=np.uint64)

b32 = bin(u32)[2:]
b32 = '0' * (32-len(b32)) + b32  # add leading 0s
print('32 bit: ', b32)
print('sign    : ', b32[0])
print('exponent: ', b32[1:9])
print('fraction: ', b32[9:])
print()

b64 = bin(u64)[2:]
b64 = '0' * (64-len(b64)) + b64  # add leading 0s
print('64 bit: ', b64)
print('sign    : ', b64[0])
print('exponent: ', b64[1:12])
print('fraction: ', b64[12:])


问:
How can I output javascript with "onclick" into a textfield?
I wrote a javascript program to generate random passwords. How can I output the result into a textfield (input tag)?

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var rs = randomString(16);
console.log(rs);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="passgen">
  <button type="button" id="pass-button" onclick="**???**">Generate Password</button>
  <br><br>
  <input type="text" name="output">
</section></code>```

答:
Give your input an ID, then:</p>

```<code>document.getElementById('yourInputID').value = rs;
</code>```

Body:
I wrote a javascript program to generate random passwords. How can I output the result into a textfield (input tag)?

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var rs = randomString(16);
console.log(rs);

  <button type="button" id="pass-button" onclick="**???**">Generate Password</button>

  <input type="text" name="output">

Body:
Give your input an ID, then:

document.getElementById('yourInputID').value = rs;


问:
Google Maps marker icon (symbol) not rotating
I posted a question yesterday which was resolved by a typographical correction, but now I have a problem which is baffling me.

I have a custom marker on a map, using a symbol as the icon so that I can rotate it. When I initialise it I set rotation to be 0, and at some point will call the updateMap() function which should give the marker a new rotation value. And it does, I'm able to see by printing the marker and its icon in the console that the rotation has changed, but the marker remains staunchly pointed north.

Here's my code for initialising and rotating the marker:

```<code>var map;
var marker;

function initMap(position) {
    var map_div = document.getElementById("map");
    map = new google.maps.Map(map_div, {
        zoom: 14,
        center: { lat: position.Latitude, lng: position.Longitude },
        mapTypeId: 'terrain'
    });
    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: "MY MARKER",
        icon: {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
            scale: 4,
            strokeColor: '#00F',
            rotation: 0,
        }
    });
}

function updateMap() {
    var bearing = 135;
    console.log(bearing);
    marker.icon.rotation = bearing;
    console.log(marker);
}
</code>```

The console tells me that the rotation of the marker has changed but the marker itself does not change direction.

Things I have tried:

Triggering a resize event at the end of the update map function

Not specifying an original rotation for the icon

Switching the rotations, so starting at 135 and trying to change to 0 (the value of the marker's rotation at marker.icon.rotation after calling updateMap() becomes 0 but the actual marker keeps pointing at 135)

Changing the rotation right at the end of the initMap() function - this does work, which leads me to believe that there's something not right about the updateMap() function. I can't figure out what though, it still executes the function. Logging the marker in the global scope also tells me that the rotation has changed.

Any ideas or suggestions are welcome.

答:
you can just change updateMap function to:

```<code>function updateMap() {
  var bearing = 135;
  console.log(marker.icon);
  marker.icon.rotation = bearing;
  marker.setMap(map);
  console.log(marker.icon);
}
</code>```

marker.setMap(map); re-adds to the map after the options are updated

JSFiddle : https://jsfiddle.net/q3wjrpdw/8/

Body:
I posted a question yesterday which was resolved by a typographical correction, but now I have a problem which is baffling me.

I have a custom marker on a map, using a symbol as the icon so that I can rotate it. When I initialise it I set rotation to be 0, and at some point will call the updateMap() function which should give the marker a new rotation value. And it does, I'm able to see by printing the marker and its icon in the console that the rotation has changed, but the marker remains staunchly pointed north.

Here's my code for initialising and rotating the marker:

var map;
var marker;

function initMap(position) {
    var map_div = document.getElementById("map");
    map = new google.maps.Map(map_div, {
        zoom: 14,
        center: { lat: position.Latitude, lng: position.Longitude },
        mapTypeId: 'terrain'
    });
    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: "MY MARKER",
        icon: {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
            scale: 4,
            strokeColor: '#00F',
            rotation: 0,
        }
    });
}

function updateMap() {
    var bearing = 135;
    console.log(bearing);
    marker.icon.rotation = bearing;
    console.log(marker);
}

The console tells me that the rotation of the marker has changed but the marker itself does not change direction.

Things I have tried:

Triggering a resize event at the end of the update map function

Not specifying an original rotation for the icon

Switching the rotations, so starting at 135 and trying to change to 0 (the value of the marker's rotation at marker.icon.rotation after calling updateMap() becomes 0 but the actual marker keeps pointing at 135)

Changing the rotation right at the end of the initMap() function - this does work, which leads me to believe that there's something not right about the updateMap() function. I can't figure out what though, it still executes the function. Logging the marker in the global scope also tells me that the rotation has changed.

Any ideas or suggestions are welcome.

Body:
you can just change updateMap function to:

function updateMap() {
  var bearing = 135;
  console.log(marker.icon);
  marker.icon.rotation = bearing;
  marker.setMap(map);
  console.log(marker.icon);
}

marker.setMap(map); re-adds to the map after the options are updated

JSFiddle : https://jsfiddle.net/q3wjrpdw/8/


问:
How to get started/use matplotlib in kivy
I have recently learned a bit of matplotlib and would like to use it within kivy. I have read a little documentation on the garden here and there but don't really understand it.
I have installed kivy garden and matplotlib but don't know how to proceed from here. I simply want to add a already completed matplotlib graph into kivy.
I would appreciate a step by step simplified set of instructions of how to get what I already coded into kivy and get it to display.
Thanks</p>

答:
Here is the simplest example possible for kivy-garden matplotlib and kivy. If you would like to do more advanced things, check out their examples: https://github.com/kivy-garden/garden.matplotlib/tree/master/examples
I think it should be enough to get you started with your plot.

Below I am adding it to a BoxLayout, you can add more widgets to this BoxLayout or add this BoxLayout somewhere else.

python code example.py:

```<code>from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import matplotlib.pyplot as plt

plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')

class MyApp(App):

    def build(self):
        box = BoxLayout()
        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        return box

MyApp().run()
</code>```

Body:
Here is the simplest example possible for kivy-garden matplotlib and kivy. If you would like to do more advanced things, check out their examples: https://github.com/kivy-garden/garden.matplotlib/tree/master/examples
I think it should be enough to get you started with your plot.

Below I am adding it to a BoxLayout, you can add more widgets to this BoxLayout or add this BoxLayout somewhere else.

python code example.py:

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import matplotlib.pyplot as plt

plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')

class MyApp(App):

    def build(self):
        box = BoxLayout()
        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        return box

MyApp().run()


问:
Two HTML headings - swap places in circles?
I have two headings/divs and I need to change places after 5 seconds in the way like on the picture. I tried some transitions and similar, but I have not find anywhere how to move elements in a circular way.

Moving of elements must be like "half circular". The example code is in the comments.

答:
Position the headings inside a container. Using CSS animation you can rotate the container, and rotate the headings in the other direction. The animation is infinite, so the delay is in the animation itself.

Due to the delay, we can't simply reverse the rotate animation, and we need to add the reverse rotateCounter animation.

.container {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto;
  animation: rotate 12s linear infinite;
}

.heading {
  position: absolute;
  animation: rotateCounter 12s linear infinite;
}

.heading1 {
  top: 0;
  left: 0;
}

.heading2 {
  right: 0;
  bottom: 0;
}

@keyframes rotate {
  8% { transform: rotate(-180deg); }
  50% { transform: rotate(-180deg); }
  58% { transform: rotate(-360deg); }
  100% { transform: rotate(-360deg); }
}

@keyframes rotateCounter {
  8% { transform: rotate(180deg); }
  50% { transform: rotate(180deg); }
  58% { transform: rotate(360deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h2 class="heading heading1">Heading 1</h2>
  <h2 class="heading heading2">Heading 2</h2>
</div></code>```

Body:
Position the headings inside a container. Using CSS animation you can rotate the container, and rotate the headings in the other direction. The animation is infinite, so the delay is in the animation itself.

Due to the delay, we can't simply reverse the rotate animation, and we need to add the reverse rotateCounter animation.

.container {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto;
  animation: rotate 12s linear infinite;
}

.heading {
  position: absolute;
  animation: rotateCounter 12s linear infinite;
}

.heading1 {
  top: 0;
  left: 0;
}

.heading2 {
  right: 0;
  bottom: 0;
}

@keyframes rotate {
  8% { transform: rotate(-180deg); }
  50% { transform: rotate(-180deg); }
  58% { transform: rotate(-360deg); }
  100% { transform: rotate(-360deg); }
}

@keyframes rotateCounter {
  8% { transform: rotate(180deg); }
  50% { transform: rotate(180deg); }
  58% { transform: rotate(360deg); }
  100% { transform: rotate(360deg); }
}

<div class="container">
  <h2 class="heading heading1">Heading 1</h2>
  <h2 class="heading heading2">Heading 2</h2>
</div>


问:
SQL Converting to HH:MM:SS with an equation - Not working Correctly
I am trying to minus the sum of one column from the sum of another column in seconds, and then convert it into HH:MM:SS. The conversion however requires it to be able to go over 24 hours as this is a sum time. My conversion works on single columns with no problem so it is clearly the equation i am trying to do it in but cant figure out how to do it.

The 2 columns are Dispo & Dead both are Ints.

Here is what i have:

```<code>CONVERT(varchar(6), SUM([Dispo])-SUM(Dead)/3600)
+ ':' + RIGHT('0' + CONVERT(varchar(2), (SUM([Dispo])-SUM(Dead)% 3600) / 60), 2)
+ ':' + RIGHT('0' + CONVERT(varchar(2), SUM([Dispo])-SUM(Dead) % 60), 2) AS [AfterCallWork],
</code>```

The Result it gives me is:

```<code>AfterCallWork
26809:0*:0*
</code>```

The Result i want for e.g. is:

```<code>AfterCallWork
35:51:09
</code>```

(The number in the e.g. wont necessarily be the result just an example of format)

Sample Data is:

```<code>UniqueID | Dead | Dispo
135151   | 20   | 200
161681   | 35   | 421
516168   | 10   | 308
</code>```

expected results for this sample is 0 hours, 14 minues and 24 seconds:

```<code>0:14:24
</code>```

Dead & Dispo are seconds in a given status or mode. Unique ID is essentially a call identifier.

答:
Here is one way to do it -

Create and populate sample table (Please save us this step in your future questions)

```<code>DECLARE @T AS TABLE
(
    UniqueID int,
    Dead int,
    Dispo int
)

INSERT INTO @T VALUES
(135151, 20, 200),
(161681, 35, 421),
(516168, 10, 308)
</code>```

Use a CTE to get the SUM([Dispo])-SUM(Dead) - This step is only to make the code more readable, you don't need to do it, but it helps:

```<code>;WITH CTE(NumberOfSeconds) AS
(
    SELECT SUM([Dispo])-SUM(Dead)
    FROM @T
)
</code>```

Convert the number of seconds you got from the CTE to a string representation of hh:mm:ss

```<code>SELECT  CAST(NumberOfSeconds /3600 as varchar(6)) + ':' +
        RIGHT('0' + CAST((NumberOfSeconds % 3600) / 60 as varchar(2)), 2) + ':' +
        RIGHT('0' + CAST(NumberOfSeconds % 60 as varchar(2)), 2) As AfterCallWork
FROM CTE
</code>```

Results:

```<code>AfterCallWork
0:14:24
</code>```

See a live demo on rextester.

Body:
I am trying to minus the sum of one column from the sum of another column in seconds, and then convert it into HH:MM:SS. The conversion however requires it to be able to go over 24 hours as this is a sum time. My conversion works on single columns with no problem so it is clearly the equation i am trying to do it in but cant figure out how to do it.

The 2 columns are Dispo & Dead both are Ints.

Here is what i have:

CONVERT(varchar(6), SUM([Dispo])-SUM(Dead)/3600)
+ ':' + RIGHT('0' + CONVERT(varchar(2), (SUM([Dispo])-SUM(Dead)% 3600) / 60), 2)
+ ':' + RIGHT('0' + CONVERT(varchar(2), SUM([Dispo])-SUM(Dead) % 60), 2) AS [AfterCallWork],

The Result it gives me is:

AfterCallWork
26809:0*:0*

The Result i want for e.g. is:

AfterCallWork
35:51:09

(The number in the e.g. wont necessarily be the result just an example of format)

Sample Data is:

UniqueID | Dead | Dispo
135151   | 20   | 200
161681   | 35   | 421
516168   | 10   | 308

expected results for this sample is 0 hours, 14 minues and 24 seconds:

0:14:24

Dead & Dispo are seconds in a given status or mode. Unique ID is essentially a call identifier.

Body:
Here is one way to do it -

Create and populate sample table (Please save us this step in your future questions)

DECLARE @T AS TABLE
(
    UniqueID int,
    Dead int,
    Dispo int
)

INSERT INTO @T VALUES
(135151, 20, 200),
(161681, 35, 421),
(516168, 10, 308)

Use a CTE to get the SUM([Dispo])-SUM(Dead) - This step is only to make the code more readable, you don't need to do it, but it helps:

;WITH CTE(NumberOfSeconds) AS
(
    SELECT SUM([Dispo])-SUM(Dead)
    FROM @T
)

Convert the number of seconds you got from the CTE to a string representation of hh:mm:ss

SELECT  CAST(NumberOfSeconds /3600 as varchar(6)) + ':' +
        RIGHT('0' + CAST((NumberOfSeconds % 3600) / 60 as varchar(2)), 2) + ':' +
        RIGHT('0' + CAST(NumberOfSeconds % 60 as varchar(2)), 2) As AfterCallWork
FROM CTE

Results:

AfterCallWork
0:14:24

See a live demo on rextester.


答:
They're equal. They're just not printing the same because they use different printing logic.

How can I get at the exact internal representation of float_32 and a in the example ?

Well, that depends on what you mean by "exact internal representation". You can get an array of bit values, if you really want one:

```<code>>>> b = numpy.float32(a)
>>> numpy.unpackbits(numpy.array([b]).view(numpy.uint8))
array([1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,
       1, 0, 1, 0, 0, 0, 1, 1, 1], dtype=uint8)
</code>```

which is as close as you'll get to the "exact internal representation", but it's not exactly the most useful thing to work with. (Also, the results will be endianness-dependent, because it really is based on the raw internal representation.)

If you want a C-level float, which is how NumPy represents float32 values at C level... well, that's C. Unless you want to write your own C extension module, you can't work with C-level values directly. The closest you can get is some sort of wrapper around a C float, and hey! You already have one! You don't seem happy with it, though, so this isn't really what you want.

If you want the exact value represented in human-readable decimal, printing it with extra precision using str.format or by converting it to a regular float and then a decimal.Decimal would do that.

```<code>>>> b
58682.758
>>> decimal.Decimal(float(b))
Decimal('58682.7578125')
</code>```

The 58682.7578125 value you picked happens to be exactly representable as a float, so the decimal representation coming out happens to be exactly the one you put in, but that won't usually be the case. The exact decimal representation you typed in is discarded and unrecoverable.

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ?

The float32 gets converted to a float64, losslessly.

Title: Numpy's float32 and float comparisons

Body:
They're equal. They're just not printing the same because they use different printing logic.

How can I get at the exact internal representation of float_32 and a in the example ?

Well, that depends on what you mean by "exact internal representation". You can get an array of bit values, if you really want one:

>>> b = numpy.float32(a)
>>> numpy.unpackbits(numpy.array([b]).view(numpy.uint8))
array([1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,
       1, 0, 1, 0, 0, 0, 1, 1, 1], dtype=uint8)

which is as close as you'll get to the "exact internal representation", but it's not exactly the most useful thing to work with. (Also, the results will be endianness-dependent, because it really is based on the raw internal representation.)

If you want a C-level float, which is how NumPy represents float32 values at C level... well, that's C. Unless you want to write your own C extension module, you can't work with C-level values directly. The closest you can get is some sort of wrapper around a C float, and hey! You already have one! You don't seem happy with it, though, so this isn't really what you want.

If you want the exact value represented in human-readable decimal, printing it with extra precision using str.format or by converting it to a regular float and then a decimal.Decimal would do that.

>>> b
58682.758
>>> decimal.Decimal(float(b))
Decimal('58682.7578125')

The 58682.7578125 value you picked happens to be exactly representable as a float, so the decimal representation coming out happens to be exactly the one you put in, but that won't usually be the case. The exact decimal representation you typed in is discarded and unrecoverable.

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ?

The float32 gets converted to a float64, losslessly.


问:
Python using regex to extract parts of a string in pandas column
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

```<code>'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'
</code>```

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

Body:
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

Body:
Try this : \(([^,]*), ([^)]*)\)

See : https://regex101.com/r/fCetWg/1


问:
Observable.doOnCompleted() after subscriber doOnCompleted() was called
I have following sample that demontrates the problem:

```<code>Observable<Integer> observable = Observable.create(subscriber -> {
    IntStream.range(0, 1_00).forEach(subscriber::onNext);
    subscriber.onCompleted();
}).doOnCompleted(() -> System.out.println("I'm first, but want to be second"));

observable.subscribe((i)-> {}, (e)-> System.err.println(e), ()-> System.out.println("I'm second, but want to be first"));
</code>```

If I replace observable doOnCompleted with doAfterTerminate it works, but it has slightly different semantics.

How to achieve that subscriber onCompleted will be called before doOnCompleted on that observable ?

答:
You should use doFinally()
This is the side effect method which will be called after onCompleted.

You can also refere this : https://stackoverflow.com/a/44922182/7409774

Body:
I have following sample that demontrates the problem:

Observable<Integer> observable = Observable.create(subscriber -> {
    IntStream.range(0, 1_00).forEach(subscriber::onNext);
    subscriber.onCompleted();
}).doOnCompleted(() -> System.out.println("I'm first, but want to be second"));

observable.subscribe((i)-> {}, (e)-> System.err.println(e), ()-> System.out.println("I'm second, but want to be first"));

If I replace observable doOnCompleted with doAfterTerminate it works, but it has slightly different semantics.

How to achieve that subscriber onCompleted will be called before doOnCompleted on that observable ?


问:
react native how to deal with Cannot read property 'undefined' of undefined
I'm expecting some data from remote server to show it in the screen but I got this error in the simulator Cannot read property 'undefined' of undefined the reason why is the content is rendered before the arrival of the results, this the part of code where I'm having this error :

```<code>caption = { this.state.customFieldDropdown['gender'][this.state.dropDownSelectedItems['gender'] ] || '---Choose---' }
</code>```

So the property caption is expecting a text, and to deal with undefined values I added this  || '---Choose---' to show text '---Choose---' in case of null but the problem is this.state.dropDownSelectedItems['gender'] is undefined and when this.state.customFieldDropdown access that value it caused the error ( reading property which is undefined)

So how to deal with this issue?

答:
You seems to have undefined value higher in the property chain. The || operator will match only last value in the chain, so if for example this.state.customFieldDropdown['gender'] is undefined it will fail.

I'll suggest you to take a look at idx function introduced by React team. More details here: https://facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html

Body:
I'm expecting some data from remote server to show it in the screen but I got this error in the simulator Cannot read property 'undefined' of undefined the reason why is the content is rendered before the arrival of the results, this the part of code where I'm having this error :

caption = { this.state.customFieldDropdown['gender'][this.state.dropDownSelectedItems['gender'] ] || '---Choose---' }

So the property caption is expecting a text, and to deal with undefined values I added this  || '---Choose---' to show text '---Choose---' in case of null but the problem is this.state.dropDownSelectedItems['gender'] is undefined and when this.state.customFieldDropdown access that value it caused the error ( reading property which is undefined)

So how to deal with this issue?


问:
mysql - selecting values from a table given column number
is it possible in mysql to select a value from a table by specifying the column number instead of the column name ?</p>

答:
No, you can not use the ordinal value of a column in the SELECT clause.

Column order is irrelevant to a database; the ordinal value is based on the list of columns in the SELECT clause.  The ordinal value is supported after the SELECT clause - IE: in the GROUP BY, and ORDER BY.  That said, using ordinals is not a recommended approach because ordinals are brittle -- if someone changes the column order in the SELECT clause, the query can be negatively impacted.


问:
Symfony app theming best practice
Still learning Symfony.
I've a generic theme based on bootstrap bought to be applied on our application.
This theme contains javascripts, less/css files, images and fonts.

I'm using assetic and i'm trying to figure which is the best practice of including this theme in the application.

Should i put all the files in a subfolder of app\Resources\public?

```<code>app/Resources/public/mytheme
app/Resources/public/mytheme/css
app/Resources/public/mytheme/js
app/Resources/public/mytheme/images
</code>```

But then, especially for images, i'd have to refer to files in twig by something like

```<code>{% image '../app/Resources/public/mytheme/images/user/no-image.png' output="images/user/no-image.png"%}
    <img src="{{ asset_url }}" alt="Example"/>
{% endimage %}
</code>```

It doesn't install any symlink or asset by using

```<code>php bin/console asset:install --symlink
</code>```

And in a css i have the ".logo" class that has a reference to "app/Resources/public/mytheme/images/theme-logo.png" that in html results in a broken link even with a cssrewrite filter.

Should i create a MyThemeBundle that contains all the assets? Or should i put all the assets in web/mytheme folder (but all the assets will be public even less files)?

I'm a bit confused.

答:
Fully read this page :

http://symfony.com/doc/current/assetic/asset_management.html#including-css-stylesheets

for an understanding about how to use the cssrewrite filter, to correctly point to your images, from inside your css

Title: Symfony app theming best practice

Body:
Still learning Symfony.
I've a generic theme based on bootstrap bought to be applied on our application.
This theme contains javascripts, less/css files, images and fonts.

I'm using assetic and i'm trying to figure which is the best practice of including this theme in the application.

Should i put all the files in a subfolder of app\Resources\public?

app/Resources/public/mytheme
app/Resources/public/mytheme/css
app/Resources/public/mytheme/js
app/Resources/public/mytheme/images

But then, especially for images, i'd have to refer to files in twig by something like

{% image '../app/Resources/public/mytheme/images/user/no-image.png' output="images/user/no-image.png"%}

{% endimage %}

It doesn't install any symlink or asset by using

php bin/console asset:install --symlink

And in a css i have the ".logo" class that has a reference to "app/Resources/public/mytheme/images/theme-logo.png" that in html results in a broken link even with a cssrewrite filter.

Should i create a MyThemeBundle that contains all the assets? Or should i put all the assets in web/mytheme folder (but all the assets will be public even less files)?

I'm a bit confused.


问:
Max difference between two adjacent values in an array, C
I want to find the max difference between two adjacent values in an array.For instance, for array int tab[6] = {1,2,8,4,5,6}; the maximum difference is 6, because of the difference between 8 and 2. Remaining differences are equal to 1. So, the result of my program should be 6. However, my program prints 1 and I do not know where's the problem:

```<code>#include <stdio.h>

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = tab[1] - tab[0], maxdiff = diff, i;

    for(i=2; i<n-1; i++)
    {
        if(diff > maxdiff)
            maxdiff = diff;

        diff = tab[i] - tab[i-1];
    }

    printf("%d\n", diff);

    return 0;
}
</code>```

答:
i<n-1 will not test the difference between the final two values of tab
and should be i<n.

The if should be below the difference calculation to catch if the final difference calculated is the largest.

You should be printing the maxdiff

You should also be taking the absolute value in your difference calculation, to account for the first number being larger than the second (As pointed out by @Felix Palmen). You can use the abs function defined in stdlib.h or write it yourself diff > 0? diff : -diff.

Fixed code:

```<code>int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = abs(tab[1] - tab[0]), maxdiff = diff, i;

    for(i=2; i<n; i++)
    {
        diff = abs(tab[i] - tab[i-1]);

        if(diff > maxdiff)
            maxdiff = diff;
    }

    printf("Max difference: %d\n", maxdiff);

    return 0;
}
</code>```

Body:
I want to find the max difference between two adjacent values in an array.For instance, for array int tab[6] = {1,2,8,4,5,6}; the maximum difference is 6, because of the difference between 8 and 2. Remaining differences are equal to 1. So, the result of my program should be 6. However, my program prints 1 and I do not know where's the problem:

#include <stdio.h>

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = tab[1] - tab[0], maxdiff = diff, i;

    for(i=2; i<n-1; i++)
    {
        if(diff > maxdiff)
            maxdiff = diff;

        diff = tab[i] - tab[i-1];
    }

    printf("%d\n", diff);

    return 0;
}

Body:
i<n-1 will not test the difference between the final two values of tab
and should be i<n.

The if should be below the difference calculation to catch if the final difference calculated is the largest.

You should be printing the maxdiff

You should also be taking the absolute value in your difference calculation, to account for the first number being larger than the second (As pointed out by @Felix Palmen). You can use the abs function defined in stdlib.h or write it yourself diff > 0? diff : -diff.

Fixed code:

int main(int argc, char **argv)
{
    int n = 6;
    int tab[6] = {1,2,8,4,5,6};
    int diff = abs(tab[1] - tab[0]), maxdiff = diff, i;

    for(i=2; i<n; i++)
    {
        diff = abs(tab[i] - tab[i-1]);

        if(diff > maxdiff)
            maxdiff = diff;
    }

    printf("Max difference: %d\n", maxdiff);

    return 0;
}


问:
SQL: How do I get all rows 30 minutes after a specific timestamp
I want to the query to return all rows which are x number of minutes after a specific timestamp, how do I go about achieving this?

答:
try this one </p>

```<code>SELECT * FROM tableName WHERE your_date_column> DATE_FORMAT(<specifictimestamp> + INTERVAL 30 MINUTE, '%Y-%m-01 %H:%i')
</code>```

Body:
try this one

SELECT * FROM tableName WHERE your_date_column> DATE_FORMAT(<specifictimestamp> + INTERVAL 30 MINUTE, '%Y-%m-01 %H:%i')


答:
Since there's only one comma, and everything is between parentheses, in your case, use .str.split() instead, after slicing appropriately:

```<code>model_region = df.Raw.str[1:-1].str.split(', ', expand = True)
</code>```

But if you insist:

```<code>model_region = df.Raw.str.extract('\((.*), (.*)\)', expand = True)
</code>```

Then

```<code>df['Model'] = model_region[0]
df['Region'] = model_region[1]
</code>```

Title: Python using regex to extract parts of a string in pandas column

Body:
Since there's only one comma, and everything is between parentheses, in your case, use .str.split() instead, after slicing appropriately:

model_region = df.Raw.str[1:-1].str.split(', ', expand = True)

But if you insist:

model_region = df.Raw.str.extract('\((.*), (.*)\)', expand = True)

Then

df['Model'] = model_region[0]
df['Region'] = model_region[1]


问:
Outlook sample addin added, but it is not shown
I have taken the sample Outlook addin from here

https://github.com/OfficeDev/Outlook-Add-in-JavaScript-ModuleExtension

If I add that addin to my Installed Outlook Apps (at the URL https://exchange.contoso.com/ecp/Extension/InstalledExtensions.slab?rfr=olk&exsvurl=1&realm=contoso.com opened via "Manage Add-Ins") the Navigation Bar entry does not show up in my Outlook 2016.

This is how it should look as per the example description:

but the "Billable Hours" part does not show up the Navigation bar, not even under "Options".

My Outlook 2016 is 16.0.7369.2130 German, and the underlying Exchange Server is Exchange 2013 CU 11, could that be an issue?

答:
The issue is that Exchange 2013 does not support this type of add-ins, and is unable to just send unsupported types of add-ins to the Client, which would support it. Also, there is no way to get this type of add-in directly into the Outlook client, circumventing the Exchange server.

Of course this is not documented anywhere.

Against an Exchange 2016 server or Office 365, the add-in works as expected.


问:
List implementation does not sum lists correctly
I am trying to dig into data structures in C++. Therefore I am learning how to write a list. Everything seemed to be working just fine until it came to overloading sum operator +. For two given lists it sums two of the highest values of the  lists.

Here is .h file:

```<code>typedef struct rob{
    int value;
    struct rob* next;
}element;

class list{
public:
    friend list& operator+(list&,list&);
    friend void merge(list& x,list& y);

    void show();
    bool search(int x);
    void append(int x);
    bool sortAppend(int x);
    list& operator--(int);

    bool empty() { return (inf.head==nullptr);}
    void clear() { inf.head = nullptr; }
    list() { inf.head = inf.tail = nullptr; }
    ~list() { while(!empty()) { (*this)--;}}

private:
    typedef struct{
        element* head;
        element* tail;
    }info;

    info inf;
};
</code>```

I know that in an .h file the typedef may seem a bit C-like, but the header design is copied from the book that I am learning from. I am trying to crack the methods by my own though using authors ideas.

And relevant function definitions:

```<code>#include "list.h"
bool list::sortAppend(int x){

element* newElem = new element;
newElem->value = x;
if (empty()){
    inf.head=inf.tail=newElem;
    newElem->next=nullptr;
    return true;
}
else if ( (newElem->value) < (inf.head->value) ){
    newElem->next=inf.head;
    inf.head=newElem;
    return true;
}
else if ( (newElem->value) > (inf.tail->value) ) {
    newElem->next=nullptr;
    inf.tail->next=newElem;
    return true;
}
element* tempHead = inf.head;
while(tempHead!=inf.tail){

    if ( (newElem->value) < (tempHead->next)->value) {
           newElem->next = (tempHead->next);
           tempHead->next = newElem;
           return true;
    }
    else{
    tempHead = tempHead->next;
    }
}
return false;
}

list& operator+(list& X, list& Y){
    list* tempListArr[2] = {&X, &Y};
    list* tempList = new list;
    for(const list* i: tempListArr)
    {
        element* tempHead = (i->inf).head;
        while(tempHead!= nullptr){
            tempList->sortAppend(tempHead->value);
            tempHead = tempHead->next;
            }
            tempList->show();
            std::cout << "--\n";
    }
    return *tempList;
}
</code>```

For given list containing values:

```<code>#include <iostream>
#include "list.cpp"

int main(){

    list myList;
    myList.sortAppend(5);
    myList.sortAppend(2);
    myList.sortAppend(4);
    list myList2;
    myList2.sortAppend(21);
    list myList3;

    myList3 = myList + myList2;

    return 0;

}
</code>```

Could anyone point me where I made a mistake? I am stuck for a few hours now and I don't know what goes wrong.

Many thanks in advance!

FOLLOW UP:

The sortAppend method surely works. It does create a sorted list as desired.
There must have been something wrong with the + operator definition itself though I have tried, instead of range loop, using for loop for one iteration and still I got a list of two values only.

答:
You are simply not setting inf.tail to the new tail in

```<code>else if ((newElem->value) > (inf.tail->value)) {
    newElem->next = nullptr;
    inf.tail->next = newElem;
    inf.tail = newElem; // <-- missing!
    return true;
}
</code>```

You should - at least - change the signature of operator+ to return a list instead of a list reference and return a local object instead of an unowned heap object (which is a memory leak). If you do so you will have to write a copy constructor and copy assignment operator too.

Body:
I am trying to dig into data structures in C++. Therefore I am learning how to write a list. Everything seemed to be working just fine until it came to overloading sum operator +. For two given lists it sums two of the highest values of the  lists.

Here is .h file:

typedef struct rob{
    int value;
    struct rob* next;
}element;

class list{
public:
    friend list& operator+(list&,list&);
    friend void merge(list& x,list& y);

    void show();
    bool search(int x);
    void append(int x);
    bool sortAppend(int x);
    list& operator--(int);

    bool empty() { return (inf.head==nullptr);}
    void clear() { inf.head = nullptr; }
    list() { inf.head = inf.tail = nullptr; }
    ~list() { while(!empty()) { (*this)--;}}

private:
    typedef struct{
        element* head;
        element* tail;
    }info;

    info inf;
};

I know that in an .h file the typedef may seem a bit C-like, but the header design is copied from the book that I am learning from. I am trying to crack the methods by my own though using authors ideas.

And relevant function definitions:

#include "list.h"
bool list::sortAppend(int x){

element* newElem = new element;
newElem->value = x;
if (empty()){
    inf.head=inf.tail=newElem;
    newElem->next=nullptr;
    return true;
}
else if ( (newElem->value) < (inf.head->value) ){
    newElem->next=inf.head;
    inf.head=newElem;
    return true;
}
else if ( (newElem->value) > (inf.tail->value) ) {
    newElem->next=nullptr;
    inf.tail->next=newElem;
    return true;
}
element* tempHead = inf.head;
while(tempHead!=inf.tail){

    if ( (newElem->value) < (tempHead->next)->value) {
           newElem->next = (tempHead->next);
           tempHead->next = newElem;
           return true;
    }
    else{
    tempHead = tempHead->next;
    }
}
return false;
}

list& operator+(list& X, list& Y){
    list* tempListArr[2] = {&X, &Y};
    list* tempList = new list;
    for(const list* i: tempListArr)
    {
        element* tempHead = (i->inf).head;
        while(tempHead!= nullptr){
            tempList->sortAppend(tempHead->value);
            tempHead = tempHead->next;
            }
            tempList->show();
            std::cout << "--\n";
    }
    return *tempList;
}

For given list containing values:

#include <iostream>
#include "list.cpp"

int main(){

    list myList;
    myList.sortAppend(5);
    myList.sortAppend(2);
    myList.sortAppend(4);
    list myList2;
    myList2.sortAppend(21);
    list myList3;

    myList3 = myList + myList2;

    return 0;

}

Could anyone point me where I made a mistake? I am stuck for a few hours now and I don't know what goes wrong.

Many thanks in advance!

FOLLOW UP:

The sortAppend method surely works. It does create a sorted list as desired.
There must have been something wrong with the + operator definition itself though I have tried, instead of range loop, using for loop for one iteration and still I got a list of two values only.

Body:
You are simply not setting inf.tail to the new tail in

else if ((newElem->value) > (inf.tail->value)) {
    newElem->next = nullptr;
    inf.tail->next = newElem;
    inf.tail = newElem; // <-- missing!
    return true;
}

You should - at least - change the signature of operator+ to return a list instead of a list reference and return a local object instead of an unowned heap object (which is a memory leak). If you do so you will have to write a copy constructor and copy assignment operator too.


问:
Create swift closure and pass it to objective-c class as completion block
Now I'm adding Swift code on objective-C based iOS application.

But I have a problem in calling the objective-C method from Swift side.

I'd like to get and draw image on UIImageView in View or ViewController which is written with Swift.
On the other hand my wrapper class of Photos Library is written with objective-C.

My wrapper class of Photos Library is below.

・MyPhotoLibraryMgr.h

```<code>typedef void (^AppPhotoLibraryGetImageCompletion)(UIImage *image, NSError *error);

- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:(AppPhotoLibraryGetImageCompletion)completion;
</code>```

・MyPhotoLibraryMgr.m

```<code>- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:
(AppPhotoLibraryGetImageCompletion)completion
{
    PHAsset *asset = _myAsetsList[index];

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;

    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:targetSize
                                              contentMode:PHImageContentModeAspectFill
                                                  options:options
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                NSError *error = [info objectForKey:PHImageErrorKey];
                                                if (error) {
                                                    NSLog(@"error=%@", error);
                                                }
                                                completion(result, error);
                                            }];
}
</code>```

I can get and draw image in View or ViewController written by objective-C like below,

・MyViewController.m

```<code>AppPhotoLibraryMgr *photoLibMgr = [AppPhotoLibraryMgr sharedInstance];
AppPhotoLibraryGetImageCompletion completion = ^(UIImage *image, NSError *error) {
                imageView.image = image;
};

[[AppPhotoLibraryMgr sharedInstance] getImageWithTarget:index
                                             targetSize:imageView.frame.size
                                             completion:completion];
</code>```

But I can't get image in View or ViewController written in Swift.

・MySwiftViewController.swift

```<code>let completion = {(image: UIImage, error: NSError) -> AppPhotoLibraryGetImageCompletion in
    let imageView = UIImageView(image: image)
}

photoLibMgr?.getImageWithTarget(index, targetSize: size, completion: completion)
</code>```

Error message from Xcode is

Cannot convert value of type 'UIImage, NSError ->
  AppPhotoLibraryGetImageCompletion" to expected argument type
  'AppPhotoLibraryGetImageCompletion'

答:
Your declaration of completion variable is wrong in MySwiftViewController.swift file.

Edit it like this:

```<code>let completion: AppPhotoLibraryGetImageCompletion = { (image, error) in
   let imageView = UIImageView(image: image)
}
</code>```

OR

If you don't want to declare completion handler as variable, then simply do the:

```<code>LinphoneLoginController.shared().getImageWithTarget(index, targetSize: size) { (image, error) in
    let imageView = UIImageView(image: image)
}
</code>```

Body:
Now I'm adding Swift code on objective-C based iOS application.

But I have a problem in calling the objective-C method from Swift side.

I'd like to get and draw image on UIImageView in View or ViewController which is written with Swift.
On the other hand my wrapper class of Photos Library is written with objective-C.

My wrapper class of Photos Library is below.

・MyPhotoLibraryMgr.h

typedef void (^AppPhotoLibraryGetImageCompletion)(UIImage *image, NSError *error);

- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:(AppPhotoLibraryGetImageCompletion)completion;

・MyPhotoLibraryMgr.m

- (void)getImageWithTarget:(NSInteger)index
                targetSize:(CGSize)targetSize
                completion:
(AppPhotoLibraryGetImageCompletion)completion
{
    PHAsset *asset = _myAsetsList[index];

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;

    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:targetSize
                                              contentMode:PHImageContentModeAspectFill
                                                  options:options
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                NSError *error = [info objectForKey:PHImageErrorKey];
                                                if (error) {
                                                    NSLog(@"error=%@", error);
                                                }
                                                completion(result, error);
                                            }];
}

I can get and draw image in View or ViewController written by objective-C like below,

・MyViewController.m

AppPhotoLibraryMgr *photoLibMgr = [AppPhotoLibraryMgr sharedInstance];
AppPhotoLibraryGetImageCompletion completion = ^(UIImage *image, NSError *error) {
                imageView.image = image;
};

[[AppPhotoLibraryMgr sharedInstance] getImageWithTarget:index
                                             targetSize:imageView.frame.size
                                             completion:completion];

But I can't get image in View or ViewController written in Swift.

・MySwiftViewController.swift

let completion = {(image: UIImage, error: NSError) -> AppPhotoLibraryGetImageCompletion in
    let imageView = UIImageView(image: image)
}

photoLibMgr?.getImageWithTarget(index, targetSize: size, completion: completion)

Error message from Xcode is

Cannot convert value of type 'UIImage, NSError ->
  AppPhotoLibraryGetImageCompletion" to expected argument type
  'AppPhotoLibraryGetImageCompletion'

Body:
Your declaration of completion variable is wrong in MySwiftViewController.swift file.

Edit it like this:

let completion: AppPhotoLibraryGetImageCompletion = { (image, error) in
   let imageView = UIImageView(image: image)
}

OR

If you don't want to declare completion handler as variable, then simply do the:

LinphoneLoginController.shared().getImageWithTarget(index, targetSize: size) { (image, error) in
    let imageView = UIImageView(image: image)
}


问:
how to display the "Game over" image in android for a fixed amount of time and restart the game when user taps the screen after a specified interval?
I made clone of ""Flappy bird" game by watching video tutorials.i programmed it so that when the bird falls or collides with the tubes a game over message appears on the screen and the game restarts when the player taps on the screen.

The problem is that when the user fails to tap the bird in time and it collides with the tube,the game over screen appears immediately and the user happens to tap on the game over screen which results in restarting of the game.

This makes the user unable to see the score.I have already tried using Thread.sleep().Following is the code

```<code>    (gameState == 2)
    {
        batch.draw(gameOver,Gdx.graphics.getWidth()/2-gameOver.getWidth()/2,Gdx.graphics.getHeight()/2-gameOver.getHeight()/2);

        try
        {
            Thread.sleep(2000);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }

        if (Gdx.input.justTouched()) {
            gameState = 1;
            startGame();
            score =0;
            scoringTube = 0;
            velocity = 0;
        }
    }
</code>```

With this code the problem is that even the gameover image is being delayed and the previous problem is still occuring but now with a delay.I basically need a way so that justTouched method becomes inactive for a while when the game over screen is there.Please help.

答:
I really wouldn't recommend using Thread.sleep; instead, you could try to use a boolean that is changed once the game ended, and prevent the method from executing in that case. Combine that with e.g a Timer that resets it after a fixed delay, and you should have the solution to your problem.

Example Usage for the timer:

```<code>new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
        public void run() {
            //execute code here (change boolean state)
        }
    },
    yourDelayHere
);
</code>```

Body:
I made clone of ""Flappy bird" game by watching video tutorials.i programmed it so that when the bird falls or collides with the tubes a game over message appears on the screen and the game restarts when the player taps on the screen.

The problem is that when the user fails to tap the bird in time and it collides with the tube,the game over screen appears immediately and the user happens to tap on the game over screen which results in restarting of the game.

This makes the user unable to see the score.I have already tried using Thread.sleep().Following is the code

    (gameState == 2)
    {
        batch.draw(gameOver,Gdx.graphics.getWidth()/2-gameOver.getWidth()/2,Gdx.graphics.getHeight()/2-gameOver.getHeight()/2);

        try
        {
            Thread.sleep(2000);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }

        if (Gdx.input.justTouched()) {
            gameState = 1;
            startGame();
            score =0;
            scoringTube = 0;
            velocity = 0;
        }
    }

With this code the problem is that even the gameover image is being delayed and the previous problem is still occuring but now with a delay.I basically need a way so that justTouched method becomes inactive for a while when the game over screen is there.Please help.

Body:
I really wouldn't recommend using Thread.sleep; instead, you could try to use a boolean that is changed once the game ended, and prevent the method from executing in that case. Combine that with e.g a Timer that resets it after a fixed delay, and you should have the solution to your problem.

Example Usage for the timer:

new java.util.Timer().schedule(
    new java.util.TimerTask() {
        @Override
        public void run() {
            //execute code here (change boolean state)
        }
    },
    yourDelayHere
);


问:
python3 urlopen raises 404 error while openning in the browser
I'm using urllib.request with python 3.4.6 to open https://www.ethz.ch/ (The actual url is longer but the problem is the same), which opens fine with Firefox but throws a 404 error with python.

Here is the code

```<code>from urllib.request import urlopen
connection = urlopen('https://www.ethz.ch/')
</code>```

and it gives the following error message

```<code>Traceback (most recent call last):
  File "./generate_group_meetings_ical.py", line 9, in <module>
    connection = urlopen('https://www.ethz.ch/')
  File "/usr/lib64/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib64/python3.4/urllib/request.py", line 470, in open
    response = meth(req, response)
  File "/usr/lib64/python3.4/urllib/request.py", line 580, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python3.4/urllib/request.py", line 508, in error
    return self._call_chain(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 442, in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 588, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not found UA
</code>```

The code used to work fine though. Another piece of information is that I'm not root on the machine and python3 was upgraded from 3.4.5 to 3.4.6. So the comes either from the web server side or from the python side. I'm not a python nor a web expert so I couldn't figure it out myself.

Hope anybody can help me.

答:
@Pheidippides Check for typos if any in your entire url, it worked for me:</p>

```<code>Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
$>from urllib.request import urlopen
$>connection = urlopen('https://www.ethz.ch/')
$>connection.read()
</code>```

Body:
I'm using urllib.request with python 3.4.6 to open https://www.ethz.ch/ (The actual url is longer but the problem is the same), which opens fine with Firefox but throws a 404 error with python.

Here is the code

from urllib.request import urlopen
connection = urlopen('https://www.ethz.ch/')

and it gives the following error message

Traceback (most recent call last):
  File "./generate_group_meetings_ical.py", line 9, in <module>
    connection = urlopen('https://www.ethz.ch/')
  File "/usr/lib64/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib64/python3.4/urllib/request.py", line 470, in open
    response = meth(req, response)
  File "/usr/lib64/python3.4/urllib/request.py", line 580, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python3.4/urllib/request.py", line 508, in error
    return self._call_chain(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 442, in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 588, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not found UA

The code used to work fine though. Another piece of information is that I'm not root on the machine and python3 was upgraded from 3.4.5 to 3.4.6. So the comes either from the web server side or from the python side. I'm not a python nor a web expert so I couldn't figure it out myself.

Hope anybody can help me.

Body:
@Pheidippides Check for typos if any in your entire url, it worked for me:

Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
$>from urllib.request import urlopen
$>connection = urlopen('https://www.ethz.ch/')
$>connection.read()


问:
Tesseract simple image with text recognition, Help wanted to convert/transform image
Hello I'm trying to use OCR tesseract to recognize some letters in a image.

I did a convert using imagemagick and image seems to be good but its not enough

The original images:

The command used with imagemagick to convert

```<code>convert input.jpg -fuzz 50% -fill black -opaque black -bordercolor white -border 2 -fill black -draw "color 0,0 floodfill" -alpha off -negate -units pixelsperinch -density 72 output.jpg
</code>```

The result images:

The OCR tesseract command:

```<code>$ tesseract output.jpg out -psm 7
</code>```

Output/result:

Text: AUGU -> AUOU

Tesseract Open Source OCR Engine v4.00.00alpha with Leptonica
Page 1

Text: VEGU -> VOR-OU

Tesseract Open Source OCR Engine v4.00.00alpha with Leptonica
Page 1

Text: EGUV -> E6UV

Tesseract Open Source OCR Engine v4.00.00alpha with Leptonica
Page 1

Text: USEA -> USSOEA

答:
Not sure if it was pure luck, as you have only provided a single image to test with, but I noticed you are using a noisy/fuzzy JPEG instead of a nice clean PNG, so I thresholded your image at 50% and made a PNG of it and it recognises all four letters correctly:</p>

```<code>convert yourImage.jpeg -threshold 50% clean.png
tesseract -psm 7 clean.png out
</code>```

Body:
Hello I'm trying to use OCR tesseract to recognize some letters in a image.

I did a convert using imagemagick and image seems to be good but its not enough

The original images:

The command used with imagemagick to convert

convert input.jpg -fuzz 50% -fill black -opaque black -bordercolor white -border 2 -fill black -draw "color 0,0 floodfill" -alpha off -negate -units pixelsperinch -density 72 output.jpg

The result images:

The OCR tesseract command:

$ tesseract output.jpg out -psm 7

Output/result:

Text: AUGU -> AUOU

Tesseract Open Source OCR Engine v4.00.00alpha with Leptonica
Page 1

Text: VEGU -> VOR-OU

Tesseract Open Source OCR Engine v4.00.00alpha with Leptonica
Page 1

Text: EGUV -> E6UV

Tesseract Open Source OCR Engine v4.00.00alpha with Leptonica
Page 1

Text: USEA -> USSOEA

Body:
Not sure if it was pure luck, as you have only provided a single image to test with, but I noticed you are using a noisy/fuzzy JPEG instead of a nice clean PNG, so I thresholded your image at 50% and made a PNG of it and it recognises all four letters correctly:

convert yourImage.jpeg -threshold 50% clean.png
tesseract -psm 7 clean.png out


问:
Spring integration test does not rollback
I've done some research through the q&a around here regarding the issue. many questions seem to address it, but not really.

So here's the thing:

I got a CaseController, which delegates to CaseService, which delegate in turn to CaseRepository.

I got @Transactional on top of each method on CaseServiceImpl

I got a CaseControllerIntegrationTest, from which I perform RESTful requests to my CaseController and test full cycles.

Problem is - my transactions are not rolled back.

One of the tests is

```<code>@Test
public void verifyDeleteSuccessfulOnExistingCase() {

        final String urlWithPlaceholders = serverPrefix + RequestMappings.CASES_RESOURCE_MAPPING + "/{caseId}";

        final ResponseEntity<CaseResource> response =
                restTemplate.exchange(
                        urlWithPlaceholders,
                        HttpMethod.DELETE,
                        null,
                        CaseResource.class, existingWsId_1, caseId);

        assertThat(response, notNullValue());
        assertThat(response.getBody(), nullValue());
        assertThat(response.getStatusCode(), is(HttpStatus.NO_CONTENT));
        assertThat(caseRepository.exists(caseId), is(false));

}
</code>```

In this test I delete a case which I had inserted for me in startup thanks to hibernate and import.sql

Test is successful, problem is that I want to keep on addressing this case in the next tests, but the transaction seems not be rolled back, and the case is permanently deleted and not available for the next tests.

I have tried moving @Transactional from CaseServiceImpl to the CaseController, yet it didn't make a difference.

I can say that my lower lever CaseRepositoryTest successfully performs the rollback after each test.

On top of CaseControllerIntegrationTest I got:

```<code>@ActiveProfiles("integration-test")
@Transactional
@TransactionConfiguration
@IntegrationTest
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AppConfiguration.class)
public class CaseControllerIntegrationTest {
...
</code>```

AppConfiguration looks like this:

```<code>@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableTransactionManagement
public class AppConfiguration {
}
</code>```

The db I'm using is hsqldb

Last important piece of info - The log actually indicates that the rollback was done:

2014-05-15 07:54:44.391 TRACE -
  o.s.t.c.t.TransactionalTestExecutionListener - Ending transaction for
  test context [DefaultTestContext@2eb0cefe testClass =
  CaseControllerIntegrationTest, testInstance =
  om.services.casemanagement.web.CaseControllerIntegrationTest@5a2ae1ab,
  testMethod = verifyDeleteSuccessfulOnExistingCase@CaseControllerIntegrationTest,
  testException = [null], mergedContextConfiguration =
  [WebMergedContextConfiguration@2bec068b testClass =
  CaseControllerIntegrationTest, locations = '{}', classes = '{class
  om.services.AppConfiguration}', contextInitializerClasses = '[]',
  activeProfiles = '{integration-test}', resourceBasePath =
  'src/main/webapp', contextLoader =
  'org.springframework.boot.test.SpringApplicationContextLoader', parent
  = [null]]]; transaction status [org.springframework.transaction.support.DefaultTransactionStatus@3869a6e5];
  rollback [true]

2014-05-15 07:54:44.403 INFO  -
  o.s.t.c.t.TransactionalTestExecutionListener - Rolled back transaction
  after test execution for test context [DefaultTestContext@2eb0cefe
  testClass = CaseControllerIntegrationTest, testInstance =
  om.services.casemanagement.web.CaseControllerIntegrationTest@5a2ae1ab,
  testMethod = verifyDeleteSuccessfulOnExistingCase@CaseControllerIntegrationTest,
  testException = [null], mergedContextConfiguration =
  [WebMergedContextConfiguration@2bec068b testClass =
  CaseControllerIntegrationTest, locations = '{}', classes = '{class
  om.services.AppConfiguration}', contextInitializerClasses = '[]',
  activeProfiles = '{integration-test}', resourceBasePath =
  'src/main/webapp', contextLoader =
  'org.springframework.boot.test.SpringApplicationContextLoader', parent
  = [null]]]

I'm using Spring 4.0.3 distribution.

Any ideas?

答:
Although @kumetix alluded to it, the correct answer to this is that,   there is no way of rolling back the transactions triggered by the requests made through the RestTemplate in a test method

Your only option is to rollback the transactions through a manual delete.

Refer this link with similiar question for another opinion.

Hope that helps.

Body:
I've done some research through the q&a around here regarding the issue. many questions seem to address it, but not really.

So here's the thing:

I got a CaseController, which delegates to CaseService, which delegate in turn to CaseRepository.

I got @Transactional on top of each method on CaseServiceImpl

I got a CaseControllerIntegrationTest, from which I perform RESTful requests to my CaseController and test full cycles.

Problem is - my transactions are not rolled back.

One of the tests is

@Test
public void verifyDeleteSuccessfulOnExistingCase() {

        final String urlWithPlaceholders = serverPrefix + RequestMappings.CASES_RESOURCE_MAPPING + "/{caseId}";

        final ResponseEntity<CaseResource> response =
                restTemplate.exchange(
                        urlWithPlaceholders,
                        HttpMethod.DELETE,
                        null,
                        CaseResource.class, existingWsId_1, caseId);

        assertThat(response, notNullValue());
        assertThat(response.getBody(), nullValue());
        assertThat(response.getStatusCode(), is(HttpStatus.NO_CONTENT));
        assertThat(caseRepository.exists(caseId), is(false));

}

In this test I delete a case which I had inserted for me in startup thanks to hibernate and import.sql

Test is successful, problem is that I want to keep on addressing this case in the next tests, but the transaction seems not be rolled back, and the case is permanently deleted and not available for the next tests.

I have tried moving @Transactional from CaseServiceImpl to the CaseController, yet it didn't make a difference.

I can say that my lower lever CaseRepositoryTest successfully performs the rollback after each test.

On top of CaseControllerIntegrationTest I got:

@ActiveProfiles("integration-test")
@Transactional
@TransactionConfiguration
@IntegrationTest
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AppConfiguration.class)
public class CaseControllerIntegrationTest {
...

AppConfiguration looks like this:

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableTransactionManagement
public class AppConfiguration {
}

The db I'm using is hsqldb

Last important piece of info - The log actually indicates that the rollback was done:

2014-05-15 07:54:44.391 TRACE -
  o.s.t.c.t.TransactionalTestExecutionListener - Ending transaction for
  test context [DefaultTestContext@2eb0cefe testClass =
  CaseControllerIntegrationTest, testInstance =
  om.services.casemanagement.web.CaseControllerIntegrationTest@5a2ae1ab,
  testMethod = verifyDeleteSuccessfulOnExistingCase@CaseControllerIntegrationTest,
  testException = [null], mergedContextConfiguration =
  [WebMergedContextConfiguration@2bec068b testClass =
  CaseControllerIntegrationTest, locations = '{}', classes = '{class
  om.services.AppConfiguration}', contextInitializerClasses = '[]',
  activeProfiles = '{integration-test}', resourceBasePath =
  'src/main/webapp', contextLoader =
  'org.springframework.boot.test.SpringApplicationContextLoader', parent
  = [null]]]; transaction status [org.springframework.transaction.support.DefaultTransactionStatus@3869a6e5];
  rollback [true]

2014-05-15 07:54:44.403 INFO  -
  o.s.t.c.t.TransactionalTestExecutionListener - Rolled back transaction
  after test execution for test context [DefaultTestContext@2eb0cefe
  testClass = CaseControllerIntegrationTest, testInstance =
  om.services.casemanagement.web.CaseControllerIntegrationTest@5a2ae1ab,
  testMethod = verifyDeleteSuccessfulOnExistingCase@CaseControllerIntegrationTest,
  testException = [null], mergedContextConfiguration =
  [WebMergedContextConfiguration@2bec068b testClass =
  CaseControllerIntegrationTest, locations = '{}', classes = '{class
  om.services.AppConfiguration}', contextInitializerClasses = '[]',
  activeProfiles = '{integration-test}', resourceBasePath =
  'src/main/webapp', contextLoader =
  'org.springframework.boot.test.SpringApplicationContextLoader', parent
  = [null]]]

I'm using Spring 4.0.3 distribution.

Any ideas?


问:
Text not showing when for() is executing
Below is the example demonstrates that the text ("A","B","C" and "testing in progress...") for each Label and TextArea will not showing when a for() is executing. It will show simultaneously once for() is finished!

Any solution to overcome this?

```<code>public class Test1Controller {

    @FXML
    private Label l1;
    @FXML
    private Label l2;
    @FXML
    private Label l3;
    @FXML
    private TextArea info;
    @FXML
    private Button B1;

    @FXML
    void B1_runing(ActionEvent event)
    {

        l1.setText("A");
        l2.setText("B");
        l3.setText("C");
        info.appendText("testing in progress...\n");
        B1.setDisable(true);

        for( int i=0; i<800; i++ )
        {
            for( int x=0; x<10000000; x++ );
        }

        info.appendText("end...\n");
    }

}
</code>```

答:
The issue is that you're running an intensive operation on the UI thread. The text area can't redraw itself until you're finished because all of this is happening on a single thread.

It's not usually a problem to do simple calculations on the UI thread, but your loops go for 8 billion iterations.

The way to avoid this situation is to push any intensive operations onto another thread. There are multiple ways to do that, which will depend on your use case. In your example, your loop doesn't really do anything so you could simply replace your loops with this:

```<code>new Thread( ()->{
    // Send the lambda to the Application (UI) thread
    Platform.runLater(()->info.appendText("testing in progress...\n"));

    for( int i=0; i<800; i++ )
    {
         for( int x=0; x<10000000; x++ );
    }

    // Send the lambda to the Application (UI) thread
    Platform.runLater(()->info.appendText("end...\n"));
}).start();
</code>```

Usage of Thread like this is kind of discouraged in modern Java, but it demonstrates the point. A better solutions might involve Futures or ExecutorServices.

Body:
Below is the example demonstrates that the text ("A","B","C" and "testing in progress...") for each Label and TextArea will not showing when a for() is executing. It will show simultaneously once for() is finished!

Any solution to overcome this?

public class Test1Controller {

    @FXML
    private Label l1;
    @FXML
    private Label l2;
    @FXML
    private Label l3;
    @FXML
    private TextArea info;
    @FXML
    private Button B1;

    @FXML
    void B1_runing(ActionEvent event)
    {

        l1.setText("A");
        l2.setText("B");
        l3.setText("C");
        info.appendText("testing in progress...\n");
        B1.setDisable(true);

        for( int i=0; i<800; i++ )
        {
            for( int x=0; x<10000000; x++ );
        }

        info.appendText("end...\n");
    }

}

Body:
The issue is that you're running an intensive operation on the UI thread. The text area can't redraw itself until you're finished because all of this is happening on a single thread.

It's not usually a problem to do simple calculations on the UI thread, but your loops go for 8 billion iterations.

The way to avoid this situation is to push any intensive operations onto another thread. There are multiple ways to do that, which will depend on your use case. In your example, your loop doesn't really do anything so you could simply replace your loops with this:

new Thread( ()->{
    // Send the lambda to the Application (UI) thread
    Platform.runLater(()->info.appendText("testing in progress...\n"));

    for( int i=0; i<800; i++ )
    {
         for( int x=0; x<10000000; x++ );
    }

    // Send the lambda to the Application (UI) thread
    Platform.runLater(()->info.appendText("end...\n"));
}).start();

Usage of Thread like this is kind of discouraged in modern Java, but it demonstrates the point. A better solutions might involve Futures or ExecutorServices.


问:
How Erasure Coding used in hadoop3 and how they achieve fault tolerance with it?
As per the Hadoop 3.x release notes, they have introduced Erasure coding to overcome the problems with storage.

Erasure coding, a new feature in HDFS, can reduce storage overhead by approximately 50% compared to replication while maintaining the same durability guarantees.

can someone explain me how Erasure coding is used in fault tolerant way with less space overhead?

答:
To understand the how HDFS Erasure Coding works and reduces the storage space.

Refer: “Introduction to HDFS Erasure Coding in Apache Hadoop”.


问:
Jenkins deployment to Tomcat failed
I'm currently learning and implementing Jenkin's Pipeline for automated integration for java web application.

My plan is that once developers successfully commit and push their codes, Jenkins on admin server check out the code, build the project, stop the currently running Tomcat, deploy the project to the Tomcat, and restart.

For testing purpose, I'm currently trying everything, including running Tomcat and Jenkins, on local machine. But Jenkins is running its own (by executing command "Java -jar jenkins.war") but not using tomcat

Everything worked fine with pipeline except for starting Tomcat.
below is the pipeline code snippet for tomcat restart.

```<code>stage('Restart') {
        steps {
            echo 'Restarting Tomcat.....'
            sh '''
                cd ~/PATH-TO-Tomcat/apache-tomcat-8.0.44/bin
                ./startup.sh
            '''
        }
}
</code>```

As you can see, it simply goes to tomcat directory and execute the startup.sh script. However, when executing the restart stage, only the message "Tomcat started." is recored in console log file, but when checking with local host, Tomcat was not started at all.

I tried to start tomcat manually by executing command using terminal, it works okay.

Please help

Thank you

答:
I have also encountered this problem when starting shell scripts from Jenkins.

Problem

The problem is that the shell script is started within the scope of the Jenkins build. As soon as the build is stopped it behaves like if you close the terminal which is running the script. Thus, Tomcat is stopped when the Job ends.

Solution (kind of)

Try to start Tomcat in background (How to run a shell script in the background and get no output) which detaches the script from the job. Or you could install your Tomcat as a service (java install tomcat as service) and start the service from Jenkins.

Title: Jenkins deployment to Tomcat failed

Body:
I'm currently learning and implementing Jenkin's Pipeline for automated integration for java web application.

My plan is that once developers successfully commit and push their codes, Jenkins on admin server check out the code, build the project, stop the currently running Tomcat, deploy the project to the Tomcat, and restart.

For testing purpose, I'm currently trying everything, including running Tomcat and Jenkins, on local machine. But Jenkins is running its own (by executing command "Java -jar jenkins.war") but not using tomcat

Everything worked fine with pipeline except for starting Tomcat.
below is the pipeline code snippet for tomcat restart.

stage('Restart') {
        steps {
            echo 'Restarting Tomcat.....'
            sh '''
                cd ~/PATH-TO-Tomcat/apache-tomcat-8.0.44/bin
                ./startup.sh
            '''
        }
}

As you can see, it simply goes to tomcat directory and execute the startup.sh script. However, when executing the restart stage, only the message "Tomcat started." is recored in console log file, but when checking with local host, Tomcat was not started at all.

I tried to start tomcat manually by executing command using terminal, it works okay.

Please help

Thank you