问:
How to reload the page while moving from tab bar in swift 3?
Here after running the application i had clicked on cart in tab bar at that time there was no items added in cart so it shown your shopping cart is empty but after adding items in cart then I clicked on cart icon on tab bar also it is showing like as in previous and the cart page was not reloading can anyone help me how to resolve this ?

I had used this code in my home view controller

```<code>func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 1 {
            let  navController = self.tabBarController?.viewControllers![1] as! UINavigationController
            let secondViewController = navController.viewControllers[0] as! AddToCartViewController
            secondViewController.firstTimeTableSkip = true
            self.tabBarController?.selectedIndex = 1
        }
    }
</code>```

in my cart view controller I used this code

```<code>override func viewWillAppear(_ animated: Bool) {
        if firstLoginCheck == true {
        checkOutButton.isHidden = false
        checkOutButton.layer.cornerRadius = 5
        if conditonCheck == true || conditonCheck == nil{
        checkOutButton.isHidden = true
        checkOutButton.layer.cornerRadius = 5
        tableDetails.isHidden = true
        emptyView.isHidden = true
        tableDetails.separatorInset = UIEdgeInsets.zero
        loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        activityIndicator.startAnimating()
        emptyView.isHidden = true
        if loginCheck == 1 {
            let token = UserDefaults.standard.value(forKey: "CustomerLoginToken")
            self.customerKeyToken = token!
            print(self.customerKeyToken!)
            if itemCode != nil {
                self.customerAddToCartItemsDownloadJsonWithURl(cartApi: customerAddtoCartApi)
       customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
            else {
                customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
        }else if (loginCheck == 0) || (loginCheck == nil) {
            if let token = UserDefaults.standard.value(forKey: "user_token")  {
                self.key = token as? String
                let defaultValue = UserDefaults.standard.value(forKey: "MenuButton") as? String
                if (defaultValue == "Tab" && itemCode == nil) {
                    check = true
           cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                }
            } else {
                gettingKeyFromJsonWithURL(keyApi: keygettingApi)
            }
            if itemCode != nil && key != nil {
                self.PostingKeyFromJsonWithURL(PostingApi: postingKeyApi)
            }
            if key != nil {
                cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                emptyView.isHidden = true
            }
            }
        }
</code>```

答:
Check the part of code where you are setting the badge icon count for "Cart". You need to persist the cart data in the same code flow.

Since you are having a boolean check in viewWillAppear, retrieve the cart data before performing the check.
It is a good idea to have CoreData for local persistence in case you are not syncing it with any server.

Body:
Here after running the application i had clicked on cart in tab bar at that time there was no items added in cart so it shown your shopping cart is empty but after adding items in cart then I clicked on cart icon on tab bar also it is showing like as in previous and the cart page was not reloading can anyone help me how to resolve this ?

I had used this code in my home view controller

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 1 {
            let  navController = self.tabBarController?.viewControllers![1] as! UINavigationController
            let secondViewController = navController.viewControllers[0] as! AddToCartViewController
            secondViewController.firstTimeTableSkip = true
            self.tabBarController?.selectedIndex = 1
        }
    }

in my cart view controller I used this code

override func viewWillAppear(_ animated: Bool) {
        if firstLoginCheck == true {
        checkOutButton.isHidden = false
        checkOutButton.layer.cornerRadius = 5
        if conditonCheck == true || conditonCheck == nil{
        checkOutButton.isHidden = true
        checkOutButton.layer.cornerRadius = 5
        tableDetails.isHidden = true
        emptyView.isHidden = true
        tableDetails.separatorInset = UIEdgeInsets.zero
        loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        activityIndicator.startAnimating()
        emptyView.isHidden = true
        if loginCheck == 1 {
            let token = UserDefaults.standard.value(forKey: "CustomerLoginToken")
            self.customerKeyToken = token!
            print(self.customerKeyToken!)
            if itemCode != nil {
                self.customerAddToCartItemsDownloadJsonWithURl(cartApi: customerAddtoCartApi)
       customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
            else {
                customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
        }else if (loginCheck == 0) || (loginCheck == nil) {
            if let token = UserDefaults.standard.value(forKey: "user_token")  {
                self.key = token as? String
                let defaultValue = UserDefaults.standard.value(forKey: "MenuButton") as? String
                if (defaultValue == "Tab" && itemCode == nil) {
                    check = true
           cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                }
            } else {
                gettingKeyFromJsonWithURL(keyApi: keygettingApi)
            }
            if itemCode != nil && key != nil {
                self.PostingKeyFromJsonWithURL(PostingApi: postingKeyApi)
            }
            if key != nil {
                cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                emptyView.isHidden = true
            }
            }
        }


来源: stackexchange

问:
How to check internet connection in alamofire?
I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code </p>

```<code>  let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)
      .responseJSON {

        let resstr = NSString(data: $0.data!, encoding: String.Encoding.utf8.rawValue)
        print("error is \(resstr)")

        if $0.result.isFailure {
          self.failure("Network")
          print("API FAILED 4")
          return
        }
        guard let result = $0.result.value else {
          self.unKnownError()
          self.failure("")
          print("API FAILED 3")

          return
        }
        self.handleSuccess(JSON(result))
    }
</code>```

答:
If Alamofire.upload result returns success then below is the way to check for internet availibility while uploading an image:

```<code>Alamofire.upload(multipartFormData: { multipartFormData in

                for (key,value) in parameters {
                 multipartFormData.append((value).data(using: .utf8)!, withName: key)
                }
                  multipartFormData.append(self.imageData!, withName: "image" ,fileName: "image.jpg" , mimeType: "image/jpeg")
            }, to:url)
            { (result) in

                switch result{

                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (progress) in
                     print("Upload Progress: \(progress.fractionCompleted)")

                    })

                    upload.responseJSON { response in
                        if  let statusCode = response.response?.statusCode{

                        if(statusCode == 201){
                         //internet available
                          }
                        }else{
                        //internet not available

                        }
                    }

                case .failure(let encodingError):
                    print(encodingError)

                }

            }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using below code for making HTTP request in server.Now I want to know whether it is connected to internet or not. Below is my code

  let request = Alamofire.request(completeURL(domainName: path), method: method, parameters: parameters, encoding: encoding.value, headers: headers)
      .responseJSON {

        let resstr = NSString(data: $0.data!, encoding: String.Encoding.utf8.rawValue)
        print("error is \(resstr)")

        if $0.result.isFailure {
          self.failure("Network")
          print("API FAILED 4")
          return
        }
        guard let result = $0.result.value else {
          self.unKnownError()
          self.failure("")
          print("API FAILED 3")

          return
        }
        self.handleSuccess(JSON(result))
    }

Body:
If Alamofire.upload result returns success then below is the way to check for internet availibility while uploading an image:

Alamofire.upload(multipartFormData: { multipartFormData in

                for (key,value) in parameters {
                 multipartFormData.append((value).data(using: .utf8)!, withName: key)
                }
                  multipartFormData.append(self.imageData!, withName: "image" ,fileName: "image.jpg" , mimeType: "image/jpeg")
            }, to:url)
            { (result) in

                switch result{

                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (progress) in
                     print("Upload Progress: \(progress.fractionCompleted)")

                    })

                    upload.responseJSON { response in
                        if  let statusCode = response.response?.statusCode{

                        if(statusCode == 201){
                         //internet available
                          }
                        }else{
                        //internet not available

                        }
                    }

                case .failure(let encodingError):
                    print(encodingError)

                }

            }

ContentLicense: CC BY-SA 3.0


问:
geospatial queries in javascript
I'm looking for a library in javascript that would allow me to make geospatial queries.  I know about OpenLayers and GoogleMaps, but this two do not support things like union intersection and so on.

```<code>+----+
|    |
|  +-+--+
+--+-+  |
   |    |
   +----+
</code>```

to

```<code>    +----+
    |    |
    |    +--+
    +--+    |
       |    |
       +----+
</code>```

答: You can get query results for a radius or rectangle that includes your polygon, then filter the results using the technique described here:  http://msdn.microsoft.com/en-us/library/cc451895.aspx.  The example uses bing maps, but you could easily use the same principles using whatever mapping service you prefer.</p>

ContentLicense: CC BY-SA 2.5

Title: geospatial queries in javascript

Body:
I'm looking for a library in javascript that would allow me to make geospatial queries.  I know about OpenLayers and GoogleMaps, but this two do not support things like union intersection and so on.

+----+
|    |
|  +-+--+
+--+-+  |
   |    |
   +----+

to

    +----+
    |    |
    |    +--+
    +--+    |
       |    |
       +----+


问:
start eclipse error, start to "Loading org.eclipse.core.filebuffers"
today, i in the console execute end eclipse process. now run eclipse is not start. start in the "Loading org.eclipse.core.filebuffers" stop start alos tip "java heap space"

workspace logs file content is:

```<code>!ENTRY org.eclipse.osgi 4 0 2017-12-05 13:55:59.305
!MESSAGE Application error
!STACK 1
java.lang.OutOfMemoryError: Java heap space
    at org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(StyledTextRenderer.java:1228)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9913)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9976)
    at org.eclipse.jface.text.TextViewer.applyTextPresentation(TextViewer.java:4884)
    at org.eclipse.jface.text.TextViewer.changeTextPresentation(TextViewer.java:4936)
    at org.eclipse.jface.text.presentation.PresentationReconciler.applyTextRegionCollection(PresentationReconciler.java:582)
    at org.eclipse.jface.text.presentation.PresentationReconciler.processDamage(PresentationReconciler.java:571)
    at org.eclipse.jface.text.presentation.PresentationReconciler.access$3(PresentationReconciler.java:567)
    at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.textChanged(PresentationReconciler.java:227)
    at org.eclipse.jface.text.TextViewer.updateTextListeners(TextViewer.java:2826)
    at org.eclipse.jface.text.TextViewer.invalidateTextPresentation(TextViewer.java:3478)
    at org.eclipse.ui.texteditor.AbstractTextEditor.handlePreferenceStoreChanged(AbstractTextEditor.java:4628)
    at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.handlePreferenceStoreChanged(AbstractDecoratedTextEditor.java:906)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.handlePreferenceStoreChanged(JavaEditor.java:2519)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor.handlePreferenceStoreChanged(CompilationUnitEditor.java:1530)
    at org.eclipse.ui.texteditor.AbstractTextEditor$PropertyChangeListener.propertyChange(AbstractTextEditor.java:715)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.firePropertyChangeEvent(ChainedPreferenceStore.java:164)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.handlePropertyChangeEvent(ChainedPreferenceStore.java:431)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.access$0(ChainedPreferenceStore.java:408)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore$PropertyChangeListener.propertyChange(ChainedPreferenceStore.java:69)
    at org.eclipse.ui.preferences.ScopedPreferenceStore$3.run(ScopedPreferenceStore.java:351)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.266
!MESSAGE
!STACK 0
java.lang.NullPointerException
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:209)
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:230)
    at org.eclipse.ui.part.WorkbenchPart.dispose(WorkbenchPart.java:109)
    at org.eclipse.ui.internal.views.markers.ExtendedMarkersView.dispose(ExtendedMarkersView.java:634)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.invalidate(CompatibilityPart.java:238)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.destroy(CompatibilityPart.java:394)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898)at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.dispose(EclipseContextOSGi.java:106)
    at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.bundleChanged(EclipseContextOSGi.java:139)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:902)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:165)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:75)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:67)
    at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:102)
    at org.eclipse.osgi.container.Module.publishEvent(Module.java:466)
    at org.eclipse.osgi.container.Module.doStop(Module.java:624)
    at org.eclipse.osgi.container.Module.stop(Module.java:488)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:186)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:159)
    at java.lang.Thread.run(Unknown Source)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.269
!MESSAGE FrameworkEvent ERROR
</code>```

if you konw ,place tell me .

                                                                 thanks

答:
The above error is due to out of space of java heap memory are, you can increase your java heap size using :

Go to the Run icon and select Run Configurations

Select Arguments and Specify head size in VM Arguments.
eg: Xmx1024

Body:
today, i in the console execute end eclipse process. now run eclipse is not start. start in the "Loading org.eclipse.core.filebuffers" stop start alos tip "java heap space"

workspace logs file content is:

!ENTRY org.eclipse.osgi 4 0 2017-12-05 13:55:59.305
!MESSAGE Application error
!STACK 1
java.lang.OutOfMemoryError: Java heap space
    at org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(StyledTextRenderer.java:1228)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9913)
    at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9976)
    at org.eclipse.jface.text.TextViewer.applyTextPresentation(TextViewer.java:4884)
    at org.eclipse.jface.text.TextViewer.changeTextPresentation(TextViewer.java:4936)
    at org.eclipse.jface.text.presentation.PresentationReconciler.applyTextRegionCollection(PresentationReconciler.java:582)
    at org.eclipse.jface.text.presentation.PresentationReconciler.processDamage(PresentationReconciler.java:571)
    at org.eclipse.jface.text.presentation.PresentationReconciler.access$3(PresentationReconciler.java:567)
    at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.textChanged(PresentationReconciler.java:227)
    at org.eclipse.jface.text.TextViewer.updateTextListeners(TextViewer.java:2826)
    at org.eclipse.jface.text.TextViewer.invalidateTextPresentation(TextViewer.java:3478)
    at org.eclipse.ui.texteditor.AbstractTextEditor.handlePreferenceStoreChanged(AbstractTextEditor.java:4628)
    at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.handlePreferenceStoreChanged(AbstractDecoratedTextEditor.java:906)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.handlePreferenceStoreChanged(JavaEditor.java:2519)
    at org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor.handlePreferenceStoreChanged(CompilationUnitEditor.java:1530)
    at org.eclipse.ui.texteditor.AbstractTextEditor$PropertyChangeListener.propertyChange(AbstractTextEditor.java:715)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.firePropertyChangeEvent(ChainedPreferenceStore.java:164)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.handlePropertyChangeEvent(ChainedPreferenceStore.java:431)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore.access$0(ChainedPreferenceStore.java:408)
    at org.eclipse.ui.texteditor.ChainedPreferenceStore$PropertyChangeListener.propertyChange(ChainedPreferenceStore.java:69)
    at org.eclipse.ui.preferences.ScopedPreferenceStore$3.run(ScopedPreferenceStore.java:351)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.266
!MESSAGE
!STACK 0
java.lang.NullPointerException
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:209)
    at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:230)
    at org.eclipse.ui.part.WorkbenchPart.dispose(WorkbenchPart.java:109)
    at org.eclipse.ui.internal.views.markers.ExtendedMarkersView.dispose(ExtendedMarkersView.java:634)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.invalidate(CompatibilityPart.java:238)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.destroy(CompatibilityPart.java:394)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898)at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.dispose(EclipseContextOSGi.java:106)
    at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.bundleChanged(EclipseContextOSGi.java:139)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:902)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:165)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:75)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:67)
    at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:102)
    at org.eclipse.osgi.container.Module.publishEvent(Module.java:466)
    at org.eclipse.osgi.container.Module.doStop(Module.java:624)
    at org.eclipse.osgi.container.Module.stop(Module.java:488)
    at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:186)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:159)
    at java.lang.Thread.run(Unknown Source)

!ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.269
!MESSAGE FrameworkEvent ERROR

if you konw ,place tell me .

                                                                 thanks


问:
Filter matched items in an array of string with another (key,value) objects in angularjs
I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

```<code>var obj = {"viki-1100":6,"mark-2100":2}
</code>```

To return only the non matched keys from stringArr,So desired output:

```<code>var result = ["vijay-1110","ram-2110"]
</code>```

I haven tried the below code which doesnot return the desired output?

```<code>var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}
</code>```

this wont filter the stringArr, It always return all the results in stringArr?

答:
You can use in to check if a key exist inside an object. Use array#filter to iterate through your array and for each value return the non-existent value.

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"];
var obj = {"viki-1100":6,"mark-2100":2};
var result = stringArr.filter(name => !(name in obj));
console.log(result);```

Body:
I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

var obj = {"viki-1100":6,"mark-2100":2}

To return only the non matched keys from stringArr,So desired output:

var result = ["vijay-1110","ram-2110"]

I haven tried the below code which doesnot return the desired output?

var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}

this wont filter the stringArr, It always return all the results in stringArr?


问:
Set transparent dots in probability plot
I'm trying to set an alpha value or some other way of making dots in a probability plot slightly translucent. This is the code I have.

```<code>import numpy as np
import pylab
import scipy.stats as stats
stats.probplot(x, dist=stats.gamma, sparams=(2.74,),plot=pylab)
</code>```

This is what the plot sort of looks like. Any tips on how to make the dots slightly translucent? I'd like to do this for aesthetic purposes.

答:
The probplot function doesn't expose an API to customize the plot. Instead, you can customize the plot after probplot returns, using additional matplotlib (i.e. pylab) functions.  Here's one way you could do it (in an ipython session).

First, the imports:

```<code>In [102]: import numpy as np

In [103]: import pylab

In [104]: from scipy import stats
</code>```

Generate some data for the plot:

```<code>In [105]: np.random.seed(8675309)

In [106]: x = np.random.gamma(3.0, scale=2.1, size=50)
</code>```

Generate the probability plot:

```<code>In [107]: pp = stats.probplot(x, dist=stats.gamma, sparams=(2.74,), plot=pylab)
</code>```

Set the alpha value for the first line in the current axes.  This is slightly "dangerous", because it relies on probplot plotting the points before plotting the red line.

```<code>In [108]: ax = pylab.gca()           # Get the current axes.

In [109]: line0 = ax.get_lines()[0]  # Get the first "line" in the axes.

In [110]: line0.set_alpha(0.25)      # Set the alpha for the "line".
</code>```

Here's the plot that is generated:

Personally, though, I prefer to take complete control of the plotting.  You can pass None for the plot argument to disable the automatic generation of a plot, and generate the plot however you like using matplotlib:

```<code>In [185]: import matplotlib.pyplot as plt

In [186]: (osm, osr), (slope, intercept, r) = stats.probplot(x, dist=stats.gamma, sparams=(2.74,), plot=None)

In [187]: plt.plot(osm, osr, 'o', alpha=0.5)
Out[187]: [<matplotlib.lines.Line2D at 0x11469a6d8>]

In [188]: plt.plot(osm, slope*osm + intercept, 'k', alpha=0.5, linewidth=1)
Out[188]: [<matplotlib.lines.Line2D at 0x114695a90>]

In [189]: plt.grid(alpha=0.15)

In [190]: plt.xlabel('Theoretical Quantiles')
Out[190]: <matplotlib.text.Text at 0x11440bac8>

In [191]: plt.ylabel('Sample Quantiles')
Out[191]: <matplotlib.text.Text at 0x1142efda0>
</code>```

Body:
I'm trying to set an alpha value or some other way of making dots in a probability plot slightly translucent. This is the code I have.

import numpy as np
import pylab
import scipy.stats as stats
stats.probplot(x, dist=stats.gamma, sparams=(2.74,),plot=pylab)

This is what the plot sort of looks like. Any tips on how to make the dots slightly translucent? I'd like to do this for aesthetic purposes.

Body:
The probplot function doesn't expose an API to customize the plot. Instead, you can customize the plot after probplot returns, using additional matplotlib (i.e. pylab) functions.  Here's one way you could do it (in an ipython session).

First, the imports:

In [102]: import numpy as np

In [103]: import pylab

In [104]: from scipy import stats

Generate some data for the plot:

In [105]: np.random.seed(8675309)

In [106]: x = np.random.gamma(3.0, scale=2.1, size=50)

Generate the probability plot:

In [107]: pp = stats.probplot(x, dist=stats.gamma, sparams=(2.74,), plot=pylab)

Set the alpha value for the first line in the current axes.  This is slightly "dangerous", because it relies on probplot plotting the points before plotting the red line.

In [108]: ax = pylab.gca()           # Get the current axes.

In [109]: line0 = ax.get_lines()[0]  # Get the first "line" in the axes.

In [110]: line0.set_alpha(0.25)      # Set the alpha for the "line".

Here's the plot that is generated:

Personally, though, I prefer to take complete control of the plotting.  You can pass None for the plot argument to disable the automatic generation of a plot, and generate the plot however you like using matplotlib:

In [185]: import matplotlib.pyplot as plt

In [186]: (osm, osr), (slope, intercept, r) = stats.probplot(x, dist=stats.gamma, sparams=(2.74,), plot=None)

In [187]: plt.plot(osm, osr, 'o', alpha=0.5)
Out[187]: [<matplotlib.lines.Line2D at 0x11469a6d8>]

In [188]: plt.plot(osm, slope*osm + intercept, 'k', alpha=0.5, linewidth=1)
Out[188]: [<matplotlib.lines.Line2D at 0x114695a90>]

In [189]: plt.grid(alpha=0.15)

In [190]: plt.xlabel('Theoretical Quantiles')
Out[190]: <matplotlib.text.Text at 0x11440bac8>

In [191]: plt.ylabel('Sample Quantiles')
Out[191]: <matplotlib.text.Text at 0x1142efda0>


答:
```<code>DF.assign(_PCT_=DF.X.pct_change(-1))

   Y    X       PCT     _PCT_
0  1  100       NaN -0.047619
1  2  105  0.050000 -0.086957
2  3  115  0.095238  0.210526
3  4   95 -0.173913  0.055556
4  5   90 -0.052632  0.022727
5  6   88 -0.022222 -0.200000
6  7  110  0.250000  0.100000
7  8  100 -0.090909       inf
8  9    0 -1.000000       NaN
</code>```

Series.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)

periods : int, default 1 Periods to shift for forming percent change

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html

Title: pandas pct_change() in reverse

Body:
Suppose we have a dataframe and we calculate as percent change between rows

y_axis = [1,2,3,4,5,6,7,8,9]
x_axis = [100,105,115,95,90,88,110,100,0]

DF = pd.DataFrame({'Y':y_axis, 'X':x_axis})

DF = DF[['Y','X']]
DF['PCT'] = DF['X'].pct_change()

    Y   X   PCT
0   1   100 NaN
1   2   105 0.050000
2   3   115 0.095238
3   4   95  -0.173913
4   5   90  -0.052632
5   6   88  -0.022222
6   7   110 0.250000
7   8   100 -0.090909
8   9   0   -1.000000

That way it starts from the first row.
I want calculate pct_change() starting from the last row.

One way to do it

DF['Reverse'] = list(reversed(x_axis))
DF['PCT_rev'] = DF['Reverse'].pct_change()
pct_rev = DF.PCT_rev.tolist()

DF['_PCT_'] = list(reversed(pct_rev))
DF2 = DF[['Y','X','PCT','_PCT_']]

    Y   X   PCT         _PCT_
0   1   100 NaN         -0.047619
1   2   105 0.050000    -0.086957
2   3   115 0.095238    0.210526
3   4   95  -0.173913   0.055556
4   5   90  -0.052632   0.022727
5   6   88  -0.022222   -0.200000
6   7   110 0.250000    0.100000
7   8   100 -0.090909   inf
8   9   0   -1.000000   NaN

But that is a very ugly and inefficient solution.
I was wondering if there are more elegant solutions?

Body:
DF.assign(_PCT_=DF.X.pct_change(-1))

   Y    X       PCT     _PCT_
0  1  100       NaN -0.047619
1  2  105  0.050000 -0.086957
2  3  115  0.095238  0.210526
3  4   95 -0.173913  0.055556
4  5   90 -0.052632  0.022727
5  6   88 -0.022222 -0.200000
6  7  110  0.250000  0.100000
7  8  100 -0.090909       inf
8  9    0 -1.000000       NaN

Series.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)

periods : int, default 1 Periods to shift for forming percent change

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html


问:
Python- The Word Game "Ghost", File I/O, and List question
I want to create computer for the word-game Ghost.   However, I'm having problems thinking of a good way to deal with accessing the huge word list.  Here's my current implementation (which doesn't work):

```<code>import os, random, sys, math, string

def main():

    #Contains a huge wordlist-- opened up for reading
    dictionary = open("wordlist.txt", "r")
    wordlist = []
    win= 0
    turn= 0
    firstrun = 0
    word = ""

    #while nobody has won the game
    while win==0:
        if turn == 0:
            #get first letter from input
            foo = raw_input("Choose a letter: ")[0]
            word+=foo
            print "**Current word**: "+ word
            #Computer's turn
            turn = 1
        if turn == 1:
            #During the first run the program gets all definitively
            #winning words (words that have odd-number lengths)
            #from the "dictionary" file and puts them in a list
            if firstrun== 0:
                for line in dictionary:
                    #if the line in the dictionary starts with the current
                    #word and has an odd-number of letters
                    if str(line).startswith(word) and len(line)%2 == 0:
                        wordlist.append(line[0: len(line)-1])
                print "first run complete... size = "+str(len(wordlist))
                firstrun = 1
            else:   #This is run after the second computer move
                for line in wordlist:
                    #THIS DOES NOT WORK-- THIS IS THE PROBLEM.
                    #I want it to remove from the list every single
                    #word that does not conform to the current limitations
                    #of the "word" variable.
                    if not line.startswith(word):
                        wordlist.remove(line)
                print "removal complete... size = "+str(len(wordlist))

            turn = 0

if __name__ == "__main__":
    main()
</code>```

I have demarcated the problem area in the code.  I have no idea why it doesn't work.  What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.

I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.

答:
I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N).

It is better to just make a new list. One possible way to do this is to replace the lines

```<code>for line in wordlist:
    if not line.startswith(word):
        wordlist.remove(line)
</code>```

with

```<code>wordlist = [w for w in wordlist if w.startswith(word)]
</code>```

Body:
I want to create computer for the word-game Ghost.   However, I'm having problems thinking of a good way to deal with accessing the huge word list.  Here's my current implementation (which doesn't work):

import os, random, sys, math, string

def main():

    #Contains a huge wordlist-- opened up for reading
    dictionary = open("wordlist.txt", "r")
    wordlist = []
    win= 0
    turn= 0
    firstrun = 0
    word = ""

    #while nobody has won the game
    while win==0:
        if turn == 0:
            #get first letter from input
            foo = raw_input("Choose a letter: ")[0]
            word+=foo
            print "**Current word**: "+ word
            #Computer's turn
            turn = 1
        if turn == 1:
            #During the first run the program gets all definitively
            #winning words (words that have odd-number lengths)
            #from the "dictionary" file and puts them in a list
            if firstrun== 0:
                for line in dictionary:
                    #if the line in the dictionary starts with the current
                    #word and has an odd-number of letters
                    if str(line).startswith(word) and len(line)%2 == 0:
                        wordlist.append(line[0: len(line)-1])
                print "first run complete... size = "+str(len(wordlist))
                firstrun = 1
            else:   #This is run after the second computer move
                for line in wordlist:
                    #THIS DOES NOT WORK-- THIS IS THE PROBLEM.
                    #I want it to remove from the list every single
                    #word that does not conform to the current limitations
                    #of the "word" variable.
                    if not line.startswith(word):
                        wordlist.remove(line)
                print "removal complete... size = "+str(len(wordlist))

            turn = 0

if __name__ == "__main__":
    main()

I have demarcated the problem area in the code.  I have no idea why it doesn't work.  What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.

I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.

Body:
I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N).

It is better to just make a new list. One possible way to do this is to replace the lines

for line in wordlist:
    if not line.startswith(word):
        wordlist.remove(line)

with

wordlist = [w for w in wordlist if w.startswith(word)]


问:
Find out Excel column character from name of cell in first row
I have an excel sheet that looks like this;

The header names are found in first row. I would like to have a VBA function that returns the column number, given the cell name in the first row. For example, getColumnNumber("B Symbol") should return B. getColumnNumber("C Symbol") should return C.

I am using Excel 2016.

答:
Find the text and then read the address.

```<code>With Worksheets(1).Range("a1:z1") '
    Set c = .Find("whatever you need to find", lookin:=xlValues)
    If Not c Is Nothing Then
        firstAddress = split(c.Address,"$")(0)
        msgbox firstAddress
    End If
End With
</code>```

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel

Body:
Find the text and then read the address.

With Worksheets(1).Range("a1:z1") '
    Set c = .Find("whatever you need to find", lookin:=xlValues)
    If Not c Is Nothing Then
        firstAddress = split(c.Address,"$")(0)
        msgbox firstAddress
    End If
End With

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel


问:
How to minimize an object and build an array from an array of objects in JavaScript
I have an array of objects and each object has around 5 properties and respective values. I would like to iterate through each object in the array and pick only two properties from it and rebuild the object and the array.

For example:

```<code>let resArray = [
{"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
{"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
{"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
{"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
{"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
{"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];
</code>```

I want to remove the "country" and the "sex" properties from the objects and retain the "name" and "id" properties and rebuild the array. i.e., the output should be as follows:

```<code>let outArray = [
{"name": "Aaron", "id": 123},
{"name": "Bert", "id": 456},
{"name": "Brenda", "id": 657},
{"name": "Chris", "id": 856},
{"name": "Angela", "id": 113},
{"name": "Maria", "id": 569}];
</code>```

As of now, I am just using the resArray and iterating through the whole array and getting whatever values I want. But I just think I can minimize the object so that it will be clear of the clutter.

Could anyone help me out with it?
Thank you.

答:
Use Array#map function and create your desired shape based on the item

let resArray = [
   {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
   {"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
   {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
   {"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
   {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
   {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}
];

let mappedArr = resArray.map(item => ({name: item.name, id: item.id}));

console.log(mappedArr);```
</div>
</div>
</p>

<p>Also you can destruct your parameter <code>item</code> inside the parameters list and get only the desired results</p>

```let mappedArr = resArray.map(({id, name}) => ({name, id}));
```

Body:
I have an array of objects and each object has around 5 properties and respective values. I would like to iterate through each object in the array and pick only two properties from it and rebuild the object and the array.

For example:

let resArray = [
{"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
{"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
{"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
{"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
{"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
{"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];

I want to remove the "country" and the "sex" properties from the objects and retain the "name" and "id" properties and rebuild the array. i.e., the output should be as follows:

let outArray = [
{"name": "Aaron", "id": 123},
{"name": "Bert", "id": 456},
{"name": "Brenda", "id": 657},
{"name": "Chris", "id": 856},
{"name": "Angela", "id": 113},
{"name": "Maria", "id": 569}];

As of now, I am just using the resArray and iterating through the whole array and getting whatever values I want. But I just think I can minimize the object so that it will be clear of the clutter.

Could anyone help me out with it?
Thank you.

Body:
Use Array#map function and create your desired shape based on the item

let resArray = [
   {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
   {"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
   {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
   {"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
   {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
   {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}
];

let mappedArr = resArray.map(item => ({name: item.name, id: item.id}));

console.log(mappedArr);

Also you can destruct your parameter item inside the parameters list and get only the desired results

let mappedArr = resArray.map(({id, name}) => ({name, id}));


答:
Try the following way:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]
var obj = {"viki-1100":6,"mark-2100":2}

var result = stringArr.filter(function(item){
  return !(item in obj)
});
console.log(result)```

Title: Filter matched items in an array of string with another (key,value) objects in angularjs


问:
Render template relation ManyToMany Symfony Doctrine
Please help with this, I am having this problem when I render the template twig in the controller, having problems with relations ManyToMany

Neither the property "nombre" nor one of the methods "nombre()", "getnombre()"/"isnombre()" or "__call()" exist and have public access in class "Doctrine\ORM\PersistentCollection"....I will put my entities and controller, please help me with this:

```<code><?php

namespace AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Menu
 *
 * @ORM\Table(name="menu")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\MenuRepository")
 */
class Menu
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var float
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @var \DateTime
     * @Assert\Date()
     * @Assert\NotBlank()
     * @ORM\Column(name="fecha", type="date")
     */
    private $fecha;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechacomprar", type="datetime")
     */
    private $fechacomprar;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechavence", type="datetime")
     */
    private $fechavence;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Menu
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     *
     * @return Menu
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Set fechacomprar
     *
     * @param \DateTime $fechacomprar
     *
     * @return Menu
     */
    public function setFechacomprar($fechacomprar)
    {
        $this->fechacomprar = $fechacomprar;

        return $this;
    }

    /**
     * Get fechacomprar
     *
     * @return \DateTime
     */
    public function getFechacomprar()
    {
        return $this->fechacomprar;
    }

    /**
     * Set fechavence
     *
     * @param \DateTime $fechavence
     *
     * @return Menu
     */
    public function setFechavence($fechavence)
    {
        $this->fechavence = $fechavence;

        return $this;
    }

    /**
     * Get fechavence
     *
     * @return \DateTime
     */
    public function getFechavence()
    {
        return $this->fechavence;
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }
}

<?php

namespace AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;

/**
 * Alimento
 *
 * @ORM\Table(name="alimento")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\AlimentoRepository")
 * @DoctrineAssert\UniqueEntity("nombre")
 */
class Alimento
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank(message="Debe escribir un alimento")
     * @Assert\Type(type="string")
     * @Assert\Regex(pattern="/\d/", match=false, message="Debe escribir un nombre válido")
     * @ORM\Column(name="nombre", type="string", length=255, unique=true)
     */
    private $nombre;

    /**
     * @var float
     * @Assert\NotBlank(message="Debe especificar un precio")
     * @Assert\Type(type="float", message="Debe escribir un precio válido")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @ORM\ManyToOne(targetEntity="TipoAlimento")
     * @Assert\NotBlank()
     */
    private $tipo;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Menu", mappedBy="alimento")
     */
    private $menu;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Alimento
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Alimento
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set tipo
     *
     * @param \AdminBundle\Entity\TipoAlimento $tipo
     *
     * @return Alimento
     */
    public function setTipo(TipoAlimento $tipo)
    {
        $this->tipo = $tipo;

        return $this;
    }

    /**
     * Get tipo
     *
     * @return \AdminBundle\Entity\TipoAlimento
     */
    public function getTipo()
    {
        return $this->tipo;
    }

    /**
     * @return string
     */
    function __toString()
    {
        return $this->getNombre();
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->menu = new ArrayCollection();
    }

    /**
     * Add menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     *
     * @return Alimento
     */
    public function addMenu(Menu $menu)
    {
        $this->menu[] = $menu;

        return $this;
    }

    /**
     * Remove menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     */
    public function removeMenu(Menu $menu)
    {
        $this->menu->removeElement($menu);
    }

    /**
     * Get menu
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMenu()
    {
        return $this->menu;
    }
}
</code>```

The controller:

```<code>    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $menu = $em->getRepository('AdminBundle:Menu')->findAll();
        return $this->render('AdminBundle:menu:index.html.twig', array(
            'menu' => $menu,
        ));`enter code here`
    }
</code>```

And in the template I am doing the things like this:

```<code> {% for m in menu %}
                    <tr>
                        <td>{{ m.id }}</td>
                        <td>{{ m.fecha | date('d/m/y') }}</td>
                        <td>{{ m.alimento.nombre }}</td>
                        <td>{{ m.fechacomprar | date('d/m/y') }}</td>
                        <td>{{ m.fechavence | date('d/m/y') }}</td>
                        <td>{{ m.precio }}</td>
                    </tr>
                {% endfor %}
</code>```

Problem here is m.alimento.nombre is wrong!

答:
If it's a many to many that means that each menu will have many alimentos so you have to loop over each of them.</p>

```<code>{% for a in m.alimento %}
<td>{{ a.nombre }}</td>
{% endfor %}
</code>```

Body:
Please help with this, I am having this problem when I render the template twig in the controller, having problems with relations ManyToMany

Neither the property "nombre" nor one of the methods "nombre()", "getnombre()"/"isnombre()" or "__call()" exist and have public access in class "Doctrine\ORM\PersistentCollection"....I will put my entities and controller, please help me with this:

<?php

namespace AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Menu
 *
 * @ORM\Table(name="menu")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\MenuRepository")
 */
class Menu
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var float
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @var \DateTime
     * @Assert\Date()
     * @Assert\NotBlank()
     * @ORM\Column(name="fecha", type="date")
     */
    private $fecha;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechacomprar", type="datetime")
     */
    private $fechacomprar;

    /**
     * @var \DateTime
     * @Assert\DateTime()
     * @Assert\NotBlank()
     * @ORM\Column(name="fechavence", type="datetime")
     */
    private $fechavence;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
     * @ORM\JoinTable(name="alimento_menu",
     *   joinColumns={
     *     @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
     *   }
     * )
     */
    private $alimento;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->alimento = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Menu
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     *
     * @return Menu
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Set fechacomprar
     *
     * @param \DateTime $fechacomprar
     *
     * @return Menu
     */
    public function setFechacomprar($fechacomprar)
    {
        $this->fechacomprar = $fechacomprar;

        return $this;
    }

    /**
     * Get fechacomprar
     *
     * @return \DateTime
     */
    public function getFechacomprar()
    {
        return $this->fechacomprar;
    }

    /**
     * Set fechavence
     *
     * @param \DateTime $fechavence
     *
     * @return Menu
     */
    public function setFechavence($fechavence)
    {
        $this->fechavence = $fechavence;

        return $this;
    }

    /**
     * Get fechavence
     *
     * @return \DateTime
     */
    public function getFechavence()
    {
        return $this->fechavence;
    }

    /**
     * Add alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     *
     * @return Menu
     */
    public function addAlimento(Alimento $alimento)
    {
        $this->alimento[] = $alimento;

        return $this;
    }

    /**
     * Remove alimento
     *
     * @param \AdminBundle\Entity\Alimento $alimento
     */
    public function removeAlimento(Alimento $alimento)
    {
        $this->alimento->removeElement($alimento);
    }

    /**
     * Get alimento
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAlimento()
    {
        return $this->alimento;
    }
}

<?php

namespace AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;

/**
 * Alimento
 *
 * @ORM\Table(name="alimento")
 * @ORM\Entity(repositoryClass="AdminBundle\Repository\AlimentoRepository")
 * @DoctrineAssert\UniqueEntity("nombre")
 */
class Alimento
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank(message="Debe escribir un alimento")
     * @Assert\Type(type="string")
     * @Assert\Regex(pattern="/\d/", match=false, message="Debe escribir un nombre válido")
     * @ORM\Column(name="nombre", type="string", length=255, unique=true)
     */
    private $nombre;

    /**
     * @var float
     * @Assert\NotBlank(message="Debe especificar un precio")
     * @Assert\Type(type="float", message="Debe escribir un precio válido")
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @ORM\ManyToOne(targetEntity="TipoAlimento")
     * @Assert\NotBlank()
     */
    private $tipo;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Menu", mappedBy="alimento")
     */
    private $menu;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Alimento
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set precio
     *
     * @param float $precio
     *
     * @return Alimento
     */
    public function setPrecio($precio)
    {
        $this->precio = $precio;

        return $this;
    }

    /**
     * Get precio
     *
     * @return float
     */
    public function getPrecio()
    {
        return $this->precio;
    }

    /**
     * Set tipo
     *
     * @param \AdminBundle\Entity\TipoAlimento $tipo
     *
     * @return Alimento
     */
    public function setTipo(TipoAlimento $tipo)
    {
        $this->tipo = $tipo;

        return $this;
    }

    /**
     * Get tipo
     *
     * @return \AdminBundle\Entity\TipoAlimento
     */
    public function getTipo()
    {
        return $this->tipo;
    }

    /**
     * @return string
     */
    function __toString()
    {
        return $this->getNombre();
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->menu = new ArrayCollection();
    }

    /**
     * Add menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     *
     * @return Alimento
     */
    public function addMenu(Menu $menu)
    {
        $this->menu[] = $menu;

        return $this;
    }

    /**
     * Remove menu
     *
     * @param \AdminBundle\Entity\Menu $menu
     */
    public function removeMenu(Menu $menu)
    {
        $this->menu->removeElement($menu);
    }

    /**
     * Get menu
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMenu()
    {
        return $this->menu;
    }
}

The controller:

    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $menu = $em->getRepository('AdminBundle:Menu')->findAll();
        return $this->render('AdminBundle:menu:index.html.twig', array(
            'menu' => $menu,
        ));`enter code here`
    }

And in the template I am doing the things like this:

 {% for m in menu %}

                        {{ m.id }}
                        {{ m.fecha | date('d/m/y') }}
                        {{ m.alimento.nombre }}
                        {{ m.fechacomprar | date('d/m/y') }}
                        {{ m.fechavence | date('d/m/y') }}
                        {{ m.precio }}

                {% endfor %}

Problem here is m.alimento.nombre is wrong!

Body:
If it's a many to many that means that each menu will have many alimentos so you have to loop over each of them.

{% for a in m.alimento %}
<td>{{ a.nombre }}</td>
{% endfor %}


问:
Cytoscape not restoring elements
According to the documentation (http://js.cytoscape.org/#eles.remove / http://js.cytoscape.org/#eles.restore), it is possible to restore previously removed elements from the graph, by using the eles.restore() method.

I am however unable to restore all elements in this facon?

```<code>applyElementFilters = () => {
    const excluded = [1, 2, 3];

    // Restore all elements first, this apparently does nothing
    this.cy.elements().restore();

    if (excluded && excluded.length > 0) {
        const excludedElements = this.cy
            .elements()
            .filter(element => excluded.includes(element.data("id")));

        this.cy.remove(excludedElements);
    }
};
</code>```

答:
As explained in documentation, you have save the reference of removed elements for restoring them.

```<code>// remove selected elements
var eles = cy.$(':selected').remove();

// ... then some time later put them back
eles.restore();
</code>```

In your case when you're removing elements by doing this

```<code>this.cy.elements().restore();
</code>```

you can save them in a variable or in this like below

```<code>this.__removedElements = this.cy.elements().remove();
// or
var removedElements; // global variable
removedElements = this.cy.elements().remove();
</code>```

then you can restore them like below

```<code>this.__removedElements.restore()
// or
removedElements.restore()
</code>```

Title: Cytoscape not restoring elements

Body:
According to the documentation (http://js.cytoscape.org/#eles.remove / http://js.cytoscape.org/#eles.restore), it is possible to restore previously removed elements from the graph, by using the eles.restore() method.

I am however unable to restore all elements in this facon?

applyElementFilters = () => {
    const excluded = [1, 2, 3];

    // Restore all elements first, this apparently does nothing
    this.cy.elements().restore();

    if (excluded && excluded.length > 0) {
        const excludedElements = this.cy
            .elements()
            .filter(element => excluded.includes(element.data("id")));

        this.cy.remove(excludedElements);
    }
};

Body:
As explained in documentation, you have save the reference of removed elements for restoring them.

// remove selected elements
var eles = cy.$(':selected').remove();

// ... then some time later put them back
eles.restore();

In your case when you're removing elements by doing this

this.cy.elements().restore();

you can save them in a variable or in this like below

this.__removedElements = this.cy.elements().remove();
// or
var removedElements; // global variable
removedElements = this.cy.elements().remove();

then you can restore them like below

this.__removedElements.restore()
// or
removedElements.restore()


问:
How to select foreign key value in Laravel
I've two tables one is car_category having the fields - id,type.
Another table named  vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,

```<code>class Car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}
</code>```

vehicle model,

```<code>class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';
    public function cars()
    {
        return $this->belongsTo('Car');
    }
}
</code>```

What 'll be my query for this? I've tried this code, results error.

```<code>$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
             WHERE cars.id = vehicles.c_id";
</code>```

How can I achieve this? Can anybody help me?

答:
Change from class car to class Car

After that you can select with Car::first(), the related table data can be found in Car::first()->vehicles

You can also add a where() method on models, if you have more than one record, use a foreach()

Body:
I've two tables one is car_category having the fields - id,type.
Another table named  vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,

class Car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}

vehicle model,

class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';
    public function cars()
    {
        return $this->belongsTo('Car');
    }
}

What 'll be my query for this? I've tried this code, results error.

$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
             WHERE cars.id = vehicles.c_id";

How can I achieve this? Can anybody help me?


问:
SQL query where ALL records in a join match a condition?
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.

Take the following:

```<code>SELECT *
FROM users INNER JOIN tags
  ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')
</code>```

This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.

'user1' tags: word1, word2, word3

'user2' tags: word1

'user3' tags: word1, word2

Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.

Hopefully I made this clear. Thanks for your help!

答:
Relying on COUNT(*) = 2 will require that there can be no duplicates of user_id and name in the tags table.  If that's the case, I'd go that route.  Otherwise, this should work: </p>

```<code>SELECT u.*
FROM users AS u
WHERE u.id NOT IN (
    SELECT DISTINCT user_id FROM tags WHERE name NOT IN ('word1', 'word2')
) AND EXISTS (SELECT user_id FROM tags WHERE user_id = u.id)
</code>```

Body:
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.

Take the following:

SELECT *
FROM users INNER JOIN tags
  ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')

This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.

'user1' tags: word1, word2, word3

'user2' tags: word1

'user3' tags: word1, word2

Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.

Hopefully I made this clear. Thanks for your help!

Body:
Relying on COUNT(*) = 2 will require that there can be no duplicates of user_id and name in the tags table.  If that's the case, I'd go that route.  Otherwise, this should work:

SELECT u.*
FROM users AS u
WHERE u.id NOT IN (
    SELECT DISTINCT user_id FROM tags WHERE name NOT IN ('word1', 'word2')
) AND EXISTS (SELECT user_id FROM tags WHERE user_id = u.id)


问:
Selectively removing trailing string
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"
</code>```

but I want

```<code>"HELLO X" "D HELLO" "TW X" "H"
</code>```

答:
Use regex alternation operator |

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("(HELLO)|O(?!\\S)", "\\1", a, perl=T)
# [1] "HELLO X" "D HELLO" "TW X"    "H"
</code>```

(HELLO)|O this regex does two things,

First it captures all the HELLO string.

Matches all the remaining 0's which are not followed by a non-space character.

Title: Selectively removing trailing string

Body:
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"

but I want

"HELLO X" "D HELLO" "TW X" "H"

Body:
Use regex alternation operator |

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("(HELLO)|O(?!\\S)", "\\1", a, perl=T)
# [1] "HELLO X" "D HELLO" "TW X"    "H"

(HELLO)|O this regex does two things,

First it captures all the HELLO string.

Matches all the remaining 0's which are not followed by a non-space character.


问:
How to initialize List<String> object in Java?
I can not initialize a List as in the following code:

```<code>List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
</code>```

I face the following error:

Cannot instantiate the type List<String>

How can I instantiate List<String>?

答:
Just in case, any one still lingering around this question. Because, i see one or two new users again asking the same question and everyone telling then , No you can't do that, Dear Prudence, Apart from all the answers given here, I would like to provide additional Information -
Yes you can actually do, List list = new List();
But at the cost of writing implementations of all the methods of Interfaces.
The notion is not simply List list = new List(); but

```<code>List<Integer> list = new List<Integer>(){

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            // TODO Auto-generated method stub
            return false;
        }
</code>```

..... and So on (Cant write all methods.)

This is an example of Anonymous class. Its correct when someone states , No you cant instantiate an interface, and that's right. But you can never say , You CANT write List list = new List(); but, evidently you can do that and that's a hard statement to make that You can't do.

Body:
I can not initialize a List as in the following code:

List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));

I face the following error:

Cannot instantiate the type List<String>

How can I instantiate List<String>?

Body:
Just in case, any one still lingering around this question. Because, i see one or two new users again asking the same question and everyone telling then , No you can't do that, Dear Prudence, Apart from all the answers given here, I would like to provide additional Information -
Yes you can actually do, List list = new List();
But at the cost of writing implementations of all the methods of Interfaces.
The notion is not simply List list = new List(); but

List<Integer> list = new List<Integer>(){

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            // TODO Auto-generated method stub
            return false;
        }

..... and So on (Cant write all methods.)

This is an example of Anonymous class. Its correct when someone states , No you cant instantiate an interface, and that's right. But you can never say , You CANT write List list = new List(); but, evidently you can do that and that's a hard statement to make that You can't do.


问:
C# new in method declaration
```<code>public new int AdjustedBaseValue
</code>```

<p>What does the new here mean or do? </p>

答: New is to hiding the baseclass implementation. Stoping the polymorphism...</p>

Title: C# new in method declaration

Body:
public new int AdjustedBaseValue

What does the new here mean or do?


答:
To get the Car along with their Vehicle information you can do a query using Eager Loading

```<code>$result = Car::with('vehicles')->get();
</code>```

One more correction you have specified class name as string literals without specifying FQN, relationships in models should be defined using fully qualified name

Car Model

```<code>class Car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany(\App\Models\Vehicle::class);
    }
}
</code>```

Vehicle Model

```<code>class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';
    public function cars()
    {
        return $this->belongsTo(\App\Models\Car::class);
    }
}
</code>```

Title: How to select foreign key value in Laravel

Body:
To get the Car along with their Vehicle information you can do a query using Eager Loading

$result = Car::with('vehicles')->get();

One more correction you have specified class name as string literals without specifying FQN, relationships in models should be defined using fully qualified name

Car Model

class Car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany(\App\Models\Vehicle::class);
    }
}

Vehicle Model

class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';
    public function cars()
    {
        return $this->belongsTo(\App\Models\Car::class);
    }
}


问:
jquery passing string reference to object as parameter to function
I'm not sure wether to pass an $(object) or a string referencing the name of an object to a function:

```<code>function makeObject(div){
    var newDiv = $(div);
    $(div).html("newDiv: " + newDiv);
    }
</code>```

and caller:

```<code><div id="myDiv">
<a href="#" onclick="makeObject($(this).parent().attr('id'));">makeObject(this</a>
</div>
</code>```

I hope this is clear. It's a test function to get the principle in my head. Thanks in advance.

答:
I got it! This way, I'm sure there is a more elegant answer but:
    function makeObject(div){
    var newDiv = {};//$(div);
    newDiv = $("#"+div+"");
    newDiv.html("newDiv: " + newDiv);
   }
and function call:

makeObject(this);

Body:
I'm not sure wether to pass an $(object) or a string referencing the name of an object to a function:

function makeObject(div){
    var newDiv = $(div);
    $(div).html("newDiv: " + newDiv);
    }

and caller:

makeObject(this

I hope this is clear. It's a test function to get the principle in my head. Thanks in advance.

Body:
I got it! This way, I'm sure there is a more elegant answer but:
    function makeObject(div){
    var newDiv = {};//$(div);
    newDiv = $("#"+div+"");
    newDiv.html("newDiv: " + newDiv);
   }
and function call:
    <div id="myDiv"><a href="#" onclick="makeObject($(this).parent().attr('id'));" >makeObject(this);</a></div>


问:
Android webview multitouch zoom not work in HVGA
On galaxy S the zoom controls work on multitouch, but on HTC Legend, the same code doesnt work. What is the matter?</p>

答:
Htc has done some changes in their webview implementation and that requires to call some API to make pinch to zoom working on those phones. Try following:</p>

```<code>_webView.getSettings().setBuiltInZoomControls(true);
        try {
            Method m = _webView.getClass().getMethod("enableMultiTouch",
                    null);
            if (m != null) {
                m.invoke(_webView, null);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }

        try {
            Method m = _webView.getClass().getMethod(
                    "enableMultiTouchTextRelow", boolean.class);
            if (m != null) {
                m.invoke(_webView, false);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        try {

            Method m = _webView.getClass().getMethod(
                    "setIsCacheDrawBitmap", boolean.class);
            if (m != null) {
                m.invoke(_webView, false);
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }

        // Must for HTC EVO to do text reflow after double tap
        try {
            Method m = _webView.getClass().getMethod("enableSmartZoom",
                    null);
            if (m != null) {
                m.invoke(_webView, null);
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }
</code>```

Body:
Htc has done some changes in their webview implementation and that requires to call some API to make pinch to zoom working on those phones. Try following:

_webView.getSettings().setBuiltInZoomControls(true);
        try {
            Method m = _webView.getClass().getMethod("enableMultiTouch",
                    null);
            if (m != null) {
                m.invoke(_webView, null);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }

        try {
            Method m = _webView.getClass().getMethod(
                    "enableMultiTouchTextRelow", boolean.class);
            if (m != null) {
                m.invoke(_webView, false);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        try {

            Method m = _webView.getClass().getMethod(
                    "setIsCacheDrawBitmap", boolean.class);
            if (m != null) {
                m.invoke(_webView, false);
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }

        // Must for HTC EVO to do text reflow after double tap
        try {
            Method m = _webView.getClass().getMethod("enableSmartZoom",
                    null);
            if (m != null) {
                m.invoke(_webView, null);
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }


答:
You can use array#map along with object#destructuring. Iterate through your object using array#map and get the name and id value and create a new object.

let resArray = [ {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"}, {"name": "Bert", "id": 456, "sex": "male", "country": "usa"}, {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"}, {"name": "Chris", "id": 856, "sex": "male","country": "usa"}, {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"}, {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];
let result = resArray.map(({name, id}) => ({name, id}));
console.log(result);```

Title: How to minimize an object and build an array from an array of objects in JavaScript

Body:
I have an array of objects and each object has around 5 properties and respective values. I would like to iterate through each object in the array and pick only two properties from it and rebuild the object and the array.

For example:

let resArray = [
{"name": "Aaron", "id": 123, "sex": "male", "country": "usa"},
{"name": "Bert", "id": 456, "sex": "male", "country": "usa"},
{"name": "Brenda", "id": 657, "sex": "female", "country": "canada"},
{"name": "Chris", "id": 856, "sex": "male", "country": "usa"},
{"name": "Angela", "id": 113, "sex": "female", "country": "columbia"},
{"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];

I want to remove the "country" and the "sex" properties from the objects and retain the "name" and "id" properties and rebuild the array. i.e., the output should be as follows:

let outArray = [
{"name": "Aaron", "id": 123},
{"name": "Bert", "id": 456},
{"name": "Brenda", "id": 657},
{"name": "Chris", "id": 856},
{"name": "Angela", "id": 113},
{"name": "Maria", "id": 569}];

As of now, I am just using the resArray and iterating through the whole array and getting whatever values I want. But I just think I can minimize the object so that it will be clear of the clutter.

Could anyone help me out with it?
Thank you.


问:
Nuxt.js - For each route a different transition
I'm currently working with Nuxt.js, which is awesome! I made some transitions for each page I created. However I want to call a specific transition when you go to a page from an archive. For example:

In an archive you have two a hrefs, each a href goes to another page. So you have different routes like: archive -> page 1 and archive -> page 2. I want to make an transition-out for the archive when it's leaving to page 1 and page 2. I need to call a specific transition for each route. But I couldn't find anything in documentation how this works. Has someone an idea or an example?

答:
I think you're on the right track.

Essentially, you just want to call in the transition key as a function. Think of the 'from' as the archive page and the 'to' as the next page.  You could do something like this:

```<code>transition (to, from) {
  if (to.path === '/page-1'){
      return 'transition-one'
  } else if (to.path === '/page-2') {
      return 'transition-two'
  }
}
</code>```

Or in pseudo code...

```<code>// If the 'to' path is the same as /path-1
    // Do the transition with the name 'transition-one'
// Otherwise, if the 'to' path is the same as /path-2
    // Do the transition with the name 'transition-two'.
</code>```

You can put this transition function in your module exports, just the same as your lifecycle hooks.  Does this help a bit?

Body:
I think you're on the right track.

Essentially, you just want to call in the transition key as a function. Think of the 'from' as the archive page and the 'to' as the next page.  You could do something like this:

transition (to, from) {
  if (to.path === '/page-1'){
      return 'transition-one'
  } else if (to.path === '/page-2') {
      return 'transition-two'
  }
}

Or in pseudo code...

// If the 'to' path is the same as /path-1
    // Do the transition with the name 'transition-one'
// Otherwise, if the 'to' path is the same as /path-2
    // Do the transition with the name 'transition-two'.

You can put this transition function in your module exports, just the same as your lifecycle hooks.  Does this help a bit?


问:
Instamojo payment gateway integration with ios objective c webview
Does anyobody know how to integrate instamojo payment gateway in objective C. I have opened Instamojo payment screen in Webview but how to handle success of payment and redirect to app.</p>

答:
HI Manish for payment gateways

You need to create Merchant account. For Merchant account you need to login in Instamojo.

After creation of Merchant account, they will provide keys and SDKs(iOS, android). You need to download that SDK and integrate that in your app. Use that key in AppDelegate Class. They will provide a sample code how to use the keys, SDK and how to do the payments. Follow the instructions.


问:
Grouping css selectors
Is it possible to group two selectors so that an element is matched only if both selectors are satisfied?  For example, if I want the element to satisfy both the selectors .a>.b~.c and .d~.e, is it possible to write a selector that matches the intersection of these selectors?

答: No, you cannot do set intersection in CSS selectors.  Sometimes you can find a way to combine two selectors into one that solves your specific problem, but I don't think there's a way to combine your two sample selectors.</p>

Title: Grouping css selectors


问:
iOS, Swift: How to save an array that contains custom objects so that I can be loaded for reuse?

I have an array that contains objects that I've created. I would like the manager class to load this array from the disk so that I can continue appending to the array.

---HERE IS THE CLASS I WOULD LIKE TO MANAGE LOADING THE ARRAY

```<code> class FoodManager{
    var foodList : [FoodItem]

    func addFood(name : String, carbs : Int, fat: Int, protein : Int) {
        let food = FoodItem(name: name, carbs: carbs, protein: protein,       fat: fat)
        foodList.append(food)
    }

    init(){
        foodList = [FoodItem]()
        //Here is where I would like to load the array to initialize foodList or if the file doesn't exist, create a new array

    }
}
</code>```

-----HERE IS THE CLASS THAT IS IN THE ARRAY----

```<code>class FoodItem{
    let name: String
    let carbs: Int
    let protein: Int
    let fat: Int

    init(name: String, carbs: Int, protein: Int, fat: Int){
        self.name = name
        self.carbs = carbs
        self.protein = protein
        self.fat = fat
    }
}
</code>```

I've found a lot of info on saving a class that has just primitive data types but have been having trouble finding examples where an array of user defined objects needs to be saved.

thanks!

答: You need to use NSCoder class to save custom object array in your manager class.</p>

Body:
I have an array that contains objects that I've created. I would like the manager class to load this array from the disk so that I can continue appending to the array.

---HERE IS THE CLASS I WOULD LIKE TO MANAGE LOADING THE ARRAY

 class FoodManager{
    var foodList : [FoodItem]

    func addFood(name : String, carbs : Int, fat: Int, protein : Int) {
        let food = FoodItem(name: name, carbs: carbs, protein: protein,       fat: fat)
        foodList.append(food)
    }

    init(){
        foodList = [FoodItem]()
        //Here is where I would like to load the array to initialize foodList or if the file doesn't exist, create a new array

    }
}

-----HERE IS THE CLASS THAT IS IN THE ARRAY----

class FoodItem{
    let name: String
    let carbs: Int
    let protein: Int
    let fat: Int

    init(name: String, carbs: Int, protein: Int, fat: Int){
        self.name = name
        self.carbs = carbs
        self.protein = protein
        self.fat = fat
    }
}

I've found a lot of info on saving a class that has just primitive data types but have been having trouble finding examples where an array of user defined objects needs to be saved.

thanks!


问:
CMAKE_PREFIX_PATH doesn't help CMake in finding Qt5
From here: https://stackoverflow.com/a/28327499/462608

I tried this:

```<code>cmake_minimum_required(VERSION 2.8.12)

project(qtquick_hello_cmake)

set(CMAKE_PREFIX_PATH "/opt/Qt5.9.1/5.9.1/")

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

find_package(Qt5 COMPONENTS Quick Core REQUIRED)

qt5_add_resources(RESOURCES qml.qrc)

add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")

qt5_use_modules(${PROJECT_NAME} Quick Core)

target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Quick)
</code>```

Here is the output of cmake .

```<code>:~/junk/qtquick_hello_cmake$ cmake .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".
</code>```

This is to show that /opt/Qt5.9.1/ does exist.

```<code>:~/junk/qtquick_hello_cmake$ cd /opt/Qt5.9.1/5.9.1/
:/opt/Qt5.9.1/5.9.1$ ls
android_armv7  android_x86  gcc_64  Src
</code>```

Here I run the cmake with -DCMAKE option, but the output is still same:

```<code>:~/junk/qtquick_hello_cmake$ cmake -DCMAKE_PREFIX_PATH=/opt/Qt5.9.1/5.9.1/ -DWITH_QT5=1 .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".
</code>```

Contents of the directory:

```<code>:~/junk/qtquick_hello_cmake$ ls
CMakeCache.txt  CMakeFiles  CMakeLists.txt  main.cpp  main.qml  qml.qrc
</code>```

答:
I installed the following missing packages:

```<code>sudo apt-get install qtbase5-dev
sudo apt-get install qtdeclarative5-dev
</code>```

Attaching any kind of prefix is not required now:

CMakeList:

```<code>    :~/junk/qtquick_hello_cmake$ cat CMakeLists.txt
    cmake_minimum_required(VERSION 2.8.12)

    project(qtquick_hello_cmake)

    set(CMAKE_INCLUDE_CURRENT_DIR ON)
    set(CMAKE_AUTOMOC ON)
    set(CMAKE_AUTORCC ON)

    find_package(Qt5 COMPONENTS Quick Core REQUIRED)

    qt5_add_resources(RESOURCES qml.qrc)

    add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")

    qt5_use_modules(${PROJECT_NAME} Quick Core)

    target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Quick)
</code>```

New output:

```<code>:~/junk/qtquick_hello_cmake$ ls
build  CMakeLists.txt  main.cpp  main.qml  qml.qrc

:~/junk/qtquick_hello_cmake$ cd build/
:~/junk/qtquick_hello_cmake/build$ rm -rf *

:~/junk/qtquick_hello_cmake/build$ cmake ../
-- The C compiler identification is GNU 4.8.4
-- The CXX compiler identification is GNU 4.8.4
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/.../junk/qtquick_hello_cmake/build
</code>```

Errors are gone now.

Thanks to:

https://answers.ros.org/question/236324/could-not-find-a-package-configuration-file-provided-by-qt5widgets/

https://askubuntu.com/questions/508503/whats-the-development-package-for-qt5-in-14-04

Body:
From here: https://stackoverflow.com/a/28327499/462608

I tried this:

cmake_minimum_required(VERSION 2.8.12)

project(qtquick_hello_cmake)

set(CMAKE_PREFIX_PATH "/opt/Qt5.9.1/5.9.1/")

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

find_package(Qt5 COMPONENTS Quick Core REQUIRED)

qt5_add_resources(RESOURCES qml.qrc)

add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")

qt5_use_modules(${PROJECT_NAME} Quick Core)

target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Quick)

Here is the output of cmake .

:~/junk/qtquick_hello_cmake$ cmake .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".

This is to show that /opt/Qt5.9.1/ does exist.

:~/junk/qtquick_hello_cmake$ cd /opt/Qt5.9.1/5.9.1/
:/opt/Qt5.9.1/5.9.1$ ls
android_armv7  android_x86  gcc_64  Src

Here I run the cmake with -DCMAKE option, but the output is still same:

:~/junk/qtquick_hello_cmake$ cmake -DCMAKE_PREFIX_PATH=/opt/Qt5.9.1/5.9.1/ -DWITH_QT5=1 .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".

Contents of the directory:

:~/junk/qtquick_hello_cmake$ ls
CMakeCache.txt  CMakeFiles  CMakeLists.txt  main.cpp  main.qml  qml.qrc

Body:
I installed the following missing packages:

sudo apt-get install qtbase5-dev
sudo apt-get install qtdeclarative5-dev

Attaching any kind of prefix is not required now:

CMakeList:

    :~/junk/qtquick_hello_cmake$ cat CMakeLists.txt
    cmake_minimum_required(VERSION 2.8.12)

    project(qtquick_hello_cmake)

    set(CMAKE_INCLUDE_CURRENT_DIR ON)
    set(CMAKE_AUTOMOC ON)
    set(CMAKE_AUTORCC ON)

    find_package(Qt5 COMPONENTS Quick Core REQUIRED)

    qt5_add_resources(RESOURCES qml.qrc)

    add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")

    qt5_use_modules(${PROJECT_NAME} Quick Core)

    target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Quick)

New output:

:~/junk/qtquick_hello_cmake$ ls
build  CMakeLists.txt  main.cpp  main.qml  qml.qrc

:~/junk/qtquick_hello_cmake$ cd build/
:~/junk/qtquick_hello_cmake/build$ rm -rf *

:~/junk/qtquick_hello_cmake/build$ cmake ../
-- The C compiler identification is GNU 4.8.4
-- The CXX compiler identification is GNU 4.8.4
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/.../junk/qtquick_hello_cmake/build

Errors are gone now.

Thanks to:

https://answers.ros.org/question/236324/could-not-find-a-package-configuration-file-provided-by-qt5widgets/

https://askubuntu.com/questions/508503/whats-the-development-package-for-qt5-in-14-04


问:
.NET hot deploy/undeploy of bundled code. How to? Which container?
We are new to the .NET world and have built a small C# application on top of Nancy

We are looking for a way to "package" the application code so that we can programmatically hot deploy and undeploy it on top of a minimal Nancy based container (or any other appropriate container you may suggest)

How do we do this in the .NET world ?

In the JVM world, one way to do it is to package a Web Application Resource (war) that is deployed on top of a servlet engine, typically Jetty or Tomcat. There are other solutions (micro-containers, using class loaders directly, etc..). We are looking of an equivalent .NET paradigm.

EDIT Dec 5

There seems to be solutions around building Assemblies and using methods such as Assembly.LoadFromString.

This still seems pretty manual and we are looking for a C# library/framework to help with loading/unloading

答:
The only way to unload code is to unload an entire AppDomain. This means that you probably want to to create a new AppDomain for every Assembly that you load dynamically.

This example gives you a starting point on how to create a new AppDomain and how to call code loaded into another AppDomain:
https://stackoverflow.com/a/2648592/540832


问:
How to validate Top Level Domain of an email address?
Let's say I have a contact form where a user can enter his email address along with his other contact details. I need to check the validity of Generic top level domain or top level domain of the email address. An example:

scarlet.1992@examplemail.paris

I need to check if .paris is a valid top level domain.

Please refer to this link for the list of domains available, which gives a number around 1200. Storing the domain names in a local table and searching is not an option since new domains are being introduced everyday.
Please let me know if there is any web service or free API available for this, or there is any other way to validate the email address.

答:
There is nothing wrong with storing a list of TLDs locally when you need a quick answer for client-side validation or don't want to consume network resources for a reverse DNS lookup.

Email addresses from newer TLDs are extremely rare for most use cases. I update my list about once per year and find that it's good enough.


问:
Find out Excel column character from name of cell in first row
I have an excel sheet that looks like this;

The header names are found in first row. I would like to have a VBA function that returns the column number, given the cell name in the first row. For example, getColumnNumber("B Symbol") should return B. getColumnNumber("C Symbol") should return C.

I am using Excel 2016.

答:
You don't need VBA for this. The following formula works just as well and any VBA is using essentially the same method.</p>

```<code>=SUBSTITUTE(ADDRESS(1, MATCH("C Symbol", 1:1, 0), 4), 1, TEXT(,))
</code>```

Body:
You don't need VBA for this. The following formula works just as well and any VBA is using essentially the same method.

=SUBSTITUTE(ADDRESS(1, MATCH("C Symbol", 1:1, 0), 4), 1, TEXT(,))