text:
Q: SpringMVC gets an error "There is already controller bean method" although there is any other methods in the same controller I am developing a REST API with Spring MVC.
And it builds successfully, but when I try to deploy it to Tomcat 8.0.57
it gives the following error saying I have already a bean method in that controller. But I dont have any two methods with same names or RequestMethod.
This is the Apache Tomcat Log
    29-Nov-2017 18:29:41.796 INFO [http-nio-8087-exec-72] org.apache.catalina.core.ApplicationContext.log 1 Spring WebApplicationInitializers detected on classpath
29-Nov-2017 18:29:41.844 INFO [http-nio-8087-exec-72] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
29-Nov-2017 18:29:42.783 SEVERE [http-nio-8087-exec-72] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'chatUserController' method
public java.lang.String org.test.chatapi.controller.ChatUserController.saveUser(org.test.chatapi.model.User)
to {[],methods=[POST]}: There is already 'chatMessageController' bean method
public java.lang.Integer org.test.chatapi.controller.ChatMessageController.saveMessage(org.test.chatapi.model.Message) mapped.
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4736)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:460)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1586)
    at sun.reflect.GeneratedMethodAccessor94.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1460)
    at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:906)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:344)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:614)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'chatUserController' method
public java.lang.String org.test.chatapi.controller.ChatUserController.saveUser(org.test.chatapi.model.User)
to {[],methods=[POST]}: There is already 'chatMessageController' bean method
public java.lang.Integer org.test.chatapi.controller.ChatMessageController.saveMessage(org.test.chatapi.model.Message) mapped.
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.assertUniqueMethodMapping(AbstractHandlerMethodMapping.java:570)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:534)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:258)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:244)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:214)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:184)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:124)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    ... 59 more

29-Nov-2017 18:29:42.789 INFO [http-nio-8087-exec-72]  org.apache.catalina.core.ApplicationContext.log Closing Spring root      WebApplicationContext

And these are the Controllers.
ChatUserController
@RestController
public class ChatUserController {

// Store the Users temporarily
ArrayList<User> users = new ArrayList<>();

// Get all the online users
@RequestMapping(name = "/users/", method = RequestMethod.GET)
public ArrayList<User> getUsers(){
    users.add(new User("Janith","Hellow worlds"));
    return users;
}

// Save new user / User Login
@RequestMapping(name = "/users/",method = RequestMethod.POST)
public String saveUser(@RequestBody User user){
    if(user != null){
        users.add(user);
        return "Successfull Saved";
    }else{
        return "Failed";
    }
}

// Remove the user /  User sign out
@RequestMapping(name = "/users/{uname}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable String uname){
    for(User u:users){
        if(u.getUsername().equals(uname)){
            users.remove(u);
            return "Removed Successfully";
        }
    }
    return "User Not found. Should be already Deleted.";
}
}

ChatMessagesController
@RestController
public class ChatMessageController {

    ArrayList<Message> messagesList = new ArrayList<>();

    @RequestMapping(name = "/messages/{username}", method = RequestMethod.PUT)
    public ArrayList<Message> getChat(@PathVariable String username) {

        // create a new list of unread messages
        ArrayList<Message> myMessages = new ArrayList<>();

        // add the unread messages to list
        for (Message m : messagesList) {
            if (m.getReciever().equals(username)) {
                if (!m.isViewed()) {
                    m.setViewed(true);
                    myMessages.add(m);
                }
            }
        }
        return myMessages;
    }

    @RequestMapping(name = "/messages/", method = RequestMethod.POST)
    public Integer saveMessage(@RequestBody Message message){
        if(message != null){
            message.setViewed(false);
            messagesList.add(message);
            return new Integer(1);
        }else{
            return new Integer(0);
        }
    }
}

But this ChatUserController worked fine, I deployed and tested it.
This error is getting after adding the ChatMessageController's second method saveMessage(). And also this same error showed when the first method getChat() was in GET RequestMethod. It was fixed after I changed it to the PUT method.
I am new to Spring MVC Web API, So I appreciate any help regarding this.

A: In my case I go to read Spring doc to find some explanation but I finished when found this in RequestMapping interface:
Note: This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.
So I decided also to prefer to use @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping and it works in my case.
Try to make:
@GetMapping("/users/")
public String saveUser(@RequestBody User user){
    //...
}

@DeleteMapping("/users/{uname}")
public String deleteUser(@PathVariable String uname){
    //...
}

P.S: also we need use value if we need set path:
@RequestMapping(value = "/users/", method = RequestMethod.GET)

name its only name, not path


text:
Q: Read a cell based of numerical input for IF command I am designing a Material Resource Plan using Excel. I have a two week lead on parts with lot sizes of 90. To auto fill the fields, I would like to be able to input '2' and have Excel recognize that if cell E30 (Planned Order Receipt) has a value, that C31 (Planned Order Release) should display the lot size (as in two weeks prior an order should be placed). Is this type of function possible?

A: Try
=IF(NOT(INDEX(ISBLANK($D$30:F30),B23)),B24,"")

where $D$30:F30 represents the value of Planned Order Receipt from Week 2 to Week 4. If you have more than 4 weeks, replace F30 with the actual ending cell of this range (and suggest to use absolute cell reference i.e. putting a dollar sign $ in front both column and row ID).

ISBLANK function will check each cell in the range $D$30:F30 is blank (not returned by a formula but a real blank cell), and return a range of TRUE or FALSE.
INDEX function will return the corresponding TRUE or FALSE based on the lead number you entered. If you enter 2, INDEX will return the second value from the range, so on so forth.
NOT function will reverse FALSE to TRUE i.e. TRUE for a non-blank cell. Then IF function will return the lot number as desired, but return a blank "" if that's not the case. You did not specify what you would like to return if the Planned Order Receipt is blank so I just used blank "".

A: I did some searching today and ask Dr. Google a little differently. I was able to locate this solution using the Offset function:
=OFFSET(C26,4,$B$23,1,1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I access the various items in this NSDictionary? Say I have NSDictionary *foo below:
complete = 1;
    list =     {
        8213812 =         {
            excerpt = "Lorem ipsum dolor...."
        }
        8810100 =         {
            another = "iasjdiasd..."
        ...

I know for accessing "complete" I use [response objectForKey:@"complete"] but what about the others?

A: You just keep accessing the keys from the nested dictionaries until you get what you want. For accessing the "list", it is, unsurprisingly
[[response objectForKey:@"complete"] objectForKey:@"list"]

And for accessing the 8213812-style keys inside list — well, it depends on their type. Assuming they're strings, it would be
[[[response objectForKey:@"complete"] objectForKey:@"list"] objectForKey:@"8213812"]

or, to use the newer, more succinct syntax
response[@"complete"][@"list"][@"8213812"]

But they might be NSNumbers or something else, and in case case you would use the appropriate NSNumber.

A: [[[response objectForKey:@"list"] objectForKey:@"8213812"] objectForKey:@"excerpt"]

Or, alternatively:
NSDictionary *list = [response objectForKey:@"list"];
NSDictionary *inner = [list objectForKey:@"8213812"];
NSString *excerpt = [inner objectForKey:@"excerpt"];

Or, alternatively:
NSString *excerpt = response[@"list"][@"8213812"][@"excerpt"];

etc..


text:
Q: WPF Custom multiple NumericUpDown always firing one event I'm using a custom NumericUpDown controls in my WPF project. Each of them have their own method assigned to its ValueChanged event:
<eisiWare:NumericUpDown x:Name="AGradeUpDown" />
<eisiWare:NumericUpDown x:Name="BGradeUpDown" />
<eisiWare:NumericUpDown x:Name="CGradeUpDown" />

and code-behind:
public _2DEditor(string filename = null)
{
    InitializeComponent();
    AGradeUpDown.ValueChanged += AGradeUpDown_ValueChanged;
    BGradeUpDown.ValueChanged += BGradeUpDown_ValueChanged;
    CGradeUpDown.ValueChanged += CGradeUpDown_ValueChanged;
}
void CGradeUpDown_ValueChanged(object sender, RoutedEventArgs e)
{}
BGradeUpDown_ValueChanged(object sender, RoutedEventArgs e)
{}
void AGradeUpDown_ValueChanged(object sender, RoutedEventArgs e)
{}

But no matter which one of of these controls has its value changed - always triggers only CGradeUpDown_ValueChanged function, with ((eisiWare.NumericUpDown)sender).Name value showing "CGradeUpDown".
Assigning ValueChanged event like this:
<eisiWare:NumericUpDown x:Name="AGradeUpDown" ValueChanged="AGradeUpDown_ValueChanged" />

leads to firing AGradeUpDown_ValueChanged only once on loading but never on actual values changed.
What am I doing wrong or what can be the issue here? Out of ideas. =(


text:
Q: how do we organize our apps in itunes library is there anyway to arrange or organize our apps in the itunes library?
I mean i have well a ton of apps and it really helps if i could put them in folders / lists / or anything?

A: No - there is nothing in iTunes to make it easier. You can also use Xcode and the iPhone configuration utility to get a little more screen real estate, but managing apps is still fairly simplistic. The configuration utility does make it possible to automate installing several apps, so that's a step in the right direction for some.
I've filed bugs and sent feedback to Apple asking for more screen real-estate in iTunes to start making app management easier.

They have a 'Use Full Window for iTunes Store' view so it's not inconceivable they might do the same for iOS management at some point. Feel free to link to my picture in your bug report or feedback if you also want to ask Apple for this change.
http://skitch.com/mbrad/fgj28/itunes-managing-ios-apps

A: Since iOS 4.0, it is possible to organize your app icons into folders: just drag one icon on top of another, it will automatically create a folder for you.
If you have tons of icons to move around, you can be slightly more efficient in iTunes by  using SHIFT to multi-select icons (or folders). Then drag them all at once onto another screen, or into an existing folder (or out of an existing folder).

A: It appears that regardless of settings, playlists and even the Library (if it's enabled) ignore all apps, and dragging apps to manual playlists doesn't seem possible. So the only options you have are those that are built-in, such as viewing the apps as a list (View>as List), selecting which columns are available (View>View Options) and sorting by the available columns.


text:
Q: Need help to understand this C# generic class I am learning Nhibernate 3.0.  In one of the sample code examples, it creates an abstract base entity class:
public abstract class Entity<T> where T : Entity<T>

then, make the Customer entity inherit from the Entity base class:
public class Customer : Entity<Customer>

I understand it's an abstract generic class, and it is using the where keyword to make sure the type T is  Entity<T>, this is where I get confused.
Customer inherits from "Entity<Customer>", this "Entity<Customer>" takes "Customer" as T, but this Customer is not "Entity<T>".
Please help me to understand this,  I'm really confused by this generic class.

A: You said

customer inherits from "Entity", this "Entity" takes "Customer" as T,
  but this customer is not "Entity"

That doesn't make any sense because that's what inheritance means.  It establishes an "is a" relationship.  So in fact a Customer is an Entity
Sorry that was based on the code with the generics stripped out because it wasn't in a code block.
The same principle is still valid though.  It's just a little confusing because it looks like it's a recursive definition, but it's not.
Think of it as Customer inherits from Entity  There just happens to be methods or fields that depend on the generic parameter being itself e.g. Customer.  I'm not familiar with NHibernate so I don't know what the rest of Entity<T> looks like, but I imagine it has some methods that use it's own type as a generic parameter.
Say for instance it has a method called
public IEnumerable<T> GetEntities()

that returned a list of it's own instances.  It needs that method to return the concrete type rather than the base type.  So in the Customer class, that method would be
public IEnumerable<Customer> GetEntities<Customer>()

If it didn't have the generic parameter, it could only return IEnumerable<Entity>
That's just an example of how it could be used, I don't know how it's actually used.

A: It will make more sense when you consider what operations the base 'Entity' class tries to perform.  I'm also not familiar with nhibernate, but I would imagine one of the methods might be something akin to a Save() method.  So any class you create that inherits from the Entity class would inherit a Save() method, keeping you from having to rewrite it for every business object you make.  However, the Base entity class has to know what type of object you are trying to save.  It could use reflection, but here it uses generics to allow you to tell it what kind of class it is that is inheriting Entity.
The thing is that when 20 different classes inherit from a base class, that base class doesn't really have any knowledge of who is using its functionality.  This is a way to let the base class know "Customer" is using its methods so that it can cater specifically to "Customer"'s needs.

A: The where clause specifies a condition that the type to be substituted for T must obey. So, if the type is Customer, as in Entity<Customer> in that second line of code, then the condition is Customer : Entity<Customer> ... i.e., Customer must be a subclass of Entity<Customer>, else there's a compile error. And indeed it is so declared, again in that second line of code.
Applying this to what you wrote:

this "Entity<Customer>" takes "Customer" as T

Here's how I would put it: Entity<Customer> is an instantiation of Entity<T> with Customer substituted for T. T is just a placeholder for some type; it's a type parameter.

but this customer is not "Entity<T>"

We could just as well write the abstract method declaration with SomeType instead of T. The condition is that, in order to instantiate Entity<SomeType>, SomeType must be a subclass of Entity<SomeType>. Substituting Customer for SomeType, that says that Customer must be a subclass of Entity<Customer>, and it is.
If you understand that T is just a parameter, and that Customer is substituted for it in the case of Entity<Customer>, then I don't understand why you say that 'this customer is not "Entity<T>"', since Customer : Entity<Customer> declares it to be just that (with Customer substituted for T in every occurrence in the definition of Entity<T>).

A: Sample showing how one can use such inheritance:
class Creatable<T> where T:Creatable<T>, new()
{
 pulibc static T Create()
 {
   T t = new T(); // we know to call new due new() constraint
   t.FinishCreation(); // we know that T implements this method due Creatable<T> constraint
   return t;
 }
 public void SomeOtherUsefulsOperation(){};
 protected virtual void FinishCreation(){};
}

class Child:Creatable<Child>
{
 public Child(){};
 protected override void FinishCreation(){/*do something special for this type */};}
}

// somewhere else
void DoSomething<T>() where T:Creatable<T>
{
 T item = Creatable<T>.Create();
 item.SomeOtherUsefulOperation();
}


text:
Q: Client event of telerik grid I am using telerik grid as below
<%= Html.Telerik().Grid(Model)
    .Name("Grid")
    .ClientEvents(events => events.OnSubmitChanges("Grid_onSubmitChanges"))
%>

Here OnSubmitChange event has 3 fields
inserted - an array of data items which have been inserted.
updated - an array of data items which have been updated.
deleted - an array of data items which have been deleted.
but what if i want to select already exist rows from grid, which user didnt update or delete
OnSubmitChange event doesn't provide those rows.


text:
Q: Using predictors observed at different times in regression I want to predict vegetable yields for each field using samples of the vegetables.
Some fields have multiple samples taken over the season and some only have one sample. Sample data consists of information such as vegetable length and weight. In the training set (fields that have already been harvested) the last sample date is much closer to harvest than for the test data, and so the sample information is much different--vegetables get longer and bigger as the season progresses.
I'm wondering how to use all the information from the sample data for prediction. I'm working in R, so any modeling techniques would need to be available in R.
I tried just using the last sample but the information from the last sample is not comparable between the training and testing data because the last sample in the training data is much closer to harvest.
I also thought about fitting many models using different time periods for the samples. So I might fit one model with sample information that was taken one week before harvest, another model using sample information two weeks before harvest, and so on. Then I can use the model which corresponds to the latest sample available for the test data. See below.
One approach might be to fit many models using different samples taken at different times.
# train data with sample two months before harvest
m_2m <- lm(yield ~ veg_length_2m_before_harv + veg_weight_2m_before_harv)

# train data with sample one month before harvest
m_1m <- lm(yield ~ veg_length_1m_before_harv + veg_weight_1m_before_harv)

# test data with sample one month before harvest
predict(m_1m, test_1m)

# test data with sample two months before harvest
predict(m_2m, test_2m)

The problem with this approach, as I understand it, is that I'm discarding a lot of information from the other samples.

A: Personally, I would start with the full model, i.e. the maximum model which makes sense, which I guess would be this one? :
m1 <- lm(yield ~ veg_length_2m_before_harv * veg_weight_2m_before_harv +
                 veg_length_1m_before_harv * veg_weight_1m_before_harv)

so you also allow of interactions of those variables within one time frame. Then I would proceed by backward elimination of the non-significant terms. You just do:
summary(m1)
summary(anova(m1))

and you especially look at the summary of the anova to see which terms are significant. Ten you remove one variable. You can then also compare the models together using anova or compare AIC.
If you have much more time frames to look for, I would do one big random forest model using randomForest package and then run varimp() function to quickly see which time frames will be of most importance. Also, there is an R package called climwin which allows to work with different time windows and find the optimal one. It is designed for climatic covariates, but I'd give it a look, if it can be used in non-climatic context (it would make sense).
EDIT: (answer to question in the comment) - how to approach the situation when records have basically data from very different time frames?
In this situation I would do an interaction of the measured variables with a quadratic term of the DAYS_BEFORE_HARVEST (DBH):
m2 <- lm(veg_length*DBH + veg_length*I(DBH^2) + veg_weight*DBH + veg_weight*I(DBH^2))

If one site has more measurements, then you would include them as multiple records; in that case, you could consider adding a random effect for each site to the model.
With this design, every record can be measured in different time frame and the interaction with the quadratic term of DBH will allow for changed response to the measured variables with certain optimal time window.
Instead of interacting with quadratic function of DBH, you could use more precise functions, like smoothing terms etc., but this leads to more complicated statistics. I would start off with the above.


text:
Q: Scratchcard PHP script I'm working on a scratchcard script and I was wondering if someone could help me out, if you don't understand odds this may melt your brain a little!
So, the odds can vary: 1/$x; Let's say for now: $x = 36;
So here's what I am trying to understand...

*

*I want to generate 9 random numbers between 1 and 5.

*I want the odds of 3 numbers matching equivalent to 1/36.

*It must be impossible to generate over 3 duplicate numbers at a time.

I can imagine an array loop of some kind would probably be the correct way of passage?

A: Sometimes - and this is one of those times - cheating is the best way to do what you want to do.
a) Set up an array of your 9 numbers, and a 2nd frequency array (5 elements) that counts which number occurs how often.
b) Generate a random number 1-5. Set the 1st and 2nd card to this number, and mark this number with 2 in your freqency array.
c) If random(36) < 1 (1/36 probability), set your 3rd card to the same number and mark this number with 3 in your frequency array.
d) Generate the rest of the cards - find a random number, repeat while frequency of the found number >=2, set the next card to number, increase frequency of the found number.
e) When finished, shuffle the cards (generate 2 random numbers between 1 and 9, swap the 2 cards, repeat 20-30 times).

Part d) is what i call cheating - you've put your 1/36 probabilty in step c), and in d) you just make sure you don't generate another match. e) is used to hide that from the user.


text:
Q: SVG / JS Interaction - THE SIMPLE VERSION I'm trying to create an SVG-based menu. I'm completely new to SVG, and have been searching for 1.5 days for a simple example of interaction between JS and SVG. My document structure is:
/LOCAL_FOLDER (not on a server yet)
   +index.html
   /CSS
      +global.css
   /JS
      +navigation.js
   /IMAGES
      +navigation.svg

I have a simple html body

            <object id="navigation" type="image/svg+xml" data="images/test.svg" >Your browser does not support SVG</object>

My SVG looks like this (for now)

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle id="test" cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
</svg>

This is the general structure I want to use. As you can see, it has JS from the html head (linked) interacting with my SVG #test. For now, I'd deal with having it change opacity on load just so I can start figuring out HOW to interact.
I've tried JQuerySVG, Raphael, straight JS, JS within SVG, etc, and I can't seem to connect. What I'm looking for (and can't seem to find an operational snippet of) is a super basic example that I can then learn from...

A: From what I've tried, I rarely had success using data="", however using something like container.load(your.svg), I could then modify to my hearts content.
another issue is to make sure that the svg data was standard.
from there (I used jQuery) jQuery('#test').attr('style','stroke:#ff0000') should change the stroke to red.


text:
Q: Representation of Array program in java I want to know the array representaion of this code,
int []x[]={{1,2},{3,4,5},{6,7,8,9}};

The program is:
 class Testsss
 {
    public static void main(String[] args)
    {
       int []x[]={{1,2},{3,4,5},{6,7,8,9}};
       int [][]y=x;
       System.out.println(y[2][1]);
    }
  }

Output is 7, as I executed. How can the values are represented in array form.

A: Maybe you are looking for something like this:
public class Test {
    public static void main(String[] args) {
        int []x[]={{1,2},{3,4,5},{6,7,8,9}};
        for(int i=0; i<x.length; i++) {
            for(int j=0; j<x[i].length; j++) {
                System.out.println("x["+i+"]["+j+"]= " + x[i][j]);
            }
        }
    }
}

the output is:
x[0][0]= 1
x[0][1]= 2
x[1][0]= 3
x[1][1]= 4
x[1][2]= 5
x[2][0]= 6
x[2][1]= 7
x[2][2]= 8
x[2][3]= 9


text:
Q: How to display some of the posts in specific places on page? I want to display a specific post in the middle of the page among other regular posts(check screenshot)
I know I could use front matter with something like featured: true but is there any other way to do this?

A: Simple. Just do this:
{% for post in site.posts %}
  {% if forloop.index == 1 or forloop.index == 4 %}
    output wide post
  {% else %}
    output normal post
  {% endif %}
{% endfor %}

A: Better answer: create similar divs around each post, and target them with CSS like this:
div {width: 50℅;}
div:nth-child(1), div:nth-child(4) {width: 100%;}

Layout should be in CSS, if possible.


text:
Q: How to write this as a differential equation? I was solving differential equations problems from Mary Boas book, and there was a problem that I couldn't write it as a differential equation
Solve the equation for the rate of growth of bacteria if the rate of increase is proportional to the number present but the population is being reduced at a constant
rate by the removal of bacteria for experimental purposes.
How can I add the removal rate to my differential equation (I write the increase rate as $$\dfrac{dN}{dt} = KN(t)$$where $K$ is a constant, and $N(t)$ is the number of bacteria at any time).

A: We should add the term for the removal at a constant rate $K_2>0$ that is

$$\dfrac{dN(t)}{dt} = KN(t)-K_2 $$


text:
Q: xsltproc: how to set attribute from attribute-set via command line? I have in my xsl file something like this:
<xsl:attribute-set name="section.level1.properties">
  <xsl:attribute name="break-before">page</xsl:attribute>
</xsl:attribute-set>

all works fine. But now I want to change this behaviour online.
Before that I used --stringparam for single attribute changes.
So I try
--stringparam /section.level1.properties/break-before page
--param /section.level1.properties/break-before "'page'"

Also I try
--xinclude ./docbook_sect_page_break.xsl

where in ./docbook_sect_page_break.xsl I put my code.
The last attempt cause empty output, the first two cause no effect (no page break).
Update
Also I try
--param xsl:attribute-set[@name='section.level1.properties']/xsl:attribute[@name='break-before'] "'page'"

Without success.
So question, how can I set attribute from attribute-set via command line of xsltproc?


text:
Q: Any idea how to pevent a listview displayed in an Android Widget to fliker every time data is refreshed? I'm displaying a widget with a listview.
When I need to refresh the listview data I'm calling the following code
appWidgetManager.notifyAppWidgetViewDataChanged(widgetIds, R.id.list);

This works fine except that the listview flickers a lot every time this is called. Is there a way to prevent this?
EDIT: After doing a lot of test it looks like the flickering only happens when I display an imageview in the listview rows using the following code
view.setImageViewBitmap(R.id.thumbnail, bitmap);

A: For some reasons using
views.setImageViewUri(R.id.thumbnail, uri);

instead of
view.setImageViewBitmap(R.id.thumbnail, bitmap);

fixes the issue. No more flickering when refreshing the listview content of a widget


text:
Q: Using a variable to select a JSON array element Is it possible to supply a variable to select a particular element within a JSON array element in order to select it?
Assuming I have many users:
"users": [
    { "id":"000000", "uname": "admin", "password": "admin", "phash": "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86",
        "profile": {
            "fullname"  : "Admin Admin",
            "datejoined": "01-01-2014",
            "reputation": "100",
            "displaypic": "http://www.google.com/logo.png",
            "cart": {
                "Cid" : "1000000",
                "item": [
                    { "Iid": "00000001", "quantity": "10" }
                ]
            }
        }
    },

Is it possible to select the above element by supplying just the username using jQuery?
I have tried:
Note: uname in the jQuery is a variable with "admin" assigned
$.getJSON('ssUsers.json', function (data) {

        $(data.users[uname].profile.cart.item).each(function () {
            ++cartItems;
        });

With little luck:
[Error] TypeError: 'undefined' is not an object (evaluating 'data.users[uname].profile')

A: Using grep:
thisUser = $.grep(data.users, function(e) { return e.uname==uname});

A:
Try this:

$.getJSON('ssUsers.json', function (data) {

        for(i=0; i<data.users.length ; i++){
            $(data.users[i].uname.profile.cart.item).each(function () {
                ++cartItems;

            }
        });


text:
Q: PHP trying to display data from MySQL Database I'm trying to display records from my database with this code:
<?php

include("carconnect.php");

$sqlGet ="SELECT * FROM cars";
$sqlData = mysqli_query($connect , $sqlGet) or die ("Error retrieving data!");

while ($row = mysqli_fetch_array($sqlData , MYSQLI_ASSOC)) {
echo $row['car'];
}

?>

Basically all I'm getting on the webpage is the Error retrieving data message..
UPDATED: Speech marks shouldnt have been there sorry.

A: There is " in $sqlData = "mysqli_query before mysqli_query. Please remove it or try the following code.
Try
include("carconnect.php");

$sqlGet ="SELECT * FROM cars";
$sqlData = mysqli_query($connect , $sqlGet) or die ("Error retrieving data!");

while ($row = mysqli_fetch_array($sqlData , MYSQLI_ASSOC)) {
echo $row['car'];
}

A: Use the another simple and very easy way:
<?php
$host='hostname';
$dbuser='dbusername';
$dbpass='pass';
$dbname='databasename';
$conn= new mysqli('$hostname','$dbuser','$dbpass','$dbname');

$sqlGet ="SELECT * FROM cars";
$result=$conn->query('$sqlget');

while($sqlData= $result->fetch_assoc())
{
   echo $row['car'];
}
?>

A: try this:
include("carconnect.php");
$sqlGet ="SELECT * FROM cars";
$sqlData = mysqli_query($connect , $sqlGet) or die ("Error retrieving data!");
$row = mysqli_fetch_array($sqlData , MYSQLI_NUM);
foreach ($row as $value) {
    echo $value;
}


text:
Q: Auto-detection application using Ionic I've got a question about use case of Ionic app.
Now I'm trying to create an application like this:
① Suppose you are a customer to go to a shop
② You have an auto-detect application installed on your mobile phone
③ Right after you enter the shop, the system in the shop detects you or the app in your phone automatically
④ You take some goods there and leave
⑤ The system in the shop detects you left the shop with the goods, and executes credit card payment automatically
I'm wondering if I can use ionic-native bluetooth library (BLE, BluetoothSerial) to implement auto-detection (③) while you have bluetooth on.
Is there any good way to realize such auto-detection using Ionic?


text:
Q: If $\int_0^1 f(x) dx=\frac{3}{2}$, could we say anything about $\int_0^1 x^2 f(x)dx$? Suppose $\int_0^1 f(x) dx=\frac{3}{2}$. Could you find $\int_0^1 x^2 f(x)dx$?
What I attempted:-
I am assuming the additional assumption that $f$ is continuous. However, not all $R$-integrable functions are continuous.
By Mean Value Theorem for Integrals, $\exists c\in (0,1)$ such that $f(c)=\int_0^1 f(x)=\frac{3}{2}$.
Moreover, $x^2$ does not change its sign in $(0,1)$. So, by Weighted Mean Value Theorem, $\exists \xi \in (0,1)$ such that $\int_0^1 x^2 f(x)dx=f(\xi)\int_0^1 x^2 dx=\frac{1}{3} \times f(\xi)$. One of my fellow mates assumed that $c=\xi$ and hence concluded that $\int_0^1 x^2 f(x)dx=\frac{1}{3} \times f(\xi)=\frac{1}{3} \times \frac{3}{2}=\frac{1}{2}$. I do not see anything vivid which clearly tells us that $c$ and $\xi$ may be same.

A: There isn't much you can conclude.
For example, if $f$ is constant, then $\int_0^1 x^2f(x)\,\mathrm{d}x=\frac12$.  On the other hand, if $f(x)=3x$ then $\int_0^1 x^2f(x)\,\mathrm{d}x=\frac34$.
If $f$ is non-negative but not almost everywhere zero, the simple bound $0<x^2f(x)<f(x)$ for all $0<x<1$ with $f(x)>0$ gives $$0<\int_0^1 x^2f(x)\,\mathrm{d}x<\int_0^1 f(x)\,\mathrm{d}x=\frac32$$
and every possible value is achieved by some $f=\frac3{2\lvert I\rvert}\mathbf{1}_I$, $I$ a subinterval of $[0,1]$.
However, if $f$ can change sign, then we don't even have a bound -- for example,
$$
f(x)=\begin{cases}
c+\frac32 & x\in[1-\frac1n,1]\\
\frac32-c & x\in[0,\frac1n]\\
\frac32 & \text{otherwise}
\end{cases}
$$
where $\lvert c\rvert,n$ are large.


text:
Q: Estimating parameters for a binomial First of all I'd like to precise that I'm not an expert of the subject.
Suppose to have two random variables $X$ and $Y$ that are binomial, respectively $X\sim B(n_1,p)$ and $Y\sim B(n_2,p),$ note here that $p$ is the same. I know that $Z=X+Y \sim B(n_1+n_2,p).$
Let $\{x_1,\ldots,x_k\}$  be a sample for $X$ and $\{y_1,\ldots,y_k\}$ be a sample for $Y$, is there a standard method for estimating $n=n_1+n_2$ and $p$?
This is what I have done:

*

*take the "new sample" for $Z$ given by $\{x_1+y_1,\ldots, x_k+y_k\}$,

*using the Likelihood Estimator, obtain an estimation for $n$ and $p$,

*use he Fisher information in order to obtain the error over $n$ and $p$.

The method seems to work, but I have still some doubts. Let $S_k$ the group of permutation over $k$ elements. For every $\sigma\in S_k$ we can consider the "sample" given by $\{x_1+y_{\sigma(1)},\dots, x_k+y_{\sigma(k)}\}.$ Applying the Likelihood Estimator for each one of the "new samples" (there are $k!$ different sums) we obtain different estimation for $n$ and $p$.
What is the meaning of this? It can be used for calculating the error for $n$?


text:
Q: How to compress python for loop How can I compress a for loop in python?
I've read a lot of books in which they compress for loops but I never really understood how to do it. In my case, I am changing the form of a dictionary,
Here's the code:
    for i in attacks.items:
      attacks[i[0]] = i[1] + round(i[1]/level)

Any help would be appreciated. Thank you!

A: First of all, a better way to iterate over the keys of a dict is to do exactly that:
for k in attacks:
    attacks[k] += round(attacks[k]/level)

Now I assume that "compressing" a loop means a "comprehension" for which there exist list, dictionary, set comprehensions etc. In your case you could write it as a dictionary comprehension.
d = {k:v+round(v/level) for k,v in attacks.items()}

Note, however, that this creates a new dictionary object, whereas your code (and my revised code) updates the existing dictionary inplace.


text:
Q: Tokens not in order for tokenization / lexer (kotlin) I am creating a tokenization system in Kotlin / JVM that takes in a file and returns each char or sequence of chars as a token. For some reason, whenever I tokenized a string, it finds the second instance of s "string" token before moving onto the next token, or in other words, the tokens are not in order. I think it might have to do with the loop, but I just can't figure it out. I am still learning Kotlin, so if anyone could give me pointers as well, that'd be great! Much appreciated any help.
output of tokens :
[["chello", string], ["tomo", string], [:, keyV], ["hunna", string], ["moobes", string], ["hunna", string]]

My file looks like this.
STORE "chello" : "tomo" as 1235312

SEND "hunna" in Hollo

GET "moobes"

GET "hunna"

fun tokenCreator (file: BufferedReader)   {
    var lexicon : String = file.readText()

    val numRegex  = Regex("^[1-9]\\d*(\\.\\d+)?\$")
    val dataRegex = Regex("[(){}]")
    val token = mutableListOf<List<Any>>()

    for((index, char) in lexicon.withIndex()) {

        println(char)
      when {
            char.isWhitespace() -> continue

            char.toString() == ":" -> token.add(listOf(char.toString(), "keyV") )

            char.toString().matches(Regex("[()]")) -> token.add(listOf(char, "group") )

            char.toString().matches(dataRegex) -> token.add(listOf(char, "data_group" ) )

            char == '>' -> token.add(listOf(char.toString(), "verbline") )

            char == '"' -> {

                var stringOf = ""
                val firstQuote = lexicon.indexOf(char)
                val secondQuote = lexicon.indexOf(char, firstQuote + 1)

                if(firstQuote == -1 || secondQuote == -1) {
                    break
                    }
                for(i in firstQuote..secondQuote) {
                    stringOf += lexicon[i]
                    }
                lexicon = lexicon.substring(secondQuote + 1, lexicon.length)
                 token.add(listOf(stringOf, "string"))
             }
           }

       }

        println(token)

    }

A: Changing the content while iterating seems like a recipe for confusion...
And you don't seem to increment the index to skip over consumed content. I'd recommend to change the loop in a way that allows you to skip over content you have consumed
I'd also remove this line:
lexicon = lexicon.substring(secondQuote + 1, lexicon.length)

Then replace
  val firstQuote = lexicon.indexOf(char)

with
  val firstQuote = index

You can also use substring instead of iteration for stringOf
  val stringOf = lexicon.substring(

Moreover, using toString to check for ':' seems inefficient


text:
Q: How to enable double tab autocompletion list in csh? I've worked in Linux before where when I press tab it autocompletes until it becomes ambiguous. If I pressed tab twice at that point it would give me a list of all possible completions.
My current Linux environment does not have the second feature(enabled?). So if I press tab it will autocomplete but it won't list all possible completions after that.
How can I add/enable this feature?
EDIT: turns out it's in csh not bash

A: Try this :
in ~/.cshrc put
set filec
set autolist

if you don't want list when autocompletes, use
set autolist = ambiguous
set complete = enhance

A: To set autolist to show choices only when completion fails and adds no new characters to the word being completed:
set autolist ambiguous


text:
Q: Partial fractions with imaginary roots: Evaluating $\mathcal{L}^{-1}\left\{\frac{1}{s^2-18s+810}\right\}$. I would like to find the Inverse Laplace transform of the following fraction:
$$\frac{1}{s^2-18s+810}$$
The problem is that the numerator has imaginary roots $9+27i$ and $9-27i$.
Can someone solve this fraction step by step, because I can't find $A$ and $B$ from imaginary roots?

A: Instead of using partial fractions, I would start by completing the square on the denominator:
$$\frac{1}{s^2-18s+810}=\frac{1}{(s-9)^2+729} \tag{*}$$
You can now easily use result 19 on the Table of Laplace Transforms, however if you wish to derive it, I provided a small proof:

It is well known that:
  $$\mathcal{L}\{\sin(bt)\}=\frac{b}{s^2+b^2} \tag{1}$$

Proof:
By definition, we know that:
$$\mathcal{L}\{\sin(bt)\}=\int_0^{\infty} e^{-st}\sin(bt)~dt$$
Consider using integration by parts twice on the indefinite integral:
$$\begin{align}\int e^{-st}\sin(bt)~dt&=-\frac{1}{s}e^{-st}\sin(bt)+\frac{b}{s}\int e^{-st}\cos(bt)~dt\\&=-\frac{1}{s}e^{-st}\sin(bt)+\frac{b}{s}\left(-\frac{1}{s}e^{-st}\cos(bt)-\frac{b}{s} \int e^{-st}\sin(bt)~dt\right)\\&=-\frac{1}{s}e^{-st}\sin(bt)-\frac{b}{s^2}e^{-st}\cos(bt)-\frac{b^2}{s^2}\int e^{-st}\sin(bt)~dt \end{align}$$
This implies that:
$$\frac{s^2+b^2}{s^2}\cdot \int e^{-st}\sin(bt)~dt=\displaystyle -e^{-st} \left({\frac{1}{s} \sin (bt) + \frac b {s^2} \cos (bt)  }\right)$$
Therefore:
$$\begin{align}\mathcal{L}\{\sin(bt)\}&=-\frac{s^2}{s^2+b^2}\left[e^{-st}\left(\frac{1}{s}\sin(bt)+\frac{b}{s^2}\cos(bt)\right)\right]_0^{\infty}\\&=-\frac{s^2}{s^2+b^2}\left(0-1\cdot \left(\frac{1}{s}\cdot 0+\frac{b}{s^2}\cdot 1\right)\right)\\&=\frac{b}{s^2+b^2} \tag*{$\blacksquare$} \end{align}$$

And, note the first shifting theorem:
  $$\mathcal{L}\{e^{at}f(t)\}=F(s-a) \tag{2}$$

Proof:
By definition:
$$\begin{align}\mathcal{L}\{e^{at}f(t)\}&=\int_0^{\infty} e^{-st}[e^{at}f(t)]~dt\\&=\int_0^{\infty}e^{-(s-a)t}f(t)~dt\\&=F(s-a) \tag*{$\blacksquare$} \end{align}$$

Therefore, it follows from $(1)$ and $(2)$ that:
$$\mathcal{L}\{e^{at}\sin(bt)\}=\frac{b}{(s-a)^2+b^2} \tag{3}$$
We can easily apply $(3)$ to evaluate the Inverse Laplace Transform of $(*)$.

A: Since you've factored the denominator, we can set
$$\frac{1}{s^2-18s+810}=\frac{A}{s-9-27i}+\frac{B}{s-9+27i}$$
for some $A,B \in \Bbb C$. Multiplying both sides by $s^2-18s+810$ yields
$$1 = A(s-9+27i) + B(s-9-27i).$$
Now gather the $s$ components and the constants on the RHS, and equate them with the respective components on the LHS:
$$0s + 1 = (A+B)s + -9A + 27Ai - 9B - 27Bi,$$
from which we gather $0 = A+B$ and $1 = -9A + 27Ai - 9B - 27Bi$. Now solve for $A$ and $B$.


text:
Q: Follow up: how to plot a function under NDSolve domain Here is the details of the code to plot.
Clear[x, y, ψ1, ψ2, ψ3, ψ4, eqn, eqnWithInitial,v, j];
eqn = Thread[
       I D[{ψ1[x, y, t], ψ2[x, y, t], ψ3[x, y, t], ψ4[
            x, y, t]},
          t] == {v (-I D[ψ3[x, y, t], x] - D[ψ3[x, y, t], y]) +
          2 Δ ψ4[x, y, t],
         v (-I D[ψ4[x, y, t], x] - D[ψ4[x, y, t], y]),
         v (-I D[ψ1[x, y, t], x] + D[ψ1[x, y, t], y]),
         v (-I D[ψ2[x, y, t], x] + D[ψ2[x, y, t], y]) +
          2 Δ ψ1[x, y, t]}];
eqnWithInitial =
      Join[eqn,
       Thread[{ψ1[x, y, 0], ψ2[x, y, 0], ψ3[x, y,
           0], ψ4[x, y, 0]} == {1, 1, 1,
           1} (x + I*y) Exp[-(x^2 + y^2)]],
       Thread[{ψ1[-5, y, t], ψ2[-5, y, t], ψ3[-5, y,
           t], ψ4[-5, y, t]} == {ψ1[5, y, t], ψ2[5, y,
           t], ψ3[5, y, t], ψ4[5, y, t]}],
       Thread[{ψ1[x, -5, t], ψ2[x, -5, t], ψ3[x, -5,
           t], ψ4[x, -5, t]} == {ψ1[x, 5, t], ψ2[x, 5,
           t], ψ3[x, 5, t], ψ4[x, 5, t]}]];

v = 1;
Δ = 1;
tMax = 8;

solution =
      First @ NDSolve[
        eqnWithInitial, {ψ1[x, y, t], ψ2[x, y, t], ψ3[x, y,
           t], ψ4[x, y, t]}, {x, -5, 5}, {y, -5, 5}, {t, 0, tMax},
        Method -> {"MethodOfLines",
          "SpatialDiscretization" -> {"TensorProductGrid",
            "DifferenceOrder" -> "Pseudospectral"}}];

Ψ1[x_, y_, t_] = ψ1[x, y, t] /. solution;
Ψ2[x_, y_, t_] = ψ2[x, y, t] /. solution;
Ψ3[x_, y_, t_] = ψ3[x, y, t] /. solution;
Ψ4[x_, y_, t_] = ψ4[x, y, t] /. solution;

myrotorz1[x_?NumericQ, y_?NumericQ, t_?NumericQ] =
  I/2 * (-Conjugate[D[Ψ1[x, y, t], y]] * D[Ψ1[x, y, t], x] +
    D[Ψ1[x, y, t],y] * Conjugate[D[Ψ1[x, y, t], x]] +
    Conjugate[D[Ψ1[x, y, t], x]] * D[Ψ1[x, y, t], y] -
    D[Ψ1[x, y, t], x] * Conjugate[D[Ψ1[x, y, t], y]]);

Here is something that may be reasonable as R. M. suggested
NIntegrate[myrotorz1[x, y, 0], {x, -5, 5}, {y, -5, 5},Method -> "Trapezoidal"]

(Debug) During evaluation of In[18]:= NIntegrate::ncvi: NIntegrate failed to converge to prescribed accuracy after 9 iterated refinements in y in the region {{-5.,5.},{-5.,5.}}. NIntegrate obtained 0.012104690946256463` and 0.8391566465710514` for the integral and error estimates. >>

(Debug) Out[18]= 0.0121047

My point is to plot for myrotorz1[x, y, t] as a function of t but takes too much time. Any tips would be greatly appreciated.
Plot[NIntegrate[myrotorz1[x, y, t], {x, -5, 5}, {y, -5, 5},Method -> "Trapezoidal"], {t, 0, 4}]

A: Nothing much can be said without knowing the form of myrotorz1[x, y, t]
I would first include NumericQ to the function. But for a simple function you can do it easily. Considering a simple function, I will do the following.
f[x_, y_, t_] := x^2 + y^2 + t^2
data[t_] := NIntegrate[f[x, y, t], {x, 0, 1}, {y, 0, 1}]
toplot = ParallelTable[data[t], {t, 0, 10}] // ListPlot


text:
Q: ant 1.9.2 + junit.. Class not found error I am using JDK 1.7, eclipse 4.2.2, JUnit 4.8.1, ant 1.9.2, windows8 64 bit** When I am running my build.xml, all targets run fine but the target with name as run is not running fine.
build.xml
<?xml version="1.0" encoding="UTF-8"?>
  <project name="AntExample" default="setclasspath" basedir=".">
    <!-- Properties Initialization -->
    <property environment="env"/>
    <property name="ws.home" value="${basedir}" />
    <property name="ws.jar" value="${basedir}/lib" />
    <property name="test.dest" value="${basedir}/build" />
    <property name="test.src" value="${basedir}/src" />
    <property name="test.reportsDir" value="E:\Reports" />

    <!-- Path Initialization -->
    <path id="testcase.path">
      <pathelement location="${ws.jar}"/>
      <pathelement path="${classes}"/>
      <fileset dir="${ws.jar}">
        <include name="**/*.jar"/>
      </fileset>
    </path>

    <!-- Target Setclasspath -->
    <target name="setclasspath" unless="testcase.path">
      <path id="classpath_jars">
        <fileset dir="${ws.jar}">
          <include name="**/*.jar"/>
        </fileset>
      </path>
      <pathconvert pathsep=";" property="testcase.path" refid="classpath_jars"/>
    </target>

    <!-- Target init -->
    <target name="init" depends="setclasspath">
      <condition property="ANT"
                 value="${env.ANT_HOME}/bin/ant.bat"
                 else="${env.ANT_HOME}/bin/ant">
        <os family="windows"/>
      </condition>
    </target>

    <!-- Target clean -->
    <target name="clean">
      <delete dir="${test.dest}"/>
    </target>

    <!-- Target compile -->
    <target name="compile" depends="init,clean">
      <delete includeemptydirs="true" quiet="true">
        <fileset dir="${test.dest}">
          <include name="**/*"/>
        </fileset>
      </delete>
      <mkdir dir="${test.dest}"/>
      <javac debug="true"
             destdir="${test.dest}"
             srcdir="${test.src}"
             target="1.7"
             classpath="${testcase.path}"/>
    </target>

    <!-- Target run -->
    <target name="run" >
      <delete includeemptydirs="true" quiet="true">
        <fileset dir="${test.reportsDir}">
          <include name="**/*"/>
        </fileset>
      </delete>
      <mkdir dir="${test.reportsDir}"/>
      <java jar="${ws.jar}"  fork="yes" spawn="yes"/>
      <junit fork="yes" haltonfailure="no" printsummary="yes" >
        <classpath refid="testcase.path" />
        <batchtest todir="${test.reportsDir}" fork="true">
          <fileset dir="${test.dest}">
            <include name="anttestcase/Login.class"/>
          </fileset>
        </batchtest>
        <formatter type="xml"/>
      </junit>

      <junitreport todir="${test.reportsDir}">
        <fileset dir="${test.reportsDir}">
          <include name="TESTS-*.xml"/>
        </fileset>
        <report todir="${test.reportsDir}"/>
      </junitreport>
    </target>
  </project>`

When I am running my build with command prompt, i am getting the below error:
C:\Users\Ashish Rathore\workspace\AntExample>ant run

Buildfile: C:\Users\Ashish Rathore\workspace\AntExample\build.xml
run:
      [junit] WARNING: multiple versions of ant detected in path for junit [junit]
  jar:file:/H:/ant1.9/apache-ant-1.9.2-bin/apache-ant-1.9.2/lib/ant.jar!/org/apache/tools/ant/Project.class
  [junit]and
  jar:file:/C:/Users/Ashish%20Rathore/workspace/AntExample/lib/ant.jar!/org/apache/tools/ant/Project.class
  [junit]Running anttestcase.Login [junit]Tests run: 1, Failures: 0,
  Errors: 1, Skipped: 0, Time elapsed: 0 sec [junit] Test
  anttestcase.Login FAILED [junitreport] Processing
  E:\Reports\TESTS-TestSuites.xml to C:\Users\ASHISH~1\Ap
  pData\Local\Temp\null1158960870 [junitreport] Loading stylesheet
  jar:file:/H:/ant1.9/apache-ant-1.9.2-bin/apache
  -ant-1.9.2/lib/ant-junit.jar!/org/apache/tools/ant/taskdefs/optional/junit/xsl/j
  unit-frames.xsl [junitreport] Transform time: 1223ms [junitreport]
  Deleting: C:\Users\ASHISH~1\AppData\Local\Temp\null1158960870
BUILD SUCCESSFUL Total time: 5 seconds

Error message in TEST-anttestcase.Login.xml in my Reports
error type="java.lang.ClassNotFoundException" message="anttestcase.Login">
 java.lang.ClassNotFoundException: anttestcase.Login at
   java.net.URLClassLoader$1.run(URLClassLoader.java:366) at
   java.net.URLClassLoader$1.run(URLClassLoader.java:355) at
   java.security.AccessController.doPrivileged(Native Method) at
   java.net.URLClassLoader.findClass(URLClassLoader.java:354) at
   java.lang.ClassLoader.loadClass(ClassLoader.java:423) at
   sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at
   java.lang.ClassLoader.loadClass(ClassLoader.java:356) at
   java.lang.Class.forName0(Native Method) at
   java.lang.Class.forName(Class.java:188)

My Login.java test case
package anttestcase;

import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class Login {
  @Rule public ErrorCollector errCollector=new ErrorCollector();

  @BeforeClass public static void setUp() throws Exception {
    System.out.println("opening Url");
  }

  @AfterClass public static void tearDown() throws Exception {
  }

  @Test public void enterCredentials() {
    try {
      Assert.assertEquals("A", "B");
      System.out.println("Enter Username and Password");
    } catch(Throwable t) {
      errCollector.addError(t);
      System.out.println("Caught");
    }
  }

  @Test public void authenticityCheck() {
    System.out.println("Login Successfully");
  }
}

A: You must add the compiled classes to the class path of the junit task.
    <junit fork="yes" haltonfailure="no" printsummary="yes" >
    <classpath>
      <path refid="testcase.path">
      <pathelement location="${test.dest}"/>
    </classpath>
    <batchtest todir="${test.reportsDir}" fork="true">
      <fileset dir="${test.dest}">
        <include name="anttestcase/Login.class"/>
      </fileset>
    </batchtest>
    <formatter type="xml"/>
  </junit>

On Github there's an example ant project, which uses JUnit: https://github.com/mplacona/java-junit-template-project Have a look at it's build.xml.


text:
Q: Why does Firebase timestamp object return undefined? I'm doing a little test thing to get into Firebase. But now when I'm trying to access my timestamp object, it returns undefined.
This is an example for one of the array items (recipe) I'm trying to log out the date for, copied from the console:
{author: "xan", created at: n, title: "awesome test"}
 author: "xan"
 created at: n
 nanoseconds: 0
 seconds: 1563660000
__proto__:
  isEqual: ƒ (t)
  toDate: ƒ ()
  toMillis: ƒ ()
  toString: ƒ ()
  _compareTo: ƒ (t)
  constructor: ƒ n(t,e)
  __proto__: Object

And here is my code:
const list = document.querySelector('ul');

const addRecipe = (recipe) => {
  let time = recipe.created_at.toDate();
  console.log(recipe.created_at);  // returns undefined ??
  let html = `

${recipe.title}

${time}

  `;

  list.innerHTML += html;
}

db.collection('recipes').get().then(snapshot => {
  snapshot.docs.forEach(doc => {
    addRecipe(doc.data());
  });
}).catch(err => {
  console.log(err);
});

Why does recipe.created_at return undefined?

A: It looks like your database field is called "created at" with a space between the words, but you're expecting it to be "created_at" with an underscore between the words.  Make sure that the code that reads the document also matches the code that writes the document.


text:
Q: Neither BindingResult nor plain target object for bean name 'xxx' available as request attribute in springBoot thymeleaf application
I am getting issue at the time of ,when I run my application and try
to redirect through click on a button at that time I am face such type
of  Exception

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'consumer' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) ~[thymeleaf-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:366) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1401) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.56.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.14.jar:5.3.14]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.56.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.14.jar:5.3.14]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.14.jar:5.3.14]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

SignUp.html

<form class="mx-1 mx-md-4" th:action="@{/save}" th:method="post" th:object="${consumer}">

        first Name
        <input class="form-control" id="fname" placeholder="name@example.com" th:type="text" th:field="*{firstName}">

        phone Number
        <input class="form-control" id="phNumber" placeholder="name@example.com" th:type="text" th:field="*{phoneNumber}">

RegisterController class

@PostMapping("/save")
    fun getConsumer(@ModelAttribute("consumer") consumer: Consumer,model:Model,result:BindingResult):String{
        model.addAttribute("consumer",consumer)
        return "SignUp"
    }

consumerEntity class

package com.nilmani.testthymeleaf.entity

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

@Entity
data class Consumer(
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    val id:Long=-1,
    val firstName:String="",
    val phoneNumber:Long=-1,
    val email:String=""
)

nav.html

        MenuBar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

when I click on the menubar button in navBar This type of exception
raises
why I am getting such type of exception ,What is the root cause of
this issue

@GetMapping("/register")
    fun registerPage():String{
        return "SignUp"
    }

Here the getMapping to get the SignUp page

A: Simple problem: We "forgot" to populate our consumer!!
Simple solution:
@GetMapping("/register")
fun registerPage(/*don't even need this: @ModelAttribute("consumer") */
  consumer: Consumer /*done!*/): String {
  return "SignUp"
}

(ref: petclinic-kotlin-PetController)
... or:
@GetMapping("/register")
fun registerPage(): String {
  return "SignUp"
}

@ModelAttribute("consumer")
fun consumer(): Consumer {
  return Consumer() // done!
}

(ref: petclinic-kotlin-VisitController)
Or:
@GetMapping("/register")
fun registerPage(model: Model) : String {
  model.addAttribute("consumer", Consumer())
  return "SignUp"
}

(ref: ...-OwnerController)
... ;)


text:
Q: Sort array in ascending order while eleminating repeated values I'm working on project where I have array simmilar to this
var sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];

I want to sort this array in ascending order while eleminating repeated values so that result should be
var sortBp = [ 'height58em', 'width480px', 'width767px', 'width768px', 'width959px' ];

I'm using following function to sort array in ascending array but how do I eliminate immediate values ?? (In above case 'width767px')
var sortBp = bpArrays.sort(function(a, b) {
                    a = a.replace(/[a-z]/g, '');
                    b = b.replace(/[a-z]/g, '');
                    return a - b;
});

A: Firstly, you can't eliminate elements while sorting. You have to sort the array first, then remove duplicates. Your solution using Array.prototype.filter and Array.prototype.indexOf might be good for unsorted array, but since your array is sorted, it's overhead here(takes O(n) for each). Instead you can just loop through the array and compare element with previous one.
function uniq(array) {
  var i, l = array.length, result = [];
  for (i = 0; i < l; i++) {
    if (result[result.length - 1] != array[i]) {
      result.push(array[i]);
    }
  }
  return result;
}

This is same with Underscore and Prototype's uniq() implemention.
Last note: remember that this will work fine with sorted array only.

A: If this is not homework, i.e. you aren't required to implement the algorithm yourself, you could use a combination of sortBy and uniq functions.
sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];
_.uniq(_.sortBy(sortBp, function(x) {return x;}), true);

This returns:
["height58em", "width480px", "width767px", "width768px", "width959px"]

Note that this will be sort by lexical order, and if you do not wish this to happen, simply substitute the identity function function(x) {return x;} with your own logic.

A: Found It !!
var sortBp = [ 'height58em', 'width480px', 'width768px', 'width959px', 'width767px', 'width767px' ];

uniqueArray = sortBp.filter(function(elem, pos) {
        return sortBp.indexOf(elem) == pos;
});

EDIT :
I have found another solution here : http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
function eliminateDuplicates(arr) {
      var i, len=arr.length, out=[], obj={};
      for (i=0;i<len;i++) {
        obj[arr[i]]=0;
      }
      for (i in obj) {
        out.push(i);
      }
      return out;
}

A: Array.prototype.contains = function(k) {
for ( var p in this)
if (this[p] === k)
  return true;
return false;
};

inputArray.sort();

function uniqueArray(inputArray){
result=[];
for(var i in inputArray){
if(!result.contains(inputArray[i])){
result.push(inputArray[i]);
}
}
return result;
}


text:
Q: What can Coq do while Agda/Idris can't do? Coq is a proof assistant, while Agda/Idris are programming languages (although they can be called proof assistants).
I was exploring these languages and I wonder if Agda/Idris are sufficient to do everything that Coq can do.
So, is there some [proof/way of managing code/IDE (Emacs) functions/something else] that Coq can do while Agda/Idris can't do?

A: Coq has been around for a while and has a strong community with many libraries and developments. It also has got a tactic language and some other extensions which make it very suitable for bigger projects.
As far as the coq core language is concerned it often offers less than for example Agda. For example it is hard to define functions by pattern matching (even though there is an extension which helps) and it doesn't feature inductive-inductive types or mixing induction and coinduction. Most coq developments don't use dependent types (because they are difficult to use in coq) but instead use rather the combination of simply (or polymorphically typed) programs with predicates on top.


text:
Q: Will the product of a real valued matrix and its transpose always have a real eigenvector? I'm trying to solve this really interesting problem, taken from "Berkeley Problmes in Mathematics" by Souza and Silva
https://www.amazon.com/Berkeley-Problems-Mathematics-Problem-Books/dp/0387204296
Trying to make headway, I've noticed that if the last two statements are correct, then $M^T(Mu)=\sigma^2 u$, so in other words, there exists an eigenvector $u$ with the eigenvalue $\sigma^2$.
Therefore, I have two questions, and I would dearly love a proof or counter-example:

*

*Is it true that $M^TM$ must have at least a (real) eigenvector?

*I strongly suspect this $\sigma$ they talk of is the operator norm of $M$. Is this true?

*Is this a dead-end way to try to solve this problem. Should I try something else?

Of course, everything is real-valued here.

A: The matrix $M^\top M$ is called the Gramian of $M$.
One important property of the Gramian is that it is symmetric. Indeed, one easily checks that
$$
(M^\top M)^\top
= M^\top (M^\top)^\top
= M^\top M
$$
This means that the spectral theorem applies to $M^\top M$.
The spectral theorem says that every symmetric matrix $S$ can be factored as $S=QDQ^\top$ where $D$ is real-diagonal and $Q$ is orthogonal. This means that every $n\times n$ symmetric matrix has real eigenvalues and that there is an orthonormal basis of $\Bbb R^n$ consisting of eigenvectors of $S$.
Applying the spectral theorem to $M^\top M$ immediately implies that $M^\top M$ has real eigenvalues and that there is an orthonormal basis of $\Bbb R^n$ consisting of eigenvectors of $M^\top $M.
One can actually say a little more. The Gramian $M^\top M$ is positive semidefinite so its eigenvalues are nonnegative. If $M$ is full column rank, then $M^\top M$ is positive definite, so its eigenvalues are all positive.

A: The spectral theorem: if $A$ is real valued matrix then $A^TA$ is symmetric. Such matrices must have a whole ON system of eigenvectors with strictly non negative real eigenvalues. It follows for example directly from for example Singular Value Decomposition (SVD) which is a more powerful result regarding $A$

A: *

*yes, obvious once you realize $M^TM$ is symmetric.

*yes, can you prove it?

*I think this is a good way to do it. Be somewhat careful in finding condition (2) since $v$ is a unit vector. I have not ideas besides doing this by construction from condition (3). have fun.


text:
Q: Using Android Webview with a Squidman Proxy and locally hosted website I am developing a mobile website which is running on Apache (XAMPP) and is mapping to https://dev.myapp.com using the HOSTS file and vhosts config. The development site also uses self-signed certificates
I can access the app fine via my browser however now I am trying to develop a WebView App using Cordova, the cordova webview works fine when loading content from our production server (https://myapp.com) but just shows a white page when I try to load content from my development server on an android device.
I use squidman on my mac to create a proxy for my phone to connect to the development server and again this works fine on a normal browser. And works ok if i run the webview on ios, I am therefore assuming this is specific to the android webview...
Has anyone come across this issue, am i missing some configuration details?
Thanks.

A: Apparently, not all applications use the proxy, but the browser definitely does.
The best solution I found so far is to install ProxyDroid on a rooted device and force all apps to use the proxy


text:
Q: Matching BlowfishJ Java implementation to dren blowfish javascript implementation; encryption values after 8-bytes are different I'm having some issues with correlating the BlowsfishJ Java implementation (BlowfishJ Javadoc) to the dren Blowfish JavaScript implementation (dren Blowfish page).
On the Java side, I'm using Blowfish CBC, with a zero IV and the key is somekey.  The plaintext is WillThisEQ.
On the JavaScript side, I PRESUME dren's implementation is using CBC and a zero IV, as well.  The key is somekey and the plaintext is WillThisEQ, as well.
Here's the JavaScript code:
var bf = new Blowfish('some key');
var ciphertext = bf.encrypt('WillThisEQ');
var plaintext = bf.decrypt(ciphertext);

For the ciphertext, The first 8-bytes match for both implementations (WillThis).  However, any subsequent bytes do NOT match (EQ000000).  The IV is factored into the first block (Block Cipher Modes Wikipedia page).  So, I don't think that's the problem.
How can I these two implementations to match?
Thank you very much for any help.

A: Your answer is at the very top of the dren BlowFish page you linked to:

You need to impliment your own cipher-block chaining if you want to encrypt anything longer than 8 bytes.

So no, it's not doing CBC. You could try the ECB version of BlowfishJ, but the security is much worse.

A: Here is Dojo version of Blowfish. Works for me.
http://sladex.org/blowfish.js/


text:
Q: Install python2 in 2020 So I'm currently using python3.9, but I want to try python2.x as well. The problem with me currently, is that the python installation page (https://www.python.org) doesn't download any file whenever I click on Python 2.7.18. And on all guides I found online, there is supposed to be a download button for python2.x and python3.x, but there isn't for me: I don't know what I'm supposed to do anymore. Is it still possible to install python 2.x in 2020? If yes, how?

A: If you go to python's windows releases website, and scroll down further, you will be able to clearly see python 2 versions up for download.
Edit: Or you could click on the link at the top for the latest python 2.7.18 download.

A: https://www.python.org/downloads/release/python-2718/
here's the link lmk if it worked

A: https://www.python.org/downloads/release/python-2718/
Windows x86-64 MSI installer
Windows x86 MSI installer


text:
Q: How to use react-data-table-component to display array stored in the constructor this:state? I am new to the React, And I want to using react-data-table-component to display my fetch data from Api in a sorted table. but the issue I do not know the correct method to use the react-data-table-component.and the instruction of react-data-table-component do not include such example.
Following is my code:
I was trying to put offence or this.state.offence direct into data, but show nothing, anyone please give me some advises about the correct way to use this or some other way create sorted table to show this data.and there is link to the react-data-table-component a link:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { off } from 'rsvp';
import DataTable from 'react-data-table-component';

const columns = [
  {
    name: 'Offences',
    selector: 'Offences',
    sortable: true,
  },
  {
    name: 'Year',
    selector: 'year',
    sortable: true,
    right: true,
  },
];

class SignInForm extends Component {
    constructor() {
        super();

        this.state = {
            email: '',
            password: '',
            offence:[],

        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleClick =this.handleClick.bind(this);
        this.handleLogin =this.handleLogin.bind(this);
    }
handleClick(){
      const url ="https://xxxxxxxxxx.sh/offences";
       fetch(url)
       .then(response => {
         console.log(response.clone().json())
         console.log(response.headers.get('Content-Type'))
        if (response.ok) {
          return response.clone().json();
        } else {
          throw new Error('Something went wrong ...');
        }
      })
      .then((res) =>{
        console.log(res)

        this.setState({
          offence: [res]
           });

      }) // get just the list of articles
      console.log(this.state.offence);

    }
render() {
        return (

                  <button className="FormField__offence" onClick{this.handleClick}>offence</button>

              </div>

              <div>
              <DataTable
        title="Offences"
        columns={columns}
        data={this.state.offence}
      />
            </div>
            </form>
          </div>

        );

    }
}

export default SignInForm;

I was expecting one column decent table show

A: Replace this,
this.setState({
  offence: [res]
});

with this,
this.setState({
  offence: res
});

In your case this is res from API call
{offences: Array(88)}
offences: (88) ["Advertising Prostitution", ... "Weapons Act Offences", "Weapons Act Offences - Other"]
__proto__: Object

So you can get offences like this,
this.setState({
      offence: res.offences
});

A:     const columns = [
      {
        name: 'Offences',
        selector: 'Offences',
        sortable: true,
      }
    ];

    class SignInForm extends React.Component {
      constructor() {
        super();

        this.state = {
          email: '',
          password: '',
          offence: [],

        };

        this.handleClick = this.handleClick.bind(this);
      }

      handleClick() {
        const url = "https://xxxxxxxx.sh/offences";
        fetch(url)
          .then(response => {
            if (response.ok) {
              return response.clone().json();
            } else {
              throw new Error('Something went wrong ...');
            }
          })
          .then((res) => {

            this.setState({
              offence: res.offences.map((item,id) => ({id, Offences: item}))
            });

          }) // get just the list of articles
      }

      render() {
          console.log(this.state.offence)

        return (
          <div className="App">
            <button
            className="FormField__offence"
            onClick={this.handleClick}>offence</button>

            <DataTable
              title="Offences"
              columns={columns}
              data={this.state.offence}
            />
          </div>
        );
      }
    }

Live Link


text:
Q: Disable button until bluetooth connected I have an android app that automatically turns on device Bluetooth and connects to a paired device. The device sends data which is updated constantly. If the user presses an enable device button, which is used to initialize the device and begin the operation, before the connection is established, all the previous data is reset.
This is an Android project I was given from an outsourced company so I didn't write the code originally. I have
private void initialize() {
        // initializing and launching the Equipment layer api
        try {
            Utility.writeLogs(this, getString(R.string.info), TAG,
"Initializing EState Manager");
           EStateManager.getInstance().launch(getResources());
           getInfo();
           requestConfiguration();
           findViewById(R.id.btn_enable).setVisibility(View.VISIBLE);
           handleConnectionDialog();
       } catch (Exception e) {
            e.printStackTrace();
            Utility.writeLogs(this, getString(R.string.error), TAG,
"EStateManger initialization failed");
            Utility.writeLogs(this, getString(R.string.error), TAG, e);
       }
    }

private void handleConnectionDialog() {

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(() -> {
            // do stuff
            if (!EStateManager.getInstance().isDataReceived()) {
                if (!new PrefUtil(this).isConnectionDialogEnabled()) {
                    runOnUiThread(() ->
onShowPopup(Utility.POPUP_MAP.get(14)));
                }
            } else {
                if (!buttonPressed) {

findViewById(R.id.btn_enable).setVisibility(View.VISIBLE);
                }
                EStateManager.getInstance().setDataReceived(false);
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

I would like to disable the button until Bluetooth is successfully connected to ensure that saved parameters are not changed.

A: Configure a broadcast receiver to listen for ACTION_STATE_CHANGED
Then check the extra EXTRA_CONNECTION_STATE and enable the button if it is STATE_CONNECTED
Also in the ACTION_STATE_CHANGED receiver, check for STATE_DISCONNECTED, and disabled the button.
Response to comment:
findViewById should be allowed in the receiver if it is defined in the MainActivity.java like so

public class HomeActivity extends Activity {

...

    private final BroadcastReceiver mRadioReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                button = (Button) findViewById(R.id.button1);
                String action = intent.getAction();
                switch (action) {
                    case ACTION__DEVICE_CONNECTED:
                        button.setEnabled(true);
                        break;
                    case ACTION_DEVICE_DISCONNECTED:
                        button.setEnabled(false);
                        break;
                }
            }
        };


text:
Q: SharePoint SOAP service GetListItem with respect to updated date? Right now I am working on a project to fetch data from a SharePoint list using SOAP API. I tried and successfully fetches the complete list, but now I want to fetch some specific data that is updated after a specific date.
Is this possible to fetch such data using SOAP query. I can see last update filed when I view single item at the bottom. Is this some how possible to use that filed?

A: Yes you can use the Web Services to do lot of things just like filtering a list result. I don't know which language you use, but with JavaScript you can look at these two frameworks that should help you:

*

*http://aymkdn.github.io/SharepointPlus/ : easy way to create your queries (I created it)

*http://spservices.codeplex.com/ : the most popular framework but less easy to use (it's my point of view)

You can also look at the documentation on MSDN (the param to use is query): http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems.aspx

A: At last found the answer,
The last update date and time can be retrieved from the list column "Modified".
The soap response will have the value in the attribute "ows_Modified".
Muhammad Usman


text:
Q: Firebase Functions - Writing to Database I'm extremely new to Firebase Functions and node.js, and I need help writing a function that completes the following workflow.
1: Listen to a write event at "/dir1/{PUSH-ID}/dir2/{MESSAGE-ID}".
2: Read data from a directory at "/dir1/{PUSH-ID}/dir2/dir3".
2.5: For each item in "/dir1/{PUSH-ID}/dir2/dir3", get the key.
3: For each key, "clone" the data from the original write to "/dir4/{key}/dir5/{MESSAGE-ID}".
How can I do this? Thanks in advance!

A: // 1: Listen to a write event at "/dir1/{PUSH-ID}/dir2/{MESSAGE-ID}".
exports.propagateMessages =
  functions.database.ref('/dir1/{PUSH_ID}/dir2/{MESSAGE_ID}')
    .onWrite((change, context) => {
      // Do Nothing when the data is deleted...
      if (!change.after.exists()) {
        // Perhaps you intend to delete from cloned dirs?
        // if so, left as reader's exercise, just follow from below
        return null;
      }
      else {
        let pushId = context.params.PUSH_ID;
        let messageID = context.params.MESSAGE_ID;

        let fireDB = change.after.ref.root;

        // 2: Read data from a directory at "/dir1/{PUSH-ID}/dir2/dir3".
        return fireDB.child(`/dir1/${pushId}/dir2/dir3`).once('value')
          .then(listenersSnapshot => {

            let listener_promises = []; // collection of writes

            // 2.5: For each item in "/dir1/{PUSH-ID}/dir2/dir3", get the key.
            listenersSnapshot.forEach(childSnapshot => {
              let child_key = childSnapshot.key;

              // 3: For each key, "clone" the data from the original write to "/dir4/{key}/dir5/{MESSAGE-ID}".
              listener_promises.push(
                fireDB.child(`/dir4/${child_key}/dir5/${messageID}`).set(change.after.val())
              );
            });

            // wait on all writes to complete
            return Promise.all(listener_promises);
          })
          .catch(err => {
            console.log(err);
          });
      }
    })


text:
Q: Google Search Results styled popout I need to make a right column popout with additional information about individual search results. Much like in Google's search results where you click the double arrows to show more information. I don't need a web preview, just to put in my own additional information.

 This is the button to make the popout >>

Info about item

Pop out data is here

Map results

As you can see, there's already a right column. When you click the >> the right column should switch to the information in the popout div. If the >> is clicked again, then it goes back to the default data in the right_col div.
http://jsfiddle.net/thepriebe/XPgdx/
I can work on the styling and effects later. Mostly just need to get this functional.

A: That functionality would look something like this using JQuery....
Let's assume .small and .popout are set to display: none in CSS
$(document).ready(function()
{
    $(".result_details_button").click(function()
    {
        //Parent >> .result_details
        $(this).parent().next(".small").css("display", "block");
        $(this).parent().next(".popout").css("display", "block");
    });
}

A: So I finally figured out how to do what I wanted to do.
Here's a fiddle: http://jsfiddle.net/XPgdx/
Here's the jQuery:
$j(".result_details_button").click(function () {
  var msg = "There are no sites associated with this service.";
  var popout = $j("#search_results_details");
  $j(".result_details_button").not(this).parent().removeClass("active_highlight").parent().removeClass("active_details");
  if($j("#search_results_details").is(":visible") && $j(this).parent().hasClass("active_highlight"))
  {
    popout.html(msg).html($j(this).parent().toggleClass("active_highlight").parent().toggleClass("active_details").find($j(".sites")).html()).hide();
  }
  else
  {
    popout.html(msg).html($j(this).parent().toggleClass("active_highlight").parent().toggleClass("active_details").find($j(".sites")).html()).show();
  };
});

And the HTML:

 Sites >>

This is a search result

Info here

Map data here

This is the popout div where the sites will populate.

And for grins, the css:
.search_result, #paginationControl { padding: 15px 0; border-top: 1px solid #ddd; position: relative;}
.search_result .service { font-size: 18px; font-weight: bold; }
.search_result .service .small { margin-left: 5px; }
.search_result .description { margin: 2px 0; font-size: 12px; color: #222; margin-right: 75px; }
.search_result .description b { color: #000; }
.search_result .small_icon { width: 10px; height: 10px; margin-right: 2px; }

.sites { font-size: 12px; display: none; }
.site_name { font-size: 14px; font-weight: bold; }
.site_block { float:left; border: 2px solid #ccc; border-radius: 4px; margin: 5px 10px 5px 0; padding: 5px; width: auto; background-color: #fff; height: auto; overflow-y: auto; }
.site_name { font-size: 14px; font-weight: bold; }

.result_details {
  background: none repeat scroll 0 0 transparent;
  bottom: 0;
  cursor: default;
  height: auto;
  margin: 0;
  min-height: 40px;
  padding-left: 9px;
  padding-right: 4px;
  position: absolute;
  right: 0px;
  top: -2px;
  width: 65px;
}
.result_details_button {
  height: 13px;
  margin-left: 6px;
  margin-top: -7px;
  opacity: 0.3;
  position: absolute;
  top: 50%;
}
.result_details_button:hover {
  opacity: 0.6;
}

#search_results_details {
  background: #efefef;
  border-left: solid 1px #ddd;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: auto;
  margin-left: 67%;
  padding: 10px;
  padding-top: 20px;
  display: none;
  box-shadow: 0px 0px 10px 5;
}
.active_details { z-index: 999; }
.active_highlight { background-color: #efefef; }


text:
Q: android firebase realtimedatabase Questions(recycler view, onclick button, remove) I want the data of item1 to be deleted when the button on item1 is clicked.
but mDatabase.getReference("Choicestore").child(String.valueOf(arrayList.get(position)));
I don't know what to do with this part.

I want the data of item1 to be deleted when the button on item1 is clicked. and I want the data of item2 to be deleted when the button on item2 is clicked.
@Override
public void onBindViewHolder(@NonNull final ChoicestoreViewHolder holder, final int position) {

    Glide.with(holder.itemView)
            .load(arrayList.get(position).getChoicestore_img())
            .into(holder.choicestore_img);
    holder.choicestore_name.setText("storename : " + arrayList.get(position).getChoicestore_name());
    holder.choicestore_time.setText("opentime : " + arrayList.get(position).getChoicestore_time());
    holder.choicestore_breaktime.setText("breaktime : " +arrayList.get(position).getChoicestore_breaktime());
    holder.choicestore_number.setText("storenumber : " + arrayList.get(position).getChoicestore_number());

    holder.choicestore_delete.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            mDatabase = FirebaseDatabase.getInstance();
            dataRef = mDatabase.getReference("Choicestore").child(String.valueOf(arrayList.get(position)));

            dataRef.removeValue();

        }
    });
}

I coded using the answers below, but I get this error.

Error Image
@Override
public void onBindViewHolder(@NonNull final ChoicestoreViewHolder holder, final int position) {

    Glide.with(holder.itemView)
            .load(arrayList.get(position).getChoicestore_img())
            .into(holder.choicestore_img);
    holder.choicestore_name.setText("매장명 : " + arrayList.get(position).getChoicestore_name());
    holder.choicestore_time.setText("운영시간 : " + arrayList.get(position).getChoicestore_time());
    holder.choicestore_breaktime.setText("브레이크타임 : " +arrayList.get(position).getChoicestore_breaktime());
    holder.choicestore_number.setText("매장번호 : " + arrayList.get(position).getChoicestore_number());

    holder.choicestore_delete.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            final String NAme= arrayList.get(position).getChoicestore_name();

            dataRef.orderByChild("choicestore_name")
                    .equalTo( NAme )
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                                String clubkey = childSnapshot.getKey();

                                Log.d(TAG, "KEY = " + clubkey );

                                childSnapshot.getRef().removeValue();

                            }

                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }

                    });
        }
    });

}

This is the code where the error occurred.

A: Inside holder.choicestore_delete.setOnClickListener
final String NAme= arrayList.get(position).getChoicestore_name();

                            mDatabasesliderRef.orderByChild("choicestore_name")
                                    .equalTo( NAme )
                                    .addListenerForSingleValueEvent(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(DataSnapshot dataSnapshot) {
                                            for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                                                String clubkey = childSnapshot.getKey();

                                                Log.d( TAG, "KEY = " + clubkey );

                                                    childSnapshot.getRef().removeValue();

                                            }

                                        }

                                        @Override
                                        public void onCancelled(@NonNull DatabaseError databaseError) {

                                        }

                                    });


text:
Q: PHP: reading the contents of fopen Hello everyone
First off I would like to thank you for taking your time to read this.
I've got a piece of code (shown below) where I'm grabbing something from an external site and displaying it on a GD Image.
When I grab 0 I would like to be able to display the text 'Offline' instead of '0' and 'Online' instead of '1'
Any suggestions on how to do so?
I've tried quite a few different methods and I have not been able to get it to work.
Any kind of help will be highly appreciated!
Sincerely yours, Malmoc
$username=$_REQUEST["user"];
$grabstat10 = fopen("http://habplus.com/fansitetools/userStats.php?user={$username}&stat=online", "r");
while (!feof($grabstat10)){
  $online1 = fgets($grabstat10);
}

Edit (@zerkms):
if ($_GET[$online1] > 0) {
    $online2 = 'online';
} else {
    $online2 = 'offline';
}

if ($online1 == "1") {
    $online2 = 'online';
} else {
    $online2 = 'offline';
}

Those were the two most recent attempts I could find in my history.
And I'm sorry for not knowing much about coding. I know I suck, and I am going to buy a book or two on PHP, but I still wanted to try and solve this problem.
And it would be lovely if you would assist me since based on what I understood from your post, anyone with basic knowledge on PHP would know the answer to this.
Edit2:
Then later included in a GD Image
imagefttext($image, $fsize, 0, 403, 96, $font_color, './volt.ttf', $online2);

A: -Fixed
Okay apparently-
    if ($online1 == "1") {
    $online2 = 'online';
} else {
    $online2 = 'offline';
}

-did the trick!
I'm not quite sure why that didn't work earlier.. Something must've gone wrong.
I'd like to thank everyone who commented, and showed interest in assisting me.
Sincerely yours, Nils