问:
Would it possible to implement a button to the approach I'm taking to display information in a Google Maps marker in Android?
I'm creating a small app that will help a user find a sports club. I'm currently creating a club coordinate variable in the MapsActivity.java file like so:

```<code>public void onMapReady(GoogleMap googleMap) {

     mMap = googleMap;

     LatLng lansdowneRFC = new LatLng(53.3334103,-6.2201649);

    // Adds location to the map (includes a small bit of info about the club)
    mMap.addMarker(new MarkerOptions().position(lansdowneRFC).title("Lansdowne RFC").snippet("Aviva Stadium, 62 Lansdowne Rd,"));
}
</code>```

This produces the following result

I'm trying to add a button to the information box that will bring the user to another activity (The activity will be a sign up form so they can join the club). Considering the approach I'm using is it possible to implement a button or will I have to approach it in another way? I've seen ideas like a custom popup window be suggested for this type of thing but how I implement that into a google maps marker instead of a button is where I'm hitting a brick wall. Any suggestions

答:
You can set your own implementation of InfoWindowAdapter to your GoogleMap object with a call to setInfoWindowAdapter().

And in the adapter you can override getInfoContents() to return whatever view you want.

But the down side is the view that is shown is not a live view, it's an image of the view you created, and you can handle the click on it using a OnInfoWindowClickListener that you set on the GoogleMap object with setOnInfoWindowClickListener().

But that handles the click on the whole window, not just the button.

Another option is to know where your marker is at the screen and show a popup manually above it that has nothing to do with the map, but I would not recommend that approach, with Android's different device sizes and all, that could quickly get very ugly.

Body:
I'm creating a small app that will help a user find a sports club. I'm currently creating a club coordinate variable in the MapsActivity.java file like so:

public void onMapReady(GoogleMap googleMap) {

     mMap = googleMap;

     LatLng lansdowneRFC = new LatLng(53.3334103,-6.2201649);

    // Adds location to the map (includes a small bit of info about the club)
    mMap.addMarker(new MarkerOptions().position(lansdowneRFC).title("Lansdowne RFC").snippet("Aviva Stadium, 62 Lansdowne Rd,"));
}

This produces the following result

I'm trying to add a button to the information box that will bring the user to another activity (The activity will be a sign up form so they can join the club). Considering the approach I'm using is it possible to implement a button or will I have to approach it in another way? I've seen ideas like a custom popup window be suggested for this type of thing but how I implement that into a google maps marker instead of a button is where I'm hitting a brick wall. Any suggestions


来源: stackexchange

问:
Get itunes link to whole developer account with no one app submitted
I know how to get a link to the app before you publish it, but is there a way to get a link to the entire profile, with no apps yet published on AppStore with this account? Link like this one: https://itunes.apple.com/us/developer/google-inc./id281956209</p>

答: It's not possible to get the link to a developer page without any apps. The ID used for the itunes.apple.com link (let's call it developer ID) is not the provider ID you will find in iTunes Connect (just checked with several accounts) and identifies the team you belong on iTunes Connect to. </p>

ContentLicense: CC BY-SA 3.0


问:
R ts with missing values
I have a data frame I read from a csv file that has daily observations:

```<code>Date        Value
2010-01-04  23.4
2010-01-05  12.7
2010-01-04  20.1
2010-01-07  18.2
</code>```

PROBLEM: Missing data.
Forecast package expects a plain ts object not containing any missing data, while my dataset has missing data on most weekends and other random points.

converting to ts should not work

```<code>ts(values, start = c(1997, 1), frequency = 1)
</code>```

the only solution I can think of is to transform daily data to weekly data but R is a new thing and other better solutions could exist.

答:
You can use the imputeTS, zoo or forecast package, which all offer methods to fill the missing data.
(the process of filling missing gaps is also called imputation)

imputeTS

```<code>na_interpolation(yourData)
na_seadec(yourdata)
na_kalman(yourdata)
na_ma(yourdata)
</code>```

zoo

```<code>na.approx(yourdata)
na.locf(yourdata)
na.StructTS(yourdata)
</code>```

forecast

```<code>na.interp(yourdata)
</code>```

These are some functions from the packages you could use.

Title: R ts with missing values

Body:
I have a data frame I read from a csv file that has daily observations:

Date        Value
2010-01-04  23.4
2010-01-05  12.7
2010-01-04  20.1
2010-01-07  18.2

PROBLEM: Missing data.
Forecast package expects a plain ts object not containing any missing data, while my dataset has missing data on most weekends and other random points.

converting to ts should not work

ts(values, start = c(1997, 1), frequency = 1)

the only solution I can think of is to transform daily data to weekly data but R is a new thing and other better solutions could exist.

Body:
You can use the imputeTS, zoo or forecast package, which all offer methods to fill the missing data.
(the process of filling missing gaps is also called imputation)

imputeTS

na_interpolation(yourData)
na_seadec(yourdata)
na_kalman(yourdata)
na_ma(yourdata)

zoo

na.approx(yourdata)
na.locf(yourdata)
na.StructTS(yourdata)

forecast

na.interp(yourdata)

These are some functions from the packages you could use.

ContentLicense: CC BY-SA 4.0


问:
Htaccess: Rewrite Rule adding Trailing Slash in the middle of URL
I am not really familiar with RegExp and it's really hard for me.
I want to do the following:

Rewriting this:

http://www.example.com/pl?utm_source=test&utm_medium=testing&utm_campaign=test-testing

to this:

http://www.example.com/pl/?utm_source=test&utm_medium=testing&utm_campaign=test-testing

As you can see I want to add a trailing slash after "pl".

Hope anyone has an idea. (or tutorials, guides etc.)

答:
GOT IT:

It was easier than I thought:

```<code>   RewriteRule ^(..)$ $1/
</code>```

Body:
GOT IT:

It was easier than I thought:

   RewriteRule ^(..)$ $1/


问:
JMeter - ElasticSearch backend listener plugin doesn't work
I have JMeter 3.3 and I added ElasticSearch backend listener plugin.

I opened JMeter GUI and tried create back end listener and it failed with error:

```<code>2017-10-17 14:35:24,785 ERROR o.a.j.g.GuiPackage: Problem retrieving gui for org.apache.jmeter.visualizers.backend.BackendListenerGui
java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    ... 26 more
2017-10-17 14:35:30,212 ERROR o.a.j.g.a.AddToTree: Exception while adding a component to tree.
java.lang.RuntimeException: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:359) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more
</code>```

Sent question in plugin group but didn't receive any answer.

Is it working only with additional plugin/jars? on different version?

Also why doesn't it have page in https://jmeter-plugins.org/ (although it displayed in search results in site)?

答:
I'm the person who reworked the plugin and put it on jmeter-plugins. It seems to be a conflict between two versions of OkHttpClient. One loaded by the plugin, and the other has yet to be found. Currently investiguating and will release 2.0 as soon as it is fixed.

I want to apologize for the delay on an answer (literally just found your post). For any more help, please oh please, feel free to open an issue on the GitHub repository page :).

https://github.com/delirius325/JMeter_ElasticsearchBackendListener/

Have a good one,

Body:
I have JMeter 3.3 and I added ElasticSearch backend listener plugin.

I opened JMeter GUI and tried create back end listener and it failed with error:

2017-10-17 14:35:24,785 ERROR o.a.j.g.GuiPackage: Problem retrieving gui for org.apache.jmeter.visualizers.backend.BackendListenerGui
java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    ... 26 more
2017-10-17 14:35:30,212 ERROR o.a.j.g.a.AddToTree: Exception while adding a component to tree.
java.lang.RuntimeException: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:359) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more

Sent question in plugin group but didn't receive any answer.

Is it working only with additional plugin/jars? on different version?

Also why doesn't it have page in https://jmeter-plugins.org/ (although it displayed in search results in site)?


问:
SciChart and SwiftyJSON
I am getting an [!] Invalid Podfile file: syntax error,

source 'https://github.com/ABTSoftware/PodSpecs.git'

platform :ios, '9.0'

target 'HavingFunWithScichart' do

use_frameworks!

# Pods for HavingFunWithScichart

```<code>pod 'SciChart'

pod 'SwiftyJSON'

pod 'Alamofire'
</code>```

end

I know that I am getting it due to the pre-install script file. For the script instructs only to install the SciChart pod file.

My question is, how can I add my SwiftyJSON and Alamofire so that I can do my
pod install
??
Can anyone help me on how I can do this? I have checked and read over and over the documentation for Cocoapods but it does not cover anything on how I can over come the Pre-install script so that I can add the additional pods that I need for my project.

答: How Do I delete this request please? I just heard back that it was a omission in their script and they will be fixing it.</p>

Title: SciChart and SwiftyJSON

Body:
I am getting an [!] Invalid Podfile file: syntax error,

source 'https://github.com/ABTSoftware/PodSpecs.git'

platform :ios, '9.0'

target 'HavingFunWithScichart' do

use_frameworks!

# Pods for HavingFunWithScichart

pod 'SciChart'

pod 'SwiftyJSON'

pod 'Alamofire'

end

I know that I am getting it due to the pre-install script file. For the script instructs only to install the SciChart pod file.

My question is, how can I add my SwiftyJSON and Alamofire so that I can do my
pod install
??
Can anyone help me on how I can do this? I have checked and read over and over the documentation for Cocoapods but it does not cover anything on how I can over come the Pre-install script so that I can add the additional pods that I need for my project.


问:
Timestamp based sorted data structure with logarithmic read complexity
I'm looking for a good sorted data structure in java. After doing some research got few hints about using TreeSet/TreeMap. But these components is lack of one thing: random access to an element in the set. For example, I want to access nth element in the sorted set, but with TreeSet, I must iterate over other n-1 elements before I can get there. It would be a waste since I would have upto several thousands elements in my Set.

The use case is like below

```<code>9:20 AM what is this object? edited by user1
9:30 AM what is this book ? edited by user2
9:40 PM what is this red book? edited by user1
</code>```

I always want to show the latest edited title by that user. I know that the latest is going to be with greatest timestamp. For this i found that ConcurrentSkipListSet/Maps are good. But, I would like to know if there are any better ways to implement this functionality.

答:
Assuming you should keep your data sorted, your best bet is TreeMap. There's no silver bullet which is a sorted collection and also perform O(1) random access. In an ordered collection, you're capable of accessing an element with index directly but you cannot benefit from index based access if your collection is required sorted.

If you need concurrency, ConcurrentSkipListMap is good. It's suitable for large-scale concurrent access to data. However, in terms of performance, it's no match for our Red-Black tree based pal, TreeMap. Thus if you don't need concurrency, forget ConcurrentSkipListMap and stick with TreeMap.

TreeMap is elegant and satisfies your need. Nonetheless, in practice, using HashMap and sorting data whenever you need might be better. Try both and find out which one is better in your case.

Body:
I'm looking for a good sorted data structure in java. After doing some research got few hints about using TreeSet/TreeMap. But these components is lack of one thing: random access to an element in the set. For example, I want to access nth element in the sorted set, but with TreeSet, I must iterate over other n-1 elements before I can get there. It would be a waste since I would have upto several thousands elements in my Set.

The use case is like below

9:20 AM what is this object? edited by user1
9:30 AM what is this book ? edited by user2
9:40 PM what is this red book? edited by user1

I always want to show the latest edited title by that user. I know that the latest is going to be with greatest timestamp. For this i found that ConcurrentSkipListSet/Maps are good. But, I would like to know if there are any better ways to implement this functionality.


问:
Puzzle on looping statement

Possible Duplicate:

  Not able to solve the puzzle regarding this code…

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that,
it doesn't work.

```<code>#include <stdio.h>
  int main()
  {
      int i;
      int n = 20;
      for( i = 0; i < n; i-- )
          printf("-");
      return 0;
  }
</code>```

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above
code, by changing exactly one character

答: You could change it so that instead of i--, you do n--.</p>

ContentLicense: CC BY-SA 2.5

Title: Puzzle on looping statement

Body:
Possible Duplicate:

  Not able to solve the puzzle regarding this code…

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that,
it doesn't work.

#include <stdio.h>
  int main()
  {
      int i;
      int n = 20;
      for( i = 0; i < n; i-- )
          printf("-");
      return 0;
  }

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above
code, by changing exactly one character


问:
Set setReadTimeout and setConnectTimeout after connect
This is a simple code:

```<code>URLConnection connection;
URL source = new URL("Some Url");
connection = source.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
connection.setConnectTimeout(500);
connection.setReadTimeout(500);
</code>```

My question is that if I reset the connection timeout and read timeout of UrlConnection after connect using respective functions, as in above code, will the new values will work or the connection will timeout according to old values? In above, when will timeout happen, after 2000 ms or 500 ms?

答:
Assuming your using Java 7, according to the docs from oracle (here)

After calling connect on URLConnection object, it is an error to try to set those options (connect time out and read time out). So the answer would be it might make your apps make a wrong turn or the set time method will be passed - Depends on what kind of try/catch you're using to wrap the code that create URLConnection.

Since in android studio when you're creating a new URLConnection or when you call source.openConnection() to open the connection it will require you to surround it with try/catch.

Hope this help :D

Body:
This is a simple code:

URLConnection connection;
URL source = new URL("Some Url");
connection = source.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
connection.setConnectTimeout(500);
connection.setReadTimeout(500);

My question is that if I reset the connection timeout and read timeout of UrlConnection after connect using respective functions, as in above code, will the new values will work or the connection will timeout according to old values? In above, when will timeout happen, after 2000 ms or 500 ms?


问:
Loss of precision when casting Math.pow()
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

```<code>2_147_483_647
</code>```

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

```<code>System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);
</code>```

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

答:
First example

Let us analyze what you have done. The first example is

```<code>((long) Math.pow(2, 31)) - 1;
</code>```

This means that you first compute Math.pow(2, 31) which yields

```<code>2.147_483_648 E9
</code>```

After that you cast to long. Note that long has enough place for this value, so it represents it as

```<code>2_147_483_648
</code>```

Then you subtract 1 and get

```<code>2_147_483_647
</code>```

Second example

Let's now see what the second example does. Your wrote

```<code>(int) Math.pow(2, 31) - 1
</code>```

This is interpreted as

```<code>((int) Math.pow(2, 31)) - 1
</code>```

So the same as before but with a cast to int instead of long. Now note that int does not have enough place for the value. The biggest int that can be represented is

```<code>2_147_483_647 // MAX_INTEGER
</code>```

and thus you will also get exactly this value here. After that you subtract 1 and get

```<code>2_147_483_646
</code>```

Correction

I think you thought that

```<code>(int) Math.pow(2, 31) - 1
</code>```

evaluates to

```<code>(int) (Math.pow(2, 31) - 1)
</code>```

but it doesn't. If you make this explicit you will indeed get

```<code>2.147_483_648 E9
</code>```0

as expected.

Operator precedence

You can read about that in the Java Language Specification, refer to JLS§15.15 Unary Operators. Casting has precedence over operators like subtraction.

That is because casting is an unary operator whereas subtraction is binary. Unary has precedence over binary. The official documentation therefore gives the following table as overview:

```<code>2.147_483_648 E9
</code>```1

Casting is of course part of the unary category.

Body:
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

2_147_483_647

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

Body:
First example

Let us analyze what you have done. The first example is

((long) Math.pow(2, 31)) - 1;

This means that you first compute Math.pow(2, 31) which yields

2.147_483_648 E9

After that you cast to long. Note that long has enough place for this value, so it represents it as

2_147_483_648

Then you subtract 1 and get

2_147_483_647

Second example

Let's now see what the second example does. Your wrote

(int) Math.pow(2, 31) - 1

This is interpreted as

((int) Math.pow(2, 31)) - 1

So the same as before but with a cast to int instead of long. Now note that int does not have enough place for the value. The biggest int that can be represented is

2_147_483_647 // MAX_INTEGER

and thus you will also get exactly this value here. After that you subtract 1 and get

2_147_483_646

Correction

I think you thought that

(int) Math.pow(2, 31) - 1

evaluates to

(int) (Math.pow(2, 31) - 1)

but it doesn't. If you make this explicit you will indeed get

2_147_483_647

as expected.

Operator precedence

You can read about that in the Java Language Specification, refer to JLS§15.15 Unary Operators. Casting has precedence over operators like subtraction.

That is because casting is an unary operator whereas subtraction is binary. Unary has precedence over binary. The official documentation therefore gives the following table as overview:

+----------------------------------------------------------------+
| Operators             | Precedence (top is high, bottom low)   |
|-----------------------|----------------------------------------|
| postfix               | expr++ expr--                          |
| unary                 | ++expr --expr +expr -expr ~ !          |
| multiplicative        | * / %                                  |
| additive              | + -                                    |
| shift                 | << >> >>>                              |
| relational            | < > <= >= instanceof                   |
| equality              | == !=                                  |
| bitwise AND           | &                                      |
| bitwise exclusive OR  | ^                                      |
| bitwise inclusive OR  | |                                      |
| logical AND           | &&                                     |
| logical OR            | ||                                     |
| ternary               | ? :                                    |
| assignment            | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
+----------------------------------------------------------------+

Casting is of course part of the unary category.


问:
Confirmation Email in aspnetboilerplate
How can i send confirmation email and validate the confirmation in aspnetboilerplate template

```<code>CheckErrors(await _userManager.CreateAsync(user));
var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
</code>```

email confirmation token is generated and sending in mail but how can i store it in database to confirm the email

答:
Simply assign it to user:

CheckErrors(await _userManager.CreateAsync(user));
await CurrentUnitOfWork.SaveChangesAsync();

var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
user.EmailConfirmationCode = emailConfirmationToken; // Here
```

Title: Confirmation Email in aspnetboilerplate

Body:
How can i send confirmation email and validate the confirmation in aspnetboilerplate template

CheckErrors(await _userManager.CreateAsync(user));
var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

email confirmation token is generated and sending in mail but how can i store it in database to confirm the email


问:
How to separate fields in a text file with a delimiter
I have a scenario where I have a text file and I want to separate the row values in the text file with a particular delimiter (say, :).

I have generated the text file by storing the output of an SQL query into a text file.

The contents of the text file are

```<code>field 1.2     xxxx
field 2.7.1   xxxx
field 1.9     xxxx
field 1.4     xxxx
field 2.7.1   xxxx
</code>```

I tried this:

```<code>cat /tmp/file.txt | sed 's/ /:/g'
</code>```

but as the space is not consistent over the rows, this does not work for me.

How can I do this?
the output that i am expecting here is something like this

```<code>field :1.2    :xxxx
field :2.7.1  :xxxx
field :1.9    :xxxx
field :1.4    :xxxx
field :2.7.1  :xxxx
</code>```

答: space-space-asterisk. The first space to say there has to be one, the second with an asterisk to say zero-or-more extras. sed 's/  */:/g'

Body:
I have a scenario where I have a text file and I want to separate the row values in the text file with a particular delimiter (say, :).

I have generated the text file by storing the output of an SQL query into a text file.

The contents of the text file are

field 1.2     xxxx
field 2.7.1   xxxx
field 1.9     xxxx
field 1.4     xxxx
field 2.7.1   xxxx

I tried this:

cat /tmp/file.txt | sed 's/ /:/g'

but as the space is not consistent over the rows, this does not work for me.

How can I do this?
the output that i am expecting here is something like this

field :1.2    :xxxx
field :2.7.1  :xxxx
field :1.9    :xxxx
field :1.4    :xxxx
field :2.7.1  :xxxx


问:
How to make Rails acceptable value out of JavaScript's array?

I'm trying to generate the value for a hidden field in a Rails form with JavaScript.

```<code>pickedImages = document.getElementsByClassName("picked_images");
imagesIds = []

for (var i = 0; i < pickedImages.length; i++) {
  imagesIds.push(pickedImages[i].id)
}

document.getElementById('user_post_materials').value = imagesIds;
</code>```

I need it like: value="150 152 146"

But when I try to make it out of JS array I get: value="150,152,146" which causes saving as a string in the database and further bugs.
I tried

```<code>imagesArray = imagesIds.join(' ')
document.getElementById('user_post_materials').value = imagesArray;
</code>```

But it still gives a wrong value: value="150, 152, 146" (Commas still present)

答:
You could try turning it into a string during this assignment:</p>

```<code>document.getElementById('user_post_materials').value = imagesArray.join(" ");
</code>```

Body:
I'm trying to generate the value for a hidden field in a Rails form with JavaScript.

pickedImages = document.getElementsByClassName("picked_images");
imagesIds = []

for (var i = 0; i < pickedImages.length; i++) {
  imagesIds.push(pickedImages[i].id)
}

document.getElementById('user_post_materials').value = imagesIds;

I need it like: value="150 152 146"

But when I try to make it out of JS array I get: value="150,152,146" which causes saving as a string in the database and further bugs.
I tried

imagesArray = imagesIds.join(' ')
document.getElementById('user_post_materials').value = imagesArray;

But it still gives a wrong value: value="150, 152, 146" (Commas still present)

Body:
You could try turning it into a string during this assignment:

document.getElementById('user_post_materials').value = imagesArray.join(" ");


问:
Trigger click on leaflet marker
I have a bunch of leaflet markers on the map. Each marker is held in array markers. The markers are created dynamically (during an ajax call).

```<code>var markers = [];
.
.
var marker = L.marker([mar.lat, mar.lng], {
  // ...build the marker...
}
marker._leaflet_id = mar.id; // give the marker an id corresponding to the id of its corresponding div
var myHoverIcon = L.icon({
  iconUrl: mar.imgUrl,
  iconSize: [40, 40],
  popupAnchor: [0, 0]
});
marker.on('click', function(e) {
  alert('Marker clicked!');
  marker.setIcon(myHoverIcon);
});
.
.
markers.push(marker);
</code>```

Each marker has an id corresponding to a particular div (stored in data-mess_id on the div). The plan is to change the marker's icon when its corresponding div in the feed is clicked on.

```<code>$('#feed').on('mouseover', '.message', function() {
  var cssid = $(this).attr('data-mess_id').toString();
  var baz = $.grep(markers, function(m) {
    return (m._leaflet_id == cssid);
  });
  baz[0].trigger('click');   // doesn't work
  alert(baz[0].getLatLng()); // does work

  // this also does not work:
  var myHoverIcon = L.icon({
    iconUrl: baz[0].imgUrl,
    iconSize: [40, 40],
    popupAnchor: [0, 0]
  });
  baz[0].setIcon(myHoverIcon);

});
</code>```

It's all working fine except for the final bit. I just can't trigger a click event on the marker. I definitely have the correct marker because baz[0].getLatLng() is working. But baz[0].trigger('click') doesn't work.

I tried creating a new icon dynamically (myHoverIcon) but it doesn't work.

How do I trigger a click event on the marker?

Is there another way to change the marker icon?

答:
To emulate a mouse click, you can use the fire method (inherited from Evented.fire) on the marker :

```<code>marker.fire('click');
</code>```

And a demo

var map = L.map('map').setView([0, 0], 12);

var icon = L.icon({
  iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png'
});
var marker = L.marker([0, 0], {icon: icon})
  .addTo(map);

var myHoverIcon = L.icon({
  iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-red.png'
});

marker.on('click', function(e) {
  marker.setIcon(myHoverIcon);
});

document.querySelector('button').addEventListener('click', function() {
  marker.fire('click');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  height: 100%;
  margin: 0;
}
#map {
  width: 100%;
  height: 100%;
}

button {position: absolute; left:10 px; top: 70px;}</code>```

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>

<button>Click me</button>```

Title: Trigger click on leaflet marker

Body:
I have a bunch of leaflet markers on the map. Each marker is held in array markers. The markers are created dynamically (during an ajax call).

var markers = [];
.
.
var marker = L.marker([mar.lat, mar.lng], {
  // ...build the marker...
}
marker._leaflet_id = mar.id; // give the marker an id corresponding to the id of its corresponding div
var myHoverIcon = L.icon({
  iconUrl: mar.imgUrl,
  iconSize: [40, 40],
  popupAnchor: [0, 0]
});
marker.on('click', function(e) {
  alert('Marker clicked!');
  marker.setIcon(myHoverIcon);
});
.
.
markers.push(marker);

Each marker has an id corresponding to a particular div (stored in data-mess_id on the div). The plan is to change the marker's icon when its corresponding div in the feed is clicked on.

$('#feed').on('mouseover', '.message', function() {
  var cssid = $(this).attr('data-mess_id').toString();
  var baz = $.grep(markers, function(m) {
    return (m._leaflet_id == cssid);
  });
  baz[0].trigger('click');   // doesn't work
  alert(baz[0].getLatLng()); // does work

  // this also does not work:
  var myHoverIcon = L.icon({
    iconUrl: baz[0].imgUrl,
    iconSize: [40, 40],
    popupAnchor: [0, 0]
  });
  baz[0].setIcon(myHoverIcon);

});

It's all working fine except for the final bit. I just can't trigger a click event on the marker. I definitely have the correct marker because baz[0].getLatLng() is working. But baz[0].trigger('click') doesn't work.

I tried creating a new icon dynamically (myHoverIcon) but it doesn't work.

How do I trigger a click event on the marker?

Is there another way to change the marker icon?

Body:
To emulate a mouse click, you can use the fire method (inherited from Evented.fire) on the marker :

marker.fire('click');

And a demo

var map = L.map('map').setView([0, 0], 12);

var icon = L.icon({
  iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png'
});
var marker = L.marker([0, 0], {icon: icon})
  .addTo(map);

var myHoverIcon = L.icon({
  iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-red.png'
});

marker.on('click', function(e) {
  marker.setIcon(myHoverIcon);
});

document.querySelector('button').addEventListener('click', function() {
  marker.fire('click');
});

html, body {
  height: 100%;
  margin: 0;
}
#map {
  width: 100%;
  height: 100%;
}

button {position: absolute; left:10 px; top: 70px;}

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>

<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>

<div id='map'></div>
<button>Click me</button>


问:
sql: ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
I am running and keep getting this error. Any help would be appreciated.
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'

I have  had other errors with senmcolons, commas and other small mistakes, but this one is eating me alive

```<code>-- 1 - Create Faculty Table
create table Faculty (
FacultyID int not null primary key,
FirstName varchar(50) not null,
LastName varchar(50) not null,
Email varchar(50) not null,
Date_of_birth date,
Number_of_courses smallint not null
);
</code>```

答:
Please use this kind of insert:

insert into Faculty (FirstName , LastName, Email, Date_of_birth, Number_of_courses) values ('Name1','Lastname2','xx@gmail.com','2016-12-07',2);

You need to specify which column you are inserting.

Body:
I am running and keep getting this error. Any help would be appreciated.
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'

I have  had other errors with senmcolons, commas and other small mistakes, but this one is eating me alive

-- 1 - Create Faculty Table
create table Faculty (
FacultyID int not null primary key,
FirstName varchar(50) not null,
LastName varchar(50) not null,
Email varchar(50) not null,
Date_of_birth date,
Number_of_courses smallint not null
);


问:
Problems with big query and subquery
I thought that I'll be clever and use subquery to get my report in one go. But after running into problems and reading documentation I saw that my approach does not work in MySQL. My inner query returns ~100 records and outer query scans 20000 records.
When I restricted outer query to 20 records then it run 20 sec - really slow.

I wonder is it possible to restructure it somehow so that inner query wouldn't be run EVERY time for every record in the outer query?

```<code>select p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
left JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
left JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
left JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
where  r1.season=2008
and p1.id in
 (
SELECT p.id
FROM ejl_players p
left JOIN ejl_registration r ON (r.player_id = p.id)
left JOIN ejl_teams t ON (r.team_id = t.id)
left JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = 2008
GROUP BY p.id
HAVING COUNT(DISTINCT c.id)  > 1
)
</code>```

Explain (I restricted outer query to maximum 20 records:

```<code>id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1 PRIMARY p1 range PRIMARY PRIMARY 4 NULL 19 Using where
1 PRIMARY r1 ref team_id,season season 10 const,d17528sd14898.p1.id 1 Using where
1 PRIMARY t1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.r1.team_id 1
1 PRIMARY c1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.t1.club_id 1
2 DEPENDENT SUBQUERY p index PRIMARY PRIMARY 5 NULL 23395 Using index
2 DEPENDENT SUBQUERY r ref team_id,season season 10 const,d17528sd14898.p.id 1 Using where; Using index
2 DEPENDENT SUBQUERY t eq_ref PRIMARY PRIMARY 4 d17528sd14898.r.team_id 1
2 DEPENDENT SUBQUERY c eq_ref PRIMARY PRIMARY 4 d17528sd14898.t.club_id 1 Using index
</code>```

答:
Try using an INNER JOIN (something like this):

```<code>SELECT p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
INNER JOIN (
    SELECT p.id
    FROM ejl_players p
    LEFT JOIN ejl_registration r ON (r.player_id = p.id)
    LEFT JOIN ejl_teams t ON (r.team_id = t.id)
    LEFT JOIN ejl_clubs c ON (t.club_id = c.id)
    WHERE r.season = 2008
    GROUP BY p.id
    HAVING COUNT(DISTINCT c.id)  > 1
) p2 ON p1.id = p2.id
LEFT JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
LEFT JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
LEFT JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
WHERE  r1.season=2008
</code>```

Using the subquery in this manner should be more efficient but isn't always. However, it does bypass the issue of having the subquery executed for every record returned in the main query. Instead the subquery is constructed as a virtual table in memory and then used for comparison with the main query.

Edit: I should point out that you'll want to use EXPLAIN in MySQL to verify that this query is indeed performing more efficiently.

OwnerDisplayName: Riho

Title: Problems with big query and subquery

Body:
I thought that I'll be clever and use subquery to get my report in one go. But after running into problems and reading documentation I saw that my approach does not work in MySQL. My inner query returns ~100 records and outer query scans 20000 records.
When I restricted outer query to 20 records then it run 20 sec - really slow.

I wonder is it possible to restructure it somehow so that inner query wouldn't be run EVERY time for every record in the outer query?

select p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
left JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
left JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
left JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
where  r1.season=2008
and p1.id in
 (
SELECT p.id
FROM ejl_players p
left JOIN ejl_registration r ON (r.player_id = p.id)
left JOIN ejl_teams t ON (r.team_id = t.id)
left JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = 2008
GROUP BY p.id
HAVING COUNT(DISTINCT c.id)  > 1
)

Explain (I restricted outer query to maximum 20 records:

id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1 PRIMARY p1 range PRIMARY PRIMARY 4 NULL 19 Using where
1 PRIMARY r1 ref team_id,season season 10 const,d17528sd14898.p1.id 1 Using where
1 PRIMARY t1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.r1.team_id 1
1 PRIMARY c1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.t1.club_id 1
2 DEPENDENT SUBQUERY p index PRIMARY PRIMARY 5 NULL 23395 Using index
2 DEPENDENT SUBQUERY r ref team_id,season season 10 const,d17528sd14898.p.id 1 Using where; Using index
2 DEPENDENT SUBQUERY t eq_ref PRIMARY PRIMARY 4 d17528sd14898.r.team_id 1
2 DEPENDENT SUBQUERY c eq_ref PRIMARY PRIMARY 4 d17528sd14898.t.club_id 1 Using index

LastEditorDisplayName: Riho

Body:
Try using an INNER JOIN (something like this):

SELECT p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
INNER JOIN (
    SELECT p.id
    FROM ejl_players p
    LEFT JOIN ejl_registration r ON (r.player_id = p.id)
    LEFT JOIN ejl_teams t ON (r.team_id = t.id)
    LEFT JOIN ejl_clubs c ON (t.club_id = c.id)
    WHERE r.season = 2008
    GROUP BY p.id
    HAVING COUNT(DISTINCT c.id)  > 1
) p2 ON p1.id = p2.id
LEFT JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
LEFT JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
LEFT JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
WHERE  r1.season=2008

Using the subquery in this manner should be more efficient but isn't always. However, it does bypass the issue of having the subquery executed for every record returned in the main query. Instead the subquery is constructed as a virtual table in memory and then used for comparison with the main query.

Edit: I should point out that you'll want to use EXPLAIN in MySQL to verify that this query is indeed performing more efficiently.


问:
IBM mobileFirst IOS application screen blackout after direct update
Details of Project :

Application Framework - Ionic V3.0

IBM MobileFirst server(devKit)   - Product version: 8.0.0.00-20170911-123510

Application Mobilefirst version -
config.xml -

mfp:platformVersion -8.0.0.00-20170218-003050

plugin name="cordova-plugin-mfp" spec="8.0.2017021815"

It's working fine in android. But in IOS, after finishing of soft update, application screen goes blank (black screen). After killing and restart of application, it's started working fine.

I have implement Direct update feature in mobilefirst 8 application as below :

```<code>// Direct Update - Used to trigger a request to the MobileFirst Server, to check for updated web resources.
WLAuthorizationManager.obtainAccessToken()
.then(
 function () {
   console.log("*** Obtained token successfully.");
 },
 function () {
   console.log("*** Failed obtaining token.");
 }
);
</code>```

Reference : https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/direct-update/#secure-direct-update

答:
This is perhaps has to do with the fact that Ionic now uses the WKWebView by default. See https://ionicframework.com/docs/wkwebview/

And it is a known limitation with MobileFirst Direct update on the WKWebview. See https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/product-overview/release-notes/known-issues-limitations/#wkwebview-support-for-ios-cordova-applications

As mentioned in the above link, use the wkwebview-engine-localhost plugin to ensure Direct update continues to work.

Body:
Details of Project :

Application Framework - Ionic V3.0

IBM MobileFirst server(devKit)   - Product version: 8.0.0.00-20170911-123510

Application Mobilefirst version -
config.xml -

mfp:platformVersion -8.0.0.00-20170218-003050

plugin name="cordova-plugin-mfp" spec="8.0.2017021815"

It's working fine in android. But in IOS, after finishing of soft update, application screen goes blank (black screen). After killing and restart of application, it's started working fine.

I have implement Direct update feature in mobilefirst 8 application as below :

// Direct Update - Used to trigger a request to the MobileFirst Server, to check for updated web resources.
WLAuthorizationManager.obtainAccessToken()
.then(
 function () {
   console.log("*** Obtained token successfully.");
 },
 function () {
   console.log("*** Failed obtaining token.");
 }
);

Reference : https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/direct-update/#secure-direct-update


问:
trigger branch io without open url
I'm trying to implement in my app in react native app which I can trigger the branch without open url when I scan QR.

here I'm register with the branch

```<code>     componentDidMount() {
    this._unsubscribeFromBranch = branch.subscribe(({ error, params }) => {
      if (error) {
        console.error("Error from Branch: " + error)
        return
      }

      console.log("Branch params: " + JSON.stringify(params));
      if (params) {
        this.setState({ scan: { ...this.state.scan, glassHash: params.hash } }, () => {
          this._getCurrentPosition();
        });
      }
    });

  }
</code>```

when I scan with Qr it run the function onSuccess and I want to trigger this branch.subscribe without openURL. if i openURL it works fine but it's not what i want

```<code>     onSuccess(e) {
    console.log(e);

    // here i want to trigger the branch

    this.setState({ barcodeText: e.data });
    console.log(e);
  }
</code>```

i found on react-native-branch-deep-links docs about BranchEvent but I don't see any example about it.
I found this

```<code>new BranchEvent("UserScannedItem", buo).logEvent()
</code>```

but not sure how to implement my custom event

答:
Jackie from Branch here.

Branch links do function properly and retain the data when they are used with QR scanners, including dynamic query parameters (params appended behind the URL). If a QR code was used to open the app, you can retrieve the session data by using getLatestReferringParams(). Here's a sample code snippet on reading deep link data:

```<code>branch.subscribe(({ error, params }) => {
  if (error) {
    console.error('Error from Branch: ' + error)
    return
  }

  // params will never be null if error is null
})

let lastParams = await branch.getLatestReferringParams() // params from last open
let installParams = await branch.getFirstReferringParams() // params from original install
</code>```

More information on using getLatestReferringParams to handle link opens: https://docs.branch.io/pages/apps/react-native/#using-getlatestreferringparams-to-handle-link-opens

Regarding custom events, here's a sample class for generating standard and custom events with the Branch SDK: https://github.com/BranchMetrics/react-native-branch-deep-linking/blob/63cfc566ea45a6af0663fc7530c36fdb5dbf75e6/src/BranchEvent.js

If you are still having issues, please send over a screenshot of an example QR code with the associated Branch link directly to support@branch.io and I'd be happy to do some testing!

Best,

Jackie

Title: trigger branch io without open url

Body:
I'm trying to implement in my app in react native app which I can trigger the branch without open url when I scan QR.

here I'm register with the branch

     componentDidMount() {
    this._unsubscribeFromBranch = branch.subscribe(({ error, params }) => {
      if (error) {
        console.error("Error from Branch: " + error)
        return
      }

      console.log("Branch params: " + JSON.stringify(params));
      if (params) {
        this.setState({ scan: { ...this.state.scan, glassHash: params.hash } }, () => {
          this._getCurrentPosition();
        });
      }
    });

  }

when I scan with Qr it run the function onSuccess and I want to trigger this branch.subscribe without openURL. if i openURL it works fine but it's not what i want

     onSuccess(e) {
    console.log(e);

    // here i want to trigger the branch

    this.setState({ barcodeText: e.data });
    console.log(e);
  }

i found on react-native-branch-deep-links docs about BranchEvent but I don't see any example about it.
I found this

new BranchEvent("UserScannedItem", buo).logEvent()

but not sure how to implement my custom event

Body:
Jackie from Branch here.

Branch links do function properly and retain the data when they are used with QR scanners, including dynamic query parameters (params appended behind the URL). If a QR code was used to open the app, you can retrieve the session data by using getLatestReferringParams(). Here's a sample code snippet on reading deep link data:

branch.subscribe(({ error, params }) => {
  if (error) {
    console.error('Error from Branch: ' + error)
    return
  }

  // params will never be null if error is null
})

let lastParams = await branch.getLatestReferringParams() // params from last open
let installParams = await branch.getFirstReferringParams() // params from original install

More information on using getLatestReferringParams to handle link opens: https://docs.branch.io/pages/apps/react-native/#using-getlatestreferringparams-to-handle-link-opens

Regarding custom events, here's a sample class for generating standard and custom events with the Branch SDK: https://github.com/BranchMetrics/react-native-branch-deep-linking/blob/63cfc566ea45a6af0663fc7530c36fdb5dbf75e6/src/BranchEvent.js

If you are still having issues, please send over a screenshot of an example QR code with the associated Branch link directly to support@branch.io and I'd be happy to do some testing!

Best,

Jackie


问:
Program encounters OpenCV Error: Assertion failed (scn == 3 || scn == 4)
I am trying detect a face in a gif image but since OpenCV doesn't support gif formats, so I used PIL module to read the gif image and convert it back to a numpy array for OpenCV to use.But doing so I am getting an assertion error.

Here is my code below

```<code>import cv2
import numpy as np
from PIL import Image

# get the features and pass it to the Cascade Classifier
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# read the image
img = Image.open("mypic.sleepy")
# check if image exists
if img is None:
    raise Exception("could not load image !")
# represent the image in matrix format for the OpenCV to work on it
img = np.array(img)
# convert it to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detect the objects resembling faces
faces = face_cascade.detectMultiScale(gray,1.5,3) #(image,scale_factor, minm_no_of_neighbours)
for face in faces:
    # the detected face is represented in the form of a rectangle
    x, y, w, h = face
    # draw a rectangle on the face in the image
    cv2.rectangle(img, (x,y), (x + w, y + h), (0, 255, 0), 2)
# show the image
cv2.imshow("Detected Faces", img)
# hold the window
cv2.waitKey(0)
# destroy all windows
cv2.destroyAllWindows()
</code>```

This is the error I am encountering

```<code>OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/souvik/opencv-3.3.0/modules/imgproc/src/color.cpp, line 10638
</code>```

The usual suggestion I found in the internet is that the image is not loaded and that's why it throws such error but clearly in my case the image is indeed loaded otherwise my code would throw an exception.Also If I try to run this code

```<code>print(img.shape)
</code>```

I get a value of (243, 320).So where am I going wrong?

答:
I've tried your code with different color gif images and using the face_cascade on img itself seems to work. Try to comment out the grayscale conversion and use

```<code>faces = face_cascade.detectMultiScale(img,1.5,3)
</code>```

Body:
I am trying detect a face in a gif image but since OpenCV doesn't support gif formats, so I used PIL module to read the gif image and convert it back to a numpy array for OpenCV to use.But doing so I am getting an assertion error.

Here is my code below

import cv2
import numpy as np
from PIL import Image

# get the features and pass it to the Cascade Classifier
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# read the image
img = Image.open("mypic.sleepy")
# check if image exists
if img is None:
    raise Exception("could not load image !")
# represent the image in matrix format for the OpenCV to work on it
img = np.array(img)
# convert it to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detect the objects resembling faces
faces = face_cascade.detectMultiScale(gray,1.5,3) #(image,scale_factor, minm_no_of_neighbours)
for face in faces:
    # the detected face is represented in the form of a rectangle
    x, y, w, h = face
    # draw a rectangle on the face in the image
    cv2.rectangle(img, (x,y), (x + w, y + h), (0, 255, 0), 2)
# show the image
cv2.imshow("Detected Faces", img)
# hold the window
cv2.waitKey(0)
# destroy all windows
cv2.destroyAllWindows()

This is the error I am encountering

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/souvik/opencv-3.3.0/modules/imgproc/src/color.cpp, line 10638

The usual suggestion I found in the internet is that the image is not loaded and that's why it throws such error but clearly in my case the image is indeed loaded otherwise my code would throw an exception.Also If I try to run this code

print(img.shape)

I get a value of (243, 320).So where am I going wrong?

Body:
I've tried your code with different color gif images and using the face_cascade on img itself seems to work. Try to comment out the grayscale conversion and use

faces = face_cascade.detectMultiScale(img,1.5,3)


问:
How can I set a string the 2 html class with same name but different values
There are 2 data-ember-action, how can I use a string for the 2 data-ember-action, I want to get the value of the 2 data-ember-action.

`

          PHP

```<code>    <div class="wallet__amount">
      6,000
    </div>
  </div>
  <div data-ember-action="1180" class="wallet__item">
    <div class="wallet__currency">
      BTC
    </div>

    <div class="wallet__amount">
      0.25588524
    </div>
  </div>
</code>```

`

There are 2 "data-ember-action" but different values, in html, mostly the values will change and what I want is to have a button that would get the 2 different values of it.

I am really confused on how to get this, I have no idea. Please help me

答:
You should  not try to parse HTML with string methods or regex. But you could use an available HTML parser like HtmlAgilityPack. For example with this LINQ version:

```<code>Dim doc As New HtmlAgilityPack.HtmlDocument()
doc.LoadHtml(html)

Dim divDataMember = doc.DocumentNode.Descendants("div").
   FirstOrDefault(Function(node) node.Attributes("data-ember-action") IsNot Nothing)

' omitting the If divDataMember IsNot Nothing check
Dim walletCurrency = divDataMember.Descendants("div").
    FirstOrDefault(Function(node) node.GetAttributeValue("class", "").Equals("wallet__currency", StringComparison.InvariantCultureIgnoreCase))?.InnerText?.Trim()
Dim walletAmount = divDataMember.Descendants("div").
    FirstOrDefault(Function(node) node.GetAttributeValue("class", "").Equals("wallet__amount", StringComparison.InvariantCultureIgnoreCase))?.InnerText?.Trim()
</code>```

Body:
There are 2 data-ember-action, how can I use a string for the 2 data-ember-action, I want to get the value of the 2 data-ember-action.

`

          PHP

      6,000

      BTC

      0.25588524

`

There are 2 "data-ember-action" but different values, in html, mostly the values will change and what I want is to have a button that would get the 2 different values of it.

I am really confused on how to get this, I have no idea. Please help me

Body:
You should  not try to parse HTML with string methods or regex. But you could use an available HTML parser like HtmlAgilityPack. For example with this LINQ version:

Dim doc As New HtmlAgilityPack.HtmlDocument()
doc.LoadHtml(html)

Dim divDataMember = doc.DocumentNode.Descendants("div").
   FirstOrDefault(Function(node) node.Attributes("data-ember-action") IsNot Nothing)

' omitting the If divDataMember IsNot Nothing check
Dim walletCurrency = divDataMember.Descendants("div").
    FirstOrDefault(Function(node) node.GetAttributeValue("class", "").Equals("wallet__currency", StringComparison.InvariantCultureIgnoreCase))?.InnerText?.Trim()
Dim walletAmount = divDataMember.Descendants("div").
    FirstOrDefault(Function(node) node.GetAttributeValue("class", "").Equals("wallet__amount", StringComparison.InvariantCultureIgnoreCase))?.InnerText?.Trim()


答:
With GNU sed, to replace two or more spaces with colon:

```<code>sed -E 's/ {2,}/:/' file
</code>```

or second string matching one or more spaces:

```<code>sed -E 's/ +/:/2' file
</code>```

Title: How to separate fields in a text file with a delimiter

Body:
With GNU sed, to replace two or more spaces with colon:

sed -E 's/ {2,}/:/' file

or second string matching one or more spaces:

sed -E 's/ +/:/2' file


问:
Does android automatically saves images into the sd card if internal storage runs out?
I am creating an app which takes photos using camera activity and I am saving those photos into the app folder inside internal storage. But if the internal storage is not free to save the image, does the android automatically saves the image into the sd card or not? If it does not how can I save images taken form my app to be saved into sd card if internal storage is not available?
Thank you.</p>

答:
No, the Camera app on Android will not automatically choose external storage when internal storage is full. It is your responsibility to check the available disk space and choose the best medium for EXTRA_OUTPUT FileProvider URI before you launch the ACTION_IMAGE_CAPTURE intent.

But you should remember that the app that will fulfill your intent may actually do whatever they want. Even the system (preinstalled) camera apps on different devices choose to respect or not to respect MediaStore.EXTRA_OUTPUT. Worse, the user is free to install a 3rd party app and use it to handle your intent, so you can never be sure how seriously your EXTRA_s will be taken.


问:
Uncaught Invariant Violation : Element type is invalid
I am just fiddling with react-native and trying to build a mock up with a simple navigation. However , I am stuck at a point where I have no clue about the reason causing this.

index.js

```<code>import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('AwesomeProject', () => App);
</code>```

App.js

```<code>import React, { Component } from 'react'
import { AppRegistry, View, Text, StyleSheet } from 'react-native'
import Routes from './src/config/routes';

export class App extends Component {
  render() {
    return (
      <View>
        <Routes/>
      </View>
    )
  }
}
</code>```

Routes.js

```<code>import React from "react";
import { Platform } from "react-native";
import { StackNavigator } from "react-navigation";

import Home from '../screens/Home';
import SignUp from '../screens/SignUp';

export default const Routes = StackNavigator(
    {
        Home: { screen: Home },
        SignUp: { screen: SignUp },
    },
    {
        initialRouteName: "Home",
        headerMode: "none",
    }
);
</code>```

Error :

答:
I am not sure if this would be helpful. but please try to check it as following:

please correct file name on App.js like this:
import Routes from './src/config/Routes';
as above your code, your file name should be Routes, not routes.

on Routes.js, please try to do as following:

export default const Routes = StackNavigator({
  initialRouteName: Home,
  Home: { screen: Home },
  SignUp: { screen: SignUp },
},
{
  headerMode: "none",
});

Body:
I am just fiddling with react-native and trying to build a mock up with a simple navigation. However , I am stuck at a point where I have no clue about the reason causing this.

index.js

import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('AwesomeProject', () => App);

App.js

import React, { Component } from 'react'
import { AppRegistry, View, Text, StyleSheet } from 'react-native'
import Routes from './src/config/routes';

export class App extends Component {
  render() {
    return (
      <View>
        <Routes/>
      </View>
    )
  }
}

Routes.js

import React from "react";
import { Platform } from "react-native";
import { StackNavigator } from "react-navigation";

import Home from '../screens/Home';
import SignUp from '../screens/SignUp';

export default const Routes = StackNavigator(
    {
        Home: { screen: Home },
        SignUp: { screen: SignUp },
    },
    {
        initialRouteName: "Home",
        headerMode: "none",
    }
);

Error :


问:
MSSQL database connection in plesk
I have tried to host my asp.net web site in a free hosting somee.com and it works perfectly with the database.

The problem is, now I want to host it in another server and i make the same steps as done in the first one, but the connection between my website and the database is not working.

The question is: Is there a problem with the configuration of the new server OR the problem is in my code?
ps: I'm using plesk in the new server.

答:
You have to perform some steps for the connection string,

Step 1:
Connect your mssql with you host provided database (by giving all the credentials)

Step 2:
Then By Using Entity Frame work connect your self with that database that you already imported in your local mssql .Entity frame work will embed the connection string automatically in your web.config file.

Title: MSSQL database connection in plesk


问:
Call function in jQuery
I have created a function inside a .click

```<code>$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});
</code>```

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

答: You have to define function Hello() outside the click scope.

Title: Call function in jQuery

Body:
I have created a function inside a .click

$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?


问:
How to write raw MongoDB command involving regex in Pymongo
In a mongo shell, I'm able to execute this command:

```<code>db.getSiblingDB('myDatabase')
.myCollection
.find({
    city_id:{$ne:123},
    company: {$not: new RegExp('^acme.*', 'i')}
})
.forEach(function (item) {
    var x = db.myCollection.findOne({
        city_id:123,
        company:'abc123'
    });
    item.address = x.address;
    item.phone = x.phone;

    db.myCollection.deleteOne({_id: item._id});
    db.myCollection.insert(item);
});
</code>```

How to write such in pymongo or any other mongodb python driver?

答:
Using pyMongo, you can do something like

```<code>for item in db.myDatabase.myCollection.find({
    city_id:{$ne:123},
    company: {$not: new RegExp('^acme.*', 'i')}
}):
   //Do what you are doing in ForEach fucntion
</code>```

You can refer insert and remove in PyMongo.

Body:
In a mongo shell, I'm able to execute this command:

db.getSiblingDB('myDatabase')
.myCollection
.find({
    city_id:{$ne:123},
    company: {$not: new RegExp('^acme.*', 'i')}
})
.forEach(function (item) {
    var x = db.myCollection.findOne({
        city_id:123,
        company:'abc123'
    });
    item.address = x.address;
    item.phone = x.phone;

    db.myCollection.deleteOne({_id: item._id});
    db.myCollection.insert(item);
});

How to write such in pymongo or any other mongodb python driver?

Body:
Using pyMongo, you can do something like

for item in db.myDatabase.myCollection.find({
    city_id:{$ne:123},
    company: {$not: new RegExp('^acme.*', 'i')}
}):
   //Do what you are doing in ForEach fucntion

You can refer insert and remove in PyMongo.


问:
Toggle class on click body
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

答:
Please check the following code:

HTML:

```<code><input class="input-search" type="search" placeholder="Search" id="inputSearch" />
</code>```

JS:

```<code>$("#inputSearch").click(function(e) {
    e.stopPropagation();
});
</code>```

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});
$("#inputSearch").click(function(e) {
    e.stopPropagation();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" id="inputSearch" />
  <input type="button" class="btn-search" value="click">

```

Is this what you expect?

Title: Toggle class on click body

Body:
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

Body:
Please check the following code:

HTML:

<input class="input-search" type="search" placeholder="Search" id="inputSearch" />

JS:

$("#inputSearch").click(function(e) {
    e.stopPropagation();
});

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});
$("#inputSearch").click(function(e) {
    e.stopPropagation();
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-search">
  <input class="input-search" type="search" placeholder="Search" id="inputSearch" />
  <input type="button" class="btn-search" value="click">
</div>

Is this what you expect?


问:
Exception when referencing MapView in a fragment - OSMdroid
I have written an app with OSMdroid using activities, but I am now trying to port it over to fragments instead (I'm new to fragments though). I am getting the error:
"java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference"

It seems that the MapView has not yet been initialised, am I initialising in the wrong place (OnCreateView)? According to the activity lifecycle, OnCreate is called before OnCreateView, so it would make sense that it is not recognised, but I am confused as to where then to put my code.

Code for my implementation of the fragment:

```<code> //inflating fragment layout
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        map = (MapView) view.findViewById(R.id.map);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));

        setupMap();
    }

//initializing map
    private void setupMap() {
        //adding zoom and touch controls
        map.setBuiltInZoomControls(true);
        map.setMultiTouchControls(true);

        //getting current location using coarse/fine location so we can set centerpoint
        currentLocation = getCurrentLocation();

... code continues ...
</code>```

Error stack trace:

```<code> java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference
                                                                               at skicompanion.skicompanion.MapFragment.setupMap(MapFragment.java:101)
                                                                               at skicompanion.skicompanion.MapFragment.onCreate(MapFragment.java:86)
                                                                               at android.app.Fragment.performCreate(Fragment.java:2214)
                                                                               at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
                                                                               at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1153)
                                                                               at android.app.BackStackRecord.run(BackStackRecord.java:800)
                                                                               at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
                                                                               at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487)
                                                                               at android.os.Handler.handleCallback(Handler.java:815)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                               at android.os.Looper.loop(Looper.java:207)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5765)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

答:
In your posted code it doesn't look like you need to override onCreate method in your case. just move this code:

```<code>    context = getActivity();
    Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));

    setupMap();
</code>```

into the onCreateView method before the return call and should be ok.

Body:
I have written an app with OSMdroid using activities, but I am now trying to port it over to fragments instead (I'm new to fragments though). I am getting the error:
"java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference"

It seems that the MapView has not yet been initialised, am I initialising in the wrong place (OnCreateView)? According to the activity lifecycle, OnCreate is called before OnCreateView, so it would make sense that it is not recognised, but I am confused as to where then to put my code.

Code for my implementation of the fragment:

 //inflating fragment layout
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        map = (MapView) view.findViewById(R.id.map);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));

        setupMap();
    }

//initializing map
    private void setupMap() {
        //adding zoom and touch controls
        map.setBuiltInZoomControls(true);
        map.setMultiTouchControls(true);

        //getting current location using coarse/fine location so we can set centerpoint
        currentLocation = getCurrentLocation();

... code continues ...

Error stack trace:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference
                                                                               at skicompanion.skicompanion.MapFragment.setupMap(MapFragment.java:101)
                                                                               at skicompanion.skicompanion.MapFragment.onCreate(MapFragment.java:86)
                                                                               at android.app.Fragment.performCreate(Fragment.java:2214)
                                                                               at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
                                                                               at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1153)
                                                                               at android.app.BackStackRecord.run(BackStackRecord.java:800)
                                                                               at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
                                                                               at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487)
                                                                               at android.os.Handler.handleCallback(Handler.java:815)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                               at android.os.Looper.loop(Looper.java:207)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5765)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Body:
In your posted code it doesn't look like you need to override onCreate method in your case. just move this code:

    context = getActivity();
    Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));

    setupMap();

into the onCreateView method before the return call and should be ok.


答:
The code sample below should get you close to where you need to be. I was not sure from your question how you planned on setting up your groups.  You will definitely want to use a cross apply if you are using a view. This can be done even more simply with a stored procedure.  For more info on Cross Apply, see section L, here https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql.</p>

```<code>CREATE VIEW MyTableAveragePrices
AS
SELECT mt.Date, mt.Period, mtAverageGroup.AveragePrice,
    CASE
       WHEN mtAvg.Period IN () THEN 'Period Group 1'
       WHEN mtAvg.Period IN () THEN 'Period Group 2'
    END AS PeriodGroup
FROM MyTable mt
    CROSS APPLY
    (
    SELECT
        AVERAGE(mtAvg.Price) AveragePrice,
        CASE
           WHEN mtAvg.Period IN () THEN 'Period Group 1'
           WHEN mtAvg.Period IN () THEN 'Period Group 2'
        END AS PeriodGroup
    FROM MyTable mtAvg
    WHERE
        mt.PeriodGroup = PeriodGroup
    GROUP BY
        CASE
           WHEN mtAvg.Period IN () THEN 'Period Group 1'
           WHEN mtAvg.Period IN () THEN 'Period Group 2'
        END
    ) mtAverageGroup
GO
</code>```

Title: GROUP BY INTERVALS

Body:
I want to take the average of multiple rows of table and insert them into a view:

My table:

Date(datetime)

Period(int) -- Half-hour

Price(decimal(18,2)

Sample data:

Date     | Period | Price
---------+--------+---------
07-12-17 |  47    | 10
07-12-17 |  48    | 20
07-12-17 |   1    | 30
07-12-17 |   2    | 40
07-12-17 |   3    | 50
07-12-17 |   4    | 60
07-12-17 |   5    | 70
07-12-17 |   6    | 80
07-12-17 |   7    | 10
07-12-17 |   8    | 10
07-12-17 |   9    | 10
07-12-17 |  10    | 10
07-12-17 |  11    | 20
07-12-17 |  12    | 20
07-12-17 |  13    | 20
07-12-17 |  14    | 20

My periods are half hours go from 1-48 and I want to take the average price of intervals of 8 periods and assign that price to all 8 periods in the set. Because of the time difference, I start with half-hour 47 instead of 1:

The intervals:

[48-6], [7-14], [15-22], [23-30], [31-38], [39-46]

I want the resulting view to look like:

Date     | Period | Price
---------+--------+---------
07-12-17 |   47   | 45
07-12-17 |   48   | 45
07-12-17 |    1   | 45
07-12-17 |    2   | 45
07-12-17 |    3   | 45
07-12-17 |    4   | 45
07-12-17 |    5   | 45
07-12-17 |    6   | 45
07-12-17 |    7   | 15
07-12-17 |    8   | 15
07-12-17 |    9   | 15
07-12-17 |   10   | 15
07-12-17 |   11   | 15
07-12-17 |   12   | 15
07-12-17 |   13   | 15
07-12-17 |   14   | 15

I have not been able to come up with a complete query, but I am thinking it has to be GROUP BY and maybe with a HAVING Statement.

Hope you can help!

Body:
The code sample below should get you close to where you need to be. I was not sure from your question how you planned on setting up your groups.  You will definitely want to use a cross apply if you are using a view. This can be done even more simply with a stored procedure.  For more info on Cross Apply, see section L, here https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql.

CREATE VIEW MyTableAveragePrices
AS
SELECT mt.Date, mt.Period, mtAverageGroup.AveragePrice,
    CASE
       WHEN mtAvg.Period IN () THEN 'Period Group 1'
       WHEN mtAvg.Period IN () THEN 'Period Group 2'
    END AS PeriodGroup
FROM MyTable mt
    CROSS APPLY
    (
    SELECT
        AVERAGE(mtAvg.Price) AveragePrice,
        CASE
           WHEN mtAvg.Period IN () THEN 'Period Group 1'
           WHEN mtAvg.Period IN () THEN 'Period Group 2'
        END AS PeriodGroup
    FROM MyTable mtAvg
    WHERE
        mt.PeriodGroup = PeriodGroup
    GROUP BY
        CASE
           WHEN mtAvg.Period IN () THEN 'Period Group 1'
           WHEN mtAvg.Period IN () THEN 'Period Group 2'
        END
    ) mtAverageGroup
GO


问:
ms Access '16 - Continuous form - OrderBy textbox value created with expression
I have a form that shows the records from Table-A, it is a continuous form. I have a textbox that uses a DCount expression to count records from Table-B that share the same SOP-Number.

```<code>=DCount("*","[Table-B]","SOP = " & [SOP])
</code>```

This works but I don't know how I would go about sorting that column based of the resulting values. The other columns are sorted thus:

```<code>" ORDER BY [FIELD NAME] ASC;"
</code>```

So without a field I don't know how (or if) I can sort the form.
Could I create a RecordSet to store the values then sort by that field (I don't know if this is even possible)

Thank you

Dan

Access 2016 (365)

答:
I'm not quite understanding why you won't know what fields you're pulling from Table B.  But you can always order by the column number.  So if you're looking to order by the first column, just put:</p>

```<code>ORDER BY 1 ASC
</code>```

Body:
I have a form that shows the records from Table-A, it is a continuous form. I have a textbox that uses a DCount expression to count records from Table-B that share the same SOP-Number.

=DCount("*","[Table-B]","SOP = " & [SOP])

This works but I don't know how I would go about sorting that column based of the resulting values. The other columns are sorted thus:

" ORDER BY [FIELD NAME] ASC;"

So without a field I don't know how (or if) I can sort the form.
Could I create a RecordSet to store the values then sort by that field (I don't know if this is even possible)

Thank you

Dan

Access 2016 (365)

Body:
I'm not quite understanding why you won't know what fields you're pulling from Table B.  But you can always order by the column number.  So if you're looking to order by the first column, just put:

ORDER BY 1 ASC


问:
Learning Python from Ruby; Differences and Similarities
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?

I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simple things like whitespace significance and looping constructs; the name of nil in Python, and what values are considered "truthy"; is it idiomatic to use the equivalent of map and each, or are mumble somethingaboutlistcomprehensions mumble the norm?

If I get a good variety of answers I'm happy to aggregate them into a community wiki. Or else  you all can fight and crib from each other to try to create the one true comprehensive list.

Edit: To be clear, my goal is "proper" and idiomatic Python. If there is a Python equivalent of inject, but nobody uses it because there is a better/different way to achieve the common functionality of iterating a list and accumulating a result along the way, I want to know how you do things. Perhaps I'll update this question with a list of common goals, how you achieve them in Ruby, and ask what the equivalent is in Python.

答:
In Ruby, instance variables and methods are completely unrelated, except when you explicitly relate them with attr_accessor or something like that.

In Python, methods are just a special class of attribute: one that is executable.

So for example:

```<code>>>> class foo:
...     x = 5
...     def y(): pass
...
>>> f = foo()
>>> type(f.x)
<type 'int'>
>>> type(f.y)
<type 'instancemethod'>
</code>```

That difference has a lot of implications, like for example that referring to f.x refers to the method object, rather than calling it. Also, as you can see, f.x is public by default, whereas in Ruby, instance variables are private by default.

Body:
In Ruby, instance variables and methods are completely unrelated, except when you explicitly relate them with attr_accessor or something like that.

In Python, methods are just a special class of attribute: one that is executable.

So for example:

>>> class foo:
...     x = 5
...     def y(): pass
...
>>> f = foo()
>>> type(f.x)
<type 'int'>
>>> type(f.y)
<type 'instancemethod'>

That difference has a lot of implications, like for example that referring to f.x refers to the method object, rather than calling it. Also, as you can see, f.x is public by default, whereas in Ruby, instance variables are private by default.