text:
Q: Spring @Repository annotation does not work but @Service annotation does? I have a simple Class called BeaconDao

    package za.co.idealize.dao.impl;

    import java.util.List;

    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import za.co.idealize.dao.BaseDao;
    import za.co.idealizeit.model.Beacon;

    @Service("beaconDao")
    public class BeaconDao extends BaseDao{

        @Autowired
        protected BeaconDao(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
            super(sessionFactory, Beacon.class);

        }

        @Transactional(readOnly = true)
        @SuppressWarnings("unchecked")
        public List findByStoreID(int storeID) {
            Session session = getSession();

            Transaction tx = session.beginTransaction();
            Query q = session.createQuery(
                    "FROM Beacon b where b.storeId = :id");
            q.setParameter("id",storeID);

            List beacon = q.list();

            tx.commit();
            return beacon;
        }

        @SuppressWarnings("unchecked")
        public List findByUUID(String UUID) {
            Session session = getSession();

            Transaction tx = session.beginTransaction();

            List beacon = session.createQuery(
                    "FROM Beacon where Beacon.Uuid = " + UUID).list();
            tx.commit();
            return beacon;
        }

    }

Whenever i start my application up with the beaconDAO marked @Repository the application comes back with the following stack trace:

    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0' defined in class path resource [application-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beaconJsonController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public za.co.idealize.dao.impl.BeaconDao za.co.idealize.controller.BeaconJsonController.beaconDao; nested exception is java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
        at java.lang.Thread.run(Thread.java:695)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beaconJsonController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public za.co.idealize.dao.impl.BeaconDao za.co.idealize.controller.BeaconJsonController.beaconDao; nested exception is java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
        at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:287)
        at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:266)
        at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82)
        at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58)
        at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:120)
        at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:73)
        at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:74)
        at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:119)
        at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:94)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1545)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
        ... 21 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public za.co.idealize.dao.impl.BeaconDao za.co.idealize.controller.BeaconJsonController.beaconDao; nested exception is java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
        ... 41 more
    Caused by: java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
        at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
        at java.lang.reflect.Field.set(Field.java:657)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:504)
        ... 43 more
    Jun 24, 2014 1:30:46 AM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0' defined in class path resource [application-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beaconJsonController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public za.co.idealize.dao.impl.BeaconDao za.co.idealize.controller.BeaconJsonController.beaconDao; nested exception is java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
        at java.lang.Thread.run(Thread.java:695)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beaconJsonController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public za.co.idealize.dao.impl.BeaconDao za.co.idealize.controller.BeaconJsonController.beaconDao; nested exception is java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
        at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:287)
        at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:266)
        at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82)
        at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58)
        at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:120)
        at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:73)
        at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:74)
        at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:119)
        at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:94)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1545)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
        ... 21 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public za.co.idealize.dao.impl.BeaconDao za.co.idealize.controller.BeaconJsonController.beaconDao; nested exception is java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
        ... 41 more
    Caused by: java.lang.IllegalArgumentException: Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
        at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
        at java.lang.reflect.Field.set(Field.java:657)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:504)
        ... 43 more

however when i mark the beaconDao with @Service or @Component everything works perfectly fine.
Can anyone see an issue here?

A: The problem lies entirely elsewhere:
Can not set za.co.idealize.dao.impl.BeaconDao field za.co.idealize.controller.BeaconJsonController.beaconDao to com.sun.proxy.$Proxy30.
Now, if I were to translate that to English then the translation would be: Spring cannot set beaconDao field on za.co.idealize.controller.BeaconJsonController singleton because JDK proxies are used and you have declared the BeaconJsonController.beaconDao as BeaconDao class when you should have used some kind of interface. I suspect your BeaconDao class hierarchy looks someting like BeaconDao -> BaseDao  -> ISomeDao where ISomeDao is an interface. Change the declaration in BeaconJsonController from
private BeaconDao beaconDao;

to
private ISomeDao beaconDao;

and use qualifier if you must.
The problem is that Spring will create proxy for ISomeDao interface rather than for BeaconDao and you then tries to assign ISomeDao proxy to BeaconDao field which causes the class cast exception.


text:
Q: Trouble starting rails server . specific module could not be found New to programming, ruby, rails, sql ect. Following along with video tutorials but ran into this error. Any help appreciated.
C:\sites\simple_cms>rails s
c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/mysql2-0.3.15/lib/mysql2.rb:8:in `requir
e': 126: The specified module could not be found.   - c:/ruby200-x64/lib/ruby/ge
ms/2.0.0/extensions/x64-mingw32/2.0.0/mysql2-0.3.15/mysql2/mysql2.so (LoadError)

        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/mysql2-0.3.15/lib/mysql2.rb
:8:in `<top (required)>'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler/runtime.rb:76:in `require'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler/runtime.rb:76:in `block (2 levels) in require'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler/runtime.rb:72:in `each'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler/runtime.rb:72:in `block in require'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler/runtime.rb:61:in `each'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler/runtime.rb:61:in `require'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/bundler-1.6.0.pre.2/lib/bun
dler.rb:132:in `require'
        from C:/sites/simple_cms/config/application.rb:7:in `<top (required)>'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.2/lib/rails/co
mmands.rb:74:in `require'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.2/lib/rails/co
mmands.rb:74:in `block in <top (required)>'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.2/lib/rails/co
mmands.rb:71:in `tap'
        from c:/ruby200-x64/lib/ruby/gems/2.0.0/gems/railties-4.0.2/lib/rails/co
mmands.rb:71:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

C:\sites\simple_cms>

A: We need to start from scratch here:

*

*Install Ruby with the Windows installer from http://rubyinstaller.org/downloads/

*Install bundler:
gem install bundler

*For mysql on Windows, I think you need the devkit. Get the one that matches your os from http://rubyinstaller.org/downloads/

*Make sure you have mysql installed on your PC.

*Make sure the mysql2 gem installs correctly. if gem install mysql2 does not install correctly, you might need something like: gem install mysql2 -- --with-mysql-dir="C:\mysql\bin" ; change c:\mysql\bin to the location where you install mysql in step 4

*Install rails: gem install rails

*Go to your directory c:\sites\simple_cms and type: bundle install

*Now attempt to start your server: rails s
Rails development on Windows has made great improvements but if you really want to stay up to date and avoid some weird issues in the future (especially with gem support), I suggest you use Ubuntu for example. If you don't have another computer or do not wish to do a dual boot, you can install VirtualBox for free (https://www.virtualbox.org/wiki/Downloads) and have Ubuntu run on it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AppRegistryNotReady ошибка при запуске проекта, что упустил?     Traceback (most recent call last):

File "/home/alexey/Projects/doors7/manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()

 File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/apps/config.py", line 87, in create
    module = import_module(entry)

File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)

File "/home/alexey/Projects/doors7/frontend/__init__.py", line 2, in <module>
    _('frontend')

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 83, in ugettext
    return _trans.ugettext(message)

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 325, in ugettext
    return do_translate(message, 'ugettext')

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 306, in do_translate
    _default = translation(settings.LANGUAGE_CODE)

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 209, in translation
    default_translation = _fetch(settings.LANGUAGE_CODE)

File "/home/alexey/door7_env/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 189, in _fetch
    "The translation infrastructure cannot be initialized before the "

**"The translation infrastructure cannot be initialized before the "
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.**

A: Прямо же и пишут: проверьте, что вы не используете не-ленивые вызовы gettext в корне модулей.


text:
Q: ReactJS/Enzyme: How to test a submit function, which calls a graphQL mutation via prop I'm trying to write a unit test (enzyme/jest) for this function:
_onSubmit = (event) => {
  event.preventDefault()
  const { username, password } = this.state

  this.props.createUserMutation({
    variables: { username, password }
  }).then(response => {
    const token = response.data.createUser.token
    if (token) {
        this.setState({ token })
    }
  }).catch(error => {
    console.warn(error)
  })
}

But I don't know how to handle this.props.createUserMutation() for proper testing.
Of course my current attempt throws a TypeError: _this.props.createUserMutation is not a function error
Unit test
it('_onSubmit() should submit form and reset state object', () => {
  const wrapper = shallow(<CreateAccount />)
  wrapper.setState({ username: 'Username', password: 'Password' })
  wrapper.find(Form).simulate('submit', {
    preventDefault: () => {}
  })
  const state = wrapper.instance().state
  expect(state).toEqual({ token: 'test' })
})

Updated unit test
it('_onSubmit() should submit data and get result dataset', () => {
    const createUserMutation = () => {
      return Promise.resolve({
        data: {
          createUser: { token: 'token' }
        }
      })
    }
    const wrapper = shallow(<CreateAccount createUserMutation={createUserMutation} />)
    wrapper.find(Form).simulate('submit', {
      preventDefault: () => {}
    })
    const state = wrapper.instance().state
    expect(state).toEqual({ token: 'token' })
  })

console.log(state) doesn't give me a token.

A: I'm assuming createUserMutation is injected to props by the compose function.
So, what you can do is import the non-default component in your test instead of the 'connected' one.
import {CreateAccount} from './CreateAcount';

Then, you can pass createUserMutation as props directly to the component when mounting it.
it('_onSubmit() should submit form and reset state object', () => {
  const createUserMutation = () => {
      return Promise.resolve({
           username: '',
           password: ''
         });
  };
  const wrapper = shallow(<CreateAccount createUserMutation={createUserMutation} />)
   ...
});

Given that createUserMutation seems to be a function that returns a promise, you can assign it Promise.resolve() in order to execute the then function which changes the state. Which is basically what you are testing.
Moreover, you're not able to test the token change in the state because the verification in the test is being run before the state changing in the method _onSubmit. (You can check this by putting console statements in both places and see which executes first).
What you need to do is return the promise in your _onSubmit method.
_onSubmit = (event) => {
  event.preventDefault()
  const { username, password } = this.state

  return this.props.createUserMutation({   // returning the promise
    variables: { username, password }
  }).then(response => {
    const token = response.data.createUser.token
    if (token) {
        this.setState({ token })
    }
  }).catch(error => {
    console.warn(error)
  })
}

Then, in your unit test you need to simulate the submit event by calling the function directly from props in order to put your verifications inside a then function. By doing this, you would run your expect statement after the state has been changed.
it('_onSubmit() should submit data and get result dataset', () => {
    const createUserMutation = () => {
      return Promise.resolve({
        data: {
          createUser: { token: 'token' }
        }
      })
    }
    const wrapper = shallow(<CreateAccount createUserMutation={createUserMutation} />)
    wrapper.find(Form).props().onSubmit({
      preventDefault: () => {}
    }).then(() =< {
       const state = wrapper.instance().state
       expect(state).toEqual({ token: 'token' })
    })
  })


text:
Q: What is a regular expression to match square brackets and the content between square brackets? I have a expression like [2180]:. I want to match everything including square brackets and colon mark.
I tried using /\[/[/d+]/\]/: but it seems it doesn't work perfectly.
Let us go for another example: vpnagent[2284]:.
What would be the regular expression for the above string?

A: You seem to be confusing slashes (used to delimit a regex) and backslashes (used to escape regex metacharacters or for special regex shorthand escape sequences):
/\[\d+\]:/

is what you need.


text:
Q: Pointer difference between 2 int pointers int main(void) {
    int *a;
    int *b = a++;
    printf("%d\n",b-a);
    return 0;
}

I expected the output to be 1 why is it -1?
Assume in the above question instead of a++ I have ++a.
Is it still undefined behavior?

A: The First problem, as I see here, is primarily with
 int *a;

a is automatic local, and the initial value is indeterminate (no explicit initialization), hence doing a++ (or, ++a, for the matter) invokes undefined behavior.
That said, regarding the pointer subtraction, see this answer on why we need the operands of subtraction operator to be address of elements from same array object.
Finally, the subtraction of two pointers produce the type ptrdiff_t, you should be using %td to print the result. Otherwise, you again invoke UB.

[As mentioned in  below comments]
Assuming the pointers are initialized properly, something like
int k[5] = {0};
int * a = &(k[0]);
int *b = a++;
printf("%td\n",b-a);

in that case, the result will be -1, as that is the difference in the index of both the elements (remember a++ is post-increment).
Chapter §6.5.6/9, C11 standard

When two pointers are subtracted, both shall point to elements of the same array object,
  or one past the last element of the array object; the result is the difference of the
  subscripts of the two array elements.

A: First of all, your code causes undefined behavior because it reads and modifies uninitialized variables.
Also the specifier %td should be used for printing pointer difference.
Let's assume the pointer a actually points to a valid object:
int i;
int *a = &i;
int *b = a++;
printf("%td\n",b-a);

The postfix ++ operator gives the current value of the operand and then increments the operand by one. The above code is identical to:
int i;
int *a = &i+1;
int *b = &i;
printf("%td\n",b-a);

Pointer a points to one-past the object i, and pointer b points to the object i. The subtraction will, due to pointer arithmetic, yield -1. If the operation was: a-b then the result would be 1.
This is defined behavior.

A: Difference of two pointers ((b-a) in this case) is not defined in C unless the two pointers are pointing to addresses of a same array.
Also, since the pointer 'a' in your code has not been assigned any address ( contains garbage value ), doing any kind of operation is a sin.
If you wish to see how does subtraction of two pointers work, then try to define an array and make these two pointers point to it.

A: When you increment the pointer, it does not add the value to 1. It just tells the pointer to point to the next location. Also, your pointers were never initialized and they are just pointing to random garbage numbers.

A: int *a is a variable with automatic storage duration and never has its address taken (&a). The code therefore invokes undefined behavior (as per 6.3.2.1, see this) and your program can't have any predictable outcome.
Using the %d format specifier on on a ptrdiff_t also invokes undefined behavior (7.21.6.1/9). You should use %td for ptrdiff_t and %p for pointers.
Thus you can't expect anything from your program. It can output anything, or nothing, or crash.

A: That is no undefine behaviour
when you declared *a, a points to a memory location, *b = a++;  b to point to the same location as a, AND increaments a to point to a location 1 factor greater than the previous location that b points to.
b - a = -1 //correct
i'll give example
int main(void)
     {
        int *a; // 0x408
        int *w = a++; // 0x400
        int *b = a++; // 0x404

        int c = (b-a);
        printf("%d\n",b-a);// -1
        printf("%d\n",w-a); // -2

        return 0;
    }

i intruduce w to better ilustrate
The run-time memory address of the variable will look similar to the ones above.
b - a ( 0x404 - 0x408) == -1( -4 );
the sizeof int( in this case ) is 4 bytes. and pointers holding the address of int will have their address changing(+/-) by factor of 4,
as far is int is concern in this case 4 bytes hold one integer(1 unit)
w - a == (0x400 - 0x408) = -2( -8 )
if you had
a - w == (0x408 - 0x400) = 2( 8 )


text:
Q: How would I extract minutes from difference of two dates that are saved in different columns in Mysql? I want to extract minutes from difference of two dates, but the dates are saved in two columns, say C1 and C2.
I used this command "SELECT TIMESTAMPDIFF(minutes, C1,C2) FROM Table ;"
Its not correct, of course, because it is giving syntax error.
Also I want to extract minutes from difference of date in a colunm and current date.

A: You can search it on stack overflow.
somebody already faced same issue and resolved here
example for second or you can use minute (MINUTE):
SELECT TIMESTAMPDIFF(SECOND, date_column_1, date_column_2) from table_name


text:
Q: Git-svn W: -empty_dir warnings. What do they mean? While trying to clone an existing Subversion repository using git-svn using standard layout, I got a bunch of W: -empty_dir (and W: +empty_dir) warnings. The cloned git repository seems to be working, i.e. I can do usual git operations and dcommit to SVN repository.
The real problem is that the initial clone and rebase create some empty directories that do not exist in SVN repository, at the top of the repository (along with other directories in trunk). These directories contain no file but just some empty directories inside them. It seems that the "W: -empty_dir" warnings correspond to these empty directories.
I looked for empty directories by checking out the whole repository using SVN, but there is no empty directory. I also checked through SVN if the repository has files with special properties, but there was not any other than "executable" and "mime-type".
The existing repository was not originally following the standard layout, but I cleaned it up so that the top directories are just "trunk", "tags", and "branches".
What can be causing the creation of these empty directories that do not exist under Subversion?

A: One of the things with git is that it does not track directories. It is all about content (files) in git. So empty directories are pretty much left to languish in your local repo. The best way to get rid of empty directories in your local repo is to do git clean -d.
Checkout man git clean for more info.

A: Regarding the question in the title (which is what draws google's attention to this page), according to my findings, using either git-svn 1.7.1 or git 1.8.5: the warning W: -empty_dir: x/y/z means that the file or folder x/y/z was removed in the SVN changeset. Unless you specified -q (--quiet), that fact was already reported as D x/y/z. What I think it tries to say is that as a consequence, the folder x/y might have become empty and was therefore removed from the git view. It is far more common that x/y did not become empty and there is nothing peculiar going on.
In practice, if removing x/y/z would have left x/y empty, you would probably have removed the whole of x/y in the SVN changeset, and the removal of x/y/z would not even be reported separately. So you would not get that warning, but instead W: -empty_dir: x/y warns you that x might have become empty, which you know it didn't because then you would have deleted x...
If, on the other hand, you did leave empty directories around and want to keep them, I guess you would use --preserve-empty-dirs and I see no point in the warning either (if it still appears in that case).
So in short, ignore it. Unlike W: +empty_dir, which is a different story.

A: Without knowing exactly where those empty directories came from, you could tell git-svn to remove them by using the --rmdir command line option or svn.rmdir configuration option.
See git-svn OPTIONS man page and

Remove directories from the SVN tree if there are no files left behind.
  SVN can version empty directories, and they are not removed by default if there are no files left in them. git cannot version empty directories.
  Enabling this flag will make the commit to SVN act like git.

The warning comes from SVN tags (which are "directories") not supported by git-svn, as in "git svn interrupted, then I lost all the tags, how to fix it?".
From this thread:

SVN tracks directories, git doesn't, so empty directories cannot be represented in git.
  Those warnings on files seem to tell you which files that got deleted, causing an empty directory to be left in place, in that particular svn commit being imported.

The difference between -empty_dir and +empty_dir is about how the empty directory appears in the SVN repo:
-empty_dir
A bunch of files are deleted, leaving a directory (branch or tag) empty.
+empty_dir
An empty branch or tag has just been created in the SVN revision being imported, and git-svn won't import an empty directory.

Note that you can restart the import after that warning.


text:
Q: Batch Sed for Windows add spaces for fixed file I have the need to output a variable to a file, but the variable can be "example" or "example of the day" or "Exmple" in other words the variable can be any length up to 32 characters. For the file format I need the variable to always output as 32 characters with the extra characters as empty spaces.
What I'm trying to do right now is echo out the variable to a tmp file then run:
sed -i --expression="1{x;:a;/.\{32\}/!{s/^/ /;ba};x};/\(.\{32\}\).*/b;G;s//\1/;y/\n/ /" tmpfile

Which when done from the command prompt gives me exactly what I need, but when done via my batch script doesn't seem to do anything... which is odd because its not even tossing out an error, syntax issue or anything.
Once the spaces are added to the end of the variable the next question I have is when I set the file contents back to the variable:
set /p var=<tmpfile

Is the variable going to keep all of the extra spaces as needed or is going to drop them? I'll have a dozen of other variables that this will need to be done for each requiring different segment lengths which will ultimately get echoed out into a single 1000 character per line file.
At this point I'm kind of lost as to why the sed command would function exactly as expected from the command line, but fail from the batch script. I'm using GNU Sed for windows btw. Any help is very much appreciated.

A: I am afraid I don't understand your concern. However, if your question is: "How to add spaces to a variable up to a fixed length?", then this is the answer:
set var=Value shorter than 32 chars

rem Spaces:   12345678901234567890123456789012
set "var=%var%                                "
set "var=%var:~0,32%"

echo Value with fixed 32-chars length: "%var%"

A: I'd suggest that certain characters in your sed command-string need to be escaped for use within a batch file. Prime candidates would be ^=|
Perhaps the easiest logical way to overcome this little quirk is to use sed's -f facility and put your sed commands in a text file
sed -fmyfile.sed filetochange.txt >changedfile.txt

where myfile.sed contains your actual sed commands.
An advantage of this approach is that you can then use exactly the same line within a batch and directly from the prompt while tinkering with the details with a text editor on the *.sed file (the .sed extension is a personal convention.)


text:
Q: How can I chain .html() and .fadeIn() in jQuery? Here is my code:
$('.container-modal-cash').html().fadeIn(1500);

It throws:

Uncaught TypeError: $(...).html(...).fadeIn is not a function

Why? And how can I fix it?
Generally I'm setting a content (using .html) inside an element and then showing it (using .fadeIn). What's wrong?

A: The .html() can be used to set the contents of the element, or get the contents of the element. FadeIn/Out methods work on the Jquery selector element ( I mean $('.test') ).
Courtesy of Trincot, you can also use the fadeIn/fadeOut() methods, when you set the content of the element using html().
$('.test').html("final content").fadeOut(1500).fadeIn(1500);

please refer the below example demonstrating this.

console.log("getting the contents inside");
console.log($('.test').html());
console.log("setting the contents inside");
$('.test').html('changed content');

//fade works on the JQuery selector element.

$('.test').fadeOut(1500);
$('.test').fadeIn(1500);

// you can chain the fadeIn/fadeOut methods like so

$('.test').fadeOut(1500).fadeIn(1500);

// you can also chain the fadeIn/fadeOut when setting the html content like so.

$('.test').html("final content").fadeOut(1500).fadeIn(1500);

content

A: This thing only works when you set some html inside html function.

$('.container-modal-cash').html("testing fadeIn").fadeIn(1500);

//below will fail with same error - uncomment below code to verify
//$('.container-modal-cash').html().fadeIn(1500);


text:
Q: I Can't understand the usage of "Would" I've somehow learned English tenses using timelines. Something like this one:

But I'm having trouble understanding 'would'. Is there a diagram, a picture or a good explanation to simplify this. How does a teacher teach kids about this?

A: I have some material that couuld help you.
Would can be used as a modal verb or in conditionals (2st conditional -> If i could, then I would... 3rd conditional -> if i had been, than I would have...). So if you search for MODAL VERBS and CONDITIONALS, i think most of your questions about "WOULD" will be answered.
Here are some images that might help you.

Also, be careful not to confuse the past perfect HAD with WOULD in the contracted form.
I WOULD DO THE SHORES EVERY DAY -> I'D DO THE SHORES EVERY DAY
I HAD DONE THE SHORES THAT DAY -> I'D DONE THE SHORES THAT DAY
Use the context to recognize both.
If you have any question, let me know.
See you!

A: Link:Learner's Dictionary
You've asked a very difficult question. I know because I am a native speaker of Canadian English, but I cannot tell you why.
When I was a child the rules were different from the examples in the link. "Can I go to bed?" Would have meant, was I physically able to go to bed. I was corrected ad nauseum to say, "May I go to bed?" That means I was asking permission to go to bed. "Can I have a pencil?" Should be, "May I have a pencil?" Of course I was able to have a pencil but I may not have one because it is time for some other activity. If I could not have a pencil it would have been because there were no pencils or the pencils were in use or broken.
Best of luck with this. I look forward to better answers than mine.
LINK: Definition of would


text:
Q: "ValueError: None is not a generator." in SimPy generator function I am trying to run a simulation with SimPy. Unlike open systems, since my system is closed, I need to generate a constant amount of entities immediately (10 in my case). So, no interarrival times.
The problem is that when I try to generate entities in a while loop with or without interarrival times, I don't get an error. (Without interarrival times, of course it doesn't stop running, cause you know, it tries to generate as much as possible in a given runtime). The code below works but it is not what I need.
    def customer_generator(self, env, resource1, resource2):
        while True:
            p = self.customer(env, resource1, resource2) # create a new customer
            env.process(p) # start the simulation of the customer

But when I try to generate them in a for loop to create only 10 entities,
    def customer_generator(self, env, resource1, resource2):
        for x in range(10):
            p = self.customer(env, resource1, resource2) # create a new customer
            env.process(p) # start the simulation of the customer

I get this "None is not a generator" error.
  File "C:\Users\Can\Anaconda3\lib\site-packages\simpy\events.py", line 310, in __init__
    raise ValueError('%s is not a generator.' % generator)

ValueError: None is not a generator.

Maybe I am missing a simple detail. Any suggestions on how I can generate only 10 entities without getting this error?

A: If we dig into source of SimPy\envents.py (https://github.com/cristiklein/simpy/blob/9ac72fee4f079da331707bbdaf7e7cda929ded0b/src/simpy/events.py#L311), we will see following:
class Process(Event):
....
    def __init__(self, env, generator):
        if not hasattr(generator, 'throw'):
            # Implementation note: Python implementations differ in the
            # generator types they provide. Cython adds its own generator type
            # in addition to the CPython type, which renders a type check
            # impractical. To workaround this issue, we check for attribute
            # name instead of type and optimistically assume that all objects
            # with a ``throw`` attribute are generators (the more intuitive
            # name ``__next__`` cannot be used because it was renamed from
            # ``next`` in Python 2).
            # Remove this workaround if it causes issues in production!
            raise ValueError('%s is not a generator.' % generator)

It looks that this part of code may give errors as noted by developers. I cannot trace back when and what. Suggestion is to follow developers instructions and remove this workaround in your copy of SimPy (C:\Users\Can\Anaconda3\lib\site-packages\simpy\events.py)

A: Does your customer class have a env.process(<some customer process>)
as part of its init method?
If so then you do not need to call env.process(p) in your generator
if not then you need to pass a process, not the object to env.process()
env.process(p.<some process>)

where <some process> is a generator that yields a event

A: By my understanding of SIMPY concepts, you should return something from the process like env.timeout(1) or env.exit()


text:
Q: How to use quotes in calling a command line tool from shell I have a self made command line tool (uses golang flags) that works very well.
The command line Parameter contains listing of a directory (ls)
When I start it from a script, I have problems with the quotes, that define the parameter text:
./Cmdlinetool -text='FileA FileB FileC'

If I use it with a script, the output is:
Parameter Text:     'FileA
tail: [ FileB FileC']

If I use it without a script, the output is:
Parameter Text:     FileA FileB FileC
tail: [ ]

The script looks like this, it replaces all line breaks with spaces:  tr '\n' ' '
tmp="'$(ls)'"
TEXT="$(echo $tmp | tr '\n' ' ' )"
./Cmdlinetool -text=$TEXT

Also masking the quotes with \ does not help,
I also tried "   and '

A: 2 problems:

*

*tmp="'$(ls)'"
You put literal single quotes into the tmp string: The first and last characters in the string are quote characters.

*./Cmdlinetool -text=$TEXT
You fail to quote the variable. This allows the shell to do "word splitting", so you're actually invoking the tool like this:
 ./Cmdlinetool -text="'File1" "File2" "File3'"

Do this instead:
files=(*)  # an array of the filenames in this directory
./Cmdlinetool -text="${files[*]}"    # a space separated string of the array contents


text:
Q: Android/Kotlin: Error: "Expecting a top level declaration > Task :app:buildInfoGeneratorDebug" I try to write a class to manage a SQLite DB, but I have the error message "Expecting a top level declaration > Task :app:buildInfoGeneratorDebug".
   package com.xexxxwxxxxs.GMP

    import android.database.sqlite.SQLiteDatabase
    import android.database.sqlite.SQLiteOpenHelper
    import android.content.Context
    import android.content.ContentValues

    class DBHandler(context: Context, name: String?, factory: SQLiteDatabase.CursorFactory?, version: Int) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION)
    {
        override fun onCreate(db: SQLiteDatabase)
        {

        }

        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int)
        {

        }

        companion object
        {
            private val DATABASE_VERSION = 1
            private val DATABASE_NAME = "GMP.db"
        }
    }

Do you have any ideas?
Thanks in advance

A: I just delete the last curly brace and write it again. It's working :)

A: The same happened to me, you just need to remove an auto-generated extra curly bracket at the end, then it works.

A: This error can show up if you have defined any object outside of class declaration
example  :
class someActivity extands something{ } private someMethod(){}
to solve this   just move  it inside
`class someActivity extands something{
private someMethod(){}
}`

A: If, like me, you are working in code (VSCode), you should remove the call to main() at the end of the file. For example
fun main(){
println("This will fail")
}
main()

For the above, we shall get the following error:

your_file.kt:50:6: error: expecting a top level declaration
main()

Removing the call to main() fixes the issue.


text:
Q: MySql ORDERBY & Limit -> wrong result I have a simple query:
SELECT post_id FROM posts WHERE post_type = 'person' ORDER BY post_date DESC LIMIT 0, 8

I also build in a pagination so there are pages (1, 2, 3, ...) that show me the next 8 records
SELECT post_id FROM posts WHERE post_type = 'person' ORDER BY post_date DESC LIMIT 8, 8

in the first query I got a person called "John Doe" and in the second query also but the person is just 1 time in the Database and another person that should appear there is not here... what is my problem?
I have to tell you, that I imported about 1K records from the old website in the new one and now i created a person and modified the post_data so this person should appear in the first or second page.

*

*Page
---------------------------
|Name          | post_date  |
---------------------------
|John Doe      | 19.11.2016 |
|Hans Mair     | 29.11.2016 |
|Peter Gray    | 29.11.2016 |
|Eric Test     | 27.11.2016 |
|Peter Henny   | 21.11.2016 |
|George Green  | 19.11.2016 |
|Susan White   | 19.11.2016 |
|Barbara Gnome | 19.11.2016 |
---------------------------

*Page
-----------------------------
|Name           | post_date    |
-----------------------------
|Simon Blue     | 19.11.2016   |
|Garry Red      | 19.11.2016   |
|Martin yellow  | 19.11.2016   |
|Mattwo Brown   | 18.11.2016   |
|Simon Bank     | 14.11.2016   |
|Christian Rock | 12.11.2016   |
|Walter White   | 12.11.2016   |
|Homer Orange   | 12.11.2016   |
-----------------------------

but in the 2. page Simon Blue doesn't appear instead there is again John doe


text:
Q: How to use sliders in clojure seesaw I'm new to clojure (and even newer to seesaw) but have a lot of Java experience and a fair amount of swing experience.
I'm trying to create a window with some drop-down text boxes and a slider on it. However, I'm having trouble getting all the pieces to be displayed on one window (rather than one at a time) and for some reason the slider isn't being displayed.
I cannot really find a lot of tutorials on this, so maybe I'm missing something obvious.
Here's what I'm trying to do...
    (defn window [cuisine-input rating-input location-slider]
        (seesaw/frame
        :title "Resturant Selector"
        :content (cuisine-input rating-input location-slider)
        :width 200
        :height 50
        :on-close :exit))

    (defn -main
    [& args]

        (def cuisine (seesaw/input "Please choose a type of cuisine: "
                           :choices ["Indian" "Japanese" "Chinese"
                                     "Burgers"]))

        (def rating (seesaw/input "Please choose the ideal rating: "
                        :choices ["1 star" "2 stars" "3 stars" "4 stars"
                                  "5 stars"]))
        (def location (seesaw/slider
                             :value 5 :min 0 :max 20
                             :minor-tick-spacing 1 :major-tick-spacing 2
                             :snap-to-ticks? true
                             :paint-ticks? true :paint-labels? true))

        (def main-window (window cuisine rating location))
        (seesaw/pack! (window main-window))
        (seesaw/show! (window main-window))

)
I've also tried something like this:
    (seesaw/frame :title "Resturant Selector" :on-close :exit
            :content (:items [
                     (seesaw/input "Please choose a type of cuisine: "
                           :choices ["Indian" "Japanese" "Chinese"
                                    "Burgers"])

                     (seesaw/input "Please choose the ideal rating: "
                        :choices ["1 star" "2 stars" "3 stars" "4 stars"
                                  "5 stars"])

                     (seesaw/slider
                       :value 5 :min 0 :max 20
                       :minor-tick-spacing 1 :major-tick-spacing 2
                       :snap-to-ticks? true
                       :paint-ticks? true :paint-labels? true)]
                              )
            )

A: seesaw/input creates an input dialog, while you want to create a JComboBox. The wiki has a nice help about how to create widgets and you can find a list of available widgets in the API doc.
To have more than one widget in a frame you need a container.
So for your particular example, you will need something similar to:
(defn window [content]
  (seesaw/frame
    :title "Resturant Selector"
    :content content
    :width 200
    :height 50
    :on-close :close))

(defn -main
  [& args]
  (let [rating-label (seesaw/label :text "Please choose rating:")
        rating (seesaw/combobox :model ["1 star" "2 star"])
        location (seesaw/slider
                   :value 5 :min 0 :max 20
                   :minor-tick-spacing 1 :major-tick-spacing 2
                   :snap-to-ticks? true
                   :paint-ticks? true :paint-labels? true)

        main-window (window (seesaw/vertical-panel :items [rating-label rating location]))]
    (seesaw/invoke-later
      (seesaw/pack! main-window)
      (seesaw/show! main-window))))


text:
Q: Java shift operator Consider the following Java code:
byte a = -64;
System.out.println(a << 1);

The output of this code is -128
I tried as follows to figure out why this is the output:
64 = 0 1000000 (the MSB is the sign bit)
-64= 1 1000000 (Tow's complement format)
Expected output after shifting:
1 0000000 (This is equal to 0, because the MSB is just a sign bit)
Please anyone explain what I am missing.

A: The two's complement representation of -128 is 10000000, thus your results are correct.

A: 10000000 is -128
10000001 is -127
10000010 is -126
...

So 10000000 is not 0. It is -128 which was your output.

A: This program
System.out.println(Integer.toBinaryString(-64));
System.out.println(Integer.toBinaryString(-64 << 1));
System.out.println("-64 << 1 = " + (-64 << 1));

prints
11111111111111111111111111000000
11111111111111111111111110000000
-64 << 1 = -128

You can see that -64 << 1 is the same as -64 except all the bits have been shift left by 1 (the lowest bit becomes a 0)

A: In shift operators sign bit is ignored. So 1 1000000 << 1 is 10000000 which is -128.what's the problem?
Our machines are using two's complement to represent numbers (signed and unsigned). For representing a negative number machine negates it's positive and adds 1.
-128 is !10000000 + 1 = 01111111 + 1 = 10000000
EDIT:
I was wrong, only right shift operator's ignoring the sign bit. 10100000 << 1 == 01000000
For unsigned right shifting there's an operator >>> which shifts sign bit too.
11000000>>1 == 10100000 and 11000000>>>1 == 01100000

A: In two's complement, the MSB is not just a sign bit, you're thinking ones'-complement maybe? In 8 bit two complement,

10000000 = 0x80 = -128

A:
<< means multiply by 2
>> means divide by 2

And, during shift operations don't consider signed bit.

A: I'm wondering. << 1 (ignoring all details) is "multiply with 2." -64 * 2 = -128. So why are you wondering that it indeed is -128?


text:
Q: Contradictory results while comparing O(n) and O(logn) program for finding largest number in an array using python? I was comparing the two algorithm for finding the largest number in an array. I made two functions named as max1, max2.
max1(arr): This function is a time complexity O(n) function which traverses the whole array to find the largest element.
max2(arr,start,end): This function does the splitting of the array into two halves recursively in order to find the largest number. Hence it's time complexity is O(log n).
As far as the time complexity is concerned the max2 function should take lesser time compared to max1 function. But for my surprise, the results are contradicting my assumptions.

Here is the following code:
def max1(arr):
    mx = float('-inf')
    for i in arr:
        if mx < i:
            mx = i
    return mx

def max2(arr,start,end):
    if start == end:
        return arr[start]
    else:
        mid = (start + end)//2
        return max(max2(arr,start,mid),max2(arr,mid+1,end))

import time
from random import randint
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

def getData():
    n = 100
    N = []
    b = []
    c = []
    while n < 1000000:
        x = [randint(0,50) for i in range(n)]

        t1 = time()
        max1(x)
        t2 = time()
        b.append(t2 - t1)

        t1 = time()
        max2(x,0,n-1)
        t2 = time()
        c.append(t2 - t1)

        N.append(n)
        n += 10000
        print('*',end = '')

    return N,b,c

def analyse(N,b,c):
    plt.plot(N,b, label = 'max1')
    plt.plot(N,c, label = 'max2')
    plt.xlabel('Amount of data', fontsize = 20)
    plt.ylabel('Time taken', fontsize = 20)
    plt.legend()
    plt.show()

# results
# b => max1
# c => max2
N,b,c = getData()
analyse(N,b,c)

If there is any error in my assumptions, kindly correct me? or If I am right, then how is this contradiction happening?


text:
Q: Strategy Stop or Halt syntax in pine script Is there any specific syntax for stopping or halting the strategy after specific condition?
I know it is possible with few manually conditions but I'm looking forward for built-in syntax if exist.
Thanks

A: You are looking for
strategy.close("entryNameHere", when = yourBoolCondition)

Cheers and best of luck


text:
Q: Log4net inside BHO does not work? I'm trying to use log4net with an external config file, but it does not work: nothing gets logged
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
        <file value="C:\\tmp\\test.log" />
        <appendToFile value="true" />
        <maximumFileSize value="100KB" />
        <maxSizeRollBackups value="2" />

        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%level %thread %logger - %message%newline" />
        </layout>
    </appender>

    <root>
         <appender-ref ref="RollingFile" />
    </root>
</log4net>

If I use this line in Assembly.cs, test.lg is creatd when the BHO is registered with regasm, but not when the plugin is running:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"C:\\tmp\\test.log4net", Watch = true)]

When I use this code inside the BHO, no log is adde to test.log:
XmlConfigurator.Configure(new System.IO.FileInfo(@"C:\\tmp\\test.log4net"));
log.Info("test");

I'm not sure what I am doing wrong.

A: The log4net configuration file was fine. The problem is that Internet Explorer ran in Protected Mode, which forbids BHOs to write to arbitrary folders. There are only a few folders where the BHO can write.


text:
Q: C# search and replace multiple URLs based on the value in the URL The example of string:
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
There are multiple links in the string, what I'd like to do is replace the link one by one based on the id in that link.  e.g.
for the link,    I'd like to replace it with,

How can I do it?
Thank you in advance!

A: EDIT: To replace all IDs use this approach:
string pattern = @"(?<=]+href=""mycompany/)product/detail\.aspx\?mId=(?<Id>\d+)(?="">)";
string replace = "detailView.aspx?pId=${Id}";
string result = Regex.Replace(input, pattern, replace);

The pattern uses a named group called Id which captures one or more digits (\d+). It is then referenced in the replacement pattern (i.e., replace). Look-arounds are used to match the general URL pattern but not capture it, allowing the focus to be on just the portion to be altered.

Original answers to change specific IDs...
To replace a single ID you could use this approach:
string targetId = "3";
string pattern = @"(?<=]+href=""mycompany/)product/detail\.aspx\?mId=(?<Id>"
                 + targetId + @")(?="">)";
string replace = "detailView.aspx?pId=${Id}";
string result = Regex.Replace(input, pattern, replace);

With a little extra effort the above can be modified to support multiple target IDs:
string[] targetIds = { "3", "61" };
string pattern = @"(?<=]+href=""mycompany/)product/detail\.aspx\?mId=(?<Id>"
                 + String.Join("|", targetIds)
                 + @")(?="">)";
string replace = "detailView.aspx?pId=${Id}";
string result = Regex.Replace(input, pattern, replace);

This works fine for numbers as IDs, but if you plan to extend this to general strings you'll want to make use of the Regex.Escape method before joining all the target items as I've done above.

A: Try something like this:
public string ReplaceString(string text) //Where text = the paragraph
{
     //New Text
     string newText = "";
     //Old text
     string oldText = "";
     //String builder to replace text
     StringBuilder newString = new StringBuilder(text);
     //Replace text
     newString.Replace(oldText, newText);
     //Return
     return newString.toString();
}

I haven't tested it so you may need to fiddle around with the code. Also you can look here for more information on StringBuilder


text:
Q: TcpListener on different network I can not connect to the TCP Server when i am on a different network
I am trying to connect to a Tcp server I created on another network, I have had no luck. Is there a way to do this?
What is is the IP Address that i need to put in to the Client program?
The server works fine if you are on the network but how do i connect is i am on a different network?
I have tried to connect with the external IP Address but the message just sat at the router, how do i make the router send the message to my PC?

*

*What am i doing wrong

*How do i fix it

A: Your TCP server should be on a system with a public(external) ip address. Clients then will be able to connect to the server even if they are inside a LAN. Note that the ip adresses in a LAN are different from external ip-addresses. The translation is called NAT.
So because your server runs on a computer inside a LAN it will not be accessible for other computers on the internet. Your router on the other hand has a public ip address which will be accessible from the internet. You can configure your router to forward a port to your computer so that your router connects your server with the internet. Note that port forwarding is often a bad security practice. Make sure that you pick a port number that's not used by any other program.
Also keep in mind that the TCP traffic from the client to the server is probably un-encrypted. This means that your traffic will be vulnerable for man-in-the-middle attacks. You should try to establish an connection which uses SSL. (Note: SSL is not equal to https) For more information please look at the OSI-model.


text:
Q: Multiple table, multiple column query I have the following tables:
transactions :  Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason
rewards :   Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System
purchases : Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name Date_DealtWith Date_Collected

Staff members award students with points which becomes an entry into the transactions table, like this:
Transaction_ID Datetime Giver_ID Recipient_ID Points Category_ID Reason
8 2011-09-07 36761 127963 2 1 Excellent behaviour in behaviour unit
Students can then purchase a reward which becomes an entry into the purchases table, like this:
Purchase_ID Datetime Reward_ID Quantity Student_ID Student_Name Date_DealtWith Date_Collected
1570 2012-05-30 12:46:36 2 1 137616 Bradley Richardson NULL NULL
All of the rewards are stored manually in the rewards database table:
Reward_ID Title Description Image_URL Date_Inactive Stock_Count Cost_to_User Cost_to_System
1 Lunch Time Queue Pass (month) Beat the queue and get to the hot food early! /user/74/167976.png 2012-04-16 11:50:00 0 100 0

My question is this:
What SQL statement can I use to return Student Name, Points Earned, Points Spent, Points Remaining?
I asked a similar question a while back, which offered the following statement. However, upon inspection, it doesn't appear to be entirely accurate - specifically Points Spent isn't working correctly.
SELECT  Recipient_ID AS StudentID,
        SumOfPointsOfPurchasesMade.Points AS PurchasesMade,
        SumOfPointsEarned.Points AS PointsEarned,
        SumOfPointsEarned.Points - COALESCE(SumOfPointsOfPurchasesMade.Points, 0) AS CurrentPoints
FROM
(
    SELECT SUM(Points) AS Points, Recipient_ID
    FROM   transactions
    GROUP  BY Recipient_ID
) AS SumOfPointsEarned
    LEFT JOIN
    (
        SELECT purchases.Student_ID,  SUM(rewards.Cost_to_User) AS Points
        FROM   purchases
            INNER JOIN rewards
            ON purchases.Reward_ID = rewards.Reward_ID
        GROUP  BY purchases.Student_ID
    ) AS SumOfPointsOfPurchasesMade
    ON SumOfPointsEarned.Recipient_ID = SumOfPointsOfPurchasesMade.Student_ID
WHERE SumOfPointsEarned.Points < SumOfPointsOfPurchasesMade.Points
ORDER BY `CurrentPoints`  DESC

Thanks in advance,

A: You just need to use an outer join to combine the tables, then group by student:
SELECT purchases.Student_Name                               AS `Student Name`,
       SUM(transactions.Points)                             AS `Points Earned`,
       SUM(rewards.Cost_to_User)                            AS `Points Spent`,
       SUM(transactions.Points) - SUM(rewards.Cost_to_User) AS `Points Remaining`
FROM   transactions
  LEFT JOIN purchases ON purchases.Student_ID = transactions.Recipient_ID
  LEFT JOIN rewards   USING (Reward_ID)
GROUP BY purchases.Student_ID
ORDER BY `Points Remaining` DESC

A: I've stupidly realised that a tiny mistake from the other post fixes the problem I was having:
SELECT SumOfPointsEarned.Points - COALESCE(SumOfPointsOfPurchasesMade.Points, 0) AS CurrentPoints
FROM
(
    SELECT SUM(Points) AS Points, Recipient_ID
    FROM   transactions
            WHERE Recipient_ID= 137642
    GROUP  BY Recipient_ID
) AS SumOfPointsEarned
    LEFT JOIN
    (
        SELECT purchases.Student_ID,  SUM(rewards.Cost_to_User * purchases.Quantity) AS Points
        FROM   purchases
            INNER JOIN rewards
            ON purchases.Reward_ID = rewards.Reward_ID
                    WHERE Student_ID = 137642
        GROUP  BY purchases.Student_ID
    ) AS SumOfPointsOfPurchasesMade
    ON SumOfPointsEarned.Recipient_ID = SumOfPointsOfPurchasesMade.Student_ID
ORDER BY CurrentPoints ASC

This one line was the problem:
SUM(rewards.Cost_to_User * purchases.Quantity) AS Points
No multiplication of quantity. Doh!


text:
Q: How to deploy new version of Web-App without owner privileges?
*

*Once we create a new version and deployment ID, what do we need to do to make that version live? Do we need to publish it via the Publish -> Deploy as web add-on? and then it will be live?

*It seems only the owner of the Project can do Publish -> Deploy as web add-on. This creates a single point of failure/bottleneck where multiple people might work on the project. What do you suggest we do to avoid this?


text:
Q: filling areas in tikzpicture I did this with geogebra, then copied the code and generate the drawing.
I am missing how too fill some areas too make it look like in the pic I added.

\documentclass[10pt]{article}
\usepackage{pgfplots}

\pgfplotsset{compat=1.15}
\usepackage{mathrsfs}
\usetikzlibrary{arrows}
\pagestyle{empty}
\begin{document}

\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=0.35cm,y=0.35cm]
\clip(-2.6084198246281884,-1.775158614705993) rectangle (39.01911524098169,25.132373556978752);
\draw [line width=1pt,color=black] (0,0)-- (0,6);
\draw [line width=1pt,color=black] (0,6)-- (1,6);
\draw [line width=1pt,color=black] (2,6)-- (3,6);
\draw [line width=1pt,color=black] (3,6)-- (3,9);
\draw [line width=1pt,color=black] (4,6)-- (5,6);
\draw [line width=1pt,color=black] (5,0)-- (5,6);
\draw [line width=1pt,color=black] (4,6)-- (4,8);
\draw [line width=1pt,color=black] (7,0)-- (7,6);
\draw [line width=1pt,color=black] (8,6)-- (7,6);
\draw [line width=1pt,color=black] (8,6)-- (8,10);
\draw [line width=1pt,color=black] (9,6)-- (10,6);
\draw [line width=1pt,color=black] (10,6)-- (10,8);
\draw [line width=1pt,color=black] (11,6)-- (11,8);
\draw [line width=1pt,color=black] (11,6)-- (12,6);
\draw [line width=1pt,color=black] (12,6)-- (12,0);
\draw [line width=1pt,color=black] (9,6)-- (9,10);
\draw [line width=1pt,color=black] (1,6)-- (1,11);
\draw [line width=1pt,color=black] (2,6)-- (2,10);
\draw [line width=1pt,color=black] (2,10)-- (8,10);
\draw [line width=1pt,color=black] (1,11)-- (28,11);
\draw [line width=1pt,color=black] (9,10)-- (15,10);
\draw [line width=1pt,color=black] (14,0)-- (14,6);
\draw [line width=1pt,color=black] (15,6)-- (14,6);
\draw [line width=1pt,color=black] (15,6)-- (15,10);
\draw [line width=1pt,color=black] (16,10)-- (16,6);
\draw [line width=1pt,color=black] (16,6)-- (17,6);
\draw [line width=1pt,color=black] (18,6)-- (19,6);
\draw [line width=1pt,color=black] (19,6)-- (19,0);
\draw [line width=1pt,color=black] (21,0)-- (21,6);
\draw [line width=1pt,color=black] (21,6)-- (22,6);
\draw [line width=1pt,color=black] (22,6)-- (22,10);
\draw [line width=1pt,color=black] (23,10)-- (23,6);
\draw [line width=1pt,color=black] (23,6)-- (24,6);
\draw [line width=1pt,color=black] (25,6)-- (26,6);
\draw [line width=1pt,color=black] (26,6)-- (26,0);
\draw [line width=1pt,color=black] (16,10)-- (22,10);
\draw [line width=1pt,color=black] (23,10)-- (29,10);
\draw [line width=1pt,color=black] (3,9)-- (8,9);
\draw [line width=1pt,color=black] (4,8)-- (8,8);
\draw [line width=1pt,color=black] (9,9)-- (15,9);
\draw [line width=1pt,color=black] (16,9)-- (22,9);
\draw [line width=1pt,color=black] (28,11)-- (28,15);
\draw [line width=1pt,color=black] (29,10)-- (29,15);
\draw [line width=1pt,color=black] (23,9)-- (34,9);
\draw [line width=1pt,color=black] (28,15)-- (26,17);
\draw [line width=1pt,color=black] (26,17)-- (26,20);
\draw [line width=1pt,color=black] (26,20)-- (29,23);
\draw [line width=1pt,color=black] (29,23)-- (29,22);
\draw [line width=1pt,color=black] (29,15)-- (29,22);
\draw [line width=1pt,color=black] (29,19)-- (34,19);
\draw [line width=1pt,color=black] (29,18)-- (34,18);
\draw [line width=1pt,color=black] (34,23)-- (34,19);
\draw [line width=1pt,color=black] (34,18)-- (34,15);
\draw [line width=1pt,color=black] (34,23)-- (37,20);
\draw [line width=1pt,color=black] (37,20)-- (37,17);
\draw [line width=1pt,color=black] (37,17)-- (35,15);
\draw [line width=1pt,color=black] (34,15)-- (34,9);
\draw [line width=1pt,color=black] (35,15)-- (35,8);
\draw [line width=1pt,color=black] (0,4)-- (1.6,4);
\draw [line width=1pt,color=black] (1.6,4)-- (1.6,0);
\draw [line width=1pt,color=black] (3.4,0)-- (3.4,4);
\draw [line width=1pt,color=black] (3.4,4)-- (5,4);
\draw [line width=1pt,color=black] (7,2)-- (8.6,2);
\draw [line width=1pt,color=black] (8.6,2)-- (8.597289004768815,-0.00494417061539465);
\draw [line width=1pt,color=black] (12,2)-- (10.4,2);
\draw [line width=1pt,color=black] (10.4,2)-- (10.4,0);
\draw [line width=1pt,color=black] (7,4)-- (12,4);
\draw [line width=1pt,color=black] (14,4)-- (19,4);
\draw [line width=1pt,color=black] (14,2)-- (15.6,2);
\draw [line width=1pt,color=black] (15.6,2)-- (15.6,0);
\draw [line width=1pt,color=black] (19,2)-- (17.4,2);
\draw [line width=1pt,color=black] (17.4,2)-- (17.4,0);
\draw [line width=1pt,color=black] (21,4)-- (22.6,4);
\draw [line width=1pt,color=black] (26,4)-- (24.4,4);
\draw [line width=1pt,color=black] (24.4,4)-- (24.4,0);
\draw [line width=1pt,color=black] (22.6,4)-- (22.6,0);
\draw (27,19) node[anchor=north west] {T};
\draw (35,19) node[anchor=north west] {C};
\draw [line width=1pt,color=black] (9,8.006521194140134)-- (10,8);
\draw [line width=1pt,color=black] (11,8)-- (15,8.006521194140134);
\draw [line width=1pt,color=black] (17,6)-- (17,8);
\draw [line width=1pt,color=black] (16,8)-- (17,8);
\draw [line width=1pt,color=black] (18,6)-- (18,8);
\draw [line width=1pt,color=black] (22,8)-- (18,8);
\draw [line width=1pt,color=black] (24,6)-- (24,8);
\draw [line width=1pt,color=black] (23,8.023862255462648)-- (24,8);
\draw [line width=1pt,color=black] (25,6)-- (25,8);
\draw [line width=1pt,color=black] (25,8)-- (35,8);
\draw [line width=1pt,color=black] (34,18)-- (34,19);
\draw [line width=1pt,color=black] (1,6)-- (2,6);
\draw [line width=1pt,color=black] (3,6)-- (4,6);
\draw [line width=1pt,color=black] (22,6)-- (23,6);
\draw [line width=1pt,color=black] (24,6)-- (25,6);

\end{tikzpicture}
\end{document}

A: If geogebra doesn't have the option to fill colors, then you have to draw continuous closed paths to fill with the required color/pattern. You can draw grid lines to find the exact coordinates and draw these paths. Here is an example:

I used two sets of grid lines - one with spacing 1 (black) and other with spacing 5 (red). Using the following commands.
\draw[step=1.0,thin,gray] (-2,-1) grid (40,26);
\draw[step=5.0,red] (-2,-1) grid (40,26);

Using these grids, I have found the coordinates and filled a small portion. I hope you do the remaining with the help of this code. You can remove the grid lines in the final version. The complete code is given below.
\documentclass[10pt]{article}
\usepackage{pgfplots}

\pgfplotsset{compat=1.15}
\usepackage{mathrsfs}
\usetikzlibrary{arrows}
\pagestyle{empty}
\begin{document}

\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=0.35cm,y=0.35cm]
\draw[step=1.0,thin,gray] (-2,-1) grid (40,26);
\draw[step=5.0,red] (-2,-1) grid (40,26);
\clip(-2.6084198246281884,-1.775158614705993) rectangle (39.01911524098169,25.132373556978752);
\draw [line width=1pt,color=black] (0,0)-- (0,6);
\draw [line width=1pt,color=black] (0,6)-- (1,6);
\draw [line width=1pt,color=black] (2,6)-- (3,6);
\draw [line width=1pt,color=black] (3,6)-- (3,9);
\draw [line width=1pt,color=black] (4,6)-- (5,6);
\draw [line width=1pt,color=black] (5,0)-- (5,6);
\draw [line width=1pt,color=black] (4,6)-- (4,8);
\draw [line width=1pt,color=black] (7,0)-- (7,6);
\draw [line width=1pt,color=black] (8,6)-- (7,6);
\draw [line width=1pt,color=black] (8,6)-- (8,10);
\draw [line width=1pt,color=black] (9,6)-- (10,6);
\draw [line width=1pt,color=black] (10,6)-- (10,8);
\draw [line width=1pt,color=black] (11,6)-- (11,8);
\draw [line width=1pt,color=black] (11,6)-- (12,6);
\draw [line width=1pt,color=black] (12,6)-- (12,0);
\draw [line width=1pt,color=black] (9,6)-- (9,10);
\draw [line width=1pt,color=black] (1,6)-- (1,11);
\draw [line width=1pt,color=black] (2,6)-- (2,10);
\draw [line width=1pt,color=black] (2,10)-- (8,10);
\draw [line width=1pt,color=black] (1,11)-- (28,11);
\draw [line width=1pt,color=black] (9,10)-- (15,10);
\draw [line width=1pt,color=black] (14,0)-- (14,6);
\draw [line width=1pt,color=black] (15,6)-- (14,6);
\draw [line width=1pt,color=black] (15,6)-- (15,10);
\draw [line width=1pt,color=black] (16,10)-- (16,6);
\draw [line width=1pt,color=black] (16,6)-- (17,6);
\draw [line width=1pt,color=black] (18,6)-- (19,6);
\draw [line width=1pt,color=black] (19,6)-- (19,0);
\draw [line width=1pt,color=black] (21,0)-- (21,6);
\draw [line width=1pt,color=black] (21,6)-- (22,6);
\draw [line width=1pt,color=black] (22,6)-- (22,10);
\draw [line width=1pt,color=black] (23,10)-- (23,6);
\draw [line width=1pt,color=black] (23,6)-- (24,6);
\draw [line width=1pt,color=black] (25,6)-- (26,6);
\draw [line width=1pt,color=black] (26,6)-- (26,0);
\draw [line width=1pt,color=black] (16,10)-- (22,10);
\draw [line width=1pt,color=black] (23,10)-- (29,10);
\draw [line width=1pt,color=black] (3,9)-- (8,9);
\draw [line width=1pt,color=black] (4,8)-- (8,8);
\draw [line width=1pt,color=black] (9,9)-- (15,9);
\draw [line width=1pt,color=black] (16,9)-- (22,9);
\draw [line width=1pt,color=black] (28,11)-- (28,15);
\draw [line width=1pt,color=black] (29,10)-- (29,15);
\draw [line width=1pt,color=black] (23,9)-- (34,9);
\draw [line width=1pt,color=black] (28,15)-- (26,17);
\draw [line width=1pt,color=black] (26,17)-- (26,20);
\draw [line width=1pt,color=black] (26,20)-- (29,23);
\draw [line width=1pt,color=black] (29,23)-- (29,22);
\draw [line width=1pt,color=black] (29,15)-- (29,22);
\draw [line width=1pt,color=black] (29,19)-- (34,19);
\draw [line width=1pt,color=black] (29,18)-- (34,18);
\draw [line width=1pt,color=black] (34,23)-- (34,19);
\draw [line width=1pt,color=black] (34,18)-- (34,15);
\draw [line width=1pt,color=black] (34,23)-- (37,20);
\draw [line width=1pt,color=black] (37,20)-- (37,17);
\draw [line width=1pt,color=black] (37,17)-- (35,15);
\draw [line width=1pt,color=black] (34,15)-- (34,9);
\draw [line width=1pt,color=black] (35,15)-- (35,8);
\draw [line width=1pt,color=black] (0,4)-- (1.6,4);
\draw [line width=1pt,color=black] (1.6,4)-- (1.6,0);
\draw [line width=1pt,color=black] (3.4,0)-- (3.4,4);
\draw [line width=1pt,color=black] (3.4,4)-- (5,4);
\draw [line width=1pt,color=black] (7,2)-- (8.6,2);
\draw [line width=1pt,color=black] (8.6,2)-- (8.597289004768815,-0.00494417061539465);
\draw [line width=1pt,color=black] (12,2)-- (10.4,2);
\draw [line width=1pt,color=black] (10.4,2)-- (10.4,0);
\draw [line width=1pt,color=black] (7,4)-- (12,4);
\draw [line width=1pt,color=black] (14,4)-- (19,4);
\draw [line width=1pt,color=black] (14,2)-- (15.6,2);
\draw [line width=1pt,color=black] (15.6,2)-- (15.6,0);
\draw [line width=1pt,color=black] (19,2)-- (17.4,2);
\draw [line width=1pt,color=black] (17.4,2)-- (17.4,0);
\draw [line width=1pt,color=black] (21,4)-- (22.6,4);
\draw [line width=1pt,color=black] (26,4)-- (24.4,4);
\draw [line width=1pt,color=black] (24.4,4)-- (24.4,0);
\draw [line width=1pt,color=black] (22.6,4)-- (22.6,0);
\draw (27,19) node[anchor=north west] {T};
\draw (35,19) node[anchor=north west] {C};
\draw [line width=1pt,color=black] (9,8.006521194140134)-- (10,8);
\draw [line width=1pt,color=black] (11,8)-- (15,8.006521194140134);
\draw [line width=1pt,color=black] (17,6)-- (17,8);
\draw [line width=1pt,color=black] (16,8)-- (17,8);
\draw [line width=1pt,color=black] (18,6)-- (18,8);
\draw [line width=1pt,color=black] (22,8)-- (18,8);
\draw [line width=1pt,color=black] (24,6)-- (24,8);
\draw [line width=1pt,color=black] (23,8.023862255462648)-- (24,8);
\draw [line width=1pt,color=black] (25,6)-- (25,8);
\draw [line width=1pt,color=black] (25,8)-- (35,8);
\draw [line width=1pt,color=black] (34,18)-- (34,19);
\draw [line width=1pt,color=black] (1,6)-- (2,6);
\draw [line width=1pt,color=black] (3,6)-- (4,6);
\draw [line width=1pt,color=black] (22,6)-- (23,6);
\draw [line width=1pt,color=black] (24,6)-- (25,6);

\fill[red,opacity=0.5] (29,23) -- (26,20) -- (26,17) -- (28,15) --(28,11) -| (1,6) -- (2,6) -- (2,10) -| (29,23) ;
\end{tikzpicture}
\end{document}


text:
Q: BouncyCastle HMAC SHA1 I have the following code using BouncyCastle (dotnet version) to get a HMAC-SHA1 from a message.
I have this small library class:
public class HashingTools
{
    static string hmacKey = "81310910a060c5705c1d3cedf370bcf9";
    public static int HashSizeInBytes = 20;
    static KeyParameter keyParameter = null;
    private static HMac hmacInstance;

    static HashingTools()
    {
        hmacInstance = new HMac(new Sha1Digest());
        hmacInstance.Init(newKeyParameter(Encoding.UTF8.GetBytes(hmacKey)));
    }

    public static byte[] HashSha1(byte[] message)
    {
        byte[] result = new byte[hmacInstance.GetMacSize()];

        hmacInstance.BlockUpdate(message, 0, message.Length);
        hmacInstance.DoFinal(result, 0);

        return result;
    }
}

And I have a lot of messages going through this method, all using the same key: hmacKey, and I would like to speed it up as much as I can, and reuse as much as I can, still with respect to security parameters (randomness, freshness...).
If I try to reuse or parallellize the hmac instance, I get an "array out of bounds" exception inside Org.BouncyCastle.Crypto.Macs.Hmac.BlockUpdate.
I've created this unittest for reproduction (1 or 2 parallel hash functions goes fine, 100 goes wrong):
[Test]
public void TestBulkHashing()
{
    var messages = new List<byte[]>();

    foreach (var index in Enumerable.Range(0, 100))
    {
        var buffer = new byte[4096];
        Random r = new Random();
        r.NextBytes(buffer);

        messages.Add(buffer);
    }

    Parallel.ForEach(messages, m =>
    {
        HashingTools.HashSha1(m);
    });
}

A: As correctly surmised by @dlatikay, this is a synchronization mistake. Bouncycastle's classes are not thread-safe unless they explicitly say it is.
If you modify your HashSha1 method to explicitly synchronize threads you will not get the exception:
public static byte[] HashSha1(byte[] message) {
    byte[] result = new byte[hmacInstance.GetMacSize()];
    lock(hmacInstance) {
        hmacInstance.BlockUpdate(message, 0, message.Length);
        hmacInstance.DoFinal(result, 0);
    }

    return result;
}

As to your question about optimization, Bouncycastle already pre-computes the part of the computation that involves the key. When you call DoFinal(...) the internal state is reset to this pre-computed value so you do not need to call Init() again for the next HMac if you use the same key. Your code already takes advantage of this optimization so I don't think there is more you can do unless you want to write your own hashing code.


text:
Q: Invalid Scope:basic_info. Use public_profile,user_friends instead I am using "Sign in with facebook" functionality in my iOS application.
When i do select "Sign in with facebook" option application is redirected to safari and shows facebook login form. When i complete with email and password and press login,i am getting error like "Invalid Scope:basic_info. Use public_profile,user_friends instead." from my iOS application. I am using Facebook SDK.
Thanks in advance

A: You are using basic_info in scope parameter.To get public informations use public_profile permission instead.


text:
Q: Common-Source Stage with Diode-Connected Load I have a question about the small-signal gain in a common-source stage with diode connected load.

I understand there are multiple equations for gm and the one you use depends on what relationship you are looking to investigate
I'm finding it hard to figure out which one to use.
As you can see from above, I get a different small-signal gain depending on what equation I use. Why?
Are they the same equation since the overdrive of M2 is completely self generated depending on how much current and overdrive M1 has?
Derivation of small-signal gain:


text:
Q: how to plot a pie of color list hi i have a dict with 3-int-tuple representing color (as key) and an int representing the numbers of occurences of that color in an image (as value)
for exemple, this is a 4x4 pixels image with 3 colors:
{(87, 82, 44): 1, (255, 245, 241): 11, (24, 13, 9): 4}
i want to plot a pie chart of list [1,11,4] in which each slice of the piechart is colored with the right color.. how can i do?

A: Update: the other answer from Paul is much better but there's not really any point in me just editing my original answer until it's essentially the same :)  (I can't delete this answer because it's accepted.)
Does this do what you want?  I just took an example from the matplotlib documentation and turned your data into parameters that pie() expects:
# This is a trivial modification of the example here:
# http://matplotlib.sourceforge.net/examples/pylab_examples/pie_demo.html

from pylab import *

data = {(87, 82, 44): 1, (255, 245, 241): 11, (24, 13, 9): 4}

colors = []
counts = []

for color, count in data.items():
    colors.append([float(x)/255 for x in color])
    counts.append(count)

figure(1, figsize=(6,6))

pie(counts, colors=colors, autopct='%1.1f%%', shadow=True)
title('Example Pie Chart', bbox={'facecolor':'0.8', 'pad':5})

show()

The result looks like this:

A: Mark beat me by 5 minutes, so points should go to him, but here's my (nearly identical, but more terse) answer anyway:
from matplotlib import pyplot

data = {(87, 82, 44): 1, (255, 245, 241): 11, (24, 13, 9): 4}
colors, values = data.keys(), data.values()
# matplotlib wants colors as 0.0-1.0 floats, not 0-255 ints
colors = [tuple(i/255. for i in c) for c in colors]
pyplot.pie(values, colors=colors)
pyplot.show()


text:
Q: Error "Could not load file" but I didn't ask for it Update: I recompiled for x86, and now it DOES work. but I still need to know what happened here, and why I need to recompile all my .net apps to x86... I never used oracle and I don't plan to do so in the future. why is it making me problems?
Since this morning I can't run all my .net programs that use the entityframework-v5 to connect to msSqlServer, I pasted the stack error below.
I tried the same files from an other pc on the network, it does work correctly. so I suspected its a windows-update that did the trouble overnight, So I did a system restore, still the same issue.
Now I ran out of ideas.. I don't use oracle, and I don't have any reference to it. and as I said the very same files in the same folder, worked yesterday on my pc, and they also work today from other pc's on the network.
    System.BadImageFormatException: Could not load file or assembly 'System.Data.OracleClient.dll' or one of its dependencies.  is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)
   at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
   at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
   at System.Type.GetType(String typeName)
   at System.Data.Common.DbProviderFactories.IncludeFrameworkFactoryClasses(DataTable configDataTable)
   at System.Data.Common.DbProviderFactories.Initialize()
   at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
   at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)

A: This question indicates that you have installed a 32-bit version of the Oracle Client Components on your machine.
Your stack trace shows the following:

*

*You trigger an Entity Framework operation.

*Entity Framework wants to read your connection string.

*It needs to initialize all database providers installed on your system.

*It finds Oracle and tries to load it.

*It fails, because the dependencies don't support 64 bit.

You should either uninstall Oracle Client completely after making sure that no other software depends on it, or additionally install the 64 bit version as stated in the answer linked above.

A: I don't really have a answer to my problem.. I spent a few days trying to solve it, with no success.
I reinstalled windows altogether, and that fixed the issue.
I really hope it doesn't happen again, installing windows (and reinstall all programs) is not something I want to do frequently...


text:
Q: Angular HttpClient causing component disappearance I am trying to set up a login system using angular. To do so, I use the HttpClient. I have set up a user service and a login form using this service as a provider. If the user service uses HttpClient as a provider, components using the user service as a provider don't appear, otherwise they do. Using a router, I am automatically redirected to my previous location, and defining one as main component (see "app.component.html") causes nothing to appear.
I used dependency injection to pass providers, and I have defined "HttpClientModule" and "UserService" as providers in my "app.module.ts" file. There is no console error. Everything seems okay according to every tutorial I saw online, if you could help me figure out what's wrong I would really appreciate it.
Here are all the files related to this problem :
  providers: [
    HttpClientModule,
    CookieService,
    UserService
  ],

app.module.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
import { CookieService } from 'ngx-cookie-service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private srvLogin: UserService,
      private router: Router,
      public activatedRoute: ActivatedRoute,
      private cookieService: CookieService) {
  }

  ngOnInit() {}
}

login.component.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { User } from '../class/User';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private http : HttpClient) {}
  //constructor(){} displays the components perfectly
  insertUser(user : User){
    this.http.post<User>('http://localhost:3000/users', user);
  }
}

user.service.ts
<app-login></app-login>

app.component.html


text:
Q: Install cplexAPI C++ library in CLion C++11 and gets error with ld.exe I'm trying to use cplexAPI C++ in a CLion project with C++11 on Windows 10. I have looked at several posts related to this question (e.g. config CMakeLists.txt, install MinG64) and I have managed to configure my CMakeLists.txt in the following way:
cmake_minimum_required(VERSION 3.15)
project(VRP_PRP)

add_executable(VRP_PRP main.cpp held-karp.h held-karp.cpp)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}  -m64 -O -fPIC -fexceptions -DNDEBUG -DIL_STD -std=c++11")

include_directories(/biblio/cplex/include/)
include_directories(/biblio/cplex/include/ilcplex)
include_directories(/biblio/concert/include)
include_directories(/biblio/concert/include/ilconcert)

target_link_libraries(VRP_PRP PUBLIC /biblio/cplex/lib/x64_windows_msvc14/stat_mda/cplex12100.lib)
target_link_libraries(VRP_PRP PUBLIC /biblio/cplex/lib/x64_windows_msvc14/stat_mda/ilocplex.lib)
target_link_libraries(VRP_PRP PUBLIC /biblio/concert/lib/x64_windows_msvc14/stat_mda/concert.lib)

target_link_libraries(VRP_PRP PUBLIC "-lilocplex -lconcert -lcplex -lm -lpthread")

it happens that when building my project it throws the following errors:
[ 33%] Linking CXX executable VRP_PRP.exe
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lilocplex
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lconcert
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lcplex
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\VRP_PRP.dir\build.make:105: VRP_PRP.exe] Error 1
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:75: CMakeFiles/VRP_PRP.dir/all] Error 2
mingw32-make.exe: *** [Makefile:83: all] Error 2

and by including the libraries (#include <ilcplex/ilocplex.h>) in my main.cpp it can't find them.
I have tried using 2 ways to link libraries in my CMakeLists.txt:
a) #set (target_link_options "-lilocplex -lconcert -lcplex -lm -lpthread  -framework CoreFoundation -framework IOKit -std=c++11")
b) #target_link_libraries(VRP_PRP PUBLIC "-lilocplex -lconcert -lcplex -lm -lpthread")
Any help or idea will be appreciated.
Thanks.

A: My solution.
I installed Visual Studio 2017 Community together with CPLEX 12.9 Academic Version, then I opened the examples which is in:

C:\Program Files\IBM\ILOG\CPLEX_Studio129\cplex\examples

and they already come with the configuration done.