问:
GemFire PDX Serialization not working with OQL in Pulse or with REST APIs?
We are using Spring as client to work with GemFire. Our data is getting saved to Regions of our running GemFire instances.

We are able to get data via Spring when we make get request.

Have done all configuration for Auto PDX serialization, However when we try to query data via OQL in Pulse or with GemFire REST Apis we get ClassNotFoundException:

```<code>{"message" : "Server has encountered while executing Adhoc query!", "stackTrace" : "com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException: Server has encountered while executing Adhoc query!
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:672)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:82)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.gemstone.gemfire.SerializationException: A ClassNotFoundException was thrown while trying to deserialize cached value.
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1561)
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1546)
at com.gemstone.gemfire.internal.cache.VMCachedDeserializable.getDeserializedValue(VMCachedDeserializable.java:124)
at com.gemstone.gemfire.internal.cache.LocalRegion.getDeserialized(LocalRegion.java:1275)
at com.gemstone.gemfire.internal.cache.LocalRegion$NonTXEntry.getValue(LocalRegion.java:9140)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.moveNext(EntriesSet.java:183)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.<init>(EntriesSet.java:121)
at com.gemstone.gemfire.internal.cache.EntriesSet.iterator(EntriesSet.java:85)
at com.gemstone.gemfire.cache.query.internal.ResultsCollectionWrapper.iterator(ResultsCollectionWrapper.java:181)
at com.gemstone.gemfire.cache.query.internal.QRegion.iterator(QRegion.java:225)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doNestedIterations(CompiledSelect.java:712)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doIterationEvaluate(CompiledSelect.java:577)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.evaluate(CompiledSelect.java:284)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.executeUsingContext(DefaultQuery.java:529)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:365)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:303)
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:180)
... 40 more
Caused by: java.lang.ClassNotFoundException: in.cycorax.User
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
</code>```

答: +1 to what Dan Smith said above.  You must also be careful with "SELECT * FROM /Region" queries as well.  This query will attempt to deserialize the entire object.  As Dan mentioned, limit your queries to the fields of your object that will get serialized to PDX.  If your object gets deserialized in anyway, then you must have your application domain object types (classes) on the GemFire server's classpath, no exceptions.

Body:
We are using Spring as client to work with GemFire. Our data is getting saved to Regions of our running GemFire instances.

We are able to get data via Spring when we make get request.

Have done all configuration for Auto PDX serialization, However when we try to query data via OQL in Pulse or with GemFire REST Apis we get ClassNotFoundException:

{"message" : "Server has encountered while executing Adhoc query!", "stackTrace" : "com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException: Server has encountered while executing Adhoc query!
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:672)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:82)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.gemstone.gemfire.SerializationException: A ClassNotFoundException was thrown while trying to deserialize cached value.
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1561)
at com.gemstone.gemfire.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1546)
at com.gemstone.gemfire.internal.cache.VMCachedDeserializable.getDeserializedValue(VMCachedDeserializable.java:124)
at com.gemstone.gemfire.internal.cache.LocalRegion.getDeserialized(LocalRegion.java:1275)
at com.gemstone.gemfire.internal.cache.LocalRegion$NonTXEntry.getValue(LocalRegion.java:9140)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.moveNext(EntriesSet.java:183)
at com.gemstone.gemfire.internal.cache.EntriesSet$EntriesIterator.<init>(EntriesSet.java:121)
at com.gemstone.gemfire.internal.cache.EntriesSet.iterator(EntriesSet.java:85)
at com.gemstone.gemfire.cache.query.internal.ResultsCollectionWrapper.iterator(ResultsCollectionWrapper.java:181)
at com.gemstone.gemfire.cache.query.internal.QRegion.iterator(QRegion.java:225)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doNestedIterations(CompiledSelect.java:712)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.doIterationEvaluate(CompiledSelect.java:577)
at com.gemstone.gemfire.cache.query.internal.CompiledSelect.evaluate(CompiledSelect.java:284)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.executeUsingContext(DefaultQuery.java:529)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:365)
at com.gemstone.gemfire.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:303)
at com.gemstone.gemfire.rest.internal.web.controllers.QueryAccessController.runAdhocQuery(QueryAccessController.java:180)
... 40 more
Caused by: java.lang.ClassNotFoundException: in.cycorax.User
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)


来源: stackexchange

问:
Kotlin Extension Any?.toString()
I have been trying to use extension functions in Kotlin.

```<code>class ExtensionExample() {

   var name: String? = null

   fun Any?.toString() : String {

       if (this == null) {
           return "Value is null"
       }

       return "Value is not null"
   }
}
</code>```

When I print the name variable like below

```<code>println(ExtensionExample().name.toString())
</code>```

It should print like

```<code>Value is null
</code>```

But it doesn't print like I expected. It only prints null.

Can someone explain please?

答:
If a class has a member function, and an extension function is defined which has the same receiver type, the same name and is applicable to given arguments, the member always wins.

Your extension method can't shadow the built-in toString method on the Any (Object) class.

As for calling toString on a nullable type, this method is already in the Kotlin runtime:

```<code>/**
 * Returns a string representation of the object. Can be called with a null receiver, in which case
 * it returns the string "null".
 */
public fun Any?.toString(): String
</code>```

See also the docs about the resolution of extensions.

ContentLicense: CC BY-SA 3.0

Title: Kotlin Extension Any?.toString()

Body:
I have been trying to use extension functions in Kotlin.

class ExtensionExample() {

   var name: String? = null

   fun Any?.toString() : String {

       if (this == null) {
           return "Value is null"
       }

       return "Value is not null"
   }
}

When I print the name variable like below

println(ExtensionExample().name.toString())

It should print like

Value is null

But it doesn't print like I expected. It only prints null.

Can someone explain please?

Body:
If a class has a member function, and an extension function is defined which has the same receiver type, the same name and is applicable to given arguments, the member always wins.

Your extension method can't shadow the built-in toString method on the Any (Object) class.

As for calling toString on a nullable type, this method is already in the Kotlin runtime:

/**
 * Returns a string representation of the object. Can be called with a null receiver, in which case
 * it returns the string "null".
 */
public fun Any?.toString(): String

See also the docs about the resolution of extensions.


问:
Android application must not run on rooted devices
I'm writing an application that must not run on rooted devices. I want to store some secure data and which is possible only on non-rooted devices as nobody can access files in /data/data/package-name.

Does anyone know:

1) Is it possible to prevent the installation of an application on rooted devices? I read something about the "copy-protection mechanism" of Android Market. This feature seems to be outdated and replaced by the licensing feature. However, licensing is only possible for paid application and mine is free...

2) Is it possible to check programmatically whether a device is rooted or not? If it would be possible to do so I could simply stop the application if the device is rooted.

Any help regarding this topic is appreciated!

答:
If you are trying to protect data for the user, it's their business to worry about other apps.
If you are trying to protect data from the user, what business do you have putting it on their device?

To answer your question, they are in control of the machine so expect them to be able to trap any call to an API checking 'Is this rooted?' and lie to you. Instead, encrypt the data on the client with a key known to the client, but make it non-obvious where and how you are doing it. Generally make things annoying for whoever is looking.

Enjoy the ensuing game of whack-a-mole. Every time someone cracks into it, you'll make a better fix, they'll make a better crack, and all along the way you will be raising the barrier for cracking it.

Don't fight against freedom - why should you turn away customers with free devices anyway? - instead, if you want a particular outcome, make it so Bother To Get Data > Value Of Getting Data. Then it won't happen. If you truly must have fool-proof security, keep the data server-side.

ContentLicense: CC BY-SA 2.5


问:
How to know if a Javascript Callback is Synchronous or Asynchronous?

Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

```<code>$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});
</code>```

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

答:
I am not sure "synchronous" and "asynchronous" makes sense in this context. You can talk about sync or async when making ajax requests, which would mean that in a sync request everything else stops until the response is received, while in an asynchronous request something else can happen until the server sends the response.

In your particular case ( https://www.w3schools.com/jquery/jquery_callback.asp )  what happens is this:

in the "slow" case a timeout is set and the callback is called when the time is out

in the second case a timeout is set for hiding the paragraph but the function is called imediately on the next line, before the time is out

this is not sync/async, it is about event programming

Body:
Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?


问:
pin subviews to leading and trailing edges of stackview
I have label1 and label2.

My stackview's axis is horizontal.

I want to pin label1 to the left and pin label2 to the far right. Similar to:

```<code>|label1-------------------label2|
</code>```

I know I can change label2's textAlignment to right but I was wondering if there is a pure stackview way of doing it (so I could use this for any other non-UILabel layouts)? I tried all kinds of distribution but non worked...

答:
```<code>stackView.distribution = .equalSpacing
</code>```

works just fine.

Not sure what I was doing wrong before...

Body:
I have label1 and label2.

My stackview's axis is horizontal.

I want to pin label1 to the left and pin label2 to the far right. Similar to:

|label1-------------------label2|

I know I can change label2's textAlignment to right but I was wondering if there is a pure stackview way of doing it (so I could use this for any other non-UILabel layouts)? I tried all kinds of distribution but non worked...

Body:
stackView.distribution = .equalSpacing

works just fine.

Not sure what I was doing wrong before...


问:
Location of docker images downloaded by Docker (1.9.1) on Mac OS X
Where are the docker images located once they are downloaded from docker hub in Mac OSX. For example if I run a command like:

```<code>docker run hello-world
</code>```

the image is downloaded and the container is run but where is that image located on my system?

Note: Where are Docker images stored on the host machine? This question has answers related to linux machine, mainly. The answers for Mac OS X are considering that boot2docker is being used alongside docker installation, which is not the case for me.

答:
In my case (Mavericks / docker brew installed / Image name: default) is located under

```<code>/Users/<Username>/.docker/machine/machines/.
</code>```

(You gotta use terminal and not finder to see it. )

```<code>   ls -lah /Users/Mitsos/.docker/machine/machines/
    total 0
    drwx------   3 Mitsos  staff   102B Dec  8 19:03 .
    drwxr-xr-x   5 Mitsos  staff   170B Sep 22 13:52 ..
    drwx------  13 Mitsos  staff   442B Dec  8 19:04 default
</code>```

Body:
Where are the docker images located once they are downloaded from docker hub in Mac OSX. For example if I run a command like:

docker run hello-world

the image is downloaded and the container is run but where is that image located on my system?

Note: Where are Docker images stored on the host machine? This question has answers related to linux machine, mainly. The answers for Mac OS X are considering that boot2docker is being used alongside docker installation, which is not the case for me.

Body:
In my case (Mavericks / docker brew installed / Image name: default) is located under

/Users/<Username>/.docker/machine/machines/.

(You gotta use terminal and not finder to see it. )

   ls -lah /Users/Mitsos/.docker/machine/machines/
    total 0
    drwx------   3 Mitsos  staff   102B Dec  8 19:03 .
    drwxr-xr-x   5 Mitsos  staff   170B Sep 22 13:52 ..
    drwx------  13 Mitsos  staff   442B Dec  8 19:04 default


问:
pandas drop values in a columns based other columns
Is there a way to drop a single entry in a df?

```<code>df1:
ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 4   15  6   25
113 6   7   4   10
114 3   8   2   1
115 7   1   8   10
</code>```

I want to drop any Value1 if Count1 < 5 and drop any Value2 if Count2 < 5.  The result would be like this:

```<code>ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 NA  NA  6   25
113 6   7   4   NA
114 NA  NA  NA  NA
115 7   1   8   10
</code>```

Thanks!

Body:
Is there a way to drop a single entry in a df?

df1:
ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 4   15  6   25
113 6   7   4   10
114 3   8   2   1
115 7   1   8   10

I want to drop any Value1 if Count1 < 5 and drop any Value2 if Count2 < 5.  The result would be like this:

ID  Count1  Value1  Count2  Value2
111 5   10  5   25
112 NA  NA  6   25
113 6   7   4   NA
114 NA  NA  NA  NA
115 7   1   8   10

Thanks!

Body:
Using loc

df.loc[df['Count1'] < 5, ['Count1','Value1']] = np.nan
df.loc[df['Count2'] < 5, ['Count2','Value2']] = np.nan

    ID  Count1  Value1  Count2  Value2
0   111 5.0     10.0    5.0     25.0
1   112 NaN     NaN     6.0     25.0
2   113 6.0     7.0     NaN     NaN
3   114 NaN     NaN     NaN     NaN
4   115 7.0     1.0     8.0     10.0


问:
Cannot find symbol when already declared
Please someone help me on this error :

```<code>import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}
</code>```

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

答:
The variable t is being declared inside the switch statement in the code above which is resulting in the error.You need to initialize it outside and change the value inside the switch statement accordingly.

```<code>import java.util.*;

public class Main {

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        int t=0;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
                System.out.println("Invalid Option");
                break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
</code>```

}

Body:
Please someone help me on this error :

import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

Body:
The variable t is being declared inside the switch statement in the code above which is resulting in the error.You need to initialize it outside and change the value inside the switch statement accordingly.

import java.util.*;

public class Main {

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        int t=0;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
                System.out.println("Invalid Option");
                break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }

}


问:
2to3 - how to keep newline characters from input file?
I'm attempting to run 2to3 on Windows machine where *.py files has Unix-style end-line characters. Running 2to3 modifies newline characters in output file.

MCVE:

print2.py content before

```<code>print "Hello, world!"\n
</code>```

Executed command:

```<code>2to3 print2.py -w -n
</code>```

print2.py content after

```<code>print("Hello, world!")\r\n
</code>```

Expected content:

```<code>print("Hello, world!")\n
</code>```

Is it possible to keep old newline characters when 2to3 conversion is performed?

答:
This issue seems to have previously been reported as Python 11594, still unresolved. In investigating, I found the recommended workaround, setting lib2to3._to_system_newlines doesn't have any effect when lib2to3 is run from Python 3. What did work for me was to override _open_with_encoding thus:

```<code>lib2to3.refactor._open_with_encoding = functools.partial(open, newline='')
</code>```

I've made this functionality available in jaraco.develop. The module can be invoked just as you would invoke lib2to3, but with the patch applied:

```<code>python -m jaraco.develop.lib2to3 .
</code>```

Or to incorporate it into another library like libmodernize:

```<code>import runpy
from jaraco.develop import lib2to3
lib2to3.patch_for_newlines()
runpy.run_module('modernize')
</code>```

These techinques probably won't work on Python 2, and so I suggest running lib2to3 from Python 3.

Body:
I'm attempting to run 2to3 on Windows machine where *.py files has Unix-style end-line characters. Running 2to3 modifies newline characters in output file.

MCVE:

print2.py content before

print "Hello, world!"\n

Executed command:

2to3 print2.py -w -n

print2.py content after

print("Hello, world!")\r\n

Expected content:

print("Hello, world!")\n

Is it possible to keep old newline characters when 2to3 conversion is performed?

Body:
This issue seems to have previously been reported as Python 11594, still unresolved. In investigating, I found the recommended workaround, setting lib2to3._to_system_newlines doesn't have any effect when lib2to3 is run from Python 3. What did work for me was to override _open_with_encoding thus:

lib2to3.refactor._open_with_encoding = functools.partial(open, newline='')

I've made this functionality available in jaraco.develop. The module can be invoked just as you would invoke lib2to3, but with the patch applied:

python -m jaraco.develop.lib2to3 .

Or to incorporate it into another library like libmodernize:

import runpy
from jaraco.develop import lib2to3
lib2to3.patch_for_newlines()
runpy.run_module('modernize')

These techinques probably won't work on Python 2, and so I suggest running lib2to3 from Python 3.


问:
Is there a practical way to use IronPython entirely within the VS 2k10 IDE?
I've looked through the existing threads on IronPython and IDEs without finding an answer.

If I don't need to support Python 3, is there a practical way to do IronPython development fully inside the VS 2k10 IDE like I used to with FORTRAN.net?

答: I'm afraid the answer is no. I have had bad luck with IronPython, especially when native modules are in play (even when they're part of the standard library). However, there is IronPython Studio, which is built on VS2008 and IPyDD. I don't think .NET is ready for Python yet :(</p>


问:
Export Stage into PDF
IS there any way to export Stage or some other component like BorderPane with visual components into PDF file? I want when I click a button to export the component into PDF file? IS there any example?</p>

答:
You can use PDFBox libreries in your javafx project . this code take a snapshot from a node , make an image file , then create a pdf file and insert the image in the pdf file . you need this .jar  http://www-us.apache.org/dist/pdfbox/2.0.8/pdfbox-app-2.0.8.jar . with pdfbox you can pass strings of javafx to text in pdf , you can do many things ( change font , size .... )</p>

```<code>import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.Button;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
 import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

 public class NodeToPdf extends Application {

@Override
public void start(Stage primaryStage) {

    CategoryAxis xAxis = new CategoryAxis();
    xAxis.setLabel("x");
     NumberAxis yAxis = new NumberAxis();
    yAxis.setLabel("y");
    BarChart bar = new BarChart(xAxis, yAxis);
    bar.setMaxSize(300, 300);
    bar.setTitle("Bar node" );
    bar.setTranslateY(-100);

    Button btn = new Button();
    btn.setTranslateY(100);
    btn.setText("To Pdf'");

    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            WritableImage nodeshot = bar.snapshot(new SnapshotParameters(), null);
            File file = new File("chart.png");

try {
    ImageIO.write(SwingFXUtils.fromFXImage(nodeshot, null), "png", file);
} catch (IOException e) {

}

            PDDocument doc    = new PDDocument();
            PDPage page = new PDPage();
            PDImageXObject pdimage;
            PDPageContentStream content;
            try {
                pdimage = PDImageXObject.createFromFile("chart.png",doc);
                content = new PDPageContentStream(doc, page);
                content.drawImage(pdimage, 100, 100);
                content.close();
                doc.addPage(page);
                doc.save("pdf_file.pdf");
                doc.close();
                file.delete();
            } catch (IOException ex) {
                Logger.getLogger(NodeToPdf.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });

    StackPane root = new StackPane();

    root.getChildren().add(btn);
    root.getChildren().add(bar);

    Scene scene = new Scene(root, 600, 600);

    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}

 }
</code>```

Title: Export Stage into PDF

Body:
You can use PDFBox libreries in your javafx project . this code take a snapshot from a node , make an image file , then create a pdf file and insert the image in the pdf file . you need this .jar  http://www-us.apache.org/dist/pdfbox/2.0.8/pdfbox-app-2.0.8.jar . with pdfbox you can pass strings of javafx to text in pdf , you can do many things ( change font , size .... )

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.Button;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
 import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

 public class NodeToPdf extends Application {

@Override
public void start(Stage primaryStage) {

    CategoryAxis xAxis = new CategoryAxis();
    xAxis.setLabel("x");
     NumberAxis yAxis = new NumberAxis();
    yAxis.setLabel("y");
    BarChart bar = new BarChart(xAxis, yAxis);
    bar.setMaxSize(300, 300);
    bar.setTitle("Bar node" );
    bar.setTranslateY(-100);

    Button btn = new Button();
    btn.setTranslateY(100);
    btn.setText("To Pdf'");

    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            WritableImage nodeshot = bar.snapshot(new SnapshotParameters(), null);
            File file = new File("chart.png");

try {
    ImageIO.write(SwingFXUtils.fromFXImage(nodeshot, null), "png", file);
} catch (IOException e) {

}

            PDDocument doc    = new PDDocument();
            PDPage page = new PDPage();
            PDImageXObject pdimage;
            PDPageContentStream content;
            try {
                pdimage = PDImageXObject.createFromFile("chart.png",doc);
                content = new PDPageContentStream(doc, page);
                content.drawImage(pdimage, 100, 100);
                content.close();
                doc.addPage(page);
                doc.save("pdf_file.pdf");
                doc.close();
                file.delete();
            } catch (IOException ex) {
                Logger.getLogger(NodeToPdf.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });

    StackPane root = new StackPane();

    root.getChildren().add(btn);
    root.getChildren().add(bar);

    Scene scene = new Scene(root, 600, 600);

    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}

 }


问:
How to keep :active css style after clicking an element
I use anchor as my site navigation.

```<code><div id='nav'>
<a href='#abouts'>
<div class='navitem about'>
about
</div>
</a>
<a href='#workss'>
<div class='navitem works'>
works
</div>
</a>
</div>
</code>```

The CSS

```<code>#nav {
margin-left: 50px;
margin-top: 50px;
text-transform: uppercase;
}
.navitem {
background: #333;
color: white;
width: 230px;
height: 50px;
font-size: 25px;
line-height: 50px;
padding-left: 20px;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
margin-top: 10px;
}
.about:hover {
background: #cc00ff;
}
.about:active {
background: #ff00ff;
color: #000;
width: 250px;
}
.works:hover {
background: #0066FF;
}
.works:active {
background: #0099cc;
color: #000;
width: 250px;
}
</code>```

I'm wondering how to keep the div element style keep in the :active state once after the click until I  hit another nav bar item, so how to do it?

答:
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.

This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label></code>```

To make button change content:

#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label></code>```

Hope it helps!!

Body:
I use anchor as my site navigation.

about

works

The CSS

#nav {
margin-left: 50px;
margin-top: 50px;
text-transform: uppercase;
}
.navitem {
background: #333;
color: white;
width: 230px;
height: 50px;
font-size: 25px;
line-height: 50px;
padding-left: 20px;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
margin-top: 10px;
}
.about:hover {
background: #cc00ff;
}
.about:active {
background: #ff00ff;
color: #000;
width: 250px;
}
.works:hover {
background: #0066FF;
}
.works:active {
background: #0099cc;
color: #000;
width: 250px;
}

I'm wondering how to keep the div element style keep in the :active state once after the click until I  hit another nav bar item, so how to do it?

Body:
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.

This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}

<input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label>

To make button change content:

#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}

<input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label>

Hope it helps!!

ContentLicense: CC BY-SA 4.0


问:
How to remove line breaks with PHP or JS
I've tried about everything to delete some extra \n  characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.

And yes I've tried things like

In JS:

```<code>text.replace(/\n/g,"")
</code>```

In PHP:

```<code>preg_replace("[\n]","",$result);
str_replace("\n","",$result);
</code>```

and when I try

```<code> text.replace(/\n/g,"")
</code>```

in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.

I'm desperate, picky and this is killing me. Any input is appreciated.

EDIT:

If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.

Answer Explanation:

Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!

In my case:

Why this works?   str_replace('\n', '', $result)

And this doesn't?   str_replace("\n", '', $result)

Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.

If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.

答:
In php, use str_replace(array('\r','\n'), '', $string).

I guess the problem is you also have \r's in your code (carriage returns, also displayed as newlines).

Body:
I've tried about everything to delete some extra \n  characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.

And yes I've tried things like

In JS:

text.replace(/\n/g,"")

In PHP:

preg_replace("[\n]","",$result);
str_replace("\n","",$result);

and when I try

 text.replace(/\n/g,"")

in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.

I'm desperate, picky and this is killing me. Any input is appreciated.

EDIT:

If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.

Answer Explanation:

Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!

In my case:

Why this works?   str_replace('\n', '', $result)

And this doesn't?   str_replace("\n", '', $result)

Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.

If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.


问:
Angular 4 + RxJS filtering
I am trying to wrap my head around RxJS and I have a question.  To better understand how everything works, I started a new blank Angular 4 application generated with Angular CLI.  In it, I am running the following code:

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .filter((item: any) => {
      let price = parseFloat(item.price);
      return price < 5.0 && price >= 2.5;
    })
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    },
    error => {
      this.error = error;
    });```
</div>
</div>
</p>

<p>The problem is that filter receives the whole object as a parameter and I cannot filter the individual items.  Using RxJS in a non-angular solution, I used this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let products = Observable.create(observer => {
    let xhr = new XMLHttpRequest();

    let onLoad = () => {
        let productsList = JSON.parse(xhr.responseText);
        observer.next(productsList);
        observer.complete();
    }

    xhr.addEventListener('load', onLoad);

    xhr.open('GET', 'products.json');
    xhr.send();

    return () => {
        console.log('cleanup');
        xhr.removeEventListener('load', onLoad);
        xhr.abort();
    }
})
.flatMap(Observable.from)
.filter(item => {
    let price = parseFloat(item.price);
    return price < 5.0 && price >= 2.5;
});

let subscr = products.subscribe(
    product => {
        let li = document.createElement('li');
        li.innerText = product.product_name + ' ' + product.price;
        list$.appendChild(li);
    },
    error => {
        console.log(`Error: ${error}`);
    },
    () => {
        console.log('complete');
        subscr.unsubscribe();
    }
);</code>```

The difference here is that I used flatMap, but if I try the same code in the Angular version I get:
Argument of type '{ (ish: ObservableInput, scheduler?: IScheduler): Observable; (ish: ArrayLike, ...' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
  Types of parameters 'scheduler' and 'index' are incompatible.
    Type 'number' is not assignable to type 'IScheduler'.

I was just wondering why the same scenario produces different results.  Is Angular using a different flavor of RxJS?  What is the most efficient way to filter the results in the Angular version?

Thank you.

答:
```<code>getItems(): Observable<any>{
    this.http.get('./src/app/data/products.json')
        .map(res => {
          const data = res.json();  // your GET returns array
          return data.filter(item => parseFloat(item.price) >= 2.5 && parseFloat(item.price) < 5.0);  // notice this is not Rxjs filter.
        });
}
</code>```

in your component:

```<code>this.xxxService.getItems()
  .subscribe(item => ...);
</code>```

Title: Angular 4 + RxJS filtering

Body:
I am trying to wrap my head around RxJS and I have a question.  To better understand how everything works, I started a new blank Angular 4 application generated with Angular CLI.  In it, I am running the following code:

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .filter((item: any) => {
      let price = parseFloat(item.price);
      return price < 5.0 && price >= 2.5;
    })
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    },
    error => {
      this.error = error;
    });

The problem is that filter receives the whole object as a parameter and I cannot filter the individual items.  Using RxJS in a non-angular solution, I used this code:

let products = Observable.create(observer => {
    let xhr = new XMLHttpRequest();

    let onLoad = () => {
        let productsList = JSON.parse(xhr.responseText);
        observer.next(productsList);
        observer.complete();
    }

    xhr.addEventListener('load', onLoad);

    xhr.open('GET', 'products.json');
    xhr.send();

    return () => {
        console.log('cleanup');
        xhr.removeEventListener('load', onLoad);
        xhr.abort();
    }
})
.flatMap(Observable.from)
.filter(item => {
    let price = parseFloat(item.price);
    return price < 5.0 && price >= 2.5;
});

let subscr = products.subscribe(
    product => {
        let li = document.createElement('li');
        li.innerText = product.product_name + ' ' + product.price;
        list$.appendChild(li);
    },
    error => {
        console.log(`Error: ${error}`);
    },
    () => {
        console.log('complete');
        subscr.unsubscribe();
    }
);

The difference here is that I used flatMap, but if I try the same code in the Angular version I get:
Argument of type '{ (ish: ObservableInput, scheduler?: IScheduler): Observable; (ish: ArrayLike, ...' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
  Types of parameters 'scheduler' and 'index' are incompatible.
    Type 'number' is not assignable to type 'IScheduler'.

I was just wondering why the same scenario produces different results.  Is Angular using a different flavor of RxJS?  What is the most efficient way to filter the results in the Angular version?

Thank you.

Body:
getItems(): Observable<any>{
    this.http.get('./src/app/data/products.json')
        .map(res => {
          const data = res.json();  // your GET returns array
          return data.filter(item => parseFloat(item.price) >= 2.5 && parseFloat(item.price) < 5.0);  // notice this is not Rxjs filter.
        });
}

in your component:

this.xxxService.getItems()
  .subscribe(item => ...);


问:
How to use Sphinx with other template?
I'm want to write a documentation for my new module, and I was inspired by the docs of sentry.io, and I find out that they are using the Sphinx module, but the interface isn't the default one. Is there a way to change the template, or the sentry team made that for their own purposes?</p>

答: Sentry has their docs open-sourced. See their documentation contributing guidelines and repository. However it is heavily modified, so you might want to start with something easier by using one of the themes that comes with Sphinx or try others.</p>

Title: How to use Sphinx with other template?


问:
Can't open url with requests and urllib2
I try to access https://www.collinsdictionary.com/browse/english/words-starting-with-a with python requests, but get requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",)).

I tried with urllib2.urlopen, but I got different html from what I see in browser (there is no
).

What am I doing wrong?

答:
the website reject the get request of requests because of the default user-agent python use, you should set customized User-Agent to act as if you come from browser, User-Agent below is just an example to get the browser user agent for more current version google search my useragent</p>
```<code>import requests

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}

r = requests.get("https://www.collinsdictionary.com/browse/english/words-starting-with-a",headers=headers)
</code>```

Body:
the website reject the get request of requests because of the default user-agent python use, you should set customized User-Agent to act as if you come from browser, User-Agent below is just an example to get the browser user agent for more current version google search my useragent

import requests

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'}

r = requests.get("https://www.collinsdictionary.com/browse/english/words-starting-with-a",headers=headers)


问:
How to serialize to a file with Microsoft Bond
The Input and output streams section of the Microsoft Bond documentation provides this sample code to deserialize from a file:

```<code>using (var stream = new FileStream("example.bin", FileMode.Open))
{
    var input = new InputStream(stream);
    var reader = new CompactBinaryReader<InputStream>(input);
    var example = Deserialize<Example>.From(reader);
}
</code>```

I tried the reverse to serialize to file, but nothing is written to the file.

```<code>using (var stream = new FileStream("example.bin", FileMode.Create))
{
    var output = new OutputStream(stream);
    var writer = new CompactBinaryWriter<OutputStream>(output);
    Serialize.To(writer, example);
}
</code>```

Any ideas?

答:
It looks like the OutputStream hasn't been flushed into the FileStream. Try adding an explicit call to OutputStream.Flush like the stream example does:

```<code>using (var stream = new FileStream("example.bin", FileMode.Create))
{
    var output = new OutputStream(stream);
    var writer = new CompactBinaryWriter<OutputStream>(output);
    Serialize.To(writer, example);
    output.Flush();
}
</code>```

I was not around when OutputStream was designed, so I cannot comment on the decision process that resulted in it not implementing IDisposable.

Body:
The Input and output streams section of the Microsoft Bond documentation provides this sample code to deserialize from a file:

using (var stream = new FileStream("example.bin", FileMode.Open))
{
    var input = new InputStream(stream);
    var reader = new CompactBinaryReader<InputStream>(input);
    var example = Deserialize<Example>.From(reader);
}

I tried the reverse to serialize to file, but nothing is written to the file.

using (var stream = new FileStream("example.bin", FileMode.Create))
{
    var output = new OutputStream(stream);
    var writer = new CompactBinaryWriter<OutputStream>(output);
    Serialize.To(writer, example);
}

Any ideas?

Body:
It looks like the OutputStream hasn't been flushed into the FileStream. Try adding an explicit call to OutputStream.Flush like the stream example does:

using (var stream = new FileStream("example.bin", FileMode.Create))
{
    var output = new OutputStream(stream);
    var writer = new CompactBinaryWriter<OutputStream>(output);
    Serialize.To(writer, example);
    output.Flush();
}

I was not around when OutputStream was designed, so I cannot comment on the decision process that resulted in it not implementing IDisposable.


问:
Understanding a big company project in Java
what is the best way to understand a big company project in java?</p>

答: Documentation my friend, look for manager patterns seek the jsp play with the code dont be afraid to make small changes and see what happens, understand the logic and the building blocks, stay way  from companies with poor documentation. </p>


问:
scala annotation argument needs to be constant but final val does not make it
In this snippet,

```<code>@SwaggerDefinition(...authorizationUrl =
SecurityConstants.authorizationUrl)
</code>```

and given that

```<code>final object SecurityConstants {
  final val authorizationUrl: String =..
}
</code>```

(only one of the two finals should be ok, but still)
I was expecting/hoping that this would compile with 2.12.3 but it is however giving
"annotation argument needs to be a constant; found: SecurityConstants.authorizationUrl
[error]         authorizationUrl = SecurityConstants.authorizationUrl,"

Also calling Java static method System.getenv("a") in annotation brings the same error, that is

```<code>@SwaggerDefinition(...authorizationUrl = System.getenv("a"))
</code>```

Please help,
Nicu M

答:
final val references can be used as Java annotation arguments under two conditions:

The value assigned to the final val must be a literal.

You must not specify the type of your final val explicitly.

So, this will work:

```<code>final val AuthorizationUrl = "http://something.com"
</code>```

but these will not work:

```<code>final val AuthorizationUrl = "http://something.com".trim
final val AuthorizationUrl: String = "http://something.com"
</code>```

The condition no. 2 may seem especially weird but it's required for the compiler to internally retain the information that the final val is holding not just a String but some particular literal string value (the compiler must infer a literal type).

Body:
In this snippet,

@SwaggerDefinition(...authorizationUrl =
SecurityConstants.authorizationUrl)

and given that

final object SecurityConstants {
  final val authorizationUrl: String =..
}

(only one of the two finals should be ok, but still)
I was expecting/hoping that this would compile with 2.12.3 but it is however giving
"annotation argument needs to be a constant; found: SecurityConstants.authorizationUrl
[error]         authorizationUrl = SecurityConstants.authorizationUrl,"

Also calling Java static method System.getenv("a") in annotation brings the same error, that is

@SwaggerDefinition(...authorizationUrl = System.getenv("a"))

Please help,
Nicu M

Body:
final val references can be used as Java annotation arguments under two conditions:

The value assigned to the final val must be a literal.

You must not specify the type of your final val explicitly.

So, this will work:

final val AuthorizationUrl = "http://something.com"

but these will not work:

final val AuthorizationUrl = "http://something.com".trim
final val AuthorizationUrl: String = "http://something.com"

The condition no. 2 may seem especially weird but it's required for the compiler to internally retain the information that the final val is holding not just a String but some particular literal string value (the compiler must infer a literal type).


答:
It is really important what is behind .. in the

```<code>final val authorizationUrl: String =..
</code>```

In Scala and Java annotation arguments must be compile-time constants rather than just "final". So System.getenv("a") (or any other function call) directly or via intermediate val will not do it as this is not a compile-time constant. This is done that way because annotations are designed to be introspectable at the compile time i.e. if you just have a .class file, you must be able to get the value of all the fields of the annotation. So the  compiler must know all the values at the compile time.

Update

Actually Swagger itself relies on the compile-time introspection. So what exactly did you expect it to do with your System.getenv call? What specification Swagger should have generated for such annotation? And why do you need it at all? AFAIU if you have several environments, you should put URLs of the production (i.e. the one accessed by outside users) into the definition.

Title: scala annotation argument needs to be constant but final val does not make it

Body:
It is really important what is behind .. in the

final val authorizationUrl: String =..

In Scala and Java annotation arguments must be compile-time constants rather than just "final". So System.getenv("a") (or any other function call) directly or via intermediate val will not do it as this is not a compile-time constant. This is done that way because annotations are designed to be introspectable at the compile time i.e. if you just have a .class file, you must be able to get the value of all the fields of the annotation. So the  compiler must know all the values at the compile time.

Update

Actually Swagger itself relies on the compile-time introspection. So what exactly did you expect it to do with your System.getenv call? What specification Swagger should have generated for such annotation? And why do you need it at all? AFAIU if you have several environments, you should put URLs of the production (i.e. the one accessed by outside users) into the definition.


问:
consolidate data from multiple sheets excel
I have 6 sheets of report data that I have run through formulas to standardize the formatting. On these sheets, the data that I need is in Columns AL:BW, with varying lengths, and matching headers.

Now, I need to pull all that data together into a summary sheet to more easily create charts/reports.  I am pretty sure that VBA will be able to solve, but I haven't found an answer online that will allow me to select the same range of columns on each sheet and compile that data in a summary sheet.

I have been experimenting with the solution from this article but I don't know enough about VBA to specifically target the data in the AL:BW columns.

```<code>Sub CopyData()

    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim shLast As Long
    Dim CopyRng As Range
    Dim StartRow As Long

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    ' Delete the summary sheet if it exists.
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("CombinedData").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    ' Add a new summary worksheet.
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "CombinedData"

    ' Fill in the start row.
    StartRow = 2

    ' Loop through all worksheets and copy the data to the
    ' summary worksheet.
    For Each sh In ActiveWorkbook.Worksheets
        If LCase(Left(sh.Name, 4)) = "?-??" Then

            ' If source worksheet is not empty and if the last
            ' row >= StartRow, copy the range.
            If shLast > 0 And shLast >= StartRow Then
                'Set the range that you want to copy
                Set CopyRng = sh.Range("AL:BL")

               ' Test to see whether there are enough rows in the summary
               ' worksheet to copy all the data.
                If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                   MsgBox "There are not enough rows in the " & _
                   "summary worksheet to place the data."
                   GoTo ExitTheSub
                End If

                ' This statement copies values and formats.
                CopyRng.Copy
                With DestSh.Cells(Last + 1, "A")
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                End With

End Sub
</code>```

I appreciate the help!

答:
This should do what you want.  Just change the copy range.</p>

```<code>'Fill in the range that you want to copy
'Set CopyRng = sh.Range("A1:G1")

Sub CopyRangeFromMultiWorksheets()
    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim CopyRng As Range

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Delete the sheet "RDBMergeSheet" if it exist
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    'Add a worksheet with the name "RDBMergeSheet"
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "RDBMergeSheet"

    'loop through all worksheets and copy the data to the DestSh
    For Each sh In ActiveWorkbook.Worksheets
        If sh.Name <> DestSh.Name Then

            'Find the last row with data on the DestSh
            Last = LastRow(DestSh)

            'Fill in the range that you want to copy
            Set CopyRng = sh.Range("A1:G1")

            'Test if there enough rows in the DestSh to copy all the data
            If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                MsgBox "There are not enough rows in the Destsh"
                GoTo ExitTheSub
            End If

            'This example copies values/formats, if you only want to copy the
            'values or want to copy everything look at the example below this macro
            CopyRng.Copy
            With DestSh.Cells(Last + 1, "A")
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
            End With

            'Optional: This will copy the sheet name in the H column
            DestSh.Cells(Last + 1, "H").Resize(CopyRng.Rows.Count).Value = sh.Name

        End If
    Next

ExitTheSub:

    Application.Goto DestSh.Cells(1)

    'AutoFit the column width in the DestSh sheet
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Function LastCol(sh As Worksheet)
    On Error Resume Next
    LastCol = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Column
    On Error GoTo 0
End Function
</code>```

Body:
I have 6 sheets of report data that I have run through formulas to standardize the formatting. On these sheets, the data that I need is in Columns AL:BW, with varying lengths, and matching headers.

Now, I need to pull all that data together into a summary sheet to more easily create charts/reports.  I am pretty sure that VBA will be able to solve, but I haven't found an answer online that will allow me to select the same range of columns on each sheet and compile that data in a summary sheet.

I have been experimenting with the solution from this article but I don't know enough about VBA to specifically target the data in the AL:BW columns.

Sub CopyData()

    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim shLast As Long
    Dim CopyRng As Range
    Dim StartRow As Long

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    ' Delete the summary sheet if it exists.
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("CombinedData").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    ' Add a new summary worksheet.
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "CombinedData"

    ' Fill in the start row.
    StartRow = 2

    ' Loop through all worksheets and copy the data to the
    ' summary worksheet.
    For Each sh In ActiveWorkbook.Worksheets
        If LCase(Left(sh.Name, 4)) = "?-??" Then

            ' If source worksheet is not empty and if the last
            ' row >= StartRow, copy the range.
            If shLast > 0 And shLast >= StartRow Then
                'Set the range that you want to copy
                Set CopyRng = sh.Range("AL:BL")

               ' Test to see whether there are enough rows in the summary
               ' worksheet to copy all the data.
                If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                   MsgBox "There are not enough rows in the " & _
                   "summary worksheet to place the data."
                   GoTo ExitTheSub
                End If

                ' This statement copies values and formats.
                CopyRng.Copy
                With DestSh.Cells(Last + 1, "A")
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                End With

End Sub

I appreciate the help!

Body:
This should do what you want.  Just change the copy range.

'Fill in the range that you want to copy
'Set CopyRng = sh.Range("A1:G1")

Sub CopyRangeFromMultiWorksheets()
    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim CopyRng As Range

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Delete the sheet "RDBMergeSheet" if it exist
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    'Add a worksheet with the name "RDBMergeSheet"
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "RDBMergeSheet"

    'loop through all worksheets and copy the data to the DestSh
    For Each sh In ActiveWorkbook.Worksheets
        If sh.Name <> DestSh.Name Then

            'Find the last row with data on the DestSh
            Last = LastRow(DestSh)

            'Fill in the range that you want to copy
            Set CopyRng = sh.Range("A1:G1")

            'Test if there enough rows in the DestSh to copy all the data
            If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                MsgBox "There are not enough rows in the Destsh"
                GoTo ExitTheSub
            End If

            'This example copies values/formats, if you only want to copy the
            'values or want to copy everything look at the example below this macro
            CopyRng.Copy
            With DestSh.Cells(Last + 1, "A")
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
            End With

            'Optional: This will copy the sheet name in the H column
            DestSh.Cells(Last + 1, "H").Resize(CopyRng.Rows.Count).Value = sh.Name

        End If
    Next

ExitTheSub:

    Application.Goto DestSh.Cells(1)

    'AutoFit the column width in the DestSh sheet
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Function LastCol(sh As Worksheet)
    On Error Resume Next
    LastCol = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Column
    On Error GoTo 0
End Function


问:
How do I disable a CSS rule?
I have the following CSS rule

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}
```

<p>What I usualy do is</p>

```document.getElementById('class').style.margin= '0px';
```

<p>Then after doing that to reset I go the same step</p>

```document.getElementById('class').style.margin= '4px 5px 6px 7px';
```

How do I disable the margin using JavaScript\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px

答:
The other answers are good, just wanted to share another way of doing this. You can keep your base CSS style rule:

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}
```

<p>And then add a noMargin class as others have suggested:</p>

```.noMargin {
    margin: 0; !important
}
```

<p>And then, use toggleClass to switch it on/off:</p>

```document.getElementById('class').classList.toggleClass('noMargin');
```

The benefit here is that A) only one line of code to on/off the margin, B) only one extra CSS rule, and C) don't have to worry about whether the margin is currently on or off before switching it.

Title: How do I disable a CSS rule?

Body:
I have the following CSS rule

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}

What I usualy do is

document.getElementById('class').style.margin= '0px';

Then after doing that to reset I go the same step

document.getElementById('class').style.margin= '4px 5px 6px 7px';

How do I disable the margin using JavaScript\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px

Body:
The other answers are good, just wanted to share another way of doing this. You can keep your base CSS style rule:

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}

And then add a noMargin class as others have suggested:

.noMargin {
    margin: 0; !important
}

And then, use toggleClass to switch it on/off:

document.getElementById('class').classList.toggleClass('noMargin');

The benefit here is that A) only one line of code to on/off the margin, B) only one extra CSS rule, and C) don't have to worry about whether the margin is currently on or off before switching it.


问:
Javascript passing var on click in a table
Trying to pass a variable when a
 in clicked, am getting "undefined".
Works if I remove the onclick="fnselect()" and use a submit button, which I don't want.

function highlight(e) {
  if (selected[0]) selected[0].className = '';
  e.target.parentNode.className = 'selected';
}

var table = document.getElementById('table'),
  selected = table.getElementsByClassName('selected');
table.onclick = highlight;

function fnselect(){
  var phpValue = $("tr.selected td:first" ).html();
  window.location.href = "http://website/test.php?phpValue="+phpValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table">
     <tr onclick="fnselect()">
      <td>1 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect()">
      <td>2 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect()">
      <td>3 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
    </table></code>```

答:
You can pass a reference of this in the onclick, which is a reference to the clicked tr

Then in fnselect you can wrap the passed in row reference in a jQuery object and get the html() of the first  for that row.

function highlight(e) {
  if (selected[0]) selected[0].className = '';
  e.target.parentNode.className = 'selected';
}

var table = document.getElementById('table'),
  selected = table.getElementsByClassName('selected');
table.onclick = highlight;

function fnselect(row){
  var phpValue = $(row).find("td:first").text();
  console.log(phpValue)
  //window.location.href = "http://website/test.php?phpValue="+phpValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
     <tr onclick="fnselect(this)">
      <td>1 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect(this)">
      <td>2 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect(this)">
      <td>3 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
    </table></code>```

Body:
Trying to pass a variable when a
 in clicked, am getting "undefined".
Works if I remove the onclick="fnselect()" and use a submit button, which I don't want.

function highlight(e) {
  if (selected[0]) selected[0].className = '';
  e.target.parentNode.className = 'selected';
}

var table = document.getElementById('table'),
  selected = table.getElementsByClassName('selected');
table.onclick = highlight;

function fnselect(){
  var phpValue = $("tr.selected td:first" ).html();
  window.location.href = "http://website/test.php?phpValue="+phpValue;
}

      1 Ferrari F138
      1 000€
      1 200€
      Model monopostu stajne Scuderia Ferrari pre sezónu 2013
      1
      F138
      Klik pre detaily

      2 Ferrari F138
      1 000€
      1 200€
      Model monopostu stajne Scuderia Ferrari pre sezónu 2013
      1
      F138
      Klik pre detaily

      3 Ferrari F138
      1 000€
      1 200€
      Model monopostu stajne Scuderia Ferrari pre sezónu 2013
      1
      F138
      Klik pre detaily

Body:
You can pass a reference of this in the onclick, which is a reference to the clicked tr

Then in fnselect you can wrap the passed in row reference in a jQuery object and get the html() of the first <td> for that row.

function highlight(e) {
  if (selected[0]) selected[0].className = '';
  e.target.parentNode.className = 'selected';
}

var table = document.getElementById('table'),
  selected = table.getElementsByClassName('selected');
table.onclick = highlight;

function fnselect(row){
  var phpValue = $(row).find("td:first").text();
  console.log(phpValue)
  //window.location.href = "http://website/test.php?phpValue="+phpValue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
     <tr onclick="fnselect(this)">
      <td>1 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect(this)">
      <td>2 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
     <tr onclick="fnselect(this)">
      <td>3 Ferrari F138</td>
      <td>1 000€</td>
      <td>1 200€</td>
      <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td>
      <td>1</td>
      <td>F138</td>
      <td>Klik pre detaily</td>
     </tr>
    </table>


问:
Select row using the length of list in pandas cell
I have a table df

```<code>    a   b    c
1   x   y   [x]

2   x   z   [c,d]

3   x   t   [e,f,g]
</code>```

Just wondering how to select the row using the length of c column

such as

```<code>df.loc[len(df.c) >1]
</code>```

I know this is not right.... what should be the right one?

答:
Try this:</p>

```<code>df[df.c.map(len)>1]
</code>```

Body:
I have a table df

    a   b    c
1   x   y   [x]

2   x   z   [c,d]

3   x   t   [e,f,g]

Just wondering how to select the row using the length of c column

such as

df.loc[len(df.c) >1]

I know this is not right.... what should be the right one?

Body:
Try this:

df[df.c.map(len)>1]


问:
Python tkinter label formulas
how can I make a label with a formula and whenever I change the value in entry, does it automatically change the value in the label? As if it were excel cells with formulas. And in case it would have to be invisible (without content) while the entry is empty.</p>

```<code>import tkinter as tk

root = tk.Tk()
ent1 = tk.Entry(root)
lab1 = tk.Label(root,text='Price')
ent2 = tk.Entry(root)
lab2 = tk.Label(root,text='Quantity')
lab3 = tk.Label(root,text='') #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack()
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()
</code>```

答:
Use the trace method to execute a function when a variable changes.

```<code>import tkinter as tk

def update(*args):
    try:
        output_var.set(price_var.get() * quantity_var.get())
    except (ValueError, tk.TclError):
        output_var.set('invalid input')

root = tk.Tk()

lab1 = tk.Label(root,text='Price')
price_var = tk.DoubleVar()
price_var.trace('w', update) # call the update() function when the value changes
ent1 = tk.Entry(root, textvariable=price_var)

lab2 = tk.Label(root,text='Quantity')
quantity_var = tk.DoubleVar()
quantity_var.trace('w', update)
ent2 = tk.Entry(root, textvariable=quantity_var)

output_var = tk.StringVar()
lab3 = tk.Label(root, textvariable=output_var) #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack()
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

root.mainloop()
</code>```

Title: Python tkinter label formulas

Body:
how can I make a label with a formula and whenever I change the value in entry, does it automatically change the value in the label? As if it were excel cells with formulas. And in case it would have to be invisible (without content) while the entry is empty.

import tkinter as tk

root = tk.Tk()
ent1 = tk.Entry(root)
lab1 = tk.Label(root,text='Price')
ent2 = tk.Entry(root)
lab2 = tk.Label(root,text='Quantity')
lab3 = tk.Label(root,text='') #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack()
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

Body:
Use the trace method to execute a function when a variable changes.

import tkinter as tk

def update(*args):
    try:
        output_var.set(price_var.get() * quantity_var.get())
    except (ValueError, tk.TclError):
        output_var.set('invalid input')

root = tk.Tk()

lab1 = tk.Label(root,text='Price')
price_var = tk.DoubleVar()
price_var.trace('w', update) # call the update() function when the value changes
ent1 = tk.Entry(root, textvariable=price_var)

lab2 = tk.Label(root,text='Quantity')
quantity_var = tk.DoubleVar()
quantity_var.trace('w', update)
ent2 = tk.Entry(root, textvariable=quantity_var)

output_var = tk.StringVar()
lab3 = tk.Label(root, textvariable=output_var) #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack()
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

root.mainloop()


问:
outputting elapsed time with powers of 10 instead of SI prefixes
In the classroom, I often use the Python module timeit to compare the execution time of code snippets. For instance, under IPython:

```<code>def test1(a, b):
    if a > b:
        (a, b) = (b, a)
    return (a,b)

def test2(a, b):
    (a, b) = (min(a, b), max(a,b))
    return (a,b)

%timeit test1(5, 6); test1(6, 5)
%timeit test2(5, 6); test2(6, 5)
</code>```

Output (YMMV):

```<code>584 ns ± 31.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.96 µs ± 212 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

The following output would make the comparison a bit easier:

```<code>5.84e-7 s ± 3.10e-8 s per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.96e-6 s ± 2.12e-7 s per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

As of Python 3.5, there is an option --unit in the command line API, which accepts sec as a value. But measuring a multi-line statement is cumbersome. And I cannot see how to use the same parameter with the Python API, much less under IPython.

I would appreciate any suggestion.

EDIT: according to Matt answer, %timeit -o returns its result as a TimeitResult, which possesses the attribute I am interested in. So, a possible workaround would be:

```<code>timeit_result1 = %timeit -oq test1(5, 6); test1(6, 5)
print("{:.2e} sec".format(timeit_result1.best))
timeit_result2 = %timeit -oq test2(5, 6); test2(6, 5)
print("{:.2e} sec".format(timeit_result2.best))
</code>```

Output:

```<code>5.34e-07 sec
1.71e-06 sec
</code>```

NB: The intermediate assignment seems mandatory. AFAIK, %timeit -o... is not a normal expression.

答:
If you use the %timeit -o option you can assign the result (a TimeitResult object), extract the relevant fields, and format the strings yourself,  or use in a graph. This include using %timeit in a loop, which can be useful to find the time complexity of a function (use {variable} to pass parameters). The time formatting code ipython uses is here in IPython/core/magics/execution.py if you need it.

IPython does not have a options (yet) to force a specific unit, though it could make sens to add it. Instead of writing your own magic (as you suggest in your comments), please propose a patch to IPython itself, we'll be happy to guide you through the process and review it.

Body:
In the classroom, I often use the Python module timeit to compare the execution time of code snippets. For instance, under IPython:

def test1(a, b):
    if a > b:
        (a, b) = (b, a)
    return (a,b)

def test2(a, b):
    (a, b) = (min(a, b), max(a,b))
    return (a,b)

%timeit test1(5, 6); test1(6, 5)
%timeit test2(5, 6); test2(6, 5)

Output (YMMV):

584 ns ± 31.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.96 µs ± 212 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The following output would make the comparison a bit easier:

5.84e-7 s ± 3.10e-8 s per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.96e-6 s ± 2.12e-7 s per loop (mean ± std. dev. of 7 runs, 100000 loops each)

As of Python 3.5, there is an option --unit in the command line API, which accepts sec as a value. But measuring a multi-line statement is cumbersome. And I cannot see how to use the same parameter with the Python API, much less under IPython.

I would appreciate any suggestion.

EDIT: according to Matt answer, %timeit -o returns its result as a TimeitResult, which possesses the attribute I am interested in. So, a possible workaround would be:

timeit_result1 = %timeit -oq test1(5, 6); test1(6, 5)
print("{:.2e} sec".format(timeit_result1.best))
timeit_result2 = %timeit -oq test2(5, 6); test2(6, 5)
print("{:.2e} sec".format(timeit_result2.best))

Output:

5.34e-07 sec
1.71e-06 sec

NB: The intermediate assignment seems mandatory. AFAIK, %timeit -o... is not a normal expression.


问:
Kannel Round Robin Setup when SMSC is absent in sendsms Query String
I want to make a Round Robin configuration setting in the Kannel for the below message sending given that I have 2 SMSC(SMSC0 and SMSC1). When no SMSC is present in the query string, I like to use SMSC0 and SMSC1 in a Round Robin fashion. This is something like making a Default SMSC setting that will handle those things not explicitly handled by any SMSC. May be denied-smsc-id, allowed-smsc-id, preferred-smsc-id have some role.

```<code>cgi-bin/sendsms?username=sendsms&password=sendsms&to=44897742898855&from=test100&text=testmessagesinfohello&dlr-mask=31
</code>```

答:
```<code>NOT ROUND-ROBIN:
================
group = smsc
smsc-id = smsc1
allowed-smsc-id = smsc1

group = smsc
smsc-id = smsc2
allowed-smsc-id = smsc2

group = sendsms-user
default-smsc = smsc1

ROUND-ROBIN:
================
group = smsc
smsc-id = smsc1
denied-smsc-id = smsc2

group = smsc
smsc-id = smsc2
denied-smsc-id = smsc1
</code>```

Body:
I want to make a Round Robin configuration setting in the Kannel for the below message sending given that I have 2 SMSC(SMSC0 and SMSC1). When no SMSC is present in the query string, I like to use SMSC0 and SMSC1 in a Round Robin fashion. This is something like making a Default SMSC setting that will handle those things not explicitly handled by any SMSC. May be denied-smsc-id, allowed-smsc-id, preferred-smsc-id have some role.

cgi-bin/sendsms?username=sendsms&password=sendsms&to=44897742898855&from=test100&text=testmessagesinfohello&dlr-mask=31


问:
Collision handeling in Panda3D with traverse()
I am new to Panda3d and I am using some of the 'roaming ralph' code to check for collisions:

In the 'roaming ralph' code example that comes with panda3d, it says

```<code>    # Normally, we would have to call traverse() to check for collisions.
    # However, the class ShowBase that we inherit from has a task to do
    # this for us, if we assign a CollisionTraverser to self.cTrav.
</code>```

I am using the normal version of Showbase, so how do I call

```<code>    traverse()
</code>```

Like it says?

答:
It's saying that if you assign the CollisionTraverser instance to base.cTrav, or self.cTrav, there is no need to call the traverse function every frame.  Indeed, this is the case in the Roaming Ralph program.

If this weren't the case, for example if you rename the variable to self.traverser, you would have to add a line like this to a task (eg. to the existing move task):

```<code>self.traverser.traverse(self.render)
</code>```

Body:
I am new to Panda3d and I am using some of the 'roaming ralph' code to check for collisions:

In the 'roaming ralph' code example that comes with panda3d, it says

    # Normally, we would have to call traverse() to check for collisions.
    # However, the class ShowBase that we inherit from has a task to do
    # this for us, if we assign a CollisionTraverser to self.cTrav.

I am using the normal version of Showbase, so how do I call

    traverse()

Like it says?

Body:
It's saying that if you assign the CollisionTraverser instance to base.cTrav, or self.cTrav, there is no need to call the traverse function every frame.  Indeed, this is the case in the Roaming Ralph program.

If this weren't the case, for example if you rename the variable to self.traverser, you would have to add a line like this to a task (eg. to the existing move task):

self.traverser.traverse(self.render)


问:
How can I read a dynamically created textbox (gridview OnRowUpdating)
```<code> <asp:GridView ID="GridView1" runat="server"  >

<asp:TemplateField HeaderText="Token" SortExpression="Token" HeaderStyle-Width="100px">
                    <ItemTemplate>

                    </ItemTemplate>
                </asp:TemplateField>

</asp:GridView>
</code>```

update:

after i view the source code of the page thsi is what i see the id of a textbox that i have created dynamic.

```<code>ctl00_ContentPlaceHolder1_tabControl_tabUsers_MyControl1_gv_ctl02__token0_3
</code>```

OnRowUpdating:

```<code> TextBox _token = gvOrg.Rows[e.RowIndex].Cells[7].FindControl("_token " + e.RowIndex + "_" + rowId) as TextBox;
</code>```

Update end:

i am adding few textbox dynamic in OnRowDataBound and whe i try getting the value then i am getting null

here is my code:

```<code> protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            for (int rowId = 0; rowId < 5; rowId++)
            {
                TextBox _token = gvOrg.Rows[e.RowIndex].Cells[7].FindControl("_token" + rowId) as TextBox;
             }
        }

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit))
            {

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    for (int rowId = 0; rowId < 5; rowId++)
                    {
                        TextBox txtBox = new TextBox();
                        txtBox.ID = "_token" + rowId;
                        txtBox.Text = "token" + rowId;
                        e.Row.Cells[7].Controls.Add(txtBox);
                    }
}
</code>```

答:
here is how i able to fix the problem: instead of creating in rowdatabound i am creating on RowCreated, hope this will help others.</p>

```<code> protected void gridviwe1_RowCreated(object sender, GridViewRowEventArgs e)
        {

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    for (int rowId = 0; rowId < 5; rowId++)
                    {
                        TextBox txtBox = new TextBox();
                        txtBox.ID = "_registration" + e.Row.RowIndex + "_" + rowId;
                        txtBox.Text = "_registration" + e.Row.RowIndex + "_" + rowId;
                        e.Row.Cells[7].Controls.Add(txtBox);
                    }
                }
            }
</code>```

Body:
 <asp:GridView ID="GridView1" runat="server"  >

<asp:TemplateField HeaderText="Token" SortExpression="Token" HeaderStyle-Width="100px">
                    <ItemTemplate>

                    </ItemTemplate>
                </asp:TemplateField>

</asp:GridView>

update:

after i view the source code of the page thsi is what i see the id of a textbox that i have created dynamic.

ctl00_ContentPlaceHolder1_tabControl_tabUsers_MyControl1_gv_ctl02__token0_3

OnRowUpdating:

 TextBox _token = gvOrg.Rows[e.RowIndex].Cells[7].FindControl("_token " + e.RowIndex + "_" + rowId) as TextBox;

Update end:

i am adding few textbox dynamic in OnRowDataBound and whe i try getting the value then i am getting null

here is my code:

 protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            for (int rowId = 0; rowId < 5; rowId++)
            {
                TextBox _token = gvOrg.Rows[e.RowIndex].Cells[7].FindControl("_token" + rowId) as TextBox;
             }
        }

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit))
            {

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    for (int rowId = 0; rowId < 5; rowId++)
                    {
                        TextBox txtBox = new TextBox();
                        txtBox.ID = "_token" + rowId;
                        txtBox.Text = "token" + rowId;
                        e.Row.Cells[7].Controls.Add(txtBox);
                    }
}

Body:
here is how i able to fix the problem: instead of creating in rowdatabound i am creating on RowCreated, hope this will help others.

 protected void gridviwe1_RowCreated(object sender, GridViewRowEventArgs e)
        {

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    for (int rowId = 0; rowId < 5; rowId++)
                    {
                        TextBox txtBox = new TextBox();
                        txtBox.ID = "_registration" + e.Row.RowIndex + "_" + rowId;
                        txtBox.Text = "_registration" + e.Row.RowIndex + "_" + rowId;
                        e.Row.Cells[7].Controls.Add(txtBox);
                    }
                }
            }


问:
js pass function by reference to override it
I have a decorator that overrides a function:

```<code>function decorator(target, key, descriptor) {
    descriptor.value = function() {
        console.log('overridden')
    }
}
</code>```

Now I would like to perform the override in another function and I therefore need to pass it as an argument in a way so I can still replace the method:

```<code>function decorator(target, key, descriptor) {
    replaceMethod(descriptor.value)
}

function replaceMethod(originalMethod) {
    originalMethod = function() {
        console.log('overridden')
    }
}
</code>```

Is it somehow possible to do it in this way?

答:
This will work:

```<code>function bark(target, key, descriptor) {
    replaceWith(descriptor, function(msg){
        console.log("Woof!");
    });
    return descriptor;
}

function replaceWith(descriptor, value){
    descriptor.value = value;
}

class Animal {
    @bark
    greet(msg) {
        console.log(msg);
    }
}

new Animal().greet("Hello");
</code>```

https://jsfiddle.net/DerekL/0sd9Lvs0/

Body:
I have a decorator that overrides a function:

function decorator(target, key, descriptor) {
    descriptor.value = function() {
        console.log('overridden')
    }
}

Now I would like to perform the override in another function and I therefore need to pass it as an argument in a way so I can still replace the method:

function decorator(target, key, descriptor) {
    replaceMethod(descriptor.value)
}

function replaceMethod(originalMethod) {
    originalMethod = function() {
        console.log('overridden')
    }
}

Is it somehow possible to do it in this way?

Body:
This will work:

function bark(target, key, descriptor) {
    replaceWith(descriptor, function(msg){
        console.log("Woof!");
    });
    return descriptor;
}

function replaceWith(descriptor, value){
    descriptor.value = value;
}

class Animal {
    @bark
    greet(msg) {
        console.log(msg);
    }
}

new Animal().greet("Hello");

https://jsfiddle.net/DerekL/0sd9Lvs0/