text:
Q: Error creating bean with name 'org.springframework.integration.internalMessagingAnnotationPostProcessor' I'm new at spring boot and my knowledge is so limited. I had an application that works with spring boot 2.1 and I want to use the last version of spring boot, which is 2.2.6. I did what should be done, changing other dependencies versions, activating bean definition overriding ..etc
But when I run the app I get this exception. any help will be very welcomed.

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name
  'org.springframework.integration.internalMessagingAnnotationPostProcessor':
  BeanPostProcessor before instantiation of bean failed; nested
  exception is org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name
  'org.springframework.cache.annotation.ProxyCachingConfiguration':
  BeanPostProcessor before instantiation of bean failed; nested
  exception is org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve
  reference to bean 'methodSecurityMetadataSource' while setting
  constructor argument; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'methodSecurityMetadataSource' defined in
  class path resource
  [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.security.access.method.MethodSecurityMetadataSource]:
  Factory method 'methodSecurityMetadataSource' threw exception; nested
  exception is java.lang.IllegalStateException: In the composition of
  all global method configuration, no annotation support was actually
  activated     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:512)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:240)
  ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:722)
  ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:535)
  ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
  ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
  ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]    at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
  ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
  ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
  ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
  ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]    at
  com.smartest.connectedwell.service.addtostore.AddToStoreApplication.main(AddToStoreApplication.java:17)
  ~[classes/:na] Caused by:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name
  'org.springframework.cache.annotation.ProxyCachingConfiguration':
  BeanPostProcessor before instantiation of bean failed; nested
  exception is org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve
  reference to bean 'methodSecurityMetadataSource' while setting
  constructor argument; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'methodSecurityMetadataSource' defined in
  class path resource
  [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.security.access.method.MethodSecurityMetadataSource]:
  Factory method 'methodSecurityMetadataSource' threw exception; nested
  exception is java.lang.IllegalStateException: In the composition of
  all global method configuration, no annotation support was actually
  activated     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:512)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:409)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:91)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:109)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:92)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:101)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:251)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1141)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1114)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:506)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   ... 14 common frames
  omitted Caused by:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'metaDataSourceAdvisor': Cannot resolve
  reference to bean 'methodSecurityMetadataSource' while setting
  constructor argument; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'methodSecurityMetadataSource' defined in
  class path resource
  [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.security.access.method.MethodSecurityMetadataSource]:
  Factory method 'methodSecurityMetadataSource' threw exception; nested
  exception is java.lang.IllegalStateException: In the composition of
  all global method configuration, no annotation support was actually
  activated     at
  org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:342)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:691)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:91)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:109)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:92)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:101)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:251)
  ~[spring-aop-5.2.5.RELEASE.jar:5.2.5.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1141)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1114)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:506)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   ... 35 common frames
  omitted Caused by:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'methodSecurityMetadataSource' defined in
  class path resource
  [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.security.access.method.MethodSecurityMetadataSource]:
  Factory method 'methodSecurityMetadataSource' threw exception; nested
  exception is java.lang.IllegalStateException: In the composition of
  all global method configuration, no annotation support was actually
  activated     at
  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   ... 54 common frames
  omitted Caused by:
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.security.access.method.MethodSecurityMetadataSource]:
  Factory method 'methodSecurityMetadataSource' threw exception; nested
  exception is java.lang.IllegalStateException: In the composition of
  all global method configuration, no annotation support was actually
  activated     at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   at
  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   ... 64 common frames
  omitted Caused by: java.lang.IllegalStateException: In the composition
  of all global method configuration, no annotation support was actually
  activated     at
  org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityMetadataSource(GlobalMethodSecurityConfiguration.java:371)
  ~[spring-security-config-5.2.2.RELEASE.jar:5.2.2.RELEASE]     at
  java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
  Method) ~[na:na]  at
  java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  ~[na:na]  at
  java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  ~[na:na]  at
  java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
  ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]   ... 65 common frames
  omitted

A: In previous versions it was okay to have a null MethodSecurityMetadataSource, but now they added this check where if you don't have at least one method security metadata source enabled, they throw the exception that you are getting ("In the composition of all global method configuration, no annotation support was actually activated"). This happened to me when I updated from spring 5.0.7 to 5.1.5. Here is the issue where this change was discussed
To fix it, either enable one of the metadata sources in the @EnableGlobalMethodSecurity annotation properties, or, if like me, you are using some kind of GlobalMethodSecurityConfiguration, make sure the method customMethodSecurityMetadataSource returns not-null

A: You are right irt works with me after tried:
@EnableGlobalMethodSecurity(prePostEnabled=true)


text:
Q: Memory leak due to class structure I have developed a python tool that interacts with various power simulation softwares to perform analytical studies. After much testing, it seems that the structure of the tool is causing a memory leak when running through a study. It seems odd that where the class sits would affect how memory is being managed. Is this possible?
There is a particular function that is embedded in a class that is accessed through a series of overarching classes. The memory leak only occurs for one particular software. If I bring this class closer to the top, i.e. not embedded so many classes deep, the memory leak goes away. Or if I skip interacting with the power simulation software with this specific function it goes away, so I know it is particular to this software, this function and the structure of the tool. The memory usage grows with each call of this function.
I am not familiar with tracing memory leaks, but have tried running gc.collect() at the highest level script controlling the number of studies being performed as well as right after the function is call and in both cases it returns 0. Pympler indicates that there are no classes specific to the Python tool growing in memory. Is there a way I can better target the memory usage of this function?
Cheers!
I should also note that the function that is causing the memory leak is not my own code. It is part of the class developed by the power simulation software provider for access.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Property access result unused I just started learning Objective-C yesterday, and i can't quite figure out this warning:
Property access result unused - getters should not be used for side effects

Using this code (line 3 gives the warning, self.addItem()):
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.itemTxt) {
        self.addItem;
        self.itemTxt.text = @"";
    }
    return YES;
}

- (IBAction)addItem {
    [self.model addItemToArray: _itemTxt.text];
    _itemTxt.text = @"";
}

Why am I getting this warning?

A: What is addItem. According to your code, it seems you're trying to call that function so use this:
[self addItem];

One more thing basically, if you see in depth about IBAction, you'll find it's void. Normally, we use IBAction when we want to use IB for event fire.
So, you can use(if you need to call manually)
- (void)addItem {
    [self.model addItemToArray: _itemTxt.text];
    _itemTxt.text = @"";
}

Hope, it'll enhance your knowledge and will assist in your warning.

A: To call the function use
[self addItem];

When you're using self.addItem you're accessing a variable named addItem.


text:
Q: Track buffer changes and trigger a hook after event in Emacs I'm trying to add some facilities to my matlab environment within Emacs.
Basically, I want to have an extra buffer (*Matlab Whos*) to display all my variables. The buffer should update automatically after matlab-shell finishes evaluating an expression. In other words, after I press return on the shell, a hook should call a function to update *Matlab Whos*.
The simple solution I came up with is:
(defvar matlab-whos-buffer-name "*Matlab Whos*")

(defun matlab-whos-buffer-update ()
 "Create Matlab Whos buffer if it doesn't exist.
 If it exists, update its values."
  (lambda)
  (interactive)
  (let ((doc-whos (matlab-shell-collect-command-output "whos")))
    (with-current-buffer (get-buffer-create matlab-whos-buffer-name)
      (erase-buffer)
      (insert doc-whos))))

(add-hook 'matlab-shell-mode-hook
          (lambda ()
            (define-key matlab-shell-mode-map (kbd "<return>")
              (lambda ()
                (interactive)
                (comint-send-input)
                (matlab-whos-buffer-update)))))

The function matlab-whos-buffer-update works fine. However, the problem with this solution is that my hook calls the function before the matlab shell finishes its evaluation (requested by (comint-send-input)). As a consequence, matlab-whos-buffer-update returns an error saying:

Matlab-shell-collect-command-output: MATLAB shell must be non-busy to
  do that.

How can I track changes to my Matlab shell buffer, so that my hook knows that it can only trigger matlab-whos-buffer-update, after the result of the evaluation has returned?

A: You can start with something like
(add-hook 'matlab-shell-mode-hook
          (lambda ()
            (add-hook 'comint-output-filter-functions
                      #'matlab-whos-buffer-update
                      nil 'local)))

But note that this will call your function everytime something is sent from the process.  I can foresee two problems with it:

*

*it may fail miserably if matlab-shell-collect-command-output ends up using that same setup (and hence also calling matlab-whos-buffer-update.

*it might be run too many times (if your process sends its output in 5 chunks, it will be run 5 times).

Try it and come back with another question if that doesn't work well enough.


text:
Q: vp8 rtp packetization data overwritten by srtp_protect I am using libsrtp for srtp encryption in a webrtc call.
After I prepare RTP packet, I call srtp_protect to encrypt it. It encrypts the data part and keeps RTP header as it is. This was working fine till now with audio only calls.
Now I am supporting VP8. As per RFC 7741 (RTP VP8 packetization), the RTP packet is like  RTP header + VP8 packetization data + Payload.
So when I feed this entire buffer to srtp_protect,it is encrypting the VP8 packetization portion and Payload. My understanding is that RTP header, VP8 packetization portion should not be encrypted. Only payload should be encrypted.
Is my understanding correct?
How can I use srtp_protect incase of RTP VP8 packetization?
Any hint highly appreciated.

A: Recently I was worked on VoIP. I found in my code RTP packet prepared properly and it contains RTP header VP8 packetization data and VP8 actual payload. After that this whole packet given to SRTP library for encryption and this encrypted packet sent to other end.
At my end I also receive encrypted packet. I first decrypt packet using SRTP library after that I can extract rest of data like RTP header, vp8 packetization data and actual encoded vp8 payload.
Hope you get clarification on your doubt.


text:
Q: SQL Update Query doesnt' Update when using Dropdown list I have 2 tables: product (id, name, quantity, c_id) and product_category (cat_id, cat_name).
I have the option to update the existing products. When I change the name and the quantity it works just fine, but when I try to change the product category the c_id doesn't change to the new one.
The code from the update page (update.php):
<?php
    include 'database.php';
    $id = $_POST['productId'];
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * FROM product where id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $name = $data['name'];
    $quantity = $data['quantity'];

    Database::disconnect();
  ?>
    <form id="updateFrom" action="update2.php" method="POST">

            Name
            <input name="name" type="text" value="<?php echo $name;?>"/>

            Quantity
            <input name="quantity" type="text" value="<?php echo $quantity;?>"/>

        <?php  $cat = $pdo->query("SELECT c_name, CATEGORY_ID  FROM product_category");

        ?>
//Here the user selects the new category from the dropdown list
            Category

                <select name="c_id">
                 <?php
                    while ($rows = $cat->fetch(PDO::FETCH_ASSOC))
                    {
                        $cat_name = $rows['c_name'];
                        $cat_id = $rows['CATEGORY_ID'];
                        echo"<option value='$cat_id'>$cat_name</option>";
                    }

                 ?>
                </select>

    <input type="hidden" id="productId" name="productId" value="<?php echo $id;?>"/>
    <button type="submit">update</button>
    </form>

The code which makes the update (update2.php):
<?php
require 'database.php';

$id = null;

if ( !empty($_POST)) {
    $id = $_POST['productId'];
    $name = $_POST['name'];
    $quantity = $_POST['quantity'];

    // update data
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "UPDATE product set name = ?, quantity = ? WHERE id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($name,$quantity,$id));
    Database::disconnect();
    header("Location: index.php");
}
?>

A: You need to set the c_id column from $_POST['c_id'].
if ( !empty($_POST)) {
    $id = $_POST['productId'];
    $name = $_POST['name'];
    $quantity = $_POST['quantity'];
    $category = $_POST['c_id'];

    // update data
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "UPDATE product set name = ?, quantity = ?, c_id = ? WHERE id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($name,$quantity,$category,$id));
    Database::disconnect();
    header("Location: index.php");
}

I also suggest that you have the existing category selected by default in the dropdown.
                    while ($rows = $cat->fetch(PDO::FETCH_ASSOC))
                    {
                        $cat_name = $rows['c_name'];
                        $cat_id = $rows['CATEGORY_ID'];
                        $selected = $cat_id == $data['c_id'] ? "selected" : "";
                        echo "<option value='$cat_id' $selected>$cat_name</option>";
                    }


text:
Q: Specify color for each listview row I fill my ListView with this code:
    final ListView lv = (ListView) findViewById(R.id.lvKinder);
    ArrayList<Kind> kisi = datenfuerlistview();
    KinderlistAdapter kiadapter = new KinderlistAdapter(this, kisi);
    lv.setAdapter(kiadapter);
    final DBHelper db = new DBHelper(this);

Now I want to analyse one entry of every Kind object I add to my ListView. If it has a certain value, I want to change the backgroundcolor for this ListView entry.
Here´s my adapter:
@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if(convertView == null){
            convertView = inflator.inflate(R.layout.list_black_text, parent, false);
            holder = new ViewHolder((TextView) convertView.findViewById(R.id.nullline), (TextView) convertView.findViewById(R.id.firstLine), (ImageView) convertView.findViewById(R.id.imgv));

            convertView.setTag(holder);
        }
        else{
            holder = (ViewHolder) convertView.getTag();
        }

        Kind ki = (Kind) getItem(position);
        holder.getName().setText(ki.getName());
        holder.getDatum().setText(ki.getDatum());

        Uri uri = Uri.parse(ki.getGeschlecht());

        String path = ki.getKinderbild();

        System.out.println("HSSSSSSSSSSSSSSSSSSSSSS" + path);
        //holder.getGeschlecht().setImageBitmap(bitmap);

        ContentResolver cr = context.getContentResolver();
        Bitmap tmp = null;
        try {
            tmp = getThumbnail(cr, path);
        } catch (Exception e) {
            System.out.println("NAAAAAAAAAAAAAAAAAAAA") ;
            e.printStackTrace();
        }

        holder.getGeschlecht().setImageBitmap(tmp);

        return convertView;

How to set the color?

A: Did you tried this ? (before returning convertView) :
convertView.setBackgroundColor(Color.BLUE);//or another color


text:
Q: Performance Improvements with Processes or Threads I've written a script that pulls data from my school's website and I'm having some trouble with execution time.
There are over 20 campuses, each with data for three semesters. The script looks up those school names, then the semesters available for each school, then the subjects/departments that are offering classes each semester. Then the script  searches for the classes per department and then I do things with that data.
I timed the execution of the script on just one campus, and it ran for over three minutes. When I ran it for all 24 campuses it took over an hour. I'm using the "requests" library, which runs each HTTP request in synchronously. I'm using the "requests" library, primarily because it handles sessions nicely.
I'm looking for ways to bring down the time the script takes to run, by making the various requests for each semester run in parallel. I suspect that if I run three semesters asynchronously, then each school should take a minute, instead of three. Then, I can run all schools in parallel and achieve the same minute for all of the data. A minute is a lot less than an hour and a quarter!

*

*Am I wrong in my guess that multithreading/processing will bring down the execution time so drastically? What Python libraries should I be using for threads or processes?

*Once I've got each school being processed on a  thread, how do I consolidate the data from all the schools into one place? I know that it's considered poor practice for threads to alter global state, but what's the alternative here?

A: 1) You are not wrong. Use threading library for threads. For processes you can use multiprocessing or os.fork or subprocess depending on how exactly you want to use them.
2) Who says that altering global state is a poor practice? That always depends on the context. Obviously you have to share a data structure between threads somehow. You don't have to use global variables for that though. For example:
from threading import Thread

def my_task(id, holder, some_other_args):
    # do something
    holder[id] = my_result

def main():
    total_data = {}
    threads = []
    for i in range(100):
        t = Thread(target=my_task, args=(i, total_data, ...))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

    print total_data  # <-- you have all results here

if __name__ == "__main__":
    main()

A: In python you want multiprocessing over multithreading. Threads don't do well in Python beacause of the GIL.

A: Why would you use a global var ? Same code as freakish but without a global var passed to the threads:
#!/usr/bin/python3

import threading

class MyThread(threading.Thread):
    def __init__(self, target, name=None, args=(), kwargs={}):
        super().__init__(target=target, name=name, args=args, kwargs=kwargs)
        self.output = None
    def run(self):
        self.output = self._target(*self._args, **self._kwargs)

def my_task(i):
    # do something
    return 'response ' + str(i)

def main():
    total_data = list()
    threads = []
    for i in range(5):
        t = MyThread(target=my_task, args=[i,])
        t.start()
        threads.append(t)

    for t in threads:
        t.join()
        total_data.append(t.output)

    print(total_data)

if __name__ == "__main__":
    main()

Output is :
Jean@MyDesktop:~$ ./test_threads.py
['response 0', 'response 1', 'response 2', 'response 3', 'response 4']

@yorodm: in this case I think multithreading should be enough, unless heavy processing is done localy on the data.


text:
Q: Transform the data from one form to another using ES6 I have the data as follows:
[
  {
    name: "ABC",
    points: [
      {
        timestamp: "2017/09/26",
        value: 1
      },
      {
        timestamp: "2017/09/27",
        value: 2
      },
    ]
  },
  {
    name: "DEF",
    points: [
      {
        timestamp: "2017/09/26",
        value: 0
      },
      {
        timestamp: "2017/09/27",
        value: 3
      },
    ]
  }
]

I would like to transform the above data into:
[
  {
    timestamp: "2017/09/26",
    "ABC": 1,
    "DEF": 0
  },
  {
    timestamp: "2017/09/27",
    "ABC": 2,
    "DEF": 3
  }
]

I've just started learning ES6 and underscore. Trying to apply underscore to transform, but not able to succeed.

A: You can do it in the following way

let arr = [
  {
    name: "ABC",
    points: [
      {
        timestamp: "2017/09/26",
        value: 1
      },
      {
        timestamp: "2017/09/27",
        value: 2
      },
    ]
  },
  {
    name: "DEF",
    points: [
      {
        timestamp: "2017/09/26",
        value: 0
      },
      {
        timestamp: "2017/09/27",
        value: 3
      },
    ]
  }
]

let result = arr.reduce((a, b) => {
    for(let element of b.points){
        a[element.timestamp] = a[element.timestamp] || {};
        let newObj = {};
        newObj[b.name] = element.value;
        Object.assign(a[element.timestamp], newObj);
    }
    return a;
}, {});

result = Object.keys(result).map(key => Object.assign(result[key], {timestamp : key}));
console.log(result);

A: Since you have not shared effort, I'll focus this answer on algorithm and leave the implementation part to you.
Algorithm:

*

*Create a hashmap that will store the groups.

*A group will have a signature { name: valueAsPerDate}

*Now loop over data. For every object,

*

*Search for current date in hashmap. If exists, add group with necessary vallue.

*If not, add it to the hashmap and then add group values to it.

*Once above loop is over, again loop over the hashmap and return objects in your format, where timestamp will be your group name and you already have values in that object.

Ta-da!!!


text:
Q: Failed to dispatch transfer event 'PUT PROGRESSED https://<>.d.codeartifact.<>.amazonaws.com/session-0.0.1.pom <> session\pom.xml' I am using maven 3.8.4 and trying to upload maven jar to aws codeartifact. Getting below error
[DEBUG] Failed to dispatch transfer event 'PUT PROGRESSED https://wolken-artifact-256162449727.d.codeartifact.us-west-2.amazonaws.com/maven/maven-repo/com/wolken/session/0.0.1/session-0.0.1.pom <> E:\Wolken\ESD\WolkenCare\Code\outbound-schedular\Checking\session\pom.xml' to org.apache.maven.cli.transfer.ConsoleMavenTransferListener
java.lang.IllegalArgumentException: progressed file size cannot be greater than size: 4970 > 2485
at org.apache.commons.lang3.Validate.isTrue (Validate.java:158)
at org.apache.maven.cli.transfer.AbstractMavenTransferListener$FileSizeFormat.formatProgress (AbstractMavenTransferListener.java:195)
at org.apache.maven.cli.transfer.ConsoleMavenTransferListener.getStatus (ConsoleMavenTransferListener.java:117)
at org.apache.maven.cli.transfer.ConsoleMavenTransferListener.transferProgressed (ConsoleMavenTransferListener.java:90)
at org.eclipse.aether.internal.impl.SafeTransferListener.transferProgressed (SafeTransferListener.java:106)
at org.eclipse.aether.connector.basic.TransferTransportListener.transportProgressed (TransferTransportListener.java:96)
at org.eclipse.aether.transport.wagon.WagonTransferListener.transferProgress (WagonTransferListener.java:64)
at org.apache.maven.wagon.events.TransferEventSupport.fireTransferProgress (TransferEventSupport.java:121)
at org.apache.maven.wagon.AbstractWagon.fireTransferProgress (AbstractWagon.java:664)
at org.apache.maven.wagon.providers.http.wagon.shared.AbstractHttpClientWagon.access$200 (AbstractHttpClientWagon.java:119)
at org.apache.maven.wagon.providers.http.wagon.shared.AbstractHttpClientWagon$WagonHttpEntity.writeTo (AbstractHttpClientWagon.java:236)
at org.apache.maven.wagon.providers.http.httpclient.impl.DefaultBHttpClientConnection.sendRequestEntity (DefaultBHttpClientConnection.java:156)
at org.apache.maven.wagon.providers.http.httpclient.impl.conn.CPoolProxy.sendRequestEntity (CPoolProxy.java:152)
at org.apache.maven.wagon.providers.http.httpclient.protocol.HttpRequestExecutor.doSendRequest (HttpRequestExecutor.java:238)
at org.apache.maven.wagon.providers.http.httpclient.protocol.HttpRequestExecutor.execute (HttpRequestExecutor.java:123)
at org.apache.maven.wagon.providers.http.httpclient.impl.execchain.MainClientExec.execute (MainClientExec.java:272)
at org.apache.maven.wagon.providers.http.httpclient.impl.execchain.ProtocolExec.execute (ProtocolExec.java:186)
at org.apache.maven.wagon.providers.http.httpclient.impl.execchain.RetryExec.execute (RetryExec.java:89)
at org.apache.maven.wagon.providers.http.httpclient.impl.execchain.RedirectExec.execute (RedirectExec.java:110)
at org.apache.maven.wagon.providers.http.httpclient.impl.client.InternalHttpClient.doExecute (InternalHttpClient.java:185)
at org.apache.maven.wagon.providers.http.httpclient.impl.client.CloseableHttpClient.execute (CloseableHttpClient.java:83)
Referred this as well https://issues.apache.org/jira/browse/WAGON-591


text:
Q: How to add vertical spacing between definitions I'm trying to add vertical space between definitions, theorems, etc. For example, if set up something like:
\begin{definition}

blah blah blah

\end{definition}

%%%should be space here but there's not

\begin{theorem}

blah blah blah

\end{theorem}

There is almost no vertical room after my definition and before my new theorem. How do I fix this?

A: Have you defined the Theorem and Definition correctly?  When I use the following code, there is space between the lines:
\documentclass{article}
\usepackage{amsmath}
\newtheorem{theorem}{Theory of Blahblah}
\newtheorem{definition}{Definition of Blah}
\begin{document}
    \begin{definition}
        blah blah blah
    \end{definition}
%%%should be space here but there's not
    \begin{theorem}
        blah blah blah
    \end{theorem}
\end{document}

If this is insufficient space for you, there are several ways you can 'brute force' vertical space between lines.  Adding a \smallskip between the lines in the text may be what you are looking for.
If you consistently need more space after every Theorem or Definition, you can try redefining the environment.  However, I will omit that at this time.  Fooling around with a strict environment such as amsmath can displease some of your audience.


text:
Q: Rails - how to render an action as JS without using ":remote => true"? In the view, I have a link that I call as AJAX:
= link_to "Show post", post, :remote => true

and action in the controller:
  def show
    respond_to do |format|
      format.js
    end
  end

When I click this link, the request is called as AJAX and a popup window with the respective content is displayed. Also, the wanted address is added to the URL (for example web.com/posts/6).
So far so good.
But now when I try to put to the URL web.com/posts/6, I get only an error message saying:
Processing by PostsController#show as HTML
  Parameters: {"id"=>"6"}
  Post Load (0.6ms)  SELECT  `posts`.* FROM `posts`  WHERE `posts`.`id` = 6 LIMIT 1
Completed 406 Not Acceptable in 535ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/posts_controller.rb:14:in `show'

I am trying to achieve that when I put the URL web.com/posts/6 to the browser, then the page will be rendered the same way as if I click on a link with the :remote => true option.
How to do that? How to force an action in controller to be rendered as JS?
Thank you.

A: Use this link (basically just add the format .js to the end):
web.com/posts/6.js

This also works with any other kind of format you want (say json or xml). Just make sure you account for those formats in your controller action.

A: Replace
= link_to "Show post", post, :remote => true

By
= link_to "Show post", post, :remote => true, :format => 'js'

Warning
@user984621 is right : this is very strange to get a link with js.


text:
Q: How to convert dateTime to Microsoft Timestamp in Flutter?
I am facing problem when trying to convert DateTime format in flutter to integer similar to format in Microsoft Excel, due to the backend-service parameter need integer similar to '44xxx' according to the DateTime(). Is there any ways to convert this ?

A: Try this:
final startOfTime = DateTime(1899, 12, 30);
double microsoftTimeStamp(DateTime date) {
  final diff = date.difference(startOfTime);
  return diff.inDays + ((diff - Duration(days: diff.inDays)).inSeconds / 86400);
}

Edit: the microsoft timestamp actually considers 1900-02-29 as a real date so using 1899-12-30 gives the correct result as long as you don't need dates before 1900-03-01


text:
Q: How to avoid running the application when a ClickOnce installation completes? I want setup.exe to do only the setup (seems like a natural thing to ask for), so that the user can later choose to run the application themselves. I tried "Block application from being activated via a URL" in publish options in Visual Studio, but that did not seem to work. There is also a specific option in MageUI to avoid running the application, but that also did not seem to work.

A: If you want to use the setup.exe file that Visual Studio generates for you, I don't think there's any way to stop it from launching your app. Most people want it to launch. I suppose in your application code you could try to detect when it was run for the first time and simply kill it, but that seems pretty flaky to me.
You don't have to even use the setup.exe that VS generates. How many prerequisites do you have? It's very handy when you have a lot of prereqs, but if you just need the .NET Framework, you could skip the generated bootstrapper and just give them a link to the download.
Couple more notes. The "Block application from being activated via a URL" won't work for you. This just means that the user has to use the start menu shortcut to run the app rather than typing the url in a browser. Also, I'm not completely sure, but I think the MageUI option only works if you install your app for the first time from a browser and not the bootstrapper. Could be wrong on that one though.
Edit
I randomly stumbled across this answer, Install ClickOnce Without Running. The accepted answer shows a quick and easy implementation of my first suggestion - quitting the app if it's the first time it has been run.

A: In Visual Studio project properties on Signing tab click on Options... and in Manifests tab check the "Block application from being activated via a URL".
publish and check. It should work.
link to resource: http://msdn.microsoft.com/en-us/library/ms404268.aspx


text:
Q: Passing a list as several arguments I'm trying to use a list as arguments, using the  :
>>> l = [1,2,3]
>>> print( *l )

I got an error :
File "<stdin>", line 1
t*
 ^
SyntaxError: invalid syntax

I'm using python 2.7 :
>>> import sys
>>> print sys.version
2.7.3 (default, Jan  2 2013, 13:56:14)
[GCC 4.7.2]

What am I missing ?
Thank you ! :)

A: By default, print isn't a function in Python 2.7. To use the function instead of the statement in a given module, use a future statement:
from __future__ import print_function

This needs to go at the top of your file, before any code that isn't a future statement (or the module docstring), because the compiler needs to see future statements first to compile the rest of the module differently based on the future statement.

A: print is NOT a function in Python 2.7. It is a statement. So, you should do
print l           # [1, 2, 3]

If you want to use print as a function in Python 2.7, you should import print_function from __future__, like this
from __future__ import print_function
l = [1,2,3]
print(l)          # [1, 2, 3]
print(*l)         # 1 2 3

A: If you want to use print as a function then you have to use __future__ or upgrade python to 3+

A: Is this what you are searching for?
>>> l = [1, 2, 3]
>>> def x(*args):
...     print args[0]
...     print args
>>> x(*l)
1
(1, 2, 3)

If yes, take also a look at Arbitrary Argument Lists in the Python documenation.


text:
Q: Generating 2D array in Bash with unknown dimension just wondering if it's possible to generate a 2D array if the dimension is not known prior to user input. For example if user input 2 2 on the commandline the shell will generate a 2D array base on that? thank you

A: bash is an interpreted language, and it doesn't need to know how much memory to allocate in advance.
So it's possible to dinamically initialize a new array without having declared it or to expand an already declared array to add more entries, however it's not possible to use multidimensional arrays.
However this can be faked: since you didn't provide an exact task to accomplish, I'll provide a bash script example which shows how to fill in an user-defined m x n table with random numbers (which are not really random, since each column will always have the same number on all its rows in each run, but this is not relevant to the question) and print it (simplified from this Stack Overflow answer):
#!/bin/bash

declare -a array
read -p 'm: ' m
read -p 'n: ' n
for ((i=0; i<m; i++))
do
    for ((j=0; j<n; j++))
    do
        a[${i},${j}]=$RANDOM
    done
done
for ((i=0; i<m; i++))
do
    for ((j=0; j<n; j++))
    do
        echo -ne "${a[${i},${j}]}\t"
    done
    echo
done

A: You could declare a 1D array and read all numbers into a 1D array at runtime. After knowing the dimension, you could process the 1D array "like a 2D array".
For instance, suppose 1D array contains
[1, 5, 9, 11]

If we really want
[[1,5], [9,11]]

as our array such that the index 0 is [1,5] then you could do something like this to access [1,5] (pos = 0)
pseudocode
for i in 0:(pos*dim + dim-1)
    echo arr[i]

to access [9,11] (pos = 1)
for i in pos*dim:(pos*dim + dim - 1)
    echo arr[i]

Hopefully this makes some sense. Really a 2D array is sort of a 1D array.


text:
Q: Dependency Error in Ruby I am trying to install a Gem named spiceweasel (https://github.com/mattray/spiceweasel). When running it I get the following error:
$ sudo gem install spiceweasel
ERROR:  While executing gem ... (Gem::DependencyError)
    Unable to resolve dependencies: ridley requires buff-extensions (~> 0.3); buff-config     requires buff-extensions (~> 0.3); varia_model requires buff-extensions (~> 1.0)

Is there a way to circumvent this?

A: Looks like you have a conflict in your dependencies:

*

*ridley requires buff-extensions (~> 0.3)

*varia_model requires buff-extensions (~> 1.0)

Ie: two gems depends on conflicting versions of a third one ("~>" in Bundler means that another minor version is correct, but not a major one).
What you can do:

*

*If your project does not require both ridley & varia_model, you may use RVM to create a specific Gemset for it.

*Update ridley (the newest version is also using buff-extension 1.0).

A: Install the buff-extensions gem.  It's currently at version 1.0, which should satisfy all of the other items that have dependencies on it.


text:
Q: Angular 2 Ahead-of-Time Compiler with gulp-typescript Angular 2 rc 6 written in Typescript 2.0.2
I'm trying to learn Ahead-of-Time compilation as outlined here.  It seems simple enough:

*

*Run ngc instead of the Typescript compiler to generate .ngfactory.ts files

*Replace platformBrowserDynamic().bootstrapModule() with platformBrowser().bootstrapModuleFactory()
I'm not sure how to apply the first step to my setup. I use gulp-typescript 2.13.6 to compile my typescript to JavaScript.
gulpfile.js
var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json', {
    //Use TS version installed by NPM instead of gulp-typescript's built-in
    typescript: require('typescript')
});
gulp.task('build-ts', function () {
    return gulp.src(appDev + '**/*.ts')
        .pipe(ts(tsProject))
        .pipe(gulp.dest(appProd));
});

So my question is; how do I integrate the instructions into my tooling? How do I get gulp-typescript to use the Angular Compiler?  I've tried:
var tsProject = ts.createProject('tsconfig.json', {
    typescript: require('@angular/compiler') // or '@angular/compiler-cli'
});

This throws errors without ever running ngc.  I also tried
var tsProject = ts.createProject('tsconfig.json', {
    typescript: require('./node_modules/.bin/ngc')
});

This does execute ngc but immediately throws error:

SyntaxError: Unexpected string at ngc:2: basedir=$(dirname "$(echo "$0" | sed -e 's,\,/,g')")

I suspect this is because no source directory is passed to ngc (the required command is ngc -p path/to/project)
Basically, is there a way to use gulp-typescript to have a one step build process? (generate .ngfactory.ts files, then compile all to JavaScript)

A: I imagine the reason why the typescript: require(..) is not working is because gulp-typescript looks for something called typescript or tries to run the command tsc, and since the angular compiler command is ngc, it doesn't find it.
For now, if your project is just as simple as compiling it, you can just run the command from gulp like so:
var exec = require('child_process').exec;

gulp.task('task', function (cb) {
  exec('ngc -p "<path to your tsconfig.json>"', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
});

This requires that you have your tsconfig.json set up correctly, with the potential extra options that Google talk about here, under the Configuration heading.
If you need the more complex functionality that the gulp-typescript package provides, I'm afraid you're either going to have to develop it yourself, or wait for someone else to.

A: I was trying to get this to work as well and William Gilmour's answer helped a lot.
I extended it a little to run a local ngc installation (like the angular 2 example that runs the one in node_modules/.bin), and which works both on Linux and Windows systems:
var exec = require('child_process').exec;
var os = require('os');

gulp.task('build-ts', function (cb) {

    var cmd = os.platform() === 'win32' ?
        'node_modules\\.bin\\ngc' : './node_modules/.bin/ngc';

    exec(cmd, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

A: This is the cross-platform version of the gulpfile, which I am currently using for Ahead-Of-Time (AOT) compilation with angular 2:
//jshint node:true
//jshint esversion: 6
'use strict';

...

// helper function for running ngc and tree shaking tasks
const run_proc = (cmd, callBack, options) => {
        process.stdout.write(stdout);
        process.stdout.write(stderr);
        callBack(err);
    });
};

gulp.task('ngc', ['css', 'html', 'ts'], cb => {
    let cmd  = 'node_modules/.bin/ngc -p tsconfig-aot.json';
    if (isWin) {
        cmd  = '"node_modules/.bin/ngc" -p tsconfig-aot.json';
    }
    return run_proc(cmd, cb);
});

Feel free to check out the entire example of the Tour of Heroes (ToH) example with gulp.js on my github repo: ng2-heroes-gulp
This is for sure the short term solution, the long term solution for me will be the gulp-ngc plugin.


text:
Q: C++ Passing unknown function as an agument My problem is following, I have a function which takes one function as a parameter. The problem is that in some cases the passed function fEval() needs to be called with two parameters instead of one as fEval(somevalue1,somevalue2)
Func(double (*fEval)(double F1),double min, double max,...)
{
    double value1 = fEval(10);

    // do something here

    double value2 = fEval(20,30);
}

So what would be the correct way to implement Func function ?
I know I can't do it either
Func(double (*fEval)(double F1),double min, double max,...)

or
Func(double (*fEval)(double F1,double F2),double min, double max,...)

Thanks !
Okay let me rephrase the problem. I need to create a function which could take a one unknown function as a first parameter, two different values and an argument list.
Something like
double Function(RandomFunction, val1, val2, ...);

The random function will be either:
double Func1(double x)
{
    m_x = x;
    //Calling function
    // Set other things
}
double Func2(double x,double y)
{
    m_y = y;
    m_x = x;
    //Calling function
    // Set other things
}

I'll try that functor way but I'm not sure is it right way to do this ? Doesn't it require me to overload () inside of the possible functions what could be called ?

A: You probably should require a functor that has operator() overloaded to take one or two arguments:
struct Functor {
    double operator()(double d) {
        ....
    }

    double operator()(double d1, double d2) {
        ....
    }
};

void Func(Functor f, double min, double max, ...) {
    double value1 = f(10);

    // do something here

    double value2 = f(20, 30);
}

Other than that (besides passing around variadic functions, which wouldn't be good because it couldn't know whether it was being called with one or two arguments) I don't think there is another good way to have a function that can take both 1 or 2 arguments.
And as ildjarn mentioned in the comments, you could also make it a template so it can take any kind of functor:
template<typename Functor_t>
void Func(Functor_t f, double min, double max, ...) {
    // same as above
}


text:
Q: PYTHON using api that returns json I am trying to use googles places api to get the place id of a coordinate.
When I load the api, it gives me a mess that looks like this:
{u'status': u'OK', u'html_attributions': [], u'results': [{u'name': u'San Francisco', u'reference': u'CmRbAAAAnnZ_G3vbVvFkLZ16Xs72Q_tCThBw8l-KRAfV-nkjJFhSct6iLCMjagLDx8fKzCe81qVelkHPCqlSo-0LghXfgrLgvHqfOL35HNBy18y2Ka6omKGFkNOmqkq1S6qI_zrBEhCogABq1AbcBQ4faNocEUr6GhQGVdTeVkvee1UlP0eNqoXphBAklg', u'geometry': {u'location': {u'lat': 37.7749295, u'lng': -122.4194155}, u'viewport': {u'northeast': {u'lat': 37.812, u'lng': -122.3482}, u'southwest': {u'lat': 37.70339999999999, u'lng': -122.527}}}, u'place_id': u'ChIJIQBpAG2ahYAR_6128GcTUEo', u'vicinity': u'San Francisco', u'photos': [{u'photo_reference': u'CoQBdwAAAMCSQa5APDsro3A01s2y_8ZJdlAfwEs8hDR-rY8qmDqpsI8lNeyAnA8ABqGdMCz7t4NDpqFEO4jyKzqrEjQfn8nX-KQrDui4Gpug9ZPFlC2tAE1mQpN-ZiqTQzi-RG1joYvP_D3x47k0IMuXg10n4omryejkNwSOIRu1lKH19ZHaEhDU41FXWZxOPntG9IiQFUaDGhR7vMx9AR77vnyYGxy5NkaqriIZgg', u'width': 3264, u'html_attributions': [u'Jasmine Crooms'], u'height': 1836}], u'scope': u'GOOGLE', u'id': u'1b9ea3c094d3ac23c9a3afa8cd4d8a41f05de50a', u'types': [u'locality', u'political'], u'icon': u'https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png'}, {u'name': u'Western Addition', u'reference': u'CmRbAAAAJczj_jM4I_aXrbmEGwb6wzdmvaf0OKjSMOgV9rXg-nyeYd-yE-jsHR-tUSl8pX0bykr-pF-boCGYt-SFQHHJYre7ohXL9JfyirKv58xuyBlYvewGsvmA8jGfpaVQKmaSEhB6JZF791kqmbSgT3xL3wEgGhQlewM9G3Tk4aLDv_IZVExxYU3EKg', u'geometry': {u'location': {u'lat': 37.7822112, u'lng': -122.4341781}, u'viewport': {u'northeast': {u'lat': 37.7903498, u'lng': -122.4210075}, u'southwest': {u'lat': 37.7690383, u'lng': -122.4476754}}}, u'place_id': u'ChIJORmAxLuAhYARJN5IphkMohE', u'vicinity': u'San Francisco', u'photos': [{u'photo_reference': u'CoQBdwAAAHZ2hI-5aQ_7YdcyvEGaNLE2P1WjCigqyq03V5PeSZkTzNEIf-Ft6OwTsdnuNbPBmDVRxTE_8KrQXdcsTr7_Z6fi5CX1WXkhRDnq58xNgl_VlvRRyAOT4aRGaWC0J6NUb9BW_1a6YuMuinqapQj3LO_esfJr2vm-E7MguPSSrdFrEhCxbibPaEYpkHZWUKAuC6j6GhQM6vPmaLMRZvXayFZ56J3p-7lFtw', u'width': 7192, u'html_attributions': [u'Mohd Al-Alami'], u'height': 4792}], u'scope': u'GOOGLE', u'id': u'59716f06d3d1b69830d34520b29ec95352234db1', u'types': [u'neighborhood', u'political'], u'icon': u'https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png'}]}

Here is my code:
import urllib2, json

latitude = '37.773972'
longitude = '-122.431297'
key = 'mykey'

url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + latitude + ',' + longitude + '&radius=1&key=' + key
json_obj = urllib2.urlopen(url)
data = json.load(json_obj)

print data["place_id"]

There is a field called place_id but when I try to call it, an error returns:
Traceback (most recent call last):
  File "C:\Users\Damon\Desktop\Coding\Python\placeid.py", line 11, in <module>
    print data["place_id"]
KeyError: 'place_id'

Is there any way to retrieve this place_id?

A: Take your result and format it like code:
{
    u'status': u'OK',
    u'html_attributions': [],
    u'results': [
        {
            u'name': u'San Francisco',
            u'reference': u'CmRbAAAAnnZ_G3vbVvFkLZ16Xs72Q_tCThBw8l-KRAfV-nkjJFhSct6iLCMjagLDx8fKzCe81qVelkHPCqlSo-0LghXfgrLgvHqfOL35HNBy18y2Ka6omKGFkNOmqkq1S6qI_zrBEhCogABq1AbcBQ4faNocEUr6GhQGVdTeVkvee1UlP0eNqoXphBAklg',
            u'geometry': {
                u'location': {
                    u'lat': 37.7749295,
                    u'lng': -122.4194155
                },
                u'viewport': {
                    u'northeast': {
                        u'lat': 37.812,
                        u'lng': -122.3482
                },
                u'southwest': {
                    u'lat': 37.70339999999999,
                    u'lng': -122.527
                }
            }
        },
        u'place_id': u'ChIJIQBpAG2ahYAR_6128GcTUEo',

You need to provide a string or number key for every unclosed { or [ bracket between the start of the result and your desired data.
You probably want something like
print data['results'][0]['place_id']

or something. You can use the pprint.pprint module to print complex data structures.


text:
Q: Question about proving that a finite intersection of big unions is a big union of finite intersections Let $I_{1}$,...$I_{k}$ be index sets and for each $1 \leq m \leq k$ and each $j \in I_{m}$, let $U_{j}$ be a set.
Prove that:
$$(\bigcup\limits_{j_{1}\in I_{1}}U_{j_{1}}) \cap ... \cap(\bigcup\limits_{j_{k}\in I_{k}}U_{j_{k}}) = \bigcup\limits_{(j_{1},...,j_{k})\in I_{1} \times ... \times I_{k}}U_{j_{1}} \cap ... \cap U_{j_{k}} $$
I understand that I need to prove a finite intersection of big unions is a big union of finite intersections. How would I prove this?

A: This reminds me of the distributive law for set theory operations. You can prove it by proving the following statements:

*

*$(\bigcup\limits_{j_{1}\in I_{1}}U_{j_{1}}) \cap ... \cap(\bigcup\limits_{j_{k}\in I_{k}}U_{j_{k}}) \subseteq \bigcup\limits_{(j_{1},...,j_{k})\in I_{1} \times ... \times I_{k}}U_{j_{1}} \cap ... \cap U_{j_{k}}$

*$\bigcup\limits_{(j_{1},...,j_{k})\in I_{1} \times ... \times I_{k}}U_{j_{1}} \cap ... \cap U_{j_{k}} \subseteq (\bigcup\limits_{j_{1}\in I_{1}}U_{j_{1}}) \cap ... \cap(\bigcup\limits_{j_{k}\in I_{k}}U_{j_{k}})$.
I'll prove the first statement. The second is left to you.
Proof. Suppose $x \in (\bigcup\limits_{j_{1}\in I_{1}}U_{j_{1}}) \cap ... \cap(\bigcup\limits_{j_{k}\in I_{k}}U_{j_{k}})$.
This means that for all $i \in \{1, 2, \ldots, k\}$, $x \in (\bigcup\limits_{j_{i}\in I_{i}}U_{j_{i}})$. Then for all $i \in \{1, 2, \ldots, k\}$, we can choose some $j_i \in I_i$ such that $x \in U_{j_{i}}$. But then since $j_1 \in I_1, \ldots, j_k \in I_k$, we can conclude that $(j_1, \ldots, j_k) \in I_1 \times \ldots \times I_k$. We also know that for all $i \in \{1, 2, \ldots, k\}$,  $x \in U_{j_{i}}$, so we can say that $x \in U_{j_1} \cap \ldots \cap U_{j_k}$. Therefore, $x \in \bigcup\limits_{(j_{1},...,j_{k})\in I_{1} \times ... \times I_{k}}U_{j_{1}} \cap ... \cap U_{j_{k}}$.


text:
Q: Display networkx graph in HTML I am trying to display a graph I have created using networkx, but the nodes are overlapping.
I want to display it in HTML so I can move nodes using the mouse (it also adds some interaction to the result).

*

*Working with python3

How can I display my nx graph in HTML?
Up to now, my code is:
G= nx.Graph()
G.add_nodes_from(nodes) # nodes is a list of nodes names (strings)
G.add_edges_from(edges) # edges is a list of edges between nodes above
pos = nx.spring_layout(G, scale=layout_scale, k=k)
plt.figure(figsize=figsize)
nx.draw_networkx(G, pos=pos)
plt.show()

For now, this code results in displaying the plot as some kind of an image (in the SciView of PyCharm).
I would appreciate any help with that!
Thanks!

A: Hi I use pyvis for interactive display. If I understand correctly, try my code, it should help you
from pyvis.network import Network
import networkx as nx

G=nx.Graph()

G.add_edge('1', '2')
G.add_edge('1', '3')

nx.draw(G, with_labels = True)
nt = Network('500px', '500px')
nt.from_nx(G)
nt.show('nx.html')


text:
Q: How do I have declarative, bidirectional bindings involving QML MouseAreas? I've created a QML UI that has a dial and a custom control. The custom control is basically a progress bar with a MouseArea to allow the user to set the value by clicking it. As Qt's property binding docs point out, as soon as I assign to the custom control's value from Javascript in the MouseArea click handler, I lose the declarative binding between it and the dial.
Is it possible to make this binding bidirectional, or even better, to link the values of both controls to a single value above both of them in the QML hierarchy? And is it possible to do this with declarative syntax so I don't have complex event handler code in every control?
import QtQuick 2.9
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.3
import QtQuick.Window 2.2
import QtQuick.Shapes 1.0

Window {
    id: window
    visible: true
    width: 800
    height: 200

    readonly property int range: 10

    RowLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        spacing: 5

        Dial {
            id: dial1
            live: true
            from: 0
            to: window.range
            stepSize: 1
            snapMode: Dial.SnapAlways
        }

        Control {
            id: dut

            implicitWidth: 200
            implicitHeight: 50

            property int range: window.range
            property int value: dial1.value

            onValueChanged: {
                console.log("New value: " + value);
            }

            Rectangle {
                width: parent.width
                height: parent.height
                color: Qt.rgba(0,0,0,0)
                border.color: Qt.rgba(0,0,0,1)
                border.width: 1
            }

            Rectangle {
                width: parent.width * dut.value/dut.range
                height: parent.height
                color: Qt.rgba(0,0,0,1)
            }

            MouseArea {
                anchors.fill: parent

                onClicked: {
                    dut.value = Math.round(mouseX/width * dut.range);
                }
            }
        }
    }
}

Note that if I reverse the relationship ie. have dial1.value: dut.value, then the binding isn't broken (although it's not quite bidirectional).
I realise that this example basically reinvents the scrollbar, but I'm trying to work my way up to more complex controls, for which declarative relationships between values would make life much easier.
Elaboration from a comment: What I don't understand, but want to, is how it's done for other QML components. For example, with a Dial I can set its value property to be bound to some other component's property, and clicking on the dial doesn't remove that binding. I don't have to hook into its mouse events to do that. Despite looking through the source for how this is done, I'm not really any closer to understanding it.
There are other questions about bidirectional property bindings in QML, but I haven't been able to apply them to my problem because (a) I really, really want something declarative, and (b) the MouseArea properties and events don't seem to work well with Binding objects (as in, I can't figure out how to integrate the two things).

A: I would have done this:
import QtQuick 2.9
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.3
import QtQuick.Window 2.2
import QtQuick.Shapes 1.0

Window {
    id: window
    visible: true
    width: 800
    height: 200

    readonly property int range: 10
    property int commonValue

    RowLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        spacing: 5

        Dial {
            id: dial1
            live: true
            from: 0
            to: window.range
            stepSize: 1
            snapMode: Dial.SnapAlways
            onValueChanged: {
                commonValue = dial1.value
                console.log("New value: " + value);
            }
        }
        Rectangle {
            width: 200
            height: 50
            color: Qt.rgba(0,0,0,0)
            border.color: Qt.rgba(0,0,0,1)
            border.width: 1

            MouseArea {
                anchors.fill: parent

                onClicked: {
                    commonValue = Math.round(mouseX/width * window.range)
                    dial1.value = commonValue
                }
            }

            Rectangle {
                width: parent.width * window.commonValue/window.range
                height: parent.height
                color: Qt.rgba(0,0,0,1)
            }
        }
    }
}

A: Use a Binding QML Type:
MouseArea {
    id: mouseArea
    anchors.fill: dut
}

Binding {
    target: dut
    property: 'value'
    value: Math.round(mouseArea.mouseX/mouseArea.width * dut.range);
    when: mouseArea.pressed && mouseArea.containsMouse
}

Note that the when property on the Binding means it's only active as a binding when those conditions are fulfilled ie. the mouse is over the area and one of the "accepted buttons" is pressed.
This does not mean that the value reverts when the conditions aren't met, just that the value stops updating when they're not met. However, if you have another binding active somewhere else, that one may cause the the value to "snap back" because it will "take over" when this Binding ceases to apply.
Depending on the other components you use, this might not even be enough, and you might need to implement your properties in C++ to get them to work as you expect.


text:
Q: How to change TextBox location at runtime I'm creating TextBoxes at runtime and add an EventHandler to eac, but I can only move the last one created, when I try to move a previous one, it disappears.
This is my code:
int Naslov_rnd;
TextBox tb;

private void Naslov_p_Click(object sender, EventArgs e)
{
    Naslov_rnd++;

    tb = new TextBox();
    VizitKartica.SuspendLayout();

    tb.Location = new Point(0, 0);
    tb.Multiline = true;
    tb.Size = new Size(200, 20);
    tb.BorderStyle = BorderStyle.None;
    tb.BackColor = Color.DodgerBlue;
    tb.ForeColor = Color.White;
    tb.Name = "Naslov_" + Naslov_rnd.ToString(); ;
    tb.Text = "Dodajte Vaš naslov";
    tb.Font = new Font("Microsoft Sans Serif", 12);

    VizitKartica.Controls.Add(tb);
    elementi_lista.AddItem(tb.Name);

    VizitKartica.ResumeLayout(true); Controls collection

      tb.MouseMove += new MouseEventHandler(tb_MouseMove);
    tb.MouseDown += new MouseEventHandler(tb_MouseDown);
}

protected void tb_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        tb.Left = e.X + tb.Left;
        tb.Top = e.Y + tb.Top;
    }
}

protected void tb_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point MouseDownLocation = e.Location;
    }
}

A: As @LarsTech said, you cannot make one TextBox object point to all of the TextBoxes that will be created, a simple and effective solution to this is to use the sender object.
The EventHandler provides you with an argument wich will get passed to the method, and it will point to the control that caused the event to be fired.
Since we know that all the TextBoxes are sharing the same event and they are all TextBoxes, we can type-cast the sender object to the TextBox class and then use it.
Here is how :
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    int Naslov_rnd;

    private void button1_Click(object sender, EventArgs e)
    {
        Naslov_rnd++;

        TextBox tb = new TextBox();
        VizitKartica.SuspendLayout();

        tb.Location = new Point(0, 0);
        tb.Multiline = true;
        tb.Size = new Size(200, 20);
        tb.BorderStyle = BorderStyle.None;
        tb.BackColor = Color.DodgerBlue;
        tb.ForeColor = Color.White;
        tb.Name = "Naslov_" + Naslov_rnd.ToString();
        tb.Text = "Dodajte Vaš naslov";
        tb.Font = new Font("Microsoft Sans Serif", 12);

        VizitKartica.Controls.Add(tb);

        VizitKartica.ResumeLayout(true);

        tb.MouseMove += new MouseEventHandler(tb_MouseMove);
        tb.MouseDown += new MouseEventHandler(tb_MouseDown);
    }

    protected void tb_MouseMove(object sender, MouseEventArgs e)
    {
        TextBox tb2 = (TextBox) sender;
        if (e.Button == MouseButtons.Left)
        {
            tb2.Left = e.X + tb2.Left;
            tb2.Top = e.Y + tb2.Top;
        }
    }

    protected void tb_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            Point MouseDownLocation = e.Location;
        }
    }
}

Hope that helped you and what you are looking for.


text:
Q: How to calculate prediction intervals for LOESS? I have some data that I fitted using a LOESS model in R, giving me this:

The data has one predictor and one response, and it is heteroscedastic.
I also added confidence intervals. The problem is that the intervals are confidence intervals for the line, whereas I am interested in the prediction intervals. For example, the bottom panel is more variable then the top panel, but this is not captured in the intervals.
This question is slightly related:
Understanding the confidence band from a polynomial regression, especially the answer by @AndyW, however in his example he uses the relatively straightforward interval="predict" argument that exists in predict.lm, but it is absent from predict.loess.
So I have two very related questions:

*

*How do I get the pointwise prediction intervals for LOESS?

*How can I predict values that will capture that interval, i.e. generate a bunch of random numbers that will eventually look somewhat like the original data?

It is possible that I don't need LOESS and should use something else, but I am unfamiliar with my options. Basically it should fit the line using local regression or multiple linear regression, giving me error estimates for the lines, and in addition also different variances for different explanatory variables, so I can predict the distribution of the response variable (y) at certain x values.

A: I don't know how to do prediction bands with the original loess function but there is a function loess.sd in the msir package that does just that! Almost verbatim from the msir documentation:
library(msir)
data(cars)
# Calculates and plots a 1.96 * SD prediction band, that is,
# a 95% prediction band
l <- loess.sd(cars, nsigma = 1.96)
plot(cars, main = "loess.sd(cars)", col="red", pch=19)
lines(l$x, l$y)
lines(l$x, l$upper, lty=2)
lines(l$x, l$lower, lty=2)

Your second question is a bit trickier since loess.sd doesn't come with a prediction function, but you can hack it together by linearly interpolating the predicted means and SDs you get out of loess.sd (using approx). These can, in turn, be used to simulate data using a normal distribution with the predicted means and SDs:
# Simulate x data uniformly and y data acording to the loess fit
sim_x <- runif(100, min(cars[,1]), max(cars[,1]))
pred_mean <- approx(l$x, l$y, xout = sim_x)$y
pred_sd <- approx(l$x, l$sd, xout = sim_x)$y
sim_y <- rnorm(100, pred_mean, pred_sd)

# Plots 95% prediction bands with simulated data
plot(cars, main = "loess.sd(cars)", col="red", pch=19)
points(sim_x, sim_y, col="blue")
lines(l$x, l$y)
lines(l$x, l$upper, lty=2)
lines(l$x, l$lower, lty=2)


text:
Q: Microsoft Information Protection SDK : using username/password to login I am building a POC application using the new MIP SDK on C#. One of the requirements is to use username/password stored on the server. All the example applications are using OAuth2 login with a popup window for user credentials input.
I believe that properly implementing the IAuthDelegate may help, but in-line documentation was not of much help.
in my engine init method I am following the SDK example
            var authDelegate = new AuthDelegateImplementation(appInfo);

            //Initialize and instantiate the File Profile
            //Create the FileProfileSettings object
            var profileSettings = new FileProfileSettings(
                path: "mip_data",
                useInMemoryStorage: true,
                authDelegate: authDelegate,
                consentDelegate: new ConsentDelegateImplementation(),
                applicationInfo: appInfo,
                minimumLogLevel: LogLevel.Trace);

            Console.WriteLine("Load the Profile async and wait for the result");
            var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;

and the AuthDelegateImplementation having following code
public string AcquireToken(Identity identity, string authority, string resource)
    {
        AuthenticationContext authContext = new AuthenticationContext(authority);
        AuthenticationResult result = authContext.AcquireTokenAsync(
                                        resource: resource,
                                        clientId: _appInfo.ApplicationId,
                                        redirectUri: new Uri(redirectUri),
                                        parameters: new PlatformParameters(PromptBehavior.Auto, null),
                                        userId: UserIdentifier.AnyUser).Result;
        return result.AccessToken;
    }

Thanks for your help,
C.

A: Well, apparently there is no MIP SDK way to login using the user/password. However, I was able to hack my way in by using other Azure API.
I send a REST call to Azure REST to acquire the access and refresh tokens.
The request is sent from an implementation of IAuthDelegate. Your implementation of method IAuthDelegate::AcquireToken will send the REST call and return the access token (string).
The login request structure is as follows:
...
client.BaseAddress = new Uri(String.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenantId));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
...
string postBody = string.Format(
                        "grant_type=password&" +
                        "resource=https://psor.o365syncservice.com&" +
                        "username={0}&" +
                        "password={1}&" +
                        "client_id={2}", credentialsIdentity.Username, credentialsIdentity.Password, _appInfo.ApplicationId);

the response structure is this:
   public class LoginResponse
    {
        public string token_type { get; set; }
        public string scope { get; set; }
        public string expires_in { get; set; }
        public string ext_expires_in { get; set; }
        public string expires_on { get; set; }
        public string not_before { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
        public string refresh_token { get; set; }
    }

Hope this will help someone down the road.

A: As a general principal, MIP SDK doesn't care about your login - it just need to know your authentication token using the IAuthDelegate callback.
You can, and should, use ADAL .Net in order to login with username and password. You can use the .Net sample in order to find how to do that


text:
Q: Submitting form does not behave as expected I am currently haunting another bug as I noticed that the form I am using calls on both buttons the onSubmitClicked() function:
Originally it looked like this:
<button mat-raised-button (click)="onBackClicked()">
  Back
</button>
<button mat-raised-button type="submit">
  Submit
</button>

No matter which button I am clicking, both call onSubmitClicked(). Just the "Back" button call onBackClicked() first. Removing the type="submit" from the "Submit" button does not change anything.
<form [formGroup]="placeInfoForm" (ngSubmit)="onSubmitClicked()">

    <mat-form-field style="width: 100%;">
      <input matInput placeholder="Name" formControlName="name"/>
    </mat-form-field>

    <button mat-raised-button (click)="onBackClicked()">
      Back
    </button>
    <button mat-raised-button>
      Submit
    </button>

</form>

The submit function:
onBackClicked() {
  console.log('onBackClicked()')
}

onSubmitClicked() {
  console.log('onSubmitClicked()');
}

A: Any <button> inside the <form> will try to submit the form unless specified explicitly.
Try this:
<button mat-raised-button type="button" (click)="onBackClicked()">
  Back
</button>


text:
Q: function_score with nested score_modes? I am using a function_score query that looks like:
{
    "query": {
        "function_score": {
            "query": {
                "multi_match": {
                    ...
                }
            },
            "functions": [
                {
                "script_score": { // f0
                        "script": {
                            ...
                        }
                    }
                },
                {
                    "field_value_factor": { // f1
                        ...
                    }
                },
                {
                    "field_value_factor": { // f2
                        ...
                    }
                },
                {
                    "field_value_factor": { // f3
                        ...
                    }
                },
            ],
            "score_mode": "multiply",
            "boost_mode": "multiply"
        }
    }
}

Current query calculates the scores as _score * (f0 * f1 * f2 * f3) but I want the final score to be _score * (f0 + (f1 * f2 * f3)).
I don't know if it is possible to have like a single function_score query with sum and multiply score modes?
I am using ElasticSearch-6.2.


text:
Q: How to keep connection alive in GO's websocket I use code.google.com/p/go.net/websocket in server, so client can get notification from server.
however, It seems after client connected to server, if there is no any data tranfer between client and server, server will return EOF error at websocket.JSON.Receive(), it looks like a timeout mechanism.
And I have search in Google, it seems websocket protocol has a ping-pong heartbeat to maintain the connection, I want to ask whether code.google.com/p/go.net/websocket support this ping protocol or not?
What should I do if I want keep connection between client and server alive?

A: As recently as 2013, the go.net websocket library does not support (automatic) keep-alive messages.  You have two options:

*

*Implement an "application level" keep-alive by periodically having your application send a message down the pipe (either direction should work), that is ignored by the other side.

*Move to a different websocket library that does support keep-alives (like this one) Edit: it looks like that library has been superseded by Gorilla websockets.

A: Here's working drop-in solution for gorilla/websocket package.
func keepAlive(c *websocket.Conn, timeout time.Duration) {
    lastResponse := time.Now()
    c.SetPongHandler(func(msg string) error {
       lastResponse = time.Now()
       return nil
   })

   go func() {
     for {
        err := c.WriteMessage(websocket.PingMessage, []byte("keepalive"))
        if err != nil {
            return
        }
        time.Sleep(timeout/2)
        if(time.Since(lastResponse) > timeout) {
            c.Close()
            return
        }
    }
  }()
}


text:
Q: how to build a routeable network for pgRouting with srid 3785 I'm following the pgrouting-workshop http://workshop.pgrouting.org/chapters/topology.html and It works, but in my project I'm working with the mercator projection(srid 3785) and there is not a routed network like the Open Street Map to work in, so I need to build my own.. so for testing purposes with the help of google maps and Proj4js I build a simple graph like this

point1 = "POINT (-7363703.972517611 -1966750.4952863816)"
point2 = "POINT (-7363530.794875402 -1966719.4427436402)"
point3 = "POINT (-7363414.945004408 -1966694.3618437336)"
point4 = "POINT (-7363365.977533163 -1966681.2242294976)"
point5 = "POINT (-7363419.722318676 -1966658.5319867264)"
point6 = "POINT (-7363344.479618957 -1966793.4911147922)"
// it's in lon / lat format
Then the geom column in ways table
way_red =   "MULTILINESTRING((point1, point2, point3, point4))"
way_green = "MULTILINESTRING((point3, point5))"
way_blue =  "MULTILINESTRING((point4, point6))"
Questions:

*

*Is it correct the format I builded the ways ??

*Exist a correct or pre-established format to  construct a routeable network?

*the workshop uses "MULTILINESTRING", is it ok if I use just "LINESTRING"??

Thanks in advance, and sorry for my english.

A:
1) Is it correct the format I builded the ways ??

Not quite. The red way has to be split at point 3. Ways have to be split at each intersection if turning should be possible there.
Also the point coordinates you specified cannot be valid latitudes/longitudes.

2) Exist a correct or pre-established format to construct a routeable network?

You generally need a source node id (or "from_node") and a target node id (or "to_node") plus some edge weight (can be length/distance or travel time or energy cost). Some algorithms will also use the actual geometry (MULTI/LINESTRING) but basic shortest path doesn't.

3) the workshop uses "MULTILINESTRING", is it ok if I use just "LINESTRING"??

That's fine. You shouldn't encounter multilinestrings in routing graphs anyway.

A:

*

*Is it correct the format I builded the ways ?

*Exist a correct or pre-established format to construct a routeable network?

If your network data is not OSM data and it doesn't contain information about source and target of each road segment, then you can use the assign_vertex_id function to prepare your data for routing.
See: http://workshop.pgrouting.org/chapters/topology.html#calculate-topology
If your data is in a different projection than you need, you can use ST_transform to re-project into the SRID you need: http://postgis.net/docs/ST_Transform.html

*

*the workshop uses "MULTILINESTRING", is it ok if I use just "LINESTRING"?

Yes.


text:
Q: Redux Saga in a loop confusion I have following (first) saga:
export function* getIdentificators() {
   while (true) {
      yield take(GetIdentificators);
      try {
         const res = yield call(api.getIds);
         const data = // some array of data

         for (const elem of data) {
            yield put(getAnotherStuff(elem));  <--- calling the second saga in a loop
         }
      }
   }
}

As you can see, it dispatches some action in a for of loop.
It works just fine, I mean - that saga is being called as many times as data length is.
And here comes the second saga, responsible for handling that getAnotherStuff action:
export function* anotherStuff() {
   while (true) {
      const action = yield take(someAction);

      const { actionId } = action;
      try {
         const { data } = yield call(apiCall, elem);

         yield put(someSuccessAction(Action, data));
      }
   }
}

So - it doesnt work just right. If I drop console.log inside, its being logged only once and only the first result is appearing. So it doesn't work as I want it to be (I would like it to work as many times as I dispatch it in the first saga).
However, if I use takeEvery instead:
export function* anotherStuffWatcher() {
   yield takeEvery(someActionType, anotherStuff);
}

It works fine - all requests are being processed.
My final question - Why if I use while(true) it processing only the first request instead of every single one? And why does it work properly when I use takeEvery? Thank you!

A:
its being logged only once

This happens because call is blocking effect. Assuming apiCall takes some time. So while this call is happening your saga is blocked and is not taking new actions.
export function* anotherStuff() {
   while (true) {
      const action = yield take(someAction);

      const { actionId } = action;
      try {
         const { data } = yield call(apiCall, elem); // this is blocking call

         yield put(someSuccessAction(Action, data));
      }
   }
}

To avoid this you could either use takeEvery helper that takes care of "taking every" action matching the pattern. Or you could use actionChannel that buffers future actions
export function* anotherStuff() {

   // buffers up to 10 actions
   // or you could provide another buffering strategy via
   // second argument https://redux-saga.js.org/docs/api/#buffers
   const someChannel = yield actionChannel(someAction);

   while (true) {
      const action = yield take(someChannel);

      const { actionId } = action;
      try {
         const { data } = yield call(apiCall, elem); // this is blocking call

         yield put(someSuccessAction(Action, data));
      } catch(blackhole) {}
   }
}

A: take and call
You are using take and call combination inside the while loop. That means, if you dispatch 4 actions. It will run for first action and remaining three actions will be dropped.

I would like it to work as many times as I dispatch it in the first saga

So there are 2 solutions.

*

*takeEvery

*take and fork combination inside while(true).

As per second solution, just replace 'call' by 'fork' in your code .


text:
Q: How to determine the partition on which Ubuntu is installed and resize it? I have four partitions on my hard-drive: C, E, F and G. Partitions C and G are NTFS and I installed Ubuntu using Wubi through Windows 7. Probably I installed it on the partition G, where Windows 7 is also installed. I guess I created a new partition within G for Ubuntu and it was a minimum 3.5 GB installation.
From Ubuntu, I want to check on which partition I installed it and how much space is left. How to do this? I also want to install any Ubuntu package that can resize the partition by taking the free space from another partition.

A: Wubi does not install Ubuntu into a real partition but instead resides in some files on your NTFS partition. I can't really say how you can find out where your files are located but you might be interested in Wubi: How do I resize the virtual disks?.

A: It's probably simplest to mount each partition in turn and look for a filesystem containing an ubuntu/disks directory.

A: The following commands show how to determine the host partition, and the space used:
bcbc@ubuntu:~$ mount | grep '/host'
/dev/sda3 on /host type fuseblk (rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other,blksize=4096)
bcbc@ubuntu:~$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/loop0            5.0G  4.0G  739M  85% /
none                  494M  672K  493M   1% /dev
none                  501M  336K  500M   1% /dev/shm
none                  501M  256K  500M   1% /var/run
none                  501M     0  501M   0% /var/lock
/dev/sda3              20G   12G  8.0G  60% /host

In the above, my host partition is /dev/sda3 and the space remaining on the virtual disk (/dev/loop0) is 739MB, the space remaining on /host is 8GB.
You cannot determine the "drive designation" that Windows uses for /dev/sda3 from within Wubi. But if you go to Windows, then the drive will contain the "ubuntu" folder in the root. e.g. G:\ubuntu
For resizing the virtual disks, please refer to the Wubi Guide


text:
Q: Replace random string starting and ending using shell command Appreciate any help to find out the solution for below scenario.
Input:
:50Kfoobar:53B:53B:53Bbaz:53B:53B;:50Kvoocar:53B:53B:53Bbaz:53B:53B

Output:
:50KCREDIT:53B:53B:53Bbaz:53B:53B;:50KCREDIT:53B:53B:53Bbaz:53B:53B

Tried using below command
sed 's/:50K.*:53B/:50KCREDIT:53B/g' <<<':50Kfoobar:53B:53B:53Bbaz:53B:53B;:50Kvoocar:53B:53B:53Bbaz:53B:53B'

producing below result
:50KCREDIT:53B

A: With your shown samples, please try following.
awk '{gsub(/:50K[^:]*:53B/,":50KCREDIT:53B")} 1' Input_file

Explanation: using regex :50K[^:]*:53B which will match :50K till next occurrence of :(non-greedy match) then matching : followed by 53B, then replacing this matched part with :50KCREDIT:53B globally, finally printing the current line.


text:
Q: Why apache cannot access location like /tmp/file.php Recently i've installed apache on lubuntu, created file in  default /var/www/html
this file was requiring file from /tmp and it was not working.
I thought it is permission problem so i made 777 for file in tmp and made it executable. but this did not help.
It's strange becaouse on my home server running by Raspberry pi(raspbian) also with apache it's working like that out of the box,
I made sure that www-data user is capable of running this script correctly and it worked file was required correctly, but by http browser its not working.
Im i missing sth crucial for config in apache2.conf i've tried to ad this directory but nothing worked as expected.


text:
Q: Android Chromecast: Call messageStream.playFrom(position) does not work in MediaProtocolCommand onCompleted I had a media player, when user connect to chromecast in the middle of the video, I would like to cast the video to chromecast at the same position in the video where the user left off.
mediaProtocolCommand.setListener(new MediaProtocolCommand.Listener() {
     public void onCompleted(MediaProtocolCommand mPCommand) {
          messageStream.playFrom(currentVideoPosition);
     }
});

Using the code snippet above I manage to get the video playing but it always start at the beginning of the video

A: Works fine for me using the Cast Android sample app. Make sure the parameter value for playFrom is the time in seconds.


text:
Q: How can i get data or pass a data from one page to another after submitting a form in reactjs i am new to Reactjs, i'm almost done with my project. i've been doing a hotel booking system. but i have a problem with my checkout page. after i submitted a form from booking page it will redirected to checking out page. now how can i be able to get the reservation data from query? i'm using a param in my other pages but how can i pass an id when it was redirected and no href to pass the id.
can anyone help me with this, i'm runnung out of time and i'm still stuck here. thank you in advance.
here is my CheckOutPage:
   const CheckoutPage = (props) => {
   const [isRedirected, setIsRedirected] = useState(false)

if (isRedirected) {
    return <Redirect to='/transaction'/>
}

return (
    <ConfirmationMessage setIsRedirected={setIsRedirected}/>
)

}

const ConfirmationMessage = ({setIsRedirected}) => {

const { user } = useContext(UserContext)

const [name, setName] = useState('')
const [roomPrice, setRoomPrice] = useState(0)

let options = {
    headers: {
        Authorization: 'Bearer ' + user.token
    }
}

useEffect(() => {
    GQLClient(options).request(Query.getUser).then((data) => {
        setName(data.getUser.name)
    })

    GQLClient({}).request(Query.getRooms).then((data) => {

        setRoomPrice(data.getRoom.roomPrice)
    })

}, [])

return(
    <Container>
        <Row> .....

here's in my schema.js
 type Query {
    getReservationForm: ReservationForm
 }

 type ReservationForm {
    id: ID!
    startDate: String!
    endDate: String!
    name: String!
    email: String!
    contactDetail: String!
    roomNumber: String!
    roomPrice: Float!
}

in my resolvers
 Query: {
    getReservationForm: (parent, args) => {
        return ReservationForm.findById(args.id)
    }
},

and in my query
 getReservationForm: `
    query (
        $id: String!
    ) {
        getReservationForm (
            id: $id
        ) {
            startDate
            endDate
            name
            email
            contactDetail
            roomNumber
            roomPrice
        }
    }

A: If you are using Redirect, you can actually pass some data:
<Redirect to={{
            pathname: '/checkout',
            state: { first: 'James', last: 'Bond', ... }
        }}
/>

You can then access this data in your CheckoutPage:
console.log(this.props.location.state);


text:
Q: How to trigger 'contenteditable' element into edit state using js? I want to implement element in-placing edit using 'contenteditable' attribute. Is it possible to go into the edit state with mouse event simulation instead of user click?
function triggerEvent(element, eventType) {
    let rect = element.getBoundingClientRect();
  console.log(rect);

    let event = new MouseEvent(eventType, {
    clientX: rect.left + 20,
    clientY: rect.top + 10,
    view: window,
    buttons: 1,
    bubbles: true,
  });
  element.dispatchEvent(event);
}

document.getElementById('btn').addEventListener('click', (event) => {
    let editArea = document.getElementById('edit-area');
  editArea.setAttribute('contenteditable', true);

  triggerEvent(editArea, 'mousedown');
});

DEMO: https://jsfiddle.net/lfree/vkeq9fza/1/

A: You just need to focus the div:

let div = document.querySelector('div');

div.focus();

Div Content

A: If I understand correctly, all you're trying to do is set focus to the element. Because you've already enabled contenteditable, the following should be adequate:
editArea.setAttribute('contenteditable', true);
editArea.focus(); // Focus on the input which will activate editing


text:
Q: Archive Fails due to Code sign error I recently created a new provisioning profile and added that to Xcode. The build compiles and runs perfectly but while archiving Xcode is getting code sign error.  This is the output at console. I couldn't figure out much from it.
CodeSign /Users/tarunkhurana/Library/Developer/Xcode/DerivedData/App-aqjeimytlifknpbxauygrrollgfw/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App
    cd /Users/tarunkhurana/Desktop/App
    setenv CODESIGN_ALLOCATE /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
    setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /usr/bin/codesign --force --sign "iPhone Developer: XXXXX" --resource-rules=/Users/tarunkhurana/Library/Developer/Xcode/DerivedData/App-aqjeimytlifknpbxauygrrollgfw/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App/ResourceRules.plist --entitlements /Users/tarunkhurana/Library/Developer/Xcode/DerivedData/App-aqjeimytlifknpbxauygrrollgfw/ArchiveIntermediates/App/IntermediateBuildFilesPath/App.build/Release-iphoneos/App.build/App.xcent /Users/tarunkhurana/Library/Developer/Xcode/DerivedData/App-aqjeimytlifknpbxauygrrollgfw/ArchiveIntermediates/App_Parse/InstallationBuildProductsLocation/Applications/App.app

/Users/tarunkhurana/Library/Developer/Xcode/DerivedData/App-aqjeimytlifknpbxauygrrollgfw/ArchiveIntermediates/App/InstallationBuildProductsLocation/Applications/App.app: object file format invalid or unsuitable
Command /usr/bin/codesign failed with exit code 1

I am using Xocde4.2 and iOS-5. Any help will be greatly appreaciated