问:
Technical detail regarding suspending and resuming a running thread
I have a class which use to perform currency exchange monitoring activities, and it is having ability to suspend and resume. I have the following questions regarding my class design.

Is it necessary to have has_started as volatile?

Is it necessary to have suspend as volatile? I had seen the example from Exampledepot, the flag is not marked as volatile.

When I catch InterruptedException during wait, shall I return, or shall I just ignore the exception?

Also, I am getting NetBeans warning on having multiple synchronized block. Is it a valid warning?

```<code>public synchronized void suspend() {
    synchronized(currencyExchangeRunnable) {
        suspend = true;
    }
}
</code>```

My first level synchronized are use to prevent multiple threads from executing suspend/resume/start/stop. And my second level of synchronized block, is to pair with wait/notify

My initial testing on suspend/resume/start/stop is that, they work as expected. However, I am not sure is there any other catches behind?

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author yccheok
 */
public class CurrencyExchangeMonitor {

    /**
     * Starts currency exchange monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void start() {
        if (has_started) {
            return;
        }
        executor.submit(currencyExchangeRunnable);
        has_started = true;
    }

    /**
     * Stop all currency exchange monitoring activities. Once it is stopped, it
     * cannot be started again. This method will only return once it is being
     * terminated completely. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void stop() {
        executor.shutdownNow();
        try {
            executor.awaitTermination(100, TimeUnit.DAYS);
        } catch (InterruptedException ex) {
            log.error(null, ex);
        }
    }

    /**
     * Temporary suspend all ongoing monitoring activities. This method can be
     * called multiple times. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void suspend() {
        synchronized(currencyExchangeRunnable) {
            suspend = true;
        }
    }

    /**
     * Resume all ongoing monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void resume() {
        synchronized(currencyExchangeRunnable) {
            suspend = false;
            currencyExchangeRunnable.notify();
        }
    }

    private class CurrencyExchangeRunnable implements Runnable {
        @Override
        public void run() {
            while (!executor.isShutdown()) {
                synchronized(this) {
                    while (suspend) {
                        try {
                            wait();
                        } catch (InterruptedException ex) {
                            log.error(null, ex);
                            // Usually triggered by executor.shutdownNow
                            return;
                        }
                    }
                }
            }
        }
    }

    private volatile boolean suspend = false;
    private volatile boolean has_started = false;
    private final CurrencyExchangeRunnable currencyExchangeRunnable = new CurrencyExchangeRunnable();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private static final Log log = LogFactory.getLog(CurrencyExchangeMonitor.class);
}
</code>```

答:
(1,2) Since both variables are accessed only in synchronized blocks, they need not be volatile.

(3) It's usually best to do something with InterruptedException.  If, however, you control all the code in the process and you never interrupt threads it can be ignored.

Nested synchronized blocks can lead to deadlocks if the code isn't written carefully.  You must always (all code paths) acquire the locks in the same order.

I agree with juskt on "Java Concurrency in Practice".  It's a very good book.

Body:
I have a class which use to perform currency exchange monitoring activities, and it is having ability to suspend and resume. I have the following questions regarding my class design.

Is it necessary to have has_started as volatile?

Is it necessary to have suspend as volatile? I had seen the example from Exampledepot, the flag is not marked as volatile.

When I catch InterruptedException during wait, shall I return, or shall I just ignore the exception?

Also, I am getting NetBeans warning on having multiple synchronized block. Is it a valid warning?

public synchronized void suspend() {
    synchronized(currencyExchangeRunnable) {
        suspend = true;
    }
}

My first level synchronized are use to prevent multiple threads from executing suspend/resume/start/stop. And my second level of synchronized block, is to pair with wait/notify

My initial testing on suspend/resume/start/stop is that, they work as expected. However, I am not sure is there any other catches behind?

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author yccheok
 */
public class CurrencyExchangeMonitor {

    /**
     * Starts currency exchange monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void start() {
        if (has_started) {
            return;
        }
        executor.submit(currencyExchangeRunnable);
        has_started = true;
    }

    /**
     * Stop all currency exchange monitoring activities. Once it is stopped, it
     * cannot be started again. This method will only return once it is being
     * terminated completely. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void stop() {
        executor.shutdownNow();
        try {
            executor.awaitTermination(100, TimeUnit.DAYS);
        } catch (InterruptedException ex) {
            log.error(null, ex);
        }
    }

    /**
     * Temporary suspend all ongoing monitoring activities. This method can be
     * called multiple times. start/stop/suspend/resume are being synchronized
     * with each others.
     */
    public synchronized void suspend() {
        synchronized(currencyExchangeRunnable) {
            suspend = true;
        }
    }

    /**
     * Resume all ongoing monitoring activities. This method can be called
     * multiple times. start/stop/suspend/resume are being synchronized with
     * each others.
     */
    public synchronized void resume() {
        synchronized(currencyExchangeRunnable) {
            suspend = false;
            currencyExchangeRunnable.notify();
        }
    }

    private class CurrencyExchangeRunnable implements Runnable {
        @Override
        public void run() {
            while (!executor.isShutdown()) {
                synchronized(this) {
                    while (suspend) {
                        try {
                            wait();
                        } catch (InterruptedException ex) {
                            log.error(null, ex);
                            // Usually triggered by executor.shutdownNow
                            return;
                        }
                    }
                }
            }
        }
    }

    private volatile boolean suspend = false;
    private volatile boolean has_started = false;
    private final CurrencyExchangeRunnable currencyExchangeRunnable = new CurrencyExchangeRunnable();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private static final Log log = LogFactory.getLog(CurrencyExchangeMonitor.class);
}


来源: stackexchange

问:
SoapFaultClientException: outputting detail
I have a org.springframework.ws.soap.client.SoapFaultClientException object. I would like to get the detail contained therein for logging purposes but am finding it difficult to identify how to do this.

The exception.getFaultStringOrReason() method will give me a basic error message. However, I need to get further details which are held in the object's fault details. The SOAP response looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<soap:Fault xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <faultcode>soap:Client</faultcode>
  <faultstring>The values from the client failed to pass validation.</faultstring>
  <detail>
    <Errors>
      <Error reason="Required on input.">
        <ErrorLocation>
          <Node level="1" name="MyElement"/>
          <Node level="2" name="MyField"/>
        </ErrorLocation>
        <Parameters/>
        <StackTrace/>
      </Error>
    </Errors>
  </detail>
</soap:Fault>
</code>```

I've got as far as iterating through a number of org.springframework.ws.soap.SoapFaultDetailElement objects but I cannot get the details contained therein. Can this be done?

Thanks in advance for any assistance

答:
This should work</p>

```<code>} catch (SoapFaultClientException e) {
    log.error(e);
    SoapFaultDetail soapFaultDetail = e.getSoapFault().getFaultDetail();
    SoapFaultDetailElement detailElementChild = (SoapFaultDetailElement) soapFaultDetail.getDetailEntries().next();
    Source detailSource = detailElementChild.getSource();

    try {
        return (JAXBElement<SearchResponse>) getWebServiceTemplate().getUnmarshaller().unmarshal(detailSource).getValue();
    } catch (IOException e1) {
        throw new IllegalArgumentException("cannot unmarshal SOAP fault detail object: " + soapFaultDetail.getSource());
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a org.springframework.ws.soap.client.SoapFaultClientException object. I would like to get the detail contained therein for logging purposes but am finding it difficult to identify how to do this.

The exception.getFaultStringOrReason() method will give me a basic error message. However, I need to get further details which are held in the object's fault details. The SOAP response looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Fault xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <faultcode>soap:Client</faultcode>
  <faultstring>The values from the client failed to pass validation.</faultstring>
  <detail>
    <Errors>
      <Error reason="Required on input.">
        <ErrorLocation>
          <Node level="1" name="MyElement"/>
          <Node level="2" name="MyField"/>
        </ErrorLocation>
        <Parameters/>
        <StackTrace/>
      </Error>
    </Errors>
  </detail>
</soap:Fault>

I've got as far as iterating through a number of org.springframework.ws.soap.SoapFaultDetailElement objects but I cannot get the details contained therein. Can this be done?

Thanks in advance for any assistance

Body:
This should work

} catch (SoapFaultClientException e) {
    log.error(e);
    SoapFaultDetail soapFaultDetail = e.getSoapFault().getFaultDetail();
    SoapFaultDetailElement detailElementChild = (SoapFaultDetailElement) soapFaultDetail.getDetailEntries().next();
    Source detailSource = detailElementChild.getSource();

    try {
        return (JAXBElement<SearchResponse>) getWebServiceTemplate().getUnmarshaller().unmarshal(detailSource).getValue();
    } catch (IOException e1) {
        throw new IllegalArgumentException("cannot unmarshal SOAP fault detail object: " + soapFaultDetail.getSource());
    }
}

ContentLicense: CC BY-SA 4.0


问:
Actionable messages for internal LOB workflows
Can i used actionable messages in Outlook for my internal LOB workflows?
I want it enabled only for my Office 365 organization</p>

答:
Yes, you can use actionable messages for your line of business workflows. Ensure that your action target URLs are internet reachable. As a developer you would have access to send actionable messages to yourself. To be able to send actionable messages to others you would have to register your email sender domain and action targets in the Actionable Messages Developer dashboard (in your case with the scope 'My Organization').

Actionable Messages Developer Dashboard

Documentation: Register your service


问:
jquery datatable - "jqueryui modal" is creating duplicate dialog html in the page
I am trying to implement jQuery datatable - jQuery UI modal functionality in my ASP.NET application. (as below)

https://datatables.net/extensions/responsive/examples/display-types/jqueryui-modal.html

The issue I am seeing is, the dialog is creating duplicate html entry in the page.

I can see the issue in the datatable website also (click on the plus sign in each row to launch the dialog. Duplicate html entry will be created.)

Any suggestion / recommendation to avoid duplicate entry will be appreciated.

答:
Ok, I really wanted to add something here to help many others. After trying all the work-arounds for this I learned something really important. If you load a complete DOM into the dialog window another instance is created and you will struggle big time. In my case, I am loading a partial view in MVC and sure enough it shows a complete DOM from  on. I've seen many posts about trying to destroy, remove, and even manually removing the duplicates with loops. These are not really answers but a band-aid for another problem. Also, when loading data in the dialog it is possible when doing an ajax call be careful you are not double loading scripts in the process. If you need to call $('.selector').dialog().dialog() then something is wrong the first instance has a conflict.

My solution which worked while none of the others did.
1) I modified my partial view placing a  to contain only the inner html I needed.
2) Fetching the data returns an entire DOM so I I used find() to limit what was returned in the dialog.
3) When closing the dialog use the dialog('close') method which is all that is required even according to the documentation.

If you have a refresh issue be careful constructing the dialog I opted to steer clear of the doc ready construct as it can sometimes cause conflicts. The dialog can be constructed when used.

Be careful what data is really being returned odd behavior will result.

And now it functions as expected as below I really hope this will save some hours of endless nothing for someone :) it worked for me.

```<code>var editOptDialog = YourOptions

Open:
         $("#dialog-edit").dialog(editOptDialog);
         $("#dialog-edit").dialog('open');
         $.get($(element).attr('url'), function (data) {
             $("#dialog-edit").dialog().html($(data).find('#content-modal'));
         });
Close:
         $("#dialog-edit").dialog().dialog("instance").close();
</code>```

Body:
Ok, I really wanted to add something here to help many others. After trying all the work-arounds for this I learned something really important. If you load a complete DOM into the dialog window another instance is created and you will struggle big time. In my case, I am loading a partial view in MVC and sure enough it shows a complete DOM from  on. I've seen many posts about trying to destroy, remove, and even manually removing the duplicates with loops. These are not really answers but a band-aid for another problem. Also, when loading data in the dialog it is possible when doing an ajax call be careful you are not double loading scripts in the process. If you need to call $('.selector').dialog().dialog() then something is wrong the first instance has a conflict.

My solution which worked while none of the others did.
1) I modified my partial view placing a  to contain only the inner html I needed.
2) Fetching the data returns an entire DOM so I I used find() to limit what was returned in the dialog.
3) When closing the dialog use the dialog('close') method which is all that is required even according to the documentation.

If you have a refresh issue be careful constructing the dialog I opted to steer clear of the doc ready construct as it can sometimes cause conflicts. The dialog can be constructed when used.

Be careful what data is really being returned odd behavior will result.

And now it functions as expected as below I really hope this will save some hours of endless nothing for someone :) it worked for me.

var editOptDialog = YourOptions

Open:
         $("#dialog-edit").dialog(editOptDialog);
         $("#dialog-edit").dialog('open');
         $.get($(element).attr('url'), function (data) {
             $("#dialog-edit").dialog().html($(data).find('#content-modal'));
         });
Close:
         $("#dialog-edit").dialog().dialog("instance").close();


问:
How to stop leaving the current page in Ionic 3?
According to Ionic 3 documentation, this is supposed to work:

```<code>ionViewWillLeave(): boolean {
    if (this.cantLeave) {
        let alert = this.alertCtrl.create({
            title: 'You can\'t leave',
            subTitle: 'You stay and work.',
            buttons: ['Oh sorry']
        });
        alert.present();
    }
    return this.cantLeave;
}
</code>```

Yet it doesn't. The alert appears, but the page changes nonetheless. However here it says that return true or return false will tell Ionic to carry on with the page change or stop it.
http://ionicframework.com/docs/api/navigation/NavController/

What am I doing wrong?

答:
You need to use Nav Guards.
Check the Nav Guards section here.

The lifecycle hook is ionViewCanLeave() not ionViewWillLeave

```<code>ionViewCanLeave(): boolean {
    if (this.cantLeave) {
        let alert = this.alertCtrl.create({
            title: 'You can\'t leave',
            subTitle: 'You stay and work.',
            buttons: ['Oh sorry']
        });
        alert.present();
    }
    return this.cantLeave;
}
</code>```

Body:
According to Ionic 3 documentation, this is supposed to work:

ionViewWillLeave(): boolean {
    if (this.cantLeave) {
        let alert = this.alertCtrl.create({
            title: 'You can\'t leave',
            subTitle: 'You stay and work.',
            buttons: ['Oh sorry']
        });
        alert.present();
    }
    return this.cantLeave;
}

Yet it doesn't. The alert appears, but the page changes nonetheless. However here it says that return true or return false will tell Ionic to carry on with the page change or stop it.
http://ionicframework.com/docs/api/navigation/NavController/

What am I doing wrong?

Body:
You need to use Nav Guards.
Check the Nav Guards section here.

The lifecycle hook is ionViewCanLeave() not ionViewWillLeave

ionViewCanLeave(): boolean {
    if (this.cantLeave) {
        let alert = this.alertCtrl.create({
            title: 'You can\'t leave',
            subTitle: 'You stay and work.',
            buttons: ['Oh sorry']
        });
        alert.present();
    }
    return this.cantLeave;
}


问:
Route Between two A and B location
There is no error but I can not get the location from my current location to what I search. Can someone please help. It says this with I click on the Car logo to get directions: MKDirectionsErrorCode=7, NSLocalizedDescription=Directions Not Available}

I am only missing the line to get to the direction. When I click on the car logo, it just does not do anything but zoom out to my current location. I am missing anything or did something wrong?

Here is my code:

```<code>  protocol HandleMapSearch {
        func dropPinZoomIn(placemark:MKPlacemark)
    }

    class ViewController: UIViewController  {

    @IBOutlet weak var mapView: MKMapView! // Handle the Map Kit View

    var selectedPin:MKPlacemark? = nil //Any incoming placemarks

    // Destination for directions*********
    var destination:MKMapItem = MKMapItem()
    var MyPosition = CLLocationCoordinate2D()

    var resultSearchController:UISearchController? = nil // Keep the UISearchController in memory after it's created

    var locationManager = CLLocationManager()  // Core Location

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest  // Accuracy level
        locationManager.requestWhenInUseAuthorization()  // Triggers the location permission dialog
        locationManager.startUpdatingLocation()
        //locationManager.requestLocation() // Trigers a one-time location request

        // Set up the search results table
        let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
        resultSearchController = UISearchController(searchResultsController: locationSearchTable)
        resultSearchController?.searchResultsUpdater = locationSearchTable

        // Set up the search bar
        let searchBar = resultSearchController!.searchBar
        searchBar.sizeToFit()
        searchBar.placeholder = "Search for places"
        navigationItem.titleView = resultSearchController?.searchBar

        // Configure the UISearchController appearance
        resultSearchController?.hidesNavigationBarDuringPresentation = false
        resultSearchController?.dimsBackgroundDuringPresentation = true
        definesPresentationContext = true

        locationSearchTable.mapView = mapView // Passes along a handle of the mapView

        locationSearchTable.handleMapSearchDelegate = self // Handles the map search

    }

    //Getting direction of location
    @objc func getDirections(sender: AnyObject){
       if let selectedPin = selectedPin {
            let mapItem = MKMapItem(placemark: selectedPin)
            //let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
            //mapItem.openInMaps(launchOptions: launchOptions)

            let request = MKDirectionsRequest()
            request.source = MKMapItem.forCurrentLocation()

            request.destination = destination
            request.requestsAlternateRoutes = false

            let directions = MKDirections(request: request)

        // 8.
        directions.calculate {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }

    }
       /*
        directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: Error!) in

            if error != nil {
                print("Error \(error)")

            } else {

                self.displayRout(response)

                var overlays = self.mapView.overlays

                for route in response.routes {

                    self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                    for next in route.steps {
                        print(next.instructions)
                    }
                }
            }
        })

    }
    */

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = UIColor.blue
            renderer.lineWidth = 4.0

            return renderer
        }
    }
        //destination = MKMapItem(placemark: selectedPin!)

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController : CLLocationManagerDelegate {
    // When user responds to the permission dialog
    private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
        locationManager.requestLocation()
    }
}

    // When location information comes back (Zoom to the user's current location)
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {

            //****
            MyPosition = location.coordinate
            locationManager.stopUpdatingLocation()

            let span = MKCoordinateSpanMake(0.01, 0.01)
            let region = MKCoordinateRegion(center: location.coordinate, span: span)
            mapView.setRegion(region, animated: true)

    }

}

    // Print out the error
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error finding location: \(error.localizedDescription)")
    }
}

// Searches the location and city/state
extension ViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        mapView.removeAnnotations(mapView.annotations)
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let city = placemark.locality,
            let state = placemark.administrativeArea {
            annotation.subtitle = "\(city) \(state)"
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }
}

// Shows Pins and Car Logo
extension ViewController : MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
        if annotation is MKUserLocation {
            //return nil so map view draws "blue dot" for standard user location
            return nil
        }
        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.pinTintColor = UIColor.red
        pinView?.canShowCallout = true
        let smallSquare = CGSize(width: 30, height: 30)
        let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
        button.setBackgroundImage(UIImage(named: "Car"), for: .normal)
        button.addTarget(self, action: #selector(getDirections), for: .touchUpInside)

        pinView?.leftCalloutAccessoryView = button
        return pinView

    }

}
</code>```

答:
Have a look at below code for reference hope it helps :

1 using two locations here as source and as destination and drawing a path according to locations

```<code>import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController,  MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        // Do any additional setup after loading the view, typically from a nib.

        let sourceLocation = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472)
        let destinationLocation = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564)

        // 3.
        let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
        let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)

        // 4.
        let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        // 5.
        let sourceAnnotation = MKPointAnnotation()
        sourceAnnotation.title = "Times Square"

        if let location = sourcePlacemark.location {
            sourceAnnotation.coordinate = location.coordinate
        }

        let destinationAnnotation = MKPointAnnotation()
        destinationAnnotation.title = "Empire State Building"

        if let location = destinationPlacemark.location {
            destinationAnnotation.coordinate = location.coordinate
        }

        // 6.
        self.mapView.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )

        // 7.
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceMapItem
        directionRequest.destination = destinationMapItem
        directionRequest.transportType = .walking

        // Calculate the direction
        let directions = MKDirections(request: directionRequest)

        // 8.
        directions.calculate {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }
    }
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 4.0

        return renderer
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Output :

Title: Route Between two A and B location

Body:
There is no error but I can not get the location from my current location to what I search. Can someone please help. It says this with I click on the Car logo to get directions: MKDirectionsErrorCode=7, NSLocalizedDescription=Directions Not Available}

I am only missing the line to get to the direction. When I click on the car logo, it just does not do anything but zoom out to my current location. I am missing anything or did something wrong?

Here is my code:

  protocol HandleMapSearch {
        func dropPinZoomIn(placemark:MKPlacemark)
    }

    class ViewController: UIViewController  {

    @IBOutlet weak var mapView: MKMapView! // Handle the Map Kit View

    var selectedPin:MKPlacemark? = nil //Any incoming placemarks

    // Destination for directions*********
    var destination:MKMapItem = MKMapItem()
    var MyPosition = CLLocationCoordinate2D()

    var resultSearchController:UISearchController? = nil // Keep the UISearchController in memory after it's created

    var locationManager = CLLocationManager()  // Core Location

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest  // Accuracy level
        locationManager.requestWhenInUseAuthorization()  // Triggers the location permission dialog
        locationManager.startUpdatingLocation()
        //locationManager.requestLocation() // Trigers a one-time location request

        // Set up the search results table
        let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
        resultSearchController = UISearchController(searchResultsController: locationSearchTable)
        resultSearchController?.searchResultsUpdater = locationSearchTable

        // Set up the search bar
        let searchBar = resultSearchController!.searchBar
        searchBar.sizeToFit()
        searchBar.placeholder = "Search for places"
        navigationItem.titleView = resultSearchController?.searchBar

        // Configure the UISearchController appearance
        resultSearchController?.hidesNavigationBarDuringPresentation = false
        resultSearchController?.dimsBackgroundDuringPresentation = true
        definesPresentationContext = true

        locationSearchTable.mapView = mapView // Passes along a handle of the mapView

        locationSearchTable.handleMapSearchDelegate = self // Handles the map search

    }

    //Getting direction of location
    @objc func getDirections(sender: AnyObject){
       if let selectedPin = selectedPin {
            let mapItem = MKMapItem(placemark: selectedPin)
            //let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
            //mapItem.openInMaps(launchOptions: launchOptions)

            let request = MKDirectionsRequest()
            request.source = MKMapItem.forCurrentLocation()

            request.destination = destination
            request.requestsAlternateRoutes = false

            let directions = MKDirections(request: request)

        // 8.
        directions.calculate {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }

    }
       /*
        directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: Error!) in

            if error != nil {
                print("Error \(error)")

            } else {

                self.displayRout(response)

                var overlays = self.mapView.overlays

                for route in response.routes {

                    self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                    for next in route.steps {
                        print(next.instructions)
                    }
                }
            }
        })

    }
    */

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = UIColor.blue
            renderer.lineWidth = 4.0

            return renderer
        }
    }
        //destination = MKMapItem(placemark: selectedPin!)

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController : CLLocationManagerDelegate {
    // When user responds to the permission dialog
    private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
        locationManager.requestLocation()
    }
}

    // When location information comes back (Zoom to the user's current location)
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {

            //****
            MyPosition = location.coordinate
            locationManager.stopUpdatingLocation()

            let span = MKCoordinateSpanMake(0.01, 0.01)
            let region = MKCoordinateRegion(center: location.coordinate, span: span)
            mapView.setRegion(region, animated: true)

    }

}

    // Print out the error
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error finding location: \(error.localizedDescription)")
    }
}

// Searches the location and city/state
extension ViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        mapView.removeAnnotations(mapView.annotations)
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let city = placemark.locality,
            let state = placemark.administrativeArea {
            annotation.subtitle = "\(city) \(state)"
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }
}

// Shows Pins and Car Logo
extension ViewController : MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
        if annotation is MKUserLocation {
            //return nil so map view draws "blue dot" for standard user location
            return nil
        }
        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.pinTintColor = UIColor.red
        pinView?.canShowCallout = true
        let smallSquare = CGSize(width: 30, height: 30)
        let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
        button.setBackgroundImage(UIImage(named: "Car"), for: .normal)
        button.addTarget(self, action: #selector(getDirections), for: .touchUpInside)

        pinView?.leftCalloutAccessoryView = button
        return pinView

    }

}

Body:
Have a look at below code for reference hope it helps :

1 using two locations here as source and as destination and drawing a path according to locations

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController,  MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        // Do any additional setup after loading the view, typically from a nib.

        let sourceLocation = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472)
        let destinationLocation = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564)

        // 3.
        let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
        let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)

        // 4.
        let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        // 5.
        let sourceAnnotation = MKPointAnnotation()
        sourceAnnotation.title = "Times Square"

        if let location = sourcePlacemark.location {
            sourceAnnotation.coordinate = location.coordinate
        }

        let destinationAnnotation = MKPointAnnotation()
        destinationAnnotation.title = "Empire State Building"

        if let location = destinationPlacemark.location {
            destinationAnnotation.coordinate = location.coordinate
        }

        // 6.
        self.mapView.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )

        // 7.
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceMapItem
        directionRequest.destination = destinationMapItem
        directionRequest.transportType = .walking

        // Calculate the direction
        let directions = MKDirections(request: directionRequest)

        // 8.
        directions.calculate {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }
    }
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 4.0

        return renderer
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Output :


问:
ng-dropdown-multiselect library not working for me
I found this cool library to do dropdown menus with angularjs + twitter-bootstrap-3, here:
http://dotansimha.github.io/angularjs-dropdown-multiselect/docs.

I am following the examples, I have this in my html:

```<code><div ng-dropdown-multiselect="" options="stringData" selected-model="stringModel" extra-settings="stringSettings">
</div>
</code>```

And this in my controller:

```<code>$scope.stringData = ['a', 'b', 'c'];

$scope.stringModel = [];

$scope.stringSettings = {
  template: '{{option}}',
  smartButtonTextConverter: function(skip, option) {
    return option;
  },
};
</code>```

And yet, absolutely nothing is being rendered to the page. :(

Anybody have any idea what might be wrong?

I have twitter-bootstrap-3, angularjs and ng-dropdown-multiselect loaded in this order:

```<code><script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angularjs-dropdown-multiselect/dist/src/angularjs-dropdown-multiselect.js"></script>
</code>```

答:
When I add the dependency here:

```<code>angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'ngDropdownMultiselect']);
</code>```

I get this error:

```<code>jquery.min.js:2 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module ngDropdownMultiselect due to:
Error: [$injector:nomod] Module 'ngDropdownMultiselect' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.6.1/$injector/nomod?p0=ngDropdownMultiselect
</code>```

So I checked the docs (again), and it says to use this instead

```<code>angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'angularjs-dropdown-multiselect']);
</code>```

now it "works"

ughh, gotta love front-end development lol

Body:
I found this cool library to do dropdown menus with angularjs + twitter-bootstrap-3, here:
http://dotansimha.github.io/angularjs-dropdown-multiselect/docs.

I am following the examples, I have this in my html:

And this in my controller:

$scope.stringData = ['a', 'b', 'c'];

$scope.stringModel = [];

$scope.stringSettings = {
  template: '{{option}}',
  smartButtonTextConverter: function(skip, option) {
    return option;
  },
};

And yet, absolutely nothing is being rendered to the page. :(

Anybody have any idea what might be wrong?

I have twitter-bootstrap-3, angularjs and ng-dropdown-multiselect loaded in this order:

Body:
When I add the dependency here:

angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'ngDropdownMultiselect']);

I get this error:

jquery.min.js:2 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module ngDropdownMultiselect due to:
Error: [$injector:nomod] Module 'ngDropdownMultiselect' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.6.1/$injector/nomod?p0=ngDropdownMultiselect

So I checked the docs (again), and it says to use this instead

angular.module('app', ['ui.router', 'ngAnimate', 'ngSanitize', 'angularjs-dropdown-multiselect']);

now it "works"

ughh, gotta love front-end development lol


问:
No Such Module 'FBSDKLoginKit' Xcode 9
Using CocoaPods, I have imported the below frameworks:

```<code>platform :ios, '11.0'
use frameworks!

target '{APP NAME}' do
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Core'
    pod 'Firebase/Database'
    pod 'Firebase/AdMob'
    pod 'Firebase/Messaging'
    pod 'Batch'
    pod 'FBSDKLoginKit'
    pod 'FBSDKCoreKit'
    pod 'Google-Mobile-Ads-SDK'
end
</code>```

When I build my project, it runs happily on my iPhone with no errors.

When I try to create an Archive of the project, it shows one of the below and refuses to build the project to Archive.

```<code>No such module 'FBSDKCoreKit'
No such module 'FBSDKLoginKit'
</code>```

I have no idea what I'm doing wrong as nothing has changed. I haven't archived in a few months and it's suddenly stopped working.

I've removed and re-installed the Pods but nothing seems to fix the issue.
Even if I remove one of the import statements the other FBSKD seems to fail.

答:
Try to update your pod file like this </p>

```<code> pod 'FacebookCore'
 pod 'FacebookLogin'
</code>```

Title: No Such Module 'FBSDKLoginKit' Xcode 9

Body:
Using CocoaPods, I have imported the below frameworks:

platform :ios, '11.0'
use frameworks!

target '{APP NAME}' do
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Core'
    pod 'Firebase/Database'
    pod 'Firebase/AdMob'
    pod 'Firebase/Messaging'
    pod 'Batch'
    pod 'FBSDKLoginKit'
    pod 'FBSDKCoreKit'
    pod 'Google-Mobile-Ads-SDK'
end

When I build my project, it runs happily on my iPhone with no errors.

When I try to create an Archive of the project, it shows one of the below and refuses to build the project to Archive.

No such module 'FBSDKCoreKit'
No such module 'FBSDKLoginKit'

I have no idea what I'm doing wrong as nothing has changed. I haven't archived in a few months and it's suddenly stopped working.

I've removed and re-installed the Pods but nothing seems to fix the issue.
Even if I remove one of the import statements the other FBSKD seems to fail.

Body:
Try to update your pod file like this

 pod 'FacebookCore'
 pod 'FacebookLogin'


问:
Changing image color on hover without having to change the image
This question is pretty basic, but I want to be sure there isn't an alternative method than what I currently do. Let's say I have a Facebook icon. As of now, when a user hovers over that image, I display a different image in order to change the color. Is there an alternative CSS method to doing this, so I am not using multiple images?

In the fiddle below, I tried changing the background, but that just covers the entire image.

.social-icon {
    width: 20px;
    height: 20px;
    transition: ease .3s;
    -webkit-transition: ease .3s;
    margin-right: 5px;
    cursor: pointer;
}
#facebook-icon {
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
    background-size: 20px 20px;
}
#facebook-icon:hover {
  background: #FFF;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="social-icon" id="facebook-icon"></div></code>```

jsFiddle

答:
If you use the Font Awesome Facebook icon, you can change of the color of it in the CSS that way.

#facebook-icon {
  color: grey;
}

#facebook-icon:hover {
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="social-icon" id="facebook-icon"><i class="fa fa-facebook"></i></div></code>```

Body:
This question is pretty basic, but I want to be sure there isn't an alternative method than what I currently do. Let's say I have a Facebook icon. As of now, when a user hovers over that image, I display a different image in order to change the color. Is there an alternative CSS method to doing this, so I am not using multiple images?

In the fiddle below, I tried changing the background, but that just covers the entire image.

.social-icon {
    width: 20px;
    height: 20px;
    transition: ease .3s;
    -webkit-transition: ease .3s;
    margin-right: 5px;
    cursor: pointer;
}
#facebook-icon {
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
    background-size: 20px 20px;
}
#facebook-icon:hover {
  background: #FFF;
}

jsFiddle

Body:
If you use the Font Awesome Facebook icon, you can change of the color of it in the CSS that way.

#facebook-icon {
  color: grey;
}

#facebook-icon:hover {
  color: blue;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="social-icon" id="facebook-icon"><i class="fa fa-facebook"></i></div>


问:
How to bind Database values to the DropDownList in C#
I have a sql server table ProjectDetails. The table has following columns ID(PK), ProjectID, Project. I need the values of ProjectID & Project to be populated into the 2 different dropdown list.

Model:

```<code>public class ViewModel
    {
        public int ID { get; set; }
        public string Project { get; set; }
        public string ProjectID { get; set; }

    }
</code>```

Controller:

```<code> [ActionName("DetailsForm")]
    [HttpGet]
    public ActionResult DetailsForm()
    {
        try
        {
            IEnumerable<ViewModel> dropConfig = new List<ViewModel>();

            IEnumerable<ViewModel> selectList = floorService.DropDownList();

            ViewModel model = new ViewModel()
         {

             dropConfig = selectList,

         };

            return View("DetailsForm",model);

        }
</code>```

I have difficulties in figuring out what should go under repository code where I need to execute the stored proc GetProjectDetails which will give me the data from Table ProjectDetails
Please help me with some examples where I can learn to go ahead with my solution. Thanks in advance.

答:
In ASP.NET MVC, Dropdownlist is generated with SelectList Helper Class, So You need to use Select List Item and You can send the value with ViewBag

```<code>ViewBag.SelectList= new SelectList(_classObject.YourClassMethod(), "DropDownListValue", "DropDownListText");
</code>```

In Razor View You Can Directly add it with Razor HTML Helper

```<code>@Html.DropDownList("SelectList", ViewBag.SelectList as SelectList,"Select Item", new {@class = "form-control" })
</code>```

Other Hand If You Want to Use Strongly Typed

```<code>@Html.DropDownListFor(model => model.SelectList, ViewBag.SelectListas SelectList, "Select Item", new { @class = "form-control" })
</code>```

Body:
I have a sql server table ProjectDetails. The table has following columns ID(PK), ProjectID, Project. I need the values of ProjectID & Project to be populated into the 2 different dropdown list.

Model:

public class ViewModel
    {
        public int ID { get; set; }
        public string Project { get; set; }
        public string ProjectID { get; set; }

    }

Controller:

 [ActionName("DetailsForm")]
    [HttpGet]
    public ActionResult DetailsForm()
    {
        try
        {
            IEnumerable<ViewModel> dropConfig = new List<ViewModel>();

            IEnumerable<ViewModel> selectList = floorService.DropDownList();

            ViewModel model = new ViewModel()
         {

             dropConfig = selectList,

         };

            return View("DetailsForm",model);

        }

I have difficulties in figuring out what should go under repository code where I need to execute the stored proc GetProjectDetails which will give me the data from Table ProjectDetails
Please help me with some examples where I can learn to go ahead with my solution. Thanks in advance.

Body:
In ASP.NET MVC, Dropdownlist is generated with SelectList Helper Class, So You need to use Select List Item and You can send the value with ViewBag

ViewBag.SelectList= new SelectList(_classObject.YourClassMethod(), "DropDownListValue", "DropDownListText");

In Razor View You Can Directly add it with Razor HTML Helper

@Html.DropDownList("SelectList", ViewBag.SelectList as SelectList,"Select Item", new {@class = "form-control" })

Other Hand If You Want to Use Strongly Typed

@Html.DropDownListFor(model => model.SelectList, ViewBag.SelectListas SelectList, "Select Item", new { @class = "form-control" })


问:
Why does x^(-1/0) = 0
The expression x^(1/0) results in undefined, and I suppose x^(-1/0) = 1/x^(1/0), but why does this equal 0? What exponent rule is at play here?

I thought (1/0) always returns undefined, so why would there be a difference if this exponent is in the numerator or denominator?

答:
Mathematically the limit of x tending to 0 of 1/x is infinity.

Under this scope you can think of 1/0 as a huge number (hn).

So the function x^(-1/0) which is the same as 1/(xˆ(hn)) can be looked at like this:

```<code>for x = 0, 0 to any power is still 0

for (0 < x < 1), x^(hn) will tend to be 0, hence we end up with 1/0 which tends to infinity.

for x = 1, xˆ(hn) will be 1

for x > 1, x^(hn) will tend to also be huge number, hence we end up with 1/(hn) which tends to be 0
</code>```

So the simple result of x^(-1/0) = 0 is not mathematically correct

Title: Why does x^(-1/0) = 0

Body:
Mathematically the limit of x tending to 0 of 1/x is infinity.

Under this scope you can think of 1/0 as a huge number (hn).

So the function x^(-1/0) which is the same as 1/(xˆ(hn)) can be looked at like this:

for x = 0, 0 to any power is still 0

for (0 < x < 1), x^(hn) will tend to be 0, hence we end up with 1/0 which tends to infinity.

for x = 1, xˆ(hn) will be 1

for x > 1, x^(hn) will tend to also be huge number, hence we end up with 1/(hn) which tends to be 0

So the simple result of x^(-1/0) = 0 is not mathematically correct


问:
Dates overwriting one another in php
Okay, so I'm trying to get two variables. One with yesterday's date, one with a date six days from today. This is so I can query google calendar for events happening this week.
I'm building a date time object, setting the date to today, then trying to store the values in two new variables. However, when I set the second variable, the first is getting modified as well. It appears to be assigning the variables by a reference to the object instead of the value I'm trying to stick into it.</p>

```<code>$todayData = explode("-", date("Y-m-d", Time()));
//Get DateTime for Yesterday
$today = new DateTime();
$today->setDate($todayData[0], $todayData[1], $todayData[2]);
echo $today->format("Y-m-d");
echo "<br />";
//Yesterday
$startDate = $today->modify("-1 day");
echo $startDate->format("Y-m-d");
echo "<br />";
//End of the week
$endDate = $today->modify("+6 day");
echo $endDate->format("Y-m-d");
echo "<br />";

//recheck yesterday
echo $startDate->format("Y-m-d");
</code>```

答:
As @Doug explained the reason why this isn't working is because $startDate and $endDate are referencing the same object.

Here's a quick solution: http://codepad.org/SKigfebO

Personally I wouldn't use the DateTime object. You can do this kind of operations using mktime:

```<code>$startDate = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('n'), date('j') - 1, date('Y')));
$endDate = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('n'), date('j') + 6, date('Y')));
</code>```

ContentLicense: CC BY-SA 2.5

Title: Dates overwriting one another in php

Body:
Okay, so I'm trying to get two variables. One with yesterday's date, one with a date six days from today. This is so I can query google calendar for events happening this week.
I'm building a date time object, setting the date to today, then trying to store the values in two new variables. However, when I set the second variable, the first is getting modified as well. It appears to be assigning the variables by a reference to the object instead of the value I'm trying to stick into it.

$todayData = explode("-", date("Y-m-d", Time()));
//Get DateTime for Yesterday
$today = new DateTime();
$today->setDate($todayData[0], $todayData[1], $todayData[2]);
echo $today->format("Y-m-d");
echo "
";
//Yesterday
$startDate = $today->modify("-1 day");
echo $startDate->format("Y-m-d");
echo "
";
//End of the week
$endDate = $today->modify("+6 day");
echo $endDate->format("Y-m-d");
echo "
";

//recheck yesterday
echo $startDate->format("Y-m-d");

Body:
As @Doug explained the reason why this isn't working is because $startDate and $endDate are referencing the same object.

Here's a quick solution: http://codepad.org/SKigfebO

Personally I wouldn't use the DateTime object. You can do this kind of operations using mktime:

$startDate = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('n'), date('j') - 1, date('Y')));
$endDate = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('n'), date('j') + 6, date('Y')));


问:
Build webpages using Python
I am very new to Python, as in I was just given a task a few minutes ago and it's the first time I've ever looked at Python. Basically, I have an index.html file, and a header and footer file, and then some other webpage files. I am trying to use Python to insert the selects webpage into the index.html page when loaded, with the header and footer already there. This is the code I received with some pseudo code shown with the #. </p>

```<code>#load main index.html
#mainHtml =
#mainHtml.replace('<!--HEADER_CONTENT-->', headerHtml)
#mainHtml.replace('<!--FOOTER_CONTENT-->', footerHtml)

copy_tree(srcLoc, buildLoc)
for dname, dirs, files in os.walk(buildLoc):
  for fname in files:
    fpath = os.path.join(dname, fname)
    #todo only use html
    print(fpath)
    if '.html' in fpath:
      print('html')
      #create whole html page
      #thisPageHtml =
      #minify
      #mainHtml_tmp is new mainHtml
      #mainHtml_tmp.replace('<!--PAGE_CONTENT-->', thisPageHtml)
      #write mainHtml_tmp to fpath
    if '.scss' in fpath:
      print('html')
      #compile to css & minify

    if '.js' in fpath:
      print('js')
      #minify
</code>```

<p>I was wondering if anyone could offer some help, guide me in the right direction, explain to me how to do this? Please let me know if I'm not being clear enough and I'll try to explain myself better. </p>

答:
Here is the relevant bit for opening up a file, assuming you know its path, and reading and writing the data

```<code>with open(FILE_PATH, 'r') as f:
    file_html = f.read()

mainHtml = mainHtml.replace('<!--FOOTER_CONTENT-->', file_html)

with open(OUTPUT_FILE_PATH, 'w') as fout:
    fout.write(mainHTML)
</code>```

You'll want to use the with open style instead of opening and closing a file manually. The open with handle closing the file once you leave the open block.

Also split code up into functions. having a single long script isn't going to benefit you for very long. For example to open a file and replace some text in a given string.

```<code>def open_and_replace(file_path, pattern_to_replace, string_to_format):
    # open the file and read data into a variable called `data`
    return string_to_format.replace(pattern_to_replace, data)
</code>```

Also note that there are various templating libraries out there, https://wiki.python.org/moin/Templating if you feel you could benefit from them

Title: Build webpages using Python

Body:
I am very new to Python, as in I was just given a task a few minutes ago and it's the first time I've ever looked at Python. Basically, I have an index.html file, and a header and footer file, and then some other webpage files. I am trying to use Python to insert the selects webpage into the index.html page when loaded, with the header and footer already there. This is the code I received with some pseudo code shown with the #.

#load main index.html
#mainHtml =
#mainHtml.replace('', headerHtml)
#mainHtml.replace('', footerHtml)

copy_tree(srcLoc, buildLoc)
for dname, dirs, files in os.walk(buildLoc):
  for fname in files:
    fpath = os.path.join(dname, fname)
    #todo only use html
    print(fpath)
    if '.html' in fpath:
      print('html')
      #create whole html page
      #thisPageHtml =
      #minify
      #mainHtml_tmp is new mainHtml
      #mainHtml_tmp.replace('', thisPageHtml)
      #write mainHtml_tmp to fpath
    if '.scss' in fpath:
      print('html')
      #compile to css & minify

    if '.js' in fpath:
      print('js')
      #minify

I was wondering if anyone could offer some help, guide me in the right direction, explain to me how to do this? Please let me know if I'm not being clear enough and I'll try to explain myself better.

Body:
Here is the relevant bit for opening up a file, assuming you know its path, and reading and writing the data

with open(FILE_PATH, 'r') as f:
    file_html = f.read()

mainHtml = mainHtml.replace('<!--FOOTER_CONTENT-->', file_html)

with open(OUTPUT_FILE_PATH, 'w') as fout:
    fout.write(mainHTML)

You'll want to use the with open style instead of opening and closing a file manually. The open with handle closing the file once you leave the open block.

Also split code up into functions. having a single long script isn't going to benefit you for very long. For example to open a file and replace some text in a given string.

def open_and_replace(file_path, pattern_to_replace, string_to_format):
    # open the file and read data into a variable called `data`
    return string_to_format.replace(pattern_to_replace, data)

Also note that there are various templating libraries out there, https://wiki.python.org/moin/Templating if you feel you could benefit from them


问:
Wordpress mysql query with many joins
Hey Guys i am trying to create something like facebook like
stuff

Friends_list Table

```<code> | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P
</code>```

User Table

```<code> | ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx
</code>```

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

```<code>SELECT DISTINCT u1.ID, u1.user_email, fl.status, ud.value, uad.image_name
FROM wp_users u1
LEFT JOIN Friends_list fl ON fl.Friend_id=u1.ID
LEFT JOIN user_details ud ON ud.user_id=u1.ID
LEFT JOIN user_additional_details uad ON uad.user_id=u1.ID
WHERE u1.ID != '".$user->ID."' AND fl.status NOT IN ('P', 'B')
</code>```

Any suggestions will be really appreciated.

答:
have you considered replacing:

```<code>WHERE u1.ID != '".$user->ID."' AND fl.status NOT IN ('P', 'B')
</code>```

with

```<code>WHERE u1.ID = '".$user->ID."' AND fl.status NOT IN ('P', 'B')
</code>```

?
can you explain what $user->id is ?

Title: Wordpress mysql query with many joins

Body:
Hey Guys i am trying to create something like facebook like
stuff

Friends_list Table

 | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P

User Table

 | ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

SELECT DISTINCT u1.ID, u1.user_email, fl.status, ud.value, uad.image_name
FROM wp_users u1
LEFT JOIN Friends_list fl ON fl.Friend_id=u1.ID
LEFT JOIN user_details ud ON ud.user_id=u1.ID
LEFT JOIN user_additional_details uad ON uad.user_id=u1.ID
WHERE u1.ID != '".$user->ID."' AND fl.status NOT IN ('P', 'B')

Any suggestions will be really appreciated.

Body:
have you considered replacing:

WHERE u1.ID != '".$user->ID."' AND fl.status NOT IN ('P', 'B')

with

WHERE u1.ID = '".$user->ID."' AND fl.status NOT IN ('P', 'B')

?
can you explain what $user->id is ?


问:
Parsing a Json to a ListView
I have this json form this URL: Website Here

The problem is that I'm trying to retrieve some of the data in the JSON like:  block_height, total, fees and size. I have 2 days trying to make it work but I have no idea why my code is not working. The last I've tried was showing the data in a alert dialog. But this isn't working yet.

JSON:

```<code>{
  "block_hash": "0000000000000397a165d83cc4640321a3b8ff4cce1f8aa2570deabf14ac14e7",
  "block_height": 154598,
  "block_index": 63,
  "hash": "b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da",
  "addresses": [
    "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV",
    "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG",
    "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
  ],
  "total": 100000000,
  "fees": 0,
  "size": 258,
  "preference": "low",
  "confirmed": "2011-11-24T11:45:54Z",
  "received": "2011-11-24T11:45:54Z",
  "ver": 1,
  "double_spend": false,
  "vin_sz": 1,
  "vout_sz": 2,
  "confirmations": 339633,
  "confidence": 1,
  "inputs": [
    {
      "prev_hash": "9fa4e0e33aba41623bc3618827d2a6495e6828ce04f26c97771a1369210e8201",
      "output_index": 2,
      "script": "48304502210098a2851420e4daba656fd79cb60cb565bd7218b6b117fda9a512ffbf17f8f178022005c61f31fef3ce3f906eb672e05b65f506045a65a80431b5eaf28e0999266993014104f0f86fa57c424deb160d0fc7693f13fce5ed6542c29483c51953e4fa87ebf247487ed79b1ddcf3de66b182217fcaf3fcef3fcb44737eb93b1fcb8927ebecea26",
      "output_value": 100000000,
      "sequence": 4294967295,
      "addresses": [
        "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
      ],
      "script_type": "pay-to-pubkey-hash",
      "age": 154567
    }
  ],
  "outputs": [
    {
      "value": 98000000,
      "script": "76a91429d6a3540acfa0a950bef2bfdc75cd51c24390fd88ac",
      "spent_by": "df0f8a4f0988de2875705a79ec826c8b9f8b08c9ffa4e5b4a5ea1b7bf956306c",
      "addresses": [
        "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG"
      ],
      "script_type": "pay-to-pubkey-hash"
    },
    {
      "value": 2000000,
      "script": "76a91417b5038a413f5c5ee288caa64cfab35a0c01914e88ac",
      "spent_by": "0c45329983279acf2f9e9c7976774ef11bdb2646d934836c53e6679281e09ac8",
      "addresses": [
        "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV"
      ],
      "script_type": "pay-to-pubkey-hash"
    }
  ]
}
</code>```

JAVA - Android Studio Fragment

```<code> private void setUpData() {
        // Retrieve the city data from the web service
        // In a worker thread since it's a network operation.
        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveData();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive Data", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveData() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL("https://api.blockcypher.com/v1/btc/main/txs/"+TxsHashs);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        }
        // Create markers for the city data.
        // Must run this on the UI thread since it's a UI operation.

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                try {
                    DataAdapter(json.toString());
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    private void DataAdapter(String json)
    {
        try
        {
            JSONObject jsonObject = new JSONObject(json);
            String block_height = jsonObject.getString("block_height");
            String total = jsonObject.getString("total");
            String fee = jsonObject.getString("fee");
            String size = jsonObject.getString("size");
            String received = jsonObject.getString("received");
            String confirmations = jsonObject.getString("confirmations");

            showalert(TxsHashs,received);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

    }

 private void showalert(String title, String msj)
    {
        AlertDialog.Builder MSGbox = new AlertDialog.Builder(getActivity());
        MSGbox.setTitle(title);
        String mensaje = msj;
        MSGbox.setMessage(mensaje)
                .setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog = MSGbox.create();
        alertDialog.show();
    }
</code>```

Please, someone Help Me

答:
Link to the working code

Add these to the build.gradle

```<code>compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:cardview-v7:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support:design:26.+'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.code.gson:gson:2.6.2'
</code>```

Create 3 model classes for Cyphers, Inputs, Outputs

```<code>package com.project.blockcypher.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;

public class Cyphers {
    @SerializedName("block_height")
    private int block_height;
    @SerializedName("block_index")
    private int block_index;
    @SerializedName("hash")
    private String hash;
    @SerializedName("addresses")
    private List<String> addresses;
    @SerializedName("total")
    private int total;
    @SerializedName("fees")
    private int fees;
    @SerializedName("size")
    private int size;
    @SerializedName("preference")
    private String preference;
    @SerializedName("relayed_by")
    private String relayed_by;
    @SerializedName("received")
    private String received;
    @SerializedName("ver")
    private int ver;
    @SerializedName("double_spend")
    private boolean double_spend;
    @SerializedName("vin_sz")
    private int vin_sz;
    @SerializedName("vout_sz")
    private int vout_sz;
    @SerializedName("confirmations")
    private int confirmations;
    @SerializedName("inputs")
    private List<Inputs> inputs;
    @SerializedName("outputs")
    private List<Outputs> outputs;

    public int getBlock_height() {
        return block_height;
    }

    public void setBlock_height(int block_height) {
        this.block_height = block_height;
    }

    public int getBlock_index() {
        return block_index;
    }

    public void setBlock_index(int block_index) {
        this.block_index = block_index;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public List<String> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<String> addresses) {
        this.addresses = addresses;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getFees() {
        return fees;
    }

    public void setFees(int fees) {
        this.fees = fees;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getPreference() {
        return preference;
    }

    public void setPreference(String preference) {
        this.preference = preference;
    }

    public String getRelayed_by() {
        return relayed_by;
    }

    public void setRelayed_by(String relayed_by) {
        this.relayed_by = relayed_by;
    }

    public String getReceived() {
        return received;
    }

    public void setReceived(String received) {
        this.received = received;
    }

    public int getVer() {
        return ver;
    }

    public void setVer(int ver) {
        this.ver = ver;
    }

    public boolean getDouble_spend() {
        return double_spend;
    }

    public void setDouble_spend(boolean double_spend) {
        this.double_spend = double_spend;
    }

    public int getVin_sz() {
        return vin_sz;
    }

    public void setVin_sz(int vin_sz) {
        this.vin_sz = vin_sz;
    }

    public int getVout_sz() {
        return vout_sz;
    }

    public void setVout_sz(int vout_sz) {
        this.vout_sz = vout_sz;
    }

    public int getConfirmations() {
        return confirmations;
    }

    public void setConfirmations(int confirmations) {
        this.confirmations = confirmations;
    }

    public List<Inputs> getInputs() {
        return inputs;
    }

    public void setInputs(List<Inputs> inputs) {
        this.inputs = inputs;
    }

    public List<Outputs> getOutputs() {
        return outputs;
    }

    public void setOutputs(List<Outputs> outputs) {
        this.outputs = outputs;
    }
}
</code>```

Code to MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

private String URL = "https://api.blockcypher.com/v1/btc/main/txs/b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da";
private RequestQueue mRequestQueue;
private Gson gson;

private static ArrayList<Cyphers> cyphersList = new ArrayList<>();

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

    if(mRequestQueue == null){
        mRequestQueue = Volley.newRequestQueue(this);
    }

    requestJsonThroughVolley();

}

private void requestJsonThroughVolley(){
    JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    gson = new Gson();
                    Cyphers cyphers;
                    cyphers = gson.fromJson(response.toString(), Cyphers.class);

                    String block_height = String.valueOf(cyphers.getBlock_height());
                    String total = String.valueOf(cyphers.getTotal());
                    String fee = String.valueOf(cyphers.getFees());
                    String size = String.valueOf(cyphers.getSize());
                    String received = String.valueOf(cyphers.getReceived());
                    String confirmations = String.valueOf(cyphers.getConfirmations());

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    mRequestQueue.add(objectRequest);
}

private void showalert(String title, String msj)
{
    AlertDialog.Builder MSGbox = new AlertDialog.Builder(this);
    MSGbox.setTitle(title);
    String mensaje = msj;
    MSGbox.setMessage(mensaje)
            .setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    AlertDialog alertDialog = MSGbox.create();
    alertDialog.show();
}

}
</code>```

Title: Parsing a Json to a ListView

Body:
I have this json form this URL: Website Here

The problem is that I'm trying to retrieve some of the data in the JSON like:  block_height, total, fees and size. I have 2 days trying to make it work but I have no idea why my code is not working. The last I've tried was showing the data in a alert dialog. But this isn't working yet.

JSON:

{
  "block_hash": "0000000000000397a165d83cc4640321a3b8ff4cce1f8aa2570deabf14ac14e7",
  "block_height": 154598,
  "block_index": 63,
  "hash": "b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da",
  "addresses": [
    "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV",
    "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG",
    "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
  ],
  "total": 100000000,
  "fees": 0,
  "size": 258,
  "preference": "low",
  "confirmed": "2011-11-24T11:45:54Z",
  "received": "2011-11-24T11:45:54Z",
  "ver": 1,
  "double_spend": false,
  "vin_sz": 1,
  "vout_sz": 2,
  "confirmations": 339633,
  "confidence": 1,
  "inputs": [
    {
      "prev_hash": "9fa4e0e33aba41623bc3618827d2a6495e6828ce04f26c97771a1369210e8201",
      "output_index": 2,
      "script": "48304502210098a2851420e4daba656fd79cb60cb565bd7218b6b117fda9a512ffbf17f8f178022005c61f31fef3ce3f906eb672e05b65f506045a65a80431b5eaf28e0999266993014104f0f86fa57c424deb160d0fc7693f13fce5ed6542c29483c51953e4fa87ebf247487ed79b1ddcf3de66b182217fcaf3fcef3fcb44737eb93b1fcb8927ebecea26",
      "output_value": 100000000,
      "sequence": 4294967295,
      "addresses": [
        "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
      ],
      "script_type": "pay-to-pubkey-hash",
      "age": 154567
    }
  ],
  "outputs": [
    {
      "value": 98000000,
      "script": "76a91429d6a3540acfa0a950bef2bfdc75cd51c24390fd88ac",
      "spent_by": "df0f8a4f0988de2875705a79ec826c8b9f8b08c9ffa4e5b4a5ea1b7bf956306c",
      "addresses": [
        "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG"
      ],
      "script_type": "pay-to-pubkey-hash"
    },
    {
      "value": 2000000,
      "script": "76a91417b5038a413f5c5ee288caa64cfab35a0c01914e88ac",
      "spent_by": "0c45329983279acf2f9e9c7976774ef11bdb2646d934836c53e6679281e09ac8",
      "addresses": [
        "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV"
      ],
      "script_type": "pay-to-pubkey-hash"
    }
  ]
}

JAVA - Android Studio Fragment

 private void setUpData() {
        // Retrieve the city data from the web service
        // In a worker thread since it's a network operation.
        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveData();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive Data", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveData() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL("https://api.blockcypher.com/v1/btc/main/txs/"+TxsHashs);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        }
        // Create markers for the city data.
        // Must run this on the UI thread since it's a UI operation.

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                try {
                    DataAdapter(json.toString());
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    private void DataAdapter(String json)
    {
        try
        {
            JSONObject jsonObject = new JSONObject(json);
            String block_height = jsonObject.getString("block_height");
            String total = jsonObject.getString("total");
            String fee = jsonObject.getString("fee");
            String size = jsonObject.getString("size");
            String received = jsonObject.getString("received");
            String confirmations = jsonObject.getString("confirmations");

            showalert(TxsHashs,received);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

    }

 private void showalert(String title, String msj)
    {
        AlertDialog.Builder MSGbox = new AlertDialog.Builder(getActivity());
        MSGbox.setTitle(title);
        String mensaje = msj;
        MSGbox.setMessage(mensaje)
                .setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog = MSGbox.create();
        alertDialog.show();
    }

Please, someone Help Me

Body:
Link to the working code

Add these to the build.gradle

compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:cardview-v7:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support:design:26.+'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.code.gson:gson:2.6.2'

Create 3 model classes for Cyphers, Inputs, Outputs

package com.project.blockcypher.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;

public class Cyphers {
    @SerializedName("block_height")
    private int block_height;
    @SerializedName("block_index")
    private int block_index;
    @SerializedName("hash")
    private String hash;
    @SerializedName("addresses")
    private List<String> addresses;
    @SerializedName("total")
    private int total;
    @SerializedName("fees")
    private int fees;
    @SerializedName("size")
    private int size;
    @SerializedName("preference")
    private String preference;
    @SerializedName("relayed_by")
    private String relayed_by;
    @SerializedName("received")
    private String received;
    @SerializedName("ver")
    private int ver;
    @SerializedName("double_spend")
    private boolean double_spend;
    @SerializedName("vin_sz")
    private int vin_sz;
    @SerializedName("vout_sz")
    private int vout_sz;
    @SerializedName("confirmations")
    private int confirmations;
    @SerializedName("inputs")
    private List<Inputs> inputs;
    @SerializedName("outputs")
    private List<Outputs> outputs;

    public int getBlock_height() {
        return block_height;
    }

    public void setBlock_height(int block_height) {
        this.block_height = block_height;
    }

    public int getBlock_index() {
        return block_index;
    }

    public void setBlock_index(int block_index) {
        this.block_index = block_index;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public List<String> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<String> addresses) {
        this.addresses = addresses;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getFees() {
        return fees;
    }

    public void setFees(int fees) {
        this.fees = fees;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getPreference() {
        return preference;
    }

    public void setPreference(String preference) {
        this.preference = preference;
    }

    public String getRelayed_by() {
        return relayed_by;
    }

    public void setRelayed_by(String relayed_by) {
        this.relayed_by = relayed_by;
    }

    public String getReceived() {
        return received;
    }

    public void setReceived(String received) {
        this.received = received;
    }

    public int getVer() {
        return ver;
    }

    public void setVer(int ver) {
        this.ver = ver;
    }

    public boolean getDouble_spend() {
        return double_spend;
    }

    public void setDouble_spend(boolean double_spend) {
        this.double_spend = double_spend;
    }

    public int getVin_sz() {
        return vin_sz;
    }

    public void setVin_sz(int vin_sz) {
        this.vin_sz = vin_sz;
    }

    public int getVout_sz() {
        return vout_sz;
    }

    public void setVout_sz(int vout_sz) {
        this.vout_sz = vout_sz;
    }

    public int getConfirmations() {
        return confirmations;
    }

    public void setConfirmations(int confirmations) {
        this.confirmations = confirmations;
    }

    public List<Inputs> getInputs() {
        return inputs;
    }

    public void setInputs(List<Inputs> inputs) {
        this.inputs = inputs;
    }

    public List<Outputs> getOutputs() {
        return outputs;
    }

    public void setOutputs(List<Outputs> outputs) {
        this.outputs = outputs;
    }
}

Code to MainActivity.java

public class MainActivity extends AppCompatActivity {

private String URL = "https://api.blockcypher.com/v1/btc/main/txs/b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da";
private RequestQueue mRequestQueue;
private Gson gson;

private static ArrayList<Cyphers> cyphersList = new ArrayList<>();

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

    if(mRequestQueue == null){
        mRequestQueue = Volley.newRequestQueue(this);
    }

    requestJsonThroughVolley();

}

private void requestJsonThroughVolley(){
    JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    gson = new Gson();
                    Cyphers cyphers;
                    cyphers = gson.fromJson(response.toString(), Cyphers.class);

                    String block_height = String.valueOf(cyphers.getBlock_height());
                    String total = String.valueOf(cyphers.getTotal());
                    String fee = String.valueOf(cyphers.getFees());
                    String size = String.valueOf(cyphers.getSize());
                    String received = String.valueOf(cyphers.getReceived());
                    String confirmations = String.valueOf(cyphers.getConfirmations());

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    mRequestQueue.add(objectRequest);
}

private void showalert(String title, String msj)
{
    AlertDialog.Builder MSGbox = new AlertDialog.Builder(this);
    MSGbox.setTitle(title);
    String mensaje = msj;
    MSGbox.setMessage(mensaje)
            .setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    AlertDialog alertDialog = MSGbox.create();
    alertDialog.show();
}

}


问:
CSS JavaScript LightBox Gallery
I am trying to make CSS & JS lightbox gallery, but I have got some trouble with navigation arrows. I tried to copy and paste the code from here.

Everything is working just fine except the navigation arrows.

As you can see there are two arrows on the right side and on the left side. I tried a different browser but the result is the same. What am I doing wrong? Thank you.

My code is the same as from the linked w3school's page. I'm trying this code on the WordPress page.

答:
If your do not show your code we cannot find your error check it below its working fine

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: Verdana, sans-serif;
  margin: 0;
}

* {
  box-sizing: border-box;
}

.row > .column {
  padding: 0 8px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.column {
  float: left;
  width: 25%;
}

/* The Modal (background) */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: black;
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  width: 90%;
  max-width: 1200px;
}

/* The Close Button */
.close {
  color: white;
  position: absolute;
  top: 10px;
  right: 25px;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #999;
  text-decoration: none;
  cursor: pointer;
}

.mySlides {
  display: none;
}

.cursor {
  cursor: pointer
}

/* Next & previous buttons */
.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -50px;
  color: white;
  font-weight: bold;
  font-size: 20px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  -webkit-user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

img {
  margin-bottom: -4px;
}

.caption-container {
  text-align: center;
  background-color: black;
  padding: 2px 16px;
  color: white;
}

.demo {
  opacity: 0.6;
}

.active,
.demo:hover {
  opacity: 1;
}

img.hover-shadow {
  transition: 0.3s
}

.hover-shadow:hover {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}</code>```

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Lightbox

  ×

1 / 4

2 / 4

3 / 4

4 / 4

    ❮
    ❯

```

Title: CSS JavaScript LightBox Gallery

Body:
If your do not show your code we cannot find your error check it below its working fine

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}

body {
  font-family: Verdana, sans-serif;
  margin: 0;
}

* {
  box-sizing: border-box;
}

.row > .column {
  padding: 0 8px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.column {
  float: left;
  width: 25%;
}

/* The Modal (background) */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: black;
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  width: 90%;
  max-width: 1200px;
}

/* The Close Button */
.close {
  color: white;
  position: absolute;
  top: 10px;
  right: 25px;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #999;
  text-decoration: none;
  cursor: pointer;
}

.mySlides {
  display: none;
}

.cursor {
  cursor: pointer
}

/* Next & previous buttons */
.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -50px;
  color: white;
  font-weight: bold;
  font-size: 20px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  -webkit-user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

img {
  margin-bottom: -4px;
}

.caption-container {
  text-align: center;
  background-color: black;
  padding: 2px 16px;
  color: white;
}

.demo {
  opacity: 0.6;
}

.active,
.demo:hover {
  opacity: 1;
}

img.hover-shadow {
  transition: 0.3s
}

.hover-shadow:hover {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<h2 style="text-align:center">Lightbox</h2>

<div class="row">
  <div class="column">
    <img src="https://www.w3schools.com/howto/img_nature.jpg" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
  </div>
  <div class="column">
    <img src="https://www.w3schools.com/howto/img_fjords.jpg" style="width:100%" onclick="openModal();currentSlide(2)" class="hover-shadow cursor">
  </div>
  <div class="column">
    <img src="https://www.w3schools.com/howto/img_mountains.jpg" style="width:100%" onclick="openModal();currentSlide(3)" class="hover-shadow cursor">
  </div>
  <div class="column">
    <img src="https://www.w3schools.com/howto/img_lights.jpg" style="width:100%" onclick="openModal();currentSlide(4)" class="hover-shadow cursor">
  </div>
</div>

<div id="myModal" class="modal">
  <span class="close cursor" onclick="closeModal()">&times;</span>
  <div class="modal-content">

    <div class="mySlides">
      <div class="numbertext">1 / 4</div>
      <img src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width:100%">
    </div>

    <div class="mySlides">
      <div class="numbertext">2 / 4</div>
      <img src="https://www.w3schools.com/howto/img_fjords_wide.jpg" style="width:100%">
    </div>

    <div class="mySlides">
      <div class="numbertext">3 / 4</div>
      <img src="https://www.w3schools.com/howto/img_mountains_wide.jpg" style="width:100%">
    </div>

    <div class="mySlides">
      <div class="numbertext">4 / 4</div>
      <img src="https://www.w3schools.com/howto/img_lights_wide.jpg" style="width:100%">
    </div>

    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>

    <div class="caption-container">
      <p id="caption"></p>
    </div>

    <div class="column">
      <img class="demo cursor" src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width:100%" onclick="currentSlide(1)" alt="Nature and sunrise">
    </div>
    <div class="column">
      <img class="demo cursor" src="https://www.w3schools.com/howto/img_fjords_wide.jpg" style="width:100%" onclick="currentSlide(2)" alt="Trolltunga, Norway">
    </div>
    <div class="column">
      <img class="demo cursor" src="https://www.w3schools.com/howto/img_mountains_wide.jpg" style="width:100%" onclick="currentSlide(3)" alt="Mountains and fjords">
    </div>
    <div class="column">
      <img class="demo cursor" src="https://www.w3schools.com/howto/img_lights_wide.jpg" style="width:100%" onclick="currentSlide(4)" alt="Northern Lights">
    </div>
  </div>
</div>