问:
Xamarin iOS Map Custom Pins
I am use the Xamarin iOS MKMapView, and i am trying to have separate images for each pin, but when I override the GetViewForAnnotation method, it makes all the pins the same image, is there a way to make every pin a different image.

```<code>class MapDelegate : MKMapViewDelegate
        {
            static string annotationId = "CustomAnnotation";
            UIImageView venueView;
            UIImage venueImage;

            public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, NSObject annotation)
            {
                MKAnnotationView annotationView = null;

                if (annotation is MKUserLocation)
                    return null;

                if (annotation is CustomAnnotation) {

                    // show conference annotation
                    annotationView = mapView.DequeueReusableAnnotation (annotationId);

                    if (annotationView == null)
                        annotationView = new MKAnnotationView (annotation, annotationId);

                    UIImage image = ImageSource.FromFile("image.png");
                }

                return annotationView;
            }

            public override MKOverlayView GetViewForOverlay (MKMapView mapView, NSObject overlay)
            {
                // return a view for the polygon
                MKPolygon polygon = overlay as MKPolygon;
                MKPolygonView polygonView = new MKPolygonView (polygon);
                polygonView.FillColor = UIColor.Blue;
                polygonView.StrokeColor = UIColor.Red;
                return polygonView;
            }
        }
</code>```

And the constructor:

```<code>map.MapType = MKMapType.Standard;
            map.ShowsUserLocation = true;
            map.ZoomEnabled = true;
            map.ScrollEnabled = true;

            map.DidUpdateUserLocation += (sender, ex) => {
                if (map.UserLocation != null) {
                    CLLocationCoordinate2D userLocation = map.UserLocation.Coordinate;
                    MKCoordinateSpan range = new MKCoordinateSpan(MilesToLatitudeDegrees(5), MilesToLongitudeDegrees(5, userLocation.Latitude));
                    MapDelegate mapDelegate = new MapDelegate();
                    map.Delegate = mapDelegate;

                    /*ADDING MULTIPLE ANNOTATIONS HERE*/
                        }
                    }
                }
            };
</code>```

I want to set each annotation to a different custom pin image, can someone help THANK YOU.

答:
This is possible by using Converter, for example you can specify concrete icon based on concrete pin property value.

```<code>private MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
    {
        MKAnnotationView annotationView = null;
        var formsMap = Element as MapWithPins;
        if (_customPins.Count == 0 || formsMap.PinsSource.Count != _customPins.Count)
        {
            //if (formsMap.PinsSource.Count != 0)
            _customPins = formsMap.PinsSource;
        }
        if (annotation is MKUserLocation)
            return null;
        if (!(annotation is MKPointAnnotation))
        {
            DrawMyLocationMarker(annotation, out annotationView);
        }
        else
        {
            var customPin = GetCustomPin(annotation as MKPointAnnotation);
            if (customPin == null)
                throw new Exception("Custom Pin not found");

            annotationView = mapView.DequeueReusableAnnotation(customPin.Guid.ToString());
            if (annotationView == null)
            {
                DrawMarkerForAnnotationView(annotation, out annotationView, customPin);
                if (customPin.Order > 0)
                    DrawNumber(customPin, annotationView);
            }
            else
                annotationView.Annotation = annotation;
        }
        return annotationView;
    }
</code>```

As you can see I draw different icons based on properties. If  Order property of my pin is more than 0, then I draw Order number on it. Otherwise in DrawMarkerFirAnnotationView I had Converter which returns proper icon based on properties.

```<code>private static void DrawMarkerForAnnotationView(IMKAnnotation annotation, out MKAnnotationView annotationView,
        PinViewModel customPin)
    {
        annotationView = new MKAnnotationView(annotation, customPin.Guid.ToString());
        var contractor= new Contractor { ContractorType = customPin.ContractorType, CompetitorPriceLastDate = customPin.CompetitorPriceLastDate, HasActivity = customPin.HasActivity };
        annotationView.Image =
            UIImage.FromFile(
                new ContractorToIconConverter().Convert(contractor, typeof(ContractorType), null, null).ToString());
    }
</code>```

I'm sure that you noticed, that icons are based on ContractorType property

```<code>public class BusRelToIconConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Contractor)
        {
            var contractor= (Contractor)value;
            if (contractor.HasActivity)
            {
                if (busRel.IsVisitedToday())
                {
                    return "marker-yellow-visited.png";
                }
                else
                {
                    return "marker-yellow.png";
                }
            }
            else if (contractor.ContractorType == CustStatus.Competitor)
            {
                if (contractor.IsVisitedToday())
                {
                    return "marker-red-visited.png";
                }
                else
                {
                    return "marker-red.png";
                }
            }
            else
            {
                if (contractor.IsVisitedToday())
                {
                    return "marker-blue-visited.png";
                }
                else
                {
                    return "marker-blue.png";
                }
            }
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Good luck!

Title: Xamarin iOS Map Custom Pins

Body:
I am use the Xamarin iOS MKMapView, and i am trying to have separate images for each pin, but when I override the GetViewForAnnotation method, it makes all the pins the same image, is there a way to make every pin a different image.

class MapDelegate : MKMapViewDelegate
        {
            static string annotationId = "CustomAnnotation";
            UIImageView venueView;
            UIImage venueImage;

            public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, NSObject annotation)
            {
                MKAnnotationView annotationView = null;

                if (annotation is MKUserLocation)
                    return null;

                if (annotation is CustomAnnotation) {

                    // show conference annotation
                    annotationView = mapView.DequeueReusableAnnotation (annotationId);

                    if (annotationView == null)
                        annotationView = new MKAnnotationView (annotation, annotationId);

                    UIImage image = ImageSource.FromFile("image.png");
                }

                return annotationView;
            }

            public override MKOverlayView GetViewForOverlay (MKMapView mapView, NSObject overlay)
            {
                // return a view for the polygon
                MKPolygon polygon = overlay as MKPolygon;
                MKPolygonView polygonView = new MKPolygonView (polygon);
                polygonView.FillColor = UIColor.Blue;
                polygonView.StrokeColor = UIColor.Red;
                return polygonView;
            }
        }

And the constructor:

map.MapType = MKMapType.Standard;
            map.ShowsUserLocation = true;
            map.ZoomEnabled = true;
            map.ScrollEnabled = true;

            map.DidUpdateUserLocation += (sender, ex) => {
                if (map.UserLocation != null) {
                    CLLocationCoordinate2D userLocation = map.UserLocation.Coordinate;
                    MKCoordinateSpan range = new MKCoordinateSpan(MilesToLatitudeDegrees(5), MilesToLongitudeDegrees(5, userLocation.Latitude));
                    MapDelegate mapDelegate = new MapDelegate();
                    map.Delegate = mapDelegate;

                    /*ADDING MULTIPLE ANNOTATIONS HERE*/
                        }
                    }
                }
            };

I want to set each annotation to a different custom pin image, can someone help THANK YOU.

Body:
This is possible by using Converter, for example you can specify concrete icon based on concrete pin property value.

private MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
    {
        MKAnnotationView annotationView = null;
        var formsMap = Element as MapWithPins;
        if (_customPins.Count == 0 || formsMap.PinsSource.Count != _customPins.Count)
        {
            //if (formsMap.PinsSource.Count != 0)
            _customPins = formsMap.PinsSource;
        }
        if (annotation is MKUserLocation)
            return null;
        if (!(annotation is MKPointAnnotation))
        {
            DrawMyLocationMarker(annotation, out annotationView);
        }
        else
        {
            var customPin = GetCustomPin(annotation as MKPointAnnotation);
            if (customPin == null)
                throw new Exception("Custom Pin not found");

            annotationView = mapView.DequeueReusableAnnotation(customPin.Guid.ToString());
            if (annotationView == null)
            {
                DrawMarkerForAnnotationView(annotation, out annotationView, customPin);
                if (customPin.Order > 0)
                    DrawNumber(customPin, annotationView);
            }
            else
                annotationView.Annotation = annotation;
        }
        return annotationView;
    }

As you can see I draw different icons based on properties. If  Order property of my pin is more than 0, then I draw Order number on it. Otherwise in DrawMarkerFirAnnotationView I had Converter which returns proper icon based on properties.

private static void DrawMarkerForAnnotationView(IMKAnnotation annotation, out MKAnnotationView annotationView,
        PinViewModel customPin)
    {
        annotationView = new MKAnnotationView(annotation, customPin.Guid.ToString());
        var contractor= new Contractor { ContractorType = customPin.ContractorType, CompetitorPriceLastDate = customPin.CompetitorPriceLastDate, HasActivity = customPin.HasActivity };
        annotationView.Image =
            UIImage.FromFile(
                new ContractorToIconConverter().Convert(contractor, typeof(ContractorType), null, null).ToString());
    }

I'm sure that you noticed, that icons are based on ContractorType property

public class BusRelToIconConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Contractor)
        {
            var contractor= (Contractor)value;
            if (contractor.HasActivity)
            {
                if (busRel.IsVisitedToday())
                {
                    return "marker-yellow-visited.png";
                }
                else
                {
                    return "marker-yellow.png";
                }
            }
            else if (contractor.ContractorType == CustStatus.Competitor)
            {
                if (contractor.IsVisitedToday())
                {
                    return "marker-red-visited.png";
                }
                else
                {
                    return "marker-red.png";
                }
            }
            else
            {
                if (contractor.IsVisitedToday())
                {
                    return "marker-blue-visited.png";
                }
                else
                {
                    return "marker-blue.png";
                }
            }
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Good luck!


来源: stackexchange

问:
How to play flv video in ios webview?
I have real time flv format video on my web page. I want to use webview to load this page in my ios app. But for flv is not a HTML5 support video format, so it cannot played directly without flash. I also try to use flv.js, flv.js is written in pure JavaScript without Flash. Then video can play in web page without flash, but still cannot paly in my app. In my app, I used WKwebview.</p>

答: You can go see ability HTML5 Supprt Video Type https://www.w3schools.com/html/html5_video.asp</p>

ContentLicense: CC BY-SA 3.0

Title: How to play flv video in ios webview?


问:
xquery function to convert a datetime value from EST to UCT based on the datetime value and not as per the current date
I am converting from EST to UTC. I need the result as below: If the dateTime passed is Feb-09-2017 11:30:00 then the UTC return should be Feb-09-2017 16:30:00 always irrespective of when I am executing the xquery. If I use the fn:adjust-dateTime-to-timezone then when I execute the xquery before the daylight saving time then the result is Feb-09-2017 16:30:00 (adds 5 hours which is correct) and however if I run the same query after the daylight saving time (ie after Mar 12) then the response becomes Feb-09-2017 15:30:00 (adds 4 hours). </p>

答:
The XPath/XSLT/XQuery date/time system only knows about numerical timezone offsets, not about civil/geographical/political conventions. So it understands -05:00, but not EST. To do this conversion you need access to external information.

If you're in Saxon there's an extension function saxon:in-summer-time(dateTime, civilTimeZone) which tells you if you're in daylight savings time, for example saxon:in-summer-time(current-dateTime(), 'America/New_York') returns true, enabling you to adjust the displacements used when calling adjust-dateTime().


问:
how to remove public folder and index.php on bonfire?
I just installed bonfire, if I want manage a module I must go to

http://localhost/bonfire/public/index.php/admin/content/blog

I would like to remove index.php on the url and I would like to access my module like.

http://localhost/bonfire/admin/content/blog

Any ideas? i have googling and try any tutorials to remove index.php but it still failed until now

答:
Below are the steps of removing public and index.php from the website / application

Move all files from public folder to the root (using older site structure).

Edit root index.php and set $path = “.”;

Rename 1.htaccess to .htaccess

Edit .htaccess line 158 Rewrite-base / (add sub folder path if site hosted under sub directory)

Open config.php in folder application/config and set $config[“base_url”] = “” and $config[“index.php”]=””

With these changes your CI Bonfire application will now have more user friendly urls.


问:
ngIf consition with observables
I've created two observables:

```<code>private sources$: Observable<Array<ISource>>;
private defaultSource$: Observable<ISource>;
</code>```

I'm using ngFor in order to get all ISource and render them into a table:

```<code><tr *ngFor="let source of sources$ | async; let index = index;">
...
</code>```

For each source I'm creating several columns using td tag. In one of them:

```<code><td>
    {{source.holdername}} <span class="tag tag-warning">DEFAULT</span>
</td>
</code>```

I need that span tag is visible if the current source is the defaultSource$.

I'm guessing that I would need to use an ngIf but I'm not able to figure out how to build the expression.

Any ideas?

答:
As simple as this :

```<code><td>
    {{source.holdername}} <span class="tag tag-warning" *ngIf="source === (defaultSource$ | async)">DEFAULT</span>
</td>
</code>```

Note that the value emitted by defaultSource$ should be the same object reference as source.

Title: ngIf consition with observables

Body:
I've created two observables:

private sources$: Observable<Array<ISource>>;
private defaultSource$: Observable<ISource>;

I'm using ngFor in order to get all ISource and render them into a table:

...

For each source I'm creating several columns using td tag. In one of them:

    {{source.holdername}} DEFAULT

I need that span tag is visible if the current source is the defaultSource$.

I'm guessing that I would need to use an ngIf but I'm not able to figure out how to build the expression.

Any ideas?

Body:
As simple as this :

<td>
    {{source.holdername}} <span class="tag tag-warning" *ngIf="source === (defaultSource$ | async)">DEFAULT</span>
</td>

Note that the value emitted by defaultSource$ should be the same object reference as source.


问:
ASP.NET Development with a Design Team
I am looking for some good information on the best way for a design and development team to work together. I am a WinForms developer and I have very little experience in .NET web development and I have been asked to take over responsibility for the website development.

Currently they are using Visual Sourcesafe, the websites are not in a solution and the whole thing is just a complete mess of thousands of random webpages created by the designers and cobbled together code put together by the developers. The different pages are released whenever they are ready - which means dependant code may not get released at the same time. At times designers are using code the developers have created but they use it in a way which will either slow down the site or cause it to crash completely - for example calling Functions.GetAddress().PhoneNumber and then Functions.GetAddress().Address1 where the GetAddress method is calling a webservice each time, if the GetAddress call fails and returns null they are not checking for null references etc and there is no error handling.

Basically the entire thing is a complete unmanaged mess which scares me to death considering I am soon going to be completely responsible for it. This is also across 3 or 4 large business critical websites. I am trying to figure out the best way going forward so that the designers can continue to create pages and design assets they need while also accessing certain exposed properties as required.

Currently on the Windows development side of things we are using Team System 2010 but this won't be appropriate for the designers as they need source control integrated into the shell where they can edit images and flash which SourceSafe currently lets them do (badly).

I think the first step is to split up the code development / data access side of things into a completely seperate project which can be referenced as a dll from different web projects which I will get created for each site under a single solution. I then need to sort out a way that we are publishing the complete site everytime an update is made - so obviously it is important that only completed / tested work is checked in - I think this is going to be incredibly tough to sort out with the design team as they are unused to source control and just upload pages one by one as they complete work / fix bugs on them. Basically I need help/ideas/pointers for the right way to go about this!

答:
Doing what you suggested yourself (i.e. complete releases, separating backend from frontend, etc.) will improve your work greatly considerring the current situation. Of course there are a lot of things you can ultimately do like introducing unit tests, dependency injection, etc. but I believe one pattern that might be directly useful when dealing with developers and designers in Web Forms environment is the MVP pattern. Here is a wonderful presentation on the subject:
http://live.visitmix.com/MIX10/Sessions/EX20</p>

ContentLicense: CC BY-SA 2.5

Title: ASP.NET Development with a Design Team


问:
How to remove element from array in Swift based on value?
I have the following code:

```<code>func mapView(mapView: GMSMapView, didTap marker: GMSMarker){
let lat: CLLocationDegrees = marker.position.latitude
let lng: CLLocationDegrees = marker.position.longitude
var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
markersArray.remove(formattedCoordinate)
self.clean()
}

func mapView(mapView: GMSMapView, didBeginDragging marker: GMSMarker){
let lat: CLLocationDegrees = marker.position.latitude
let lng: CLLocationDegrees = marker.position.longitude
var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
markersArray.remove(formattedCoordinate)
}
</code>```

As you can see I am trying to "remove" the "formattedCoordinate" from markersArray. I saw that there are options like .filter and other methods which enables removing an element at a specific index, but here I would like to remove that specific coordinate from the array. How do I do that?

答:
```<code>    markers = markers.filter({ (coordinateToRemove) -> Bool in
        return coordinateToRemove.latitude == formattedCoordinate.latitude && coordinateToRemove.longitude == formattedCoordinate.longitude
    })
</code>```

I had the same problem solved it by rounding off the values of latitude and longitude(as they can be different by some decimal in formattedCoordinate Object) that you are comparing using

round(coordinateToRemove.latitude)

and comparing them separately.

Body:
I have the following code:

func mapView(mapView: GMSMapView, didTap marker: GMSMarker){
let lat: CLLocationDegrees = marker.position.latitude
let lng: CLLocationDegrees = marker.position.longitude
var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
markersArray.remove(formattedCoordinate)
self.clean()
}

func mapView(mapView: GMSMapView, didBeginDragging marker: GMSMarker){
let lat: CLLocationDegrees = marker.position.latitude
let lng: CLLocationDegrees = marker.position.longitude
var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
markersArray.remove(formattedCoordinate)
}

As you can see I am trying to "remove" the "formattedCoordinate" from markersArray. I saw that there are options like .filter and other methods which enables removing an element at a specific index, but here I would like to remove that specific coordinate from the array. How do I do that?

Body:
    markers = markers.filter({ (coordinateToRemove) -> Bool in
        return coordinateToRemove.latitude == formattedCoordinate.latitude && coordinateToRemove.longitude == formattedCoordinate.longitude
    })

I had the same problem solved it by rounding off the values of latitude and longitude(as they can be different by some decimal in formattedCoordinate Object) that you are comparing using

round(coordinateToRemove.latitude)

and comparing them separately.


问:
Windows Azure VM Filezilla FTP Setup
I am using Windows 2012 R2 VM machine in Azure. I have read multiple article to setup Filezilla server in this environment. However, I am not successful. Any one faced this issue? Any solution will be greatly appreciated.</p>

答: Just remember to add Filezilla to Windows Firewall :-)</p>

Title: Windows Azure VM Filezilla FTP Setup


问:
Laravel string is not entering/updating in the database
First is it checks if request form has the same username in the database and then the first name that is saved in the database to be compared with the request form. But it is not entering in the database I may have done something wrong when turning the strings into arrays or using the for loop to compare both strings but I can't spot the error can you help me?</p>

```<code>if (User::where('username', $request->username)->exists()) {//check if request form has the same username in the database

    //first name that is saved in the database to be compared with the request form
    $fnameSavedInDatabase = DB::select('select first_name from users where username = ? and first_name != ?', [$request->username, $request->first_name]);

    //turn into array
    $fnameSavedInDatabaseArray = str_split($fnameSavedInDatabase);

    //request form value turn in to an array
    $fnameIncomingArray = str_split($request->first_name);

    //value that will be saved/updated in the database
    $fnameFinalIncomingString;

    for ($index = 0; $index < strlen($request->first_name); $index++) {
        if ($fnameIncomingArray[$index] == $fnameSavedInDatabaseArray[$index]) {
            $fnameFinalIncomingString = $fnameFinalIncomingString . $fnameIncomingArray[$index];
        }
    }

    $user = User::create($request->all());

    $user->update(['role_id' => $request->role]);
    $user->save();
    $user->update(['username' => $fnameFinalIncomingString]);
    $user->save();

    $roleName = $user->role()->name;

    return response()->json(['user' => $user, 'roleName' => $roleName, 'manager_exists' => '0']);
}
</code>```

答:
check your model User.
It has to have in

```<code>protected $fillable = ['username',....]
</code>```

then in your dev envirenoment using tinker debug updating username without mess you have.

in cmd

```<code>php artisan tinker
</code>```

Then

```<code>$user = \App\User::find(1);
$user->update(['username' => 'mytestname']);
</code>```

Body:
First is it checks if request form has the same username in the database and then the first name that is saved in the database to be compared with the request form. But it is not entering in the database I may have done something wrong when turning the strings into arrays or using the for loop to compare both strings but I can't spot the error can you help me?

if (User::where('username', $request->username)->exists()) {//check if request form has the same username in the database

    //first name that is saved in the database to be compared with the request form
    $fnameSavedInDatabase = DB::select('select first_name from users where username = ? and first_name != ?', [$request->username, $request->first_name]);

    //turn into array
    $fnameSavedInDatabaseArray = str_split($fnameSavedInDatabase);

    //request form value turn in to an array
    $fnameIncomingArray = str_split($request->first_name);

    //value that will be saved/updated in the database
    $fnameFinalIncomingString;

    for ($index = 0; $index < strlen($request->first_name); $index++) {
        if ($fnameIncomingArray[$index] == $fnameSavedInDatabaseArray[$index]) {
            $fnameFinalIncomingString = $fnameFinalIncomingString . $fnameIncomingArray[$index];
        }
    }

    $user = User::create($request->all());

    $user->update(['role_id' => $request->role]);
    $user->save();
    $user->update(['username' => $fnameFinalIncomingString]);
    $user->save();

    $roleName = $user->role()->name;

    return response()->json(['user' => $user, 'roleName' => $roleName, 'manager_exists' => '0']);
}

Body:
check your model User.
It has to have in

protected $fillable = ['username',....]

then in your dev envirenoment using tinker debug updating username without mess you have.

in cmd

php artisan tinker

Then

$user = \App\User::find(1);
$user->update(['username' => 'mytestname']);


问:
WordPress + jQuery Mobile - Synchronous XMLHttpRequest on the main thread is deprecated?
Why do I get these errors below after adding jquery mobile to my WordPress website?

```<code>Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ jquery.min.js?ver=3.1.1:4
ajax @ jquery.min.js?ver=3.1.1:4
a.ajax @ jquery-migrate.min.js?ver=3.0.0:2
r._evalUrl @ jquery.min.js?ver=3.1.1:4
Ia @ jquery.min.js?ver=3.1.1:3
append @ jquery.min.js?ver=3.1.1:3
r.fn.(anonymous function) @ jquery.min.js?ver=3.1.1:3
_include @ jquery.mobile.js:4790
(anonymous) @ jquery.mobile.js:890
(anonymous) @ jquery.mobile.js:4997
e @ jquery.min.js?ver=3.1.1:2
i @ jquery.min.js?ver=3.1.1:2
fireWith @ jquery.min.js?ver=3.1.1:2
A @ jquery.min.js?ver=3.1.1:4
(anonymous) @ jquery.min.js?ver=3.1.1:4

my-wordpress:1 IntersectionObserver.observe(target): target element is not a descendant of root.
</code>```

The WP just stopped working - when I click to the menu and I can see that URL has changed but the page content stay the same.

Any ideas?

This is how I add the jquery stuff in the function.php:

```<code>    // Load latest compiled and minified jquery.
    wp_enqueue_script( 'jquery-min', get_template_directory_uri() . '/node_modules/jquery/dist/jquery.min.js', array(), '3.1.1' );

    // Load latest compiled and minified jquery migrate.
    wp_enqueue_script( 'jquery-migrate-2', get_template_directory_uri() . '/node_modules/jquery-migrate/dist/jquery-migrate.min.js', array(), '3.0.0' );

    // Load latest compiled and minified jquery mobile.
    wp_enqueue_script( 'jquery-mobile', get_template_directory_uri() . '/node_modules/jquery-mobile/dist/jquery.mobile.min.js', array(), '1.4.1' );
</code>```

Notes: I don't have any AJAX call on my WP site.#

I found something odd at the bottom of my page - Loading:

What's that? Is not from me!

I use jQuery mobile because I need to touch and swipe images on mobile devices:

```<code>// bind scroll to anchor links
// http://stackoverflow.com/questions/11397028/document-click-function-for-touch-device
$(document).on("click touchstart", "a[href^='#']", function (e) {
  var id = $(this).attr("href");
  if ($(id).length > 0) {
    e.preventDefault();

    // trigger scroll
    scrollMagicController.scrollTo(id);

      // if supported by the browser we can even update the URL.
    if (window.history && window.history.pushState) {
      history.pushState("", document.title, id);
    }
  }
});

// Add swipe to carousel.
$("#myCarousel").swiperight(function() {
  $(this).carousel('prev');
});
$("#myCarousel").swipeleft(function() {
  $(this).carousel('next');
});
</code>```

答: The main thread is used for UI rendering. Here you're trying to make synchronous requests on this same thread, which would result in screen freezes while you waiting for the HttpResponse.</p>

Body:
Why do I get these errors below after adding jquery mobile to my WordPress website?

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ jquery.min.js?ver=3.1.1:4
ajax @ jquery.min.js?ver=3.1.1:4
a.ajax @ jquery-migrate.min.js?ver=3.0.0:2
r._evalUrl @ jquery.min.js?ver=3.1.1:4
Ia @ jquery.min.js?ver=3.1.1:3
append @ jquery.min.js?ver=3.1.1:3
r.fn.(anonymous function) @ jquery.min.js?ver=3.1.1:3
_include @ jquery.mobile.js:4790
(anonymous) @ jquery.mobile.js:890
(anonymous) @ jquery.mobile.js:4997
e @ jquery.min.js?ver=3.1.1:2
i @ jquery.min.js?ver=3.1.1:2
fireWith @ jquery.min.js?ver=3.1.1:2
A @ jquery.min.js?ver=3.1.1:4
(anonymous) @ jquery.min.js?ver=3.1.1:4

my-wordpress:1 IntersectionObserver.observe(target): target element is not a descendant of root.

The WP just stopped working - when I click to the menu and I can see that URL has changed but the page content stay the same.

Any ideas?

This is how I add the jquery stuff in the function.php:

    // Load latest compiled and minified jquery.
    wp_enqueue_script( 'jquery-min', get_template_directory_uri() . '/node_modules/jquery/dist/jquery.min.js', array(), '3.1.1' );

    // Load latest compiled and minified jquery migrate.
    wp_enqueue_script( 'jquery-migrate-2', get_template_directory_uri() . '/node_modules/jquery-migrate/dist/jquery-migrate.min.js', array(), '3.0.0' );

    // Load latest compiled and minified jquery mobile.
    wp_enqueue_script( 'jquery-mobile', get_template_directory_uri() . '/node_modules/jquery-mobile/dist/jquery.mobile.min.js', array(), '1.4.1' );

Notes: I don't have any AJAX call on my WP site.#

I found something odd at the bottom of my page - Loading:

What's that? Is not from me!

I use jQuery mobile because I need to touch and swipe images on mobile devices:

// bind scroll to anchor links
// http://stackoverflow.com/questions/11397028/document-click-function-for-touch-device
$(document).on("click touchstart", "a[href^='#']", function (e) {
  var id = $(this).attr("href");
  if ($(id).length > 0) {
    e.preventDefault();

    // trigger scroll
    scrollMagicController.scrollTo(id);

      // if supported by the browser we can even update the URL.
    if (window.history && window.history.pushState) {
      history.pushState("", document.title, id);
    }
  }
});

// Add swipe to carousel.
$("#myCarousel").swiperight(function() {
  $(this).carousel('prev');
});
$("#myCarousel").swipeleft(function() {
  $(this).carousel('next');
});


问:
Pandas column contents as index
I am trying to set a new pandas column using an existing pandas columns as set of indices to separate list, but I keep getting the following error:

```<code>TypeError: list indices must be integers or slices, not Series
</code>```

See code below:

```<code>import pandas as pd

monthvalues=[1,4,9,16,25,36,49,64,81,100,121,144]

df=pd.DataFrame([1,4,7,9], columns=['month'])

df['value']=monthvalues[df['month']-1]
</code>```

Expected result

```<code>    "month" "value"
0   1       1
1   4       16
2   7       49
3   9       81
</code>```

Note that this is just an example, I'm not actually trying to square the month digit in reality.

答:
If you construct a Series from the list you can pass this as a lookup using iloc and importantly convert the Series to a numpy array so it aligns correctly:

```<code>In [41]:
monthvalues=[1,4,9,16,25,36,49,64,81,100,121,144]
df=pd.DataFrame([1,4,7,9], columns=['month'])
df['value']=pd.Series(monthvalues).iloc[df['month']-1].values
df

Out[41]:
   month  value
0      1      1
1      4     16
2      7     49
3      9     81
</code>```

Title: Pandas column contents as index

Body:
I am trying to set a new pandas column using an existing pandas columns as set of indices to separate list, but I keep getting the following error:

TypeError: list indices must be integers or slices, not Series

See code below:

import pandas as pd

monthvalues=[1,4,9,16,25,36,49,64,81,100,121,144]

df=pd.DataFrame([1,4,7,9], columns=['month'])

df['value']=monthvalues[df['month']-1]

Expected result

    "month" "value"
0   1       1
1   4       16
2   7       49
3   9       81

Note that this is just an example, I'm not actually trying to square the month digit in reality.

Body:
If you construct a Series from the list you can pass this as a lookup using iloc and importantly convert the Series to a numpy array so it aligns correctly:

In [41]:
monthvalues=[1,4,9,16,25,36,49,64,81,100,121,144]
df=pd.DataFrame([1,4,7,9], columns=['month'])
df['value']=pd.Series(monthvalues).iloc[df['month']-1].values
df

Out[41]:
   month  value
0      1      1
1      4     16
2      7     49
3      9     81


问:
Set custom layout in popup window in android
I have a problem with popup window. I want to create popup window with my own layout.
This is code:

```<code>public class PopupWindowView extends PopupWindow{

    PopupWindow popup;
    boolean click = true;
    LayoutParams params;
    RelativeLayout mainLayout;
    TextView tv;
    LinearLayout layout;
    ImageView chooseFlag;

    public void createPopupWindow(Activity act){
        popup = new PopupWindow(act);
        chooseFlag = (ImageView) act.findViewById(R.id.login_choose_flag);
        mainLayout = (RelativeLayout) act.findViewById(R.id.login_layout);
        tv = new TextView(act);
        layout = new LinearLayout(act);
        //layout = (LinearLayout) findViewById(R.id.popuplayout);
        chooseFlag.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (click) {
                    int[] values = new int[2];
                    v.getLocationOnScreen(values);
                    popup.showAtLocation(mainLayout, Gravity.NO_GRAVITY, 10, 10);
                    popup.update(values[0], values[1], 300, 80);
                    click = false;
                } else {
                    popup.dismiss();
                    click = true;
                }
            }
        });
        params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        tv.setText("Hi this is a sample text for popup window");
        layout.addView(tv, params);
        popup.setContentView(layout);
    }
}
</code>```

and this is layout which I want to set in my popup window:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <LinearLayout
        android:id="@+id/popuplayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/patient_button_bg">
    </LinearLayout>

</LinearLayout>
</code>```

In my class I can't use findbyid method because this is not Activity. How I can set my own layout in popup widow in my class?

Edit:
this is stack trace where I get error:

```<code>03-01 09:48:48.761: E/AndroidRuntime(16776): FATAL EXCEPTION: main
03-01 09:48:48.761: E/AndroidRuntime(16776): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addViewInner(ViewGroup.java:3337)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addView(ViewGroup.java:3208)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addView(ViewGroup.java:3188)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.preparePopup(PopupWindow.java:969)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.showAtLocation(PopupWindow.java:840)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.showAtLocation(PopupWindow.java:813)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at pl.asseco.amms.mobile.tools.PopupWindowView$1.onClick(PopupWindowView.java:44)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.View.performClick(View.java:3558)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.View$PerformClick.run(View.java:14152)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Handler.handleCallback(Handler.java:605)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Looper.loop(Looper.java:137)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.app.ActivityThread.main(ActivityThread.java:4514)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at java.lang.reflect.Method.invokeNative(Native Method)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at java.lang.reflect.Method.invoke(Method.java:511)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at dalvik.system.NativeStart.main(Native Method)
</code>```

Edit
Activity which use popup:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getActionBar().hide();

    mainMenuGenerator = new MainMenuGenerator();
    mainMenuGenerator.generateMainMenu(this);
    mainMenuGenerator.hideIcons();
    popup = new PopupWindowView();

    popup.createPopupWindow(this);

}
</code>```

答:
```<code>    alert=(Button)findViewById(R.id.click);
    detail=(ImageView)findViewById(R.id.goDetail);

    alert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // custom dialog

            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.custom);
            dialog.setTitle(Html.fromHtml("<font color='#EC407A'>About</font>"));
            Button dialogButton = (Button) dialog.findViewById(R.id.dialogOK);
            ImageView img = (ImageView) dialog.findViewById(R.id.goDetail);
            // if button is clicked, close the custom dialog
            dialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT).show();
                }
            });
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    i=new Intent(getApplication(),CustomDetail.class);
                    setIntent(i);
                    Toast.makeText(Dashboard.this, "Check detail ", Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show();
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with popup window. I want to create popup window with my own layout.
This is code:

public class PopupWindowView extends PopupWindow{

    PopupWindow popup;
    boolean click = true;
    LayoutParams params;
    RelativeLayout mainLayout;
    TextView tv;
    LinearLayout layout;
    ImageView chooseFlag;

    public void createPopupWindow(Activity act){
        popup = new PopupWindow(act);
        chooseFlag = (ImageView) act.findViewById(R.id.login_choose_flag);
        mainLayout = (RelativeLayout) act.findViewById(R.id.login_layout);
        tv = new TextView(act);
        layout = new LinearLayout(act);
        //layout = (LinearLayout) findViewById(R.id.popuplayout);
        chooseFlag.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (click) {
                    int[] values = new int[2];
                    v.getLocationOnScreen(values);
                    popup.showAtLocation(mainLayout, Gravity.NO_GRAVITY, 10, 10);
                    popup.update(values[0], values[1], 300, 80);
                    click = false;
                } else {
                    popup.dismiss();
                    click = true;
                }
            }
        });
        params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        tv.setText("Hi this is a sample text for popup window");
        layout.addView(tv, params);
        popup.setContentView(layout);
    }
}

and this is layout which I want to set in my popup window:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <LinearLayout
        android:id="@+id/popuplayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/patient_button_bg">
    </LinearLayout>

</LinearLayout>

In my class I can't use findbyid method because this is not Activity. How I can set my own layout in popup widow in my class?

Edit:
this is stack trace where I get error:

03-01 09:48:48.761: E/AndroidRuntime(16776): FATAL EXCEPTION: main
03-01 09:48:48.761: E/AndroidRuntime(16776): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addViewInner(ViewGroup.java:3337)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addView(ViewGroup.java:3208)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.ViewGroup.addView(ViewGroup.java:3188)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.preparePopup(PopupWindow.java:969)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.showAtLocation(PopupWindow.java:840)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.widget.PopupWindow.showAtLocation(PopupWindow.java:813)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at pl.asseco.amms.mobile.tools.PopupWindowView$1.onClick(PopupWindowView.java:44)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.View.performClick(View.java:3558)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.view.View$PerformClick.run(View.java:14152)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Handler.handleCallback(Handler.java:605)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.os.Looper.loop(Looper.java:137)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at android.app.ActivityThread.main(ActivityThread.java:4514)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at java.lang.reflect.Method.invokeNative(Native Method)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at java.lang.reflect.Method.invoke(Method.java:511)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-01 09:48:48.761: E/AndroidRuntime(16776):    at dalvik.system.NativeStart.main(Native Method)

Edit
Activity which use popup:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getActionBar().hide();

    mainMenuGenerator = new MainMenuGenerator();
    mainMenuGenerator.generateMainMenu(this);
    mainMenuGenerator.hideIcons();
    popup = new PopupWindowView();

    popup.createPopupWindow(this);

}


问:
launch several computation in batch in a shell
I have 16 computation to do and I'd like to launch it in batch in order to use the 16 cores of my machine at the same time.
I'd like to do a shell script of this kind: </p>

```<code>#!/bin/ksh
for i in `seq 16`
do
  cd directory$i
  <batch command>
done
</code>```

<p>is it possible? </p>

答:
You can. You just have to ensure they run as background tasks, something like:

```<code>#!/bin/ksh
for i in `seq 16`
do
  cd directory$i
  <batch command> &
done
</code>```

Without that, it will just run the jobs sequentially. You may also want to ensure you wait for them all to finish as well, by using wait:

```<code>#!/bin/ksh
for i in `seq 16` ; do
  cd directory$i
  <batch command> &
done
wait # May depends on shell, bash/ksh waits for all
</code>```

Body:
I have 16 computation to do and I'd like to launch it in batch in order to use the 16 cores of my machine at the same time.
I'd like to do a shell script of this kind:

#!/bin/ksh
for i in `seq 16`
do
  cd directory$i
  <batch command>
done

is it possible?

Body:
You can. You just have to ensure they run as background tasks, something like:

#!/bin/ksh
for i in `seq 16`
do
  cd directory$i
  <batch command> &
done

Without that, it will just run the jobs sequentially. You may also want to ensure you wait for them all to finish as well, by using wait:

#!/bin/ksh
for i in `seq 16` ; do
  cd directory$i
  <batch command> &
done
wait # May depends on shell, bash/ksh waits for all


答:
You can subscribe defaultSource in OnInit method (with ngOnInit lifehook) and save source in variable if there is any new default source:

```<code>private currentDefaultSource: ISource;

public OnInit(): void {
    this.defaultSource$.subscribe(
        data => this.currentDefaultSource = data,
        error => console.log(error)
    );
}
</code>```

Now, you have subscription and saved default source which be automatically updated. After that, you can use ngIf to do simple comparision.

```<code><td>
    {{source.holdername}} <span *ngIf="source === currentDefaultSource" class="tag tag-warning">DEFAULT</span>
</td>
</code>```

If you want, you can create function in your component and check it there. In HTML:

```<code><td>
    {{source.holdername}} <span *ngIf="isDefaultSource(source)" class="tag tag-warning">DEFAULT</span>
</td>
</code>```

And in your component:

```<code>isDefaultSource(source: ISource): boolean {
   return this.currentDefaultSource === source
}
</code>```

Title: ngIf consition with observables

Body:
You can subscribe defaultSource in OnInit method (with ngOnInit lifehook) and save source in variable if there is any new default source:

private currentDefaultSource: ISource;

public OnInit(): void {
    this.defaultSource$.subscribe(
        data => this.currentDefaultSource = data,
        error => console.log(error)
    );
}

Now, you have subscription and saved default source which be automatically updated. After that, you can use ngIf to do simple comparision.

<td>
    {{source.holdername}} <span *ngIf="source === currentDefaultSource" class="tag tag-warning">DEFAULT</span>
</td>

If you want, you can create function in your component and check it there. In HTML:

<td>
    {{source.holdername}} <span *ngIf="isDefaultSource(source)" class="tag tag-warning">DEFAULT</span>
</td>

And in your component:

isDefaultSource(source: ISource): boolean {
   return this.currentDefaultSource === source
}


问:
CFQuery not saving time portion to Oracle Datetime field
I am having a problem using a datetime field in an Oracle database with Coldfusion with and don't know how to solve it.

I have a table (Subject) which contains a datetime field ("MODIFIED"). If I look the date I obtain 04-JAN-17 for instance. If I do this query:

select to_char(MODIFIED, 'DD-MM-YYYY HH24:MI:SS') from Subject

It returns:

04-01-2017 09:57:43

I can retrieve this same result in ColdFusion.

I then try to copy that data to another table with the same structure if the "MODIFIED" value has changed. For doing that I retrieved the data in a first query and insert it into the new table. The data is retrieved correctly. Especially the date (I can see it in the ColdFusion script). However, the time of the date is lost. So for instance, I obtain 04-01-2017 00:00:00 instead of 04-01-2017 09:57:43.

Here is the relevant part of my script:

Main page:

```<code><!-------- Get data -------->
<cfquery name="select_Subject_to_insert" datasource="#application.datasource#">
    SELECT CODE, MODIFIED, NAME FROM Subject
</query>

<cfloop query="select_Subject_to_insert">
    <!-------- Create an object "Subject" -------->
    <cfscript>
        subject_to_insert = createObject("component", "Subject").init();
        subject_to_insert.id = -1;
        subject_to_insert.Code = select_Subject_to_insert.CODE;
        subject_to_insert.modified = select_Subject_to_insert.MODIFIED;
        subject_to_insert.name = select_Subject_to_insert.NAME;
    </cfscript>
    <!-------- Call the function for saving data -------->
    saveSubject(subject_to_insert)
</cfloop>
</code>```

Main component:

```<code><!--- Function to save (update) Subject. --->
<cffunction name="saveSubject" returntype="string" access="remote">
    <cfargument name="subject" required="yes" type="vo.Subject" />
    <cfset var timestp = createTimeStamp() />

    <!--- insert --->
    <cfquery name="insertSubject" datasource="#application.datasource#" result="insertSubjectResult">
        insert into Subject (
            CODE,
            MODIFIED,
            NAME
            TIMESTAMP
        )values (
            <cfqueryparam value="#arguments.subject.CODE#" null="no" cfsqltype="cf_sql_varchar"/>,
            <cfqueryparam value="#arguments.subject.MODIFIED#" null="no" cfsqltype="cf_sql_date"/>,
            <cfqueryparam value="#arguments.subject.NAME#" null="no" cfsqltype="cf_sql_varchar"/>,
            <cfqueryparam value="#timestp#" null="no" cfsqltype="cf_sql_numeric"/>
        )
    </cfquery>

    ........................................

</cffunction>
</code>```

Could you please help me to understand why the time is not inserted correctly and solve the problem?

答:
You want to use:

```<code><cfqueryparam value="#arguments.subject.MODIFIED#" null="no" cfsqltype="cf_sql_timestamp"/>
</code>```

The cf_sql_date type does not have a time component whereas cf_sql_timestamp does. You can check the compatability matrix in the documentation to see that cf_sql_timestamp corresponds to the Oracle DATE data type.

You can also simplify your page to get rid of the function call (assuming it is not doing extra processing):

```<code><cfquery name="insertSubject" datasource="#application.datasource#" result="insertSubjectResult">
  insert into Subject (
    CODE,
    MODIFIED,
    NAME
    TIMESTAMP
  )
  SELECT code,
         modified,
         name,
         <cfqueryparam value=createTimeStamp() null="no" cfsqltype="cf_sql_numeric"/>
  FROM   subject
  -- WHERE some_condition
</cfquery>
</code>```

Body:
I am having a problem using a datetime field in an Oracle database with Coldfusion with and don't know how to solve it.

I have a table (Subject) which contains a datetime field ("MODIFIED"). If I look the date I obtain 04-JAN-17 for instance. If I do this query:

select to_char(MODIFIED, 'DD-MM-YYYY HH24:MI:SS') from Subject

It returns:

04-01-2017 09:57:43

I can retrieve this same result in ColdFusion.

I then try to copy that data to another table with the same structure if the "MODIFIED" value has changed. For doing that I retrieved the data in a first query and insert it into the new table. The data is retrieved correctly. Especially the date (I can see it in the ColdFusion script). However, the time of the date is lost. So for instance, I obtain 04-01-2017 00:00:00 instead of 04-01-2017 09:57:43.

Here is the relevant part of my script:

Main page:

<cfquery name="select_Subject_to_insert" datasource="#application.datasource#">
    SELECT CODE, MODIFIED, NAME FROM Subject
</query>

<cfloop query="select_Subject_to_insert">

    <cfscript>
        subject_to_insert = createObject("component", "Subject").init();
        subject_to_insert.id = -1;
        subject_to_insert.Code = select_Subject_to_insert.CODE;
        subject_to_insert.modified = select_Subject_to_insert.MODIFIED;
        subject_to_insert.name = select_Subject_to_insert.NAME;
    </cfscript>

    saveSubject(subject_to_insert)
</cfloop>

Main component:

<cffunction name="saveSubject" returntype="string" access="remote">
    <cfargument name="subject" required="yes" type="vo.Subject" />
    <cfset var timestp = createTimeStamp() />

    <cfquery name="insertSubject" datasource="#application.datasource#" result="insertSubjectResult">
        insert into Subject (
            CODE,
            MODIFIED,
            NAME
            TIMESTAMP
        )values (
            <cfqueryparam value="#arguments.subject.CODE#" null="no" cfsqltype="cf_sql_varchar"/>,
            <cfqueryparam value="#arguments.subject.MODIFIED#" null="no" cfsqltype="cf_sql_date"/>,
            <cfqueryparam value="#arguments.subject.NAME#" null="no" cfsqltype="cf_sql_varchar"/>,
            <cfqueryparam value="#timestp#" null="no" cfsqltype="cf_sql_numeric"/>
        )
    </cfquery>

    ........................................

</cffunction>

Could you please help me to understand why the time is not inserted correctly and solve the problem?

Body:
You want to use:

<cfqueryparam value="#arguments.subject.MODIFIED#" null="no" cfsqltype="cf_sql_timestamp"/>

The cf_sql_date type does not have a time component whereas cf_sql_timestamp does. You can check the compatability matrix in the documentation to see that cf_sql_timestamp corresponds to the Oracle DATE data type.

You can also simplify your page to get rid of the function call (assuming it is not doing extra processing):

<cfquery name="insertSubject" datasource="#application.datasource#" result="insertSubjectResult">
  insert into Subject (
    CODE,
    MODIFIED,
    NAME
    TIMESTAMP
  )
  SELECT code,
         modified,
         name,
         <cfqueryparam value=createTimeStamp() null="no" cfsqltype="cf_sql_numeric"/>
  FROM   subject
  -- WHERE some_condition
</cfquery>


问:
app.config file is not giving connection properly
I am on a desktop application and retrieving the list of databases on a local server
by this function

```<code>/// <summary>
/// This function populates the databases list in the drop down after the user is connected.
/// </summary>
public void BindDBDropDown()

        {

        //Create the connection object
        SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");

        //To Open the connection.
        sConnection.Open();

        //Query to select the list of databases.
        string selectDatabaseNames = @"SELECT
                                            NAME
                                        FROM
                                            MASTER..SYSDATABASES";

        //Create the command object
        SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);

        try
            {
            //Create the data set
            DataSet sDataset = new DataSet("master..sysdatabases");

            //Create the dataadapter object
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
            sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");

            //Fill the dataset
            sDataAdapter.Fill(sDataset);

            //Bind the database names in combobox
            DataViewManager dsv = sDataset.DefaultViewManager;

            //Provides the master mapping between the sourcr table and system.data.datatable
            cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
            cmbDatabases.DisplayMember = "NAME";
            cmbDatabases.ValueMember = ("NAME");
            }
        catch(Exception ex)
            {
            //All the exceptions are handled and written in the EventLog.
            EventLog logException = new EventLog("Application");
            logException.Source = "MFDBAnalyser";
            logException.WriteEntry(ex.Message);
            }
        finally
            {
            //If connection is not closed then close the connection
            if(sConnection.State != ConnectionState.Closed)
                {
                sConnection.Close();
                }
            }
        }
</code>```

This function is working fine if I am letting it to be hardcoded but when I tried to use the connection string declared in the app.config file as

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
  </appSettings>
</configuration>
</code>```

Then it is not working...

What I need to do??

答: This isnt anything to do with the fact you have left ; [semi-colon] off the end of the string is it?</p>

Body:
I am on a desktop application and retrieving the list of databases on a local server
by this function

///
/// This function populates the databases list in the drop down after the user is connected.
///
public void BindDBDropDown()

        {

        //Create the connection object
        SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");

        //To Open the connection.
        sConnection.Open();

        //Query to select the list of databases.
        string selectDatabaseNames = @"SELECT
                                            NAME
                                        FROM
                                            MASTER..SYSDATABASES";

        //Create the command object
        SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);

        try
            {
            //Create the data set
            DataSet sDataset = new DataSet("master..sysdatabases");

            //Create the dataadapter object
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
            sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");

            //Fill the dataset
            sDataAdapter.Fill(sDataset);

            //Bind the database names in combobox
            DataViewManager dsv = sDataset.DefaultViewManager;

            //Provides the master mapping between the sourcr table and system.data.datatable
            cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
            cmbDatabases.DisplayMember = "NAME";
            cmbDatabases.ValueMember = ("NAME");
            }
        catch(Exception ex)
            {
            //All the exceptions are handled and written in the EventLog.
            EventLog logException = new EventLog("Application");
            logException.Source = "MFDBAnalyser";
            logException.WriteEntry(ex.Message);
            }
        finally
            {
            //If connection is not closed then close the connection
            if(sConnection.State != ConnectionState.Closed)
                {
                sConnection.Close();
                }
            }
        }

This function is working fine if I am letting it to be hardcoded but when I tried to use the connection string declared in the app.config file as

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
  </appSettings>
</configuration>

Then it is not working...

What I need to do??


问:
How to merge multiple objects if for loop in Zend Framework 1.12
I need to get all products which belong to main category and its subcategories.
Controller part:

```<code>$categories = new Application_Model_DbTable_Categories();

$this->view->children = $categories->fetchAll($categories->select()->where('parent_category = ?', $this->view->category->category_id));

for ($i=0; $i < count($this->view->children); $i++) {
  $this->view->products = $products->fetchAll($products->select()->where('belongs_to_category = ?', $this->view->children[$i]->category_id));
}
</code>```

Then I'd like to display all in for loop in view part, which is easy.
The solution above does not work correctly, because during each iteration the result object is overwritten by new one.

How to concatenate these objects in 1 variable ($this->view->products)?

答:
Read before PHP manual ;)

```<code>$data = array();

for ($i=0; $i < count($this->view->children); $i++) {
  $data = $products->fetchAll($products->select()
                   ->where('belongs_to_category = ?', $this->view->children[$i]->category_id);
  $this->view->products = array_merge($this->view->products , $data);
}
</code>```

or

```<code>$data = array();
for ($i=0; $i < count($this->view->children); $i++) {
  $data[] = $this->view->children[$i]->category_id;
}
// here some error check - sizeof($data) > 0
$this->view->products = $products->fetchAll($products->select()
                                 ->where('belongs_to_category IN (?)', implode(',', $data));
</code>```

Body:
I need to get all products which belong to main category and its subcategories.
Controller part:

$categories = new Application_Model_DbTable_Categories();

$this->view->children = $categories->fetchAll($categories->select()->where('parent_category = ?', $this->view->category->category_id));

for ($i=0; $i < count($this->view->children); $i++) {
  $this->view->products = $products->fetchAll($products->select()->where('belongs_to_category = ?', $this->view->children[$i]->category_id));
}

Then I'd like to display all in for loop in view part, which is easy.
The solution above does not work correctly, because during each iteration the result object is overwritten by new one.

How to concatenate these objects in 1 variable ($this->view->products)?

Body:
Read before PHP manual ;)

$data = array();

for ($i=0; $i < count($this->view->children); $i++) {
  $data = $products->fetchAll($products->select()
                   ->where('belongs_to_category = ?', $this->view->children[$i]->category_id);
  $this->view->products = array_merge($this->view->products , $data);
}

or

$data = array();
for ($i=0; $i < count($this->view->children); $i++) {
  $data[] = $this->view->children[$i]->category_id;
}
// here some error check - sizeof($data) > 0
$this->view->products = $products->fetchAll($products->select()
                                 ->where('belongs_to_category IN (?)', implode(',', $data));


问:
JQuery .each() backwards
I'm using JQuery to select some elements on a page and then move them around in the DOM. The problem I'm having is I need to select all the elements in the reverse order that JQuery naturally wants to select them. For example:

```<code><ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
   <li>Item 5</li>
</ul>
</code>```

I want to select all the li items and use the .each() command on them but I want to start with Item 5, then Item 4 etc. Is this possible?

答:
If you don't want to save method into jQuery.fn you can use</p>

```<code>[].reverse.call($('li'));
</code>```

Title: JQuery .each() backwards

Body:
I'm using JQuery to select some elements on a page and then move them around in the DOM. The problem I'm having is I need to select all the elements in the reverse order that JQuery naturally wants to select them. For example:

Item 1

Item 2

Item 3

Item 4

Item 5

I want to select all the li items and use the .each() command on them but I want to start with Item 5, then Item 4 etc. Is this possible?

Body:
If you don't want to save method into jQuery.fn you can use

[].reverse.call($('li'));


问:
VARCHAR SQL contains numbers how to get 2 decimals after comma
I'm having some trouble getting the price to show correct on my website. Currently i have a row VerkoopPP40 which is a VARCHAR input. In this row there is a price e.g. 89,5 or just 9. When I try to get these values it does some unexpected things.

**** Update ****

I've just tried this code:

```<code><?php
function formatNumber($number, $format=[], $oldDecimalSeparator=",.·'", $multiplier=1)
{

    if ($format) {
        $format += ['numOfDecimals' => 0, 'decimalSeparator' => '.', 'thousandSeparator' => '']; # Default format
        # Find decimal separator
        # The decimal separator is the one that is the last and does not occur more than once
        if ($letters = str_replace(' ', '', $number)) { # Replace spaces
            if ($letters = preg_replace('/^-/', '', $letters)) { # Remove minus
                if ($letters = preg_replace('/[0-9]/', '', $letters)) { # Get all non digits
                    $lastletter = substr($letters, -1); # Returns last char
                    if (substr_count($letters, $lastletter) == 1) {
                        if (strpos($oldDecimalSeparator, $lastletter)  !== false)
                            $oldDecimalSep = $lastletter;
                        else
                            return $number;
                    }
                }
            }
        }
        $number = preg_replace('/[^0-9-]/', '', $number); # Remove all non digits except 'minus'
        if ($oldDecimalSep)
            $number = str_replace($oldDecimalSep, '.', $number); # Format to float
        if ($multiplier != 1)
            $number = $number * $multiplier;
        # Convert float to new format
        $number = number_format($number,
            $format['numOfDecimals'],
            $format['decimalSeparator'],
            $format['thousandSeparator']
        );
    }
    return $number;
}
</code>```

This returns: 9,00 and 895,00 so the comma is in a different place right now. It's something I guess... Anyone got an idea to move the comma and remove a 0.

**** End Update ****

And echo-ed it like this:

```<code><td><p>vanaf " . formatNumber($number, [
    'numOfDecimals' => 2,
    'decimalSeparator' => ',',
    'thousandSeparator' => ' '
], ',.') . " p.p. <small>Excl btw</small></p></td>
</code>```

If I just echo the VerkoopPP40 row it returns: €89,5 or €9.

So I googled around some and found this:

```<code>$var = $row["VerkoopPP40"];
$var = ltrim($var, '0');
$foo = $var;
$prijzen = number_format($foo, 2, ',', '');
</code>```

This turns the . into a ,. But also returns €9,00 for the row that has 9 in it. But the strange thing is the row that has 89.5 in it now just returns €89,00. So somewhere in the code it rounds the numbers down.

Does anyone know how to get the price to show just €9,00 and €89,50 respectively.

I tried the following codes as well:

```<code>SELECT ROUND(VerkoopPP40,2) AS RoundedPrice
</code>```

As database query. That didn't work.

```<code>$prijzen = CAST($prijzen as decimal(2,2));
</code>```

Also didn't work. Any more ideas?

答:
Don't know if this will help you, but found in the comments of the PHP doc : "To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people)..." read more</p>

```<code>$num1 = "89,5";
$num2 = str_replace(',', '.', $num1);

$price = number_format($num2, 2, '.', '');

echo"[ $price ]";
</code>```

Body:
I'm having some trouble getting the price to show correct on my website. Currently i have a row VerkoopPP40 which is a VARCHAR input. In this row there is a price e.g. 89,5 or just 9. When I try to get these values it does some unexpected things.

**** Update ****

I've just tried this code:

<?php
function formatNumber($number, $format=[], $oldDecimalSeparator=",.·'", $multiplier=1)
{

    if ($format) {
        $format += ['numOfDecimals' => 0, 'decimalSeparator' => '.', 'thousandSeparator' => '']; # Default format
        # Find decimal separator
        # The decimal separator is the one that is the last and does not occur more than once
        if ($letters = str_replace(' ', '', $number)) { # Replace spaces
            if ($letters = preg_replace('/^-/', '', $letters)) { # Remove minus
                if ($letters = preg_replace('/[0-9]/', '', $letters)) { # Get all non digits
                    $lastletter = substr($letters, -1); # Returns last char
                    if (substr_count($letters, $lastletter) == 1) {
                        if (strpos($oldDecimalSeparator, $lastletter)  !== false)
                            $oldDecimalSep = $lastletter;
                        else
                            return $number;
                    }
                }
            }
        }
        $number = preg_replace('/[^0-9-]/', '', $number); # Remove all non digits except 'minus'
        if ($oldDecimalSep)
            $number = str_replace($oldDecimalSep, '.', $number); # Format to float
        if ($multiplier != 1)
            $number = $number * $multiplier;
        # Convert float to new format
        $number = number_format($number,
            $format['numOfDecimals'],
            $format['decimalSeparator'],
            $format['thousandSeparator']
        );
    }
    return $number;
}

This returns: 9,00 and 895,00 so the comma is in a different place right now. It's something I guess... Anyone got an idea to move the comma and remove a 0.

**** End Update ****

And echo-ed it like this:

vanaf " . formatNumber($number, [
    'numOfDecimals' => 2,
    'decimalSeparator' => ',',
    'thousandSeparator' => ' '
], ',.') . " p.p. Excl btw

If I just echo the VerkoopPP40 row it returns: €89,5 or €9.

So I googled around some and found this:

$var = $row["VerkoopPP40"];
$var = ltrim($var, '0');
$foo = $var;
$prijzen = number_format($foo, 2, ',', '');

This turns the . into a ,. But also returns €9,00 for the row that has 9 in it. But the strange thing is the row that has 89.5 in it now just returns €89,00. So somewhere in the code it rounds the numbers down.

Does anyone know how to get the price to show just €9,00 and €89,50 respectively.

I tried the following codes as well:

SELECT ROUND(VerkoopPP40,2) AS RoundedPrice

As database query. That didn't work.

$prijzen = CAST($prijzen as decimal(2,2));

Also didn't work. Any more ideas?

Body:
Don't know if this will help you, but found in the comments of the PHP doc : "To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people)..." read more

$num1 = "89,5";
$num2 = str_replace(',', '.', $num1);

$price = number_format($num2, 2, '.', '');

echo"[ $price ]";


问:
Understanding Spring's Web Reactive Framework
I am currently developing an application with SpringBoot 2, spring-boot-starter-webflux on netty and jOOQ.

Below is the code that I have come up with after hours of research and stackoverflow searches. I have built in a lot of
logging in order to see what's happening on which thread.

UserController:

```<code>@RequestMapping(value = "/user", method = RequestMethod.POST)
public Mono<ResponseEntity<Integer>> createUser(@RequestBody ImUser user) {
    return Mono.just(user)
            .map(it -> {
                logger.debug("Receiving request on thread: " + Thread.currentThread().getName());
                return it;
            })
            .map(userService::create)
            .map(it -> {
                logger.debug("Sending response on thread: " + Thread.currentThread().getName());
                return ResponseEntity.status(HttpStatus.CREATED).body(it);
            })
            .mapError(DuplicateKeyException.class, e -> new SomeSpecialException(e.getMessage(), e));
}
</code>```

UserService:

```<code>public int create(ImUser user) {
    return Mono.just(user)
            .subscribeOn(Schedulers.elastic())
            .map(u -> {
                logger.debug("UserService thread: " + Thread.currentThread().getName());
                return imUserDao.insertUser(u);
            })
            .block();
}
</code>```

UserDao:

```<code>@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public int insertUser(ImUser user) {
    logger.debug("Insert DB on thread: " + Thread.currentThread().getName());
    return dsl.insertInto(IM_USER,IM_USER.VERSION, IM_USER.FIRST_NAME, IM_USER.LAST_NAME, IM_USER.BIRTHDATE, IM_USER.GENDER)
            .values(1, user.getFirstName(), user.getLastName(), user.getBirthdate(), user.getGender())
            .returning(IM_USER.ID)
            .fetchOne()
            .getId();
}
</code>```

The code works as expected, "Receiving request" and "Sending response" both run on the same thread (reactor-http-server-epoll-x)
while the blocking code ( the call to imUserDao.insertUser(u) ) runs on an elastic Scheduler thread (elastic-x).
The transaction is bound to the thread on which the annotated method is called (which is elastic-x) and thus works as expected (I have tested
it with a different method which is not posted here, to keep things simple).

Here is a log sample:

```<code>20:57:21,384 DEBUG         admin.UserController| Receiving request on thread: reactor-http-server-epoll-7
20:57:21,387 DEBUG            admin.UserService| UserService thread: elastic-2
20:57:21,391 DEBUG        admin.ExtendedUserDao| Insert DB on thread: elastic-2
20:57:21,393 DEBUG         tools.LoggerListener| Executing query
...
20:57:21,401 DEBUG              tools.StopWatch| Finishing                : Total: 9.355ms, +3.355ms
20:57:21,409 DEBUG         admin.UserController| Sending response on thread: reactor-http-server-epoll-7
</code>```

I have researched reactive programming for a long time now, but never quite got to program anything reactive. Now that I am, I am wondering if I am doing it correctly.
So here are my questions:

1. Is the code above a good way to handle incoming HTTP requests, query the DB and then respond?
Please ignore the logger.debug(...) calls which I have built in for the sake of my sanity :) I kind of expected to have a Flux< ImUser> as the argument to the controller method, in the sense that I have a stream of multiple potential requests
that will come at some point and will all be handled in the same way. Instead, the examples that I have found create a Mono.from(...); every time a request comes in.

2. The second Mono created in the UserService ( Mono.just(user) ) feels somewhat awkward. I understand that I need to start a new stream to be able to
run code on the elastic Scheduler, but isn't there an operator that does this?

3. From the way the code is written, I understand that the Mono inside the UserService will be blocked until the DB operation finishes,
 but the original stream, which serves the requests, isn't blocked. Is this correct?

4. I plan to replace Schedulers.elastic() with a parallel Scheduler where I can configure the number of worker threads. The idea is that the number of maximum worker threads should be the same as maximum DB connections.
 What will happen when all worker threads inside the Scheduler will be busy? Is that when backpressure jumps in?

5. I initially expected to have this code inside my controller:

```<code>return userService.create(user)
            .map(it -> ResponseEntity.status(HttpStatus.CREATED).body(it))
            .mapError(DuplicateKeyException.class, e -> new SomeSpecialException(e.getMessage(), e));
</code>```

but I have not been able to achieve that AND keep the things running in the correct threads. Is there any way to achieve this inside my code?

Any help would be greatly appreciated. Thanks!

答:
Service and Controller

The fact that your service is blocking is problematic, because then in the controller you are calling a blocking method from inside a map that isn't moved on a separate thread. This has the potential to block all controllers.

What you could do instead is return a Mono from UserService#create (remove the block() at the end). Since the service ensures that the Dao method call is isolated, it is less problematic. From there, no need to do Mono.just(user) in the Controller: just call create and start chaining operators directly on the resulting Mono:

```<code>@RequestMapping(value = "/user", method = RequestMethod.POST)
public Mono<ResponseEntity<Integer>> createUser(@RequestBody ImUser user) {
    //this log as you saw was executed in the same thread as the controller method
    logger.debug("Receiving request on thread: " + Thread.currentThread().getName());
    return userService.create(user)
        .map(it -> {
            logger.debug("Sending response on thread: " + Thread.currentThread().getName());
            return ResponseEntity.status(HttpStatus.CREATED).body(it);
        })
        .mapError(DuplicateKeyException.class, e -> new SomeSpecialException(e.getMessage(), e));
}
</code>```

Logging

Note that if you want to log something there are a couple better options than doing a map and returning it:

doOnNext method is tailored for that: react to one of the reactive signals (in this instance, onNext: a value is emitted) and perform some non-mutating action, leaving the output sequence exactly the same as the source sequence. The "side-effect" of the doOn can be writing to the console or incrementing statistic counters for instance... There's also doOnComplete, doOnError, doOnSubscribe, doOnCancel, etc...

log simply logs all events in the sequence above it. It will detect if you use SLF4J and use the configured logger at DEBUG level if so. Otherwise it'll use the JDK Logging features (so you also need to configure that to display DEBUG level logs).

A word about transactions or rather anything relying on ThreadLocal

ThreadLocal and thread-stickiness can be problematic in reactive programming, because there's less guarantee of the underlying execution model staying the same throughout a whole sequence. A Flux can execute in several steps, each in a different Scheduler (and so thread or thread pool). Even at a specific step, one value could be processed by thread A of the underlying thread pool while the next one, arriving later on, would be processed on thread B.

Relying on Thread Local is less straightforward in this context, and we are currently actively working on providing alternatives that fit better in the reactive world.

Your idea of making a pool of the size of the connection pool is good, but not necessarily sufficient, with the potential of several threads being used by a transactional flux, thus maybe polluting some threads with the transaction.

What happens when a pool runs out of threads

If you are using a particular Scheduler to isolate blocking behavior like here, once it runs out of threads it would throw a RejectedExecutionException.

Body:
I am currently developing an application with SpringBoot 2, spring-boot-starter-webflux on netty and jOOQ.

Below is the code that I have come up with after hours of research and stackoverflow searches. I have built in a lot of
logging in order to see what's happening on which thread.

UserController:

@RequestMapping(value = "/user", method = RequestMethod.POST)
public Mono<ResponseEntity<Integer>> createUser(@RequestBody ImUser user) {
    return Mono.just(user)
            .map(it -> {
                logger.debug("Receiving request on thread: " + Thread.currentThread().getName());
                return it;
            })
            .map(userService::create)
            .map(it -> {
                logger.debug("Sending response on thread: " + Thread.currentThread().getName());
                return ResponseEntity.status(HttpStatus.CREATED).body(it);
            })
            .mapError(DuplicateKeyException.class, e -> new SomeSpecialException(e.getMessage(), e));
}

UserService:

public int create(ImUser user) {
    return Mono.just(user)
            .subscribeOn(Schedulers.elastic())
            .map(u -> {
                logger.debug("UserService thread: " + Thread.currentThread().getName());
                return imUserDao.insertUser(u);
            })
            .block();
}

UserDao:

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public int insertUser(ImUser user) {
    logger.debug("Insert DB on thread: " + Thread.currentThread().getName());
    return dsl.insertInto(IM_USER,IM_USER.VERSION, IM_USER.FIRST_NAME, IM_USER.LAST_NAME, IM_USER.BIRTHDATE, IM_USER.GENDER)
            .values(1, user.getFirstName(), user.getLastName(), user.getBirthdate(), user.getGender())
            .returning(IM_USER.ID)
            .fetchOne()
            .getId();
}

The code works as expected, "Receiving request" and "Sending response" both run on the same thread (reactor-http-server-epoll-x)
while the blocking code ( the call to imUserDao.insertUser(u) ) runs on an elastic Scheduler thread (elastic-x).
The transaction is bound to the thread on which the annotated method is called (which is elastic-x) and thus works as expected (I have tested
it with a different method which is not posted here, to keep things simple).

Here is a log sample:

20:57:21,384 DEBUG         admin.UserController| Receiving request on thread: reactor-http-server-epoll-7
20:57:21,387 DEBUG            admin.UserService| UserService thread: elastic-2
20:57:21,391 DEBUG        admin.ExtendedUserDao| Insert DB on thread: elastic-2
20:57:21,393 DEBUG         tools.LoggerListener| Executing query
...
20:57:21,401 DEBUG              tools.StopWatch| Finishing                : Total: 9.355ms, +3.355ms
20:57:21,409 DEBUG         admin.UserController| Sending response on thread: reactor-http-server-epoll-7

I have researched reactive programming for a long time now, but never quite got to program anything reactive. Now that I am, I am wondering if I am doing it correctly.
So here are my questions:

1. Is the code above a good way to handle incoming HTTP requests, query the DB and then respond?
Please ignore the logger.debug(...) calls which I have built in for the sake of my sanity :) I kind of expected to have a Flux< ImUser> as the argument to the controller method, in the sense that I have a stream of multiple potential requests
that will come at some point and will all be handled in the same way. Instead, the examples that I have found create a Mono.from(...); every time a request comes in.

2. The second Mono created in the UserService ( Mono.just(user) ) feels somewhat awkward. I understand that I need to start a new stream to be able to
run code on the elastic Scheduler, but isn't there an operator that does this?

3. From the way the code is written, I understand that the Mono inside the UserService will be blocked until the DB operation finishes,
 but the original stream, which serves the requests, isn't blocked. Is this correct?

4. I plan to replace Schedulers.elastic() with a parallel Scheduler where I can configure the number of worker threads. The idea is that the number of maximum worker threads should be the same as maximum DB connections.
 What will happen when all worker threads inside the Scheduler will be busy? Is that when backpressure jumps in?

5. I initially expected to have this code inside my controller:

return userService.create(user)
            .map(it -> ResponseEntity.status(HttpStatus.CREATED).body(it))
            .mapError(DuplicateKeyException.class, e -> new SomeSpecialException(e.getMessage(), e));

but I have not been able to achieve that AND keep the things running in the correct threads. Is there any way to achieve this inside my code?

Any help would be greatly appreciated. Thanks!

Body:
Service and Controller

The fact that your service is blocking is problematic, because then in the controller you are calling a blocking method from inside a map that isn't moved on a separate thread. This has the potential to block all controllers.

What you could do instead is return a Mono from UserService#create (remove the block() at the end). Since the service ensures that the Dao method call is isolated, it is less problematic. From there, no need to do Mono.just(user) in the Controller: just call create and start chaining operators directly on the resulting Mono:

@RequestMapping(value = "/user", method = RequestMethod.POST)
public Mono<ResponseEntity<Integer>> createUser(@RequestBody ImUser user) {
    //this log as you saw was executed in the same thread as the controller method
    logger.debug("Receiving request on thread: " + Thread.currentThread().getName());
    return userService.create(user)
        .map(it -> {
            logger.debug("Sending response on thread: " + Thread.currentThread().getName());
            return ResponseEntity.status(HttpStatus.CREATED).body(it);
        })
        .mapError(DuplicateKeyException.class, e -> new SomeSpecialException(e.getMessage(), e));
}

Logging

Note that if you want to log something there are a couple better options than doing a map and returning it:

doOnNext method is tailored for that: react to one of the reactive signals (in this instance, onNext: a value is emitted) and perform some non-mutating action, leaving the output sequence exactly the same as the source sequence. The "side-effect" of the doOn can be writing to the console or incrementing statistic counters for instance... There's also doOnComplete, doOnError, doOnSubscribe, doOnCancel, etc...

log simply logs all events in the sequence above it. It will detect if you use SLF4J and use the configured logger at DEBUG level if so. Otherwise it'll use the JDK Logging features (so you also need to configure that to display DEBUG level logs).

A word about transactions or rather anything relying on ThreadLocal

ThreadLocal and thread-stickiness can be problematic in reactive programming, because there's less guarantee of the underlying execution model staying the same throughout a whole sequence. A Flux can execute in several steps, each in a different Scheduler (and so thread or thread pool). Even at a specific step, one value could be processed by thread A of the underlying thread pool while the next one, arriving later on, would be processed on thread B.

Relying on Thread Local is less straightforward in this context, and we are currently actively working on providing alternatives that fit better in the reactive world.

Your idea of making a pool of the size of the connection pool is good, but not necessarily sufficient, with the potential of several threads being used by a transactional flux, thus maybe polluting some threads with the transaction.

What happens when a pool runs out of threads

If you are using a particular Scheduler to isolate blocking behavior like here, once it runs out of threads it would throw a RejectedExecutionException.