text:
Q: WSO2 APIM 2.0 Clustering deployment with traffic manager issue I deployed 2 keymanager nodes, 2 pub-store nodes, 1 gateway manager node and 2 gateway worker nodes, 1 traffic manager node in one server, and deployed nginx for load balance. Note, i deployed 2 keymanager nodes, and due to i encountered error when EnableAdvanceThrottling=false, so i started to deploy 1 traffic manager and set EnableAdvanceThrottling=true. but it seems all nodes have exceptions there except traffic manager node.
both keymanager & pub-store nodes report below error:
TID: [-1234] [] [2016-08-31 02:19:43,624] FATAL {org.wso2.carbon.mediation.initializer.ServiceBusInitializer} -  Failed to initialize ESB due to a fatal error {org.wso2.carbon.mediation.initializer.ServiceBusInitializer}
java.lang.ExceptionInInitializerError
    at org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisherPool.getInstance(ThrottleDataPublisherPool.java:68)
    at org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisher.<init>(ThrottleDataPublisher.java:67)
    at org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler.<init>(ThrottleHandler.java:131)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at org.apache.synapse.config.xml.rest.APIFactory.defineHandler(APIFactory.java:162)
    at org.apache.synapse.config.xml.rest.APIFactory.createAPI(APIFactory.java:103)
    at org.apache.synapse.config.xml.SynapseXMLConfigurationFactory.defineAPI(SynapseXMLConfigurationFactory.java:405)
    at org.apache.synapse.config.xml.MultiXMLConfigurationBuilder.createAPIs(MultiXMLConfigurationBuilder.java:581)
    at org.apache.synapse.config.xml.MultiXMLConfigurationBuilder.getConfiguration(MultiXMLConfigurationBuilder.java:153)
    at org.apache.synapse.config.SynapseConfigurationBuilder.getConfiguration(SynapseConfigurationBuilder.java:100)
    at org.apache.synapse.Axis2SynapseController.createSynapseConfiguration(Axis2SynapseController.java:471)
    at org.wso2.carbon.mediation.initializer.CarbonSynapseController.createSynapseConfiguration(CarbonSynapseController.java:180)
    at org.apache.synapse.ServerManager.start(ServerManager.java:179)
    at org.wso2.carbon.mediation.initializer.ServiceBusInitializer.initESB(ServiceBusInitializer.java:452)
    at org.wso2.carbon.mediation.initializer.ServiceBusInitializer.activate(ServiceBusInitializer.java:196)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:107)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:861)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:819)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:771)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:214)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:433)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:451)
    at org.wso2.carbon.inbound.endpoint.persistence.service.InboundEndpointPersistenceServiceDSComponent.activate(InboundEndpointPersistenceServiceDSComponent.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:107)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:861)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:819)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:771)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:214)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:433)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:451)
    at org.wso2.carbon.core.init.CarbonServerManager.initializeCarbon(CarbonServerManager.java:514)
    at org.wso2.carbon.core.init.CarbonServerManager.start(CarbonServerManager.java:219)
    at org.wso2.carbon.core.internal.CarbonCoreServiceComponent.activate(CarbonCoreServiceComponent.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:107)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:861)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:819)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:771)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:214)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:433)
    at org.eclipse.equinox.http.servlet.internal.Activator.registerHttpService(Activator.java:81)
    at org.eclipse.equinox.http.servlet.internal.Activator.addProxyServlet(Activator.java:60)
    at org.eclipse.equinox.http.servlet.internal.ProxyServlet.init(ProxyServlet.java:40)
    at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.init(DelegationServlet.java:38)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5318)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5610)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1572)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1562)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisherPool.<init>(ThrottleDataPublisherPool.java:50)
    at org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisherPool.<init>(ThrottleDataPublisherPool.java:34)
    at org.wso2.carbon.apimgt.gateway.throttling.publisher.ThrottleDataPublisherPool$ThrottleDataPublisherPoolHolder.<clinit>(ThrottleDataPublisherPool.java:62)
    ... 101 more

and gateway node report below error:
TID: [-1234] [] [2016-08-31 02:33:46,553]  WARN {org.wso2.carbon.apimgt.impl.internal.APIManagerComponent} -  Exception occurred while creating JMS Event Adapter. Request Blocking may not work properly {org.wso2.carbon.apimgt.impl.internal.APIManagerComponent}
org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException: Output Event Adapter not created as no adapter factory is registered with type jms
    at org.wso2.carbon.event.output.adapter.core.internal.CarbonOutputEventAdapterService.create(CarbonOutputEventAdapterService.java:89)
    at org.wso2.carbon.apimgt.impl.internal.APIManagerComponent.configureJMSPublisher(APIManagerComponent.java:546)
    at org.wso2.carbon.apimgt.impl.internal.APIManagerComponent.activate(APIManagerComponent.java:202)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:107)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:861)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:819)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:771)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:214)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:433)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:451)
    at org.wso2.carbon.core.init.CarbonServerManager.initializeCarbon(CarbonServerManager.java:514)
    at org.wso2.carbon.core.init.CarbonServerManager.start(CarbonServerManager.java:219)
    at org.wso2.carbon.core.internal.CarbonCoreServiceComponent.activate(CarbonCoreServiceComponent.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:107)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:861)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:819)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:771)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:214)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.registerService(BundleContextImpl.java:433)
    at org.eclipse.equinox.http.servlet.internal.Activator.registerHttpService(Activator.java:81)
    at org.eclipse.equinox.http.servlet.internal.Activator.addProxyServlet(Activator.java:60)
    at org.eclipse.equinox.http.servlet.internal.ProxyServlet.init(ProxyServlet.java:40)
    at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.init(DelegationServlet.java:38)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5318)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5610)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1572)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1562)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

and
TID: [-1] [] [2016-08-31 02:34:46,668] ERROR {org.wso2.carbon.apimgt.gateway.throttling.util.KeyTemplateRetriever} -  Exception when retrieving throttling data from remote endpoint  {org.wso2.carbon.apimgt.gateway.throttling.util.KeyTemplateRetriever}
Unexpected character (<) at position 0.
    at org.json.simple.parser.Yylex.yylex(Unknown Source)
    at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.wso2.carbon.apimgt.gateway.throttling.util.KeyTemplateRetriever.retrieveKeyTemplateData(KeyTemplateRetriever.java:100)
    at org.wso2.carbon.apimgt.gateway.throttling.util.KeyTemplateRetriever.loadKeyTemplatesFromWebService(KeyTemplateRetriever.java:111)
    at org.wso2.carbon.apimgt.gateway.throttling.util.KeyTemplateRetriever.run(KeyTemplateRetriever.java:54)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

I'm following APIM 2.0 clustering, what's possible config error?

A: Please verify whether you have comment out the following section in api-manager.xml file to prevent warning messages during startup of the gateway node [1].
<JMSEventPublisherParameters>
....
</JMSEventPublisherParameters>

[1] https://docs.wso2.com/display/CLUSTER44x/Clustering+API+Manager+2.0.0


text:
Q: pynput is installed with pip, but `import pynput` in PyCharm can't find it I installed the pynput Python package with pip. I got this error in PyCharm when trying to import pynput with import pynput.
C:\Users\User\PycharmProjects\keyloger.py\Scripts\python.exe "C:/Users/User/Desktop/hello world.py"
Traceback (most recent call last):
  File "C:/Users/User/Desktop/hello world.py", line 1, in <module>
    import pynput
ModuleNotFoundError: No module named 'pynput'

Process finished with exit code 1

Even though pynput is installed, import pynput in PyCharm can't find it.

A: By default, PyCharm uses pip to manage project packages. To manage Python packages for the project interpreter, select the Project Interpreter page in the project Settings/Preferences or select Interpreter Settings in the Python Interpreter widget.
Select File -> Settings -> Project: project_name -> Project Interpreter. Click the + button which is marked by the mouse cursor in the screenshot to install Python packages in the selected project.

Search for any Python package. Select it and click the Install Package button in the lower left corner of the Available Packages window to install it. PyCharm will automatically choose the package version for you or you can check the checkbox to the left of Specify version and select the package version from the Specify version dropdown menu.
As you can see in the above screenshot pynput is not in the list of available packages, so you need to follow the instructions after the 2nd screenshot to use the pynput package that you already installed with pip instead of reinstalling pynput in PyCharm.

Whenever you install a Python package specifically for a project, PyCharm adds the packages that were installed to the project's venv directory where PyCharm will find them automatically.
PyCharm does not automatically find your globally installed Python packages unless the project has been configured to find them. To do this select the Inherit global-site packages option when you create a new project.
Select File -> New Project to create a new project. Click the triangle marked by the mouse cursor in the below screenshot to show the new project's options.

Then check the Inherit global-site packages checkbox and click the  Create  button in the lower right corner of the Create Project window.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does a*ad$ match the string "ad"? Shouldn't the a* of the following regex match with the a in the string, which only leaves d so the ad$ shouldn't match, right? Why is this true?
pattern = r"a*ad$"

print(re.search(pattern, "ad"))

A:
Shouldn't the a* match with the a in the string?

No, because * means a can match zero or more times, so the '' empty string also matches that expression. That leaves 'ad' after the initial empty string to match for the remainder of the expression.
A regex will consider both options here (both '', the empty string, and 'a' satisfy the a* pattern).
Use a+ if you wanted the pattern to match at least once.


text:
Q: Take a picture and reduce the quality In my Android app, I have a button to take a picture like this :
button_photo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "fname_" +
                    String.valueOf(System.currentTimeMillis()) + ".jpg"));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    });

and in my ActivityResult :
Intent intent = new Intent(this, UploadPicture.class);
            intent.putExtra("URI", imageUri.toString());
            startActivity(intent);

I would like to reduce the quality of my picture (I want a picture lighter for the server) before starting the activity of upload.
How can I do that ?
Thanks

A: Convert the image into Bitmap before uploading and compress the bitmap set the quality of the image and write it to the correct path.The quality of the image can be changed and hope this will help you to reduce the size of the image.
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
compress method is defined as
public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
You can take help from this also Bitmap.compress


text:
Q: In SQL Alchemy, how do I include a field from a joined table in fields list? Take these table definitions:
class Device(Base):
    __tablename__ = 'devices'

    id = Column(Integer, primary_key = True)
    imei = Column(String(19))

class Position(Base):
    __tablename__ = 'positions'

    id = Column(Integer, primary_key = True)
    device_id = Column(Integer, ForeignKey('devices.id'))
    latitude = Column(Float(8))
    longitude = Column(Float(8))
    other = Column(String(512))

    device = relationship('Device', foreign_keys = [device_id])

I can query for specific fields of a position like this:
>>> pos = session.query(Position.latitude, Position.longitude).first()
>>> pos
(-22.929775, -43.23409)
>>>

I can get long, lat and imei like this:
>>> pos = session.query(Position).first()
>>> pos.latitude, pos.longitude, pos.device.imei
(-22.929775, -43.23409, '123456789')
>>>

How can I query for latitude, longitude and device.imei (like in 1st example) without having to select all other data that comes with it (like in 2nd example)?

A: I think I've found the answer:
>>> session.query(Position.latitude, Position.longitude, Device.imei).join('device').first()
(-22.929775, -43.23409, '356891051241497')
>>>

The funny thing is that order matters. This one doesn't work:
>>> session.query(Device.imei, Position.latitude, Position.longitude).join('device').first()
Traceback (most recent call last):
  File "/Users/leandro/test/env/lib/python3.4/site-packages/sqlalchemy/orm/base.py", line 370, in _entity_descriptor
    return getattr(entity, key)
AttributeError: type object 'Device' has no attribute 'device'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/leandro/test/env/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 1724, in join
    from_joinpoint=from_joinpoint)
  File "<string>", line 2, in _join
  File "/Users/leandro/test/env/lib/python3.4/site-packages/sqlalchemy/orm/base.py", line 191, in generate
    fn(self, *args[1:], **kw)
  File "/Users/leandro/test/env/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 1798, in _join
    descriptor = _entity_descriptor(left_entity, onclause)
  File "/Users/leandro/test/env/lib/python3.4/site-packages/sqlalchemy/orm/base.py", line 374, in _entity_descriptor
    (description, key)
sqlalchemy.exc.InvalidRequestError: Entity '<class 'test.Device'>' has no property 'device'
>>>


text:
Q: CodeIgniter with PHPExcel fatal error cannot redeclare class IOFactory I'm trying to use PHPExcel with CodeIgniter.
My problem is when i want to use this method below, I got PHP Fatal Error : Cannot redeclare class IOFactory

If you're uncertain of the filetype, you can use the IO Factory's identify() method to identify the reader that you need, before using the createReader() method to instantiate the reader object.

Below is my code:
$this->load->library('PHPExcel');

$this->load->library('PHPExcel/IOFactory');

$path = $upload_data['full_path'];

$inputFileType = PHPExcel_IOFactory::identify($path);

$objReader = PHPExcel_IOFactory::createReader($inputFileType);

$objPHPExcel = $objReader->load($path);

$objWorksheet = $objPHPExcel->getActiveSheet();

I try to find if the IOFactory class already created somewhere but cannot find it.
FYI, im using the latest version of CodeIgniter (2.1) and PHPExcel (1.7.6) at this time of writing.

A: No need to write
$this->load->library('PHPExcel');

Just start with
$this->load->library('PHPExcel/IOFactory');

Edited :::
In my project I have done by these way,
Step1:
in libraries\PHPExcel\Reader
Rename Excel5.php to PHPExcel_Reader_Excel5.php
Step2:
$filePath = $dir.$uploadedfile;
$objReader = $this->load->library('PHPExcel/Reader/PHPExcel_Reader_Excel5', $filePath);
$objReader = new PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load($filePath);
$rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
$sheet = $objPHPExcel->getActiveSheet();
$maxRowIndex = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$maxColIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

A: all
I am using PHPExcel to upload data from Excel in Mysql with CI and grocery_CRUD. This is my way:
// My Excel CI Lib
<?php

if (!defined('BASEPATH'))     exit('No direct script access allowed');
require_once APPPATH . "/third_party/PHPExcel/IOFactory.php";
/*
 * PHPExcel Lib For CI
 *
 * Class Excel
 *
 * Using PHP Excel Class
 */
class Lib_excel extends PHPExcel_IOFactory {
    public function __construct() {
    }
}
?>

//My Excel CI Model
<?php
// My CI Model for handling all Excel methods
if (!defined('BASEPATH'))     exit('No direct script access allowed');
// Class Model extend with CI Model
class Mod_excel extends CI_Model {
    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }
    /**
     * Read data from Excel file
     *

     * @input string $excelFileName
     * @input string $columnName (starting column point)
     * @input string $startRow (starting column point)
     * @return array $cellValues
     *
     * @example code
     *  $excelFileName = $_FILES['uploadedfile']['tmp_name'];
     *  $columnName = 'B';
     *  $startRow = '2';
     *  $cellValues = readWithExcel($excelFileName, $columnName, $startRow);
     *  $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($cellValues));
     *  foreach($iterator as $value) {
     *      $insert_data[] = $value;
     *  }
     */
    function readWithExcel($excelFileName, $columnName, $startRow) {
        //load our new Lib Excel library as object excel
        $this->load->library('Lib_excel', null, 'excel');
        // load excel file
        $objPHPExcel  = $this->excel->load($excelFileName);
        // get active sheets
        $objWorksheet = $objPHPExcel->getActiveSheet();
        // get highest row column
        $lastRow      = $objWorksheet->getHighestRow();
        // check cell value empty or not
        for ($i = $startRow; $i < $lastRow; $i++) {
            $colB = $objPHPExcel->getActiveSheet()->getCell($columnName . $i)->getValue();
            if ($colB == NULL || $colB == '') {
                die('The Cell' . ' B' . $i . ' is empty. Please, remove or fill with data');
            }
        }
        // get excel data with range e.g. (B2:B56)
        $cellValues = $objPHPExcel->getActiveSheet()->rangeToArray("$columnName$startRow:$columnName$lastRow");
        // return all data as array
        return $cellValues;
    }
}
?>

// My Controller to call method
<?php
// My Admin Controller with grocery CRUD createCouponCode method (URL: admin/createCouponCode)
if (!defined('BASEPATH'))     exit('No direct script access allowed');
class Admin extends CI_Controller {
    /**
     * Just construct method to load
     */
    function __construct() {
        parent::__construct();
        // Load Model excel and use as object ModExcel
        $this->load->model('Mod_excel', 'ModExcel', true);
        // Load CRUD lib
        $this->load->library('grocery_CRUD');
    }
    /**
     * Upload Coupon Code from Excel
     */
    public function createCouponCode() {
        $crud = new grocery_CRUD();
        $crud->set_table('coupon_code');
        $crud->fields('coupon_no');
        $crud->columns('coupon_no');
        $crud->set_subject('Coupon');
        $crud->required_fields('coupon_no');
        $crud->set_field_upload('coupon_no', '../public/uploads/');
        $crud->callback_before_upload(array(
            $this,
            '_excel_uploaded_file'
        ));
        $output = $crud->render();
        $this->_example_output($output);
    }
    /**
     * Call back Function form CRUD Upload
     * @param array $files_to_upload
     * @param array $field_info
     * @return string
     */
    function _excel_uploaded_file($files_to_upload = array(), $field_info = array()) {
        $insert_data   = array();
        $ext           = '';
        $file_tmp_path = '';
        foreach ($files_to_upload as $value) {
            $ext           = pathinfo($value['name'], PATHINFO_EXTENSION);
            $file_tmp_path = $value['tmp_name'];
        }
        $allowed_formats = array(
            "xlsx"
        );
        if (in_array($ext, $allowed_formats)) {
            $excelFileName = $file_tmp_path;
            $columnName    = 'B';
            $startRow      = '2';
            $cellValues    = $this->ModExcel->readWithExcel($excelFileName, $columnName, $startRow);
            $iterator      = new RecursiveIteratorIterator(new RecursiveArrayIterator($cellValues));
            foreach ($iterator as $value) {
                $insert_data[] = array(
                    'coupon_no' => $value
                );
            }
            $this->output->enable_profiler(TRUE); //Turns on CI debugging
            $this->db->insert_batch('coupon_code', $insert_data);
            echo ($status) ? true : false;
        } else {
            return 'Error: Wrong file format. Use Excel 2007 format';
        }
    }
}
?>

// My Folder where I put PHPExcel Lib in CI

A: You could try this one and it works for me:
$filePath = "uploads/import/test.xlx";
$this->load->library('PHPExcel');
$objReader = new PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load($filePath);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);


text:
Q: Draw shadow around images In my application I am merging different image files which would be markers for my google maps application. Here is how the marker looks afterwards
This is how I achieve it
foreach (ImageInfo imageInfo in files)
{

System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageInfo.path);

g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

if (imageInfo.position == ImagePosition.Base)
{
    if (imageInfo.isZoomed)
        isZoomed = true;
    g.DrawImage(image, new System.Drawing.Rectangle(0, 0, image.Width, image.Height));
}
else if (imageInfo.position == ImagePosition.TopRight)
{
    g.DrawImage(image, new System.Drawing.Rectangle(image.Width + 70, 10, 200, 200));
}

else if (imageInfo.position == ImagePosition.TopLeft)
{
    g.DrawImage(image, new System.Drawing.Rectangle(10, -10, 200, 200));
}

else if (imageInfo.position == ImagePosition.BottomRight)
{
    g.DrawImage(image, new System.Drawing.Rectangle(image.Width + 70, image.Height - 40, 200, 200));
}

}

The only thing I am missing is a shadow around the marker, here you can see what I am talking about . There is a slight shadow around the marker in the above image.
Anyone knows how to achieve it?

A: This is how I solved it finally
Bitmap shadow = (Bitmap)finalImage.Clone();
for (int y = 0; y < shadow.Height; y++)
{
for (int x = 0; x < shadow.Width; x++)
{
    var color = shadow.GetPixel(x, y);

    color = Color.FromArgb((int)((double)color.A * 0.2), 0, 0, 0);

    shadow.SetPixel(x, y, color);

}
}

var finalComposite = new Bitmap(finalImage.Width, finalImage.Height, PixelFormat.Format32bppArgb);

using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalComposite))
{
g.Transform = new Matrix(new Rectangle(0, 0, shadow.Width, shadow.Height), new Point[]{
    new Point(50,20),
    new Point(width+50, 20),
    new Point(0, height)
});

g.DrawImageUnscaled(shadow, new Point(0, 0));

g.ResetTransform();
g.DrawImageUnscaled(finalImage, new Point(0, 0));
}


text:
Q: Specifying doc-id and plot-id (i.e. the URL) for output_server() I would like to be able to specify the URL where output_server publishes my app in bokeh-server (as an example, I am trying to do this in the animate_widgets.py example that Christine Doig presented in Scipy2015).
I am already running bokeh-server in a separate terminal. When I run my app with output_server, is there any way to specify the URL where the app will be rendered?
It seems to currently follow the syntax:
 http://localhost:5006/bokeh/doc/some-doc-id/some-plot-id

but I don't see the ability to specify those fields <doc-id> and <plot-id> with output_server (documentation for output_server below).
Is there  any way to specify where exactly (URL-wise) I want the app to be published?

Note that just entering the string http://localhost:5006/bokeh/doc/some-doc-id/some-plot-id as URL for output_server() does not work.

A: The short answer is not really. Those URLs are meant to be unambiguous and to avoid collisions. Letting users choose their own URLs would be fairly unworkable in the general multi-user scenario. But that's OK, what you really probably want to is to embed a Bokeh server plot in your own document (as opposed to just linking to the bare page that has the plot and nothing else). This you can accomplish easily with server_session:
https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#bokeh-applications
Edit: I won't actually say its impossible, but it's far enough outside normal usage that I don't know offhand how you could accomplish it, and even if you could it would probably not be advisable for several reasons.


text:
Q: TSQL: Flag 3 days, starting from 3 workdays ago My aim is to build a flag, indicating the last 3 days, with the condition that 3 workdays must have passed.
Under the assumption that todays date is the 27th of february:
I have the following input:
input:
date              workday
----------        -------
2017-02-27        1
2017-02-26        0
2017-02-25        0
2017-02-24        1
2017-02-23        1
2017-02-22        1
2017-02-21        1
2017-02-20        1
2017-02-19        1
2017-02-18        1
2017-02-17        0

Desired output:
date              workday    flag
----------        -------    ----
2017-02-27        1          0
2017-02-26        0          0
2017-02-25        0          0
2017-02-24        1          0
2017-02-23        1          0
2017-02-22        1          1
2017-02-21        1          1
2017-02-20        1          1
2017-02-19        1          0

I have been working with several ideas, but nothing good.

A: One option here, though perhaps not the most optimal, would be to use a correlated subquery to tally workdays for the two previous days and current day.  In cases where this tally be 3, we print 1 as the flag, otherwise we print 0.
WITH cte AS (
    SELECT date, workday,
           (SELECT SUM(t2.workday) FROM yourTable t2
            WHERE t2.date BEWTEEN DATEADD(day, -2, t1.date) AND t1.date) AS w_sum
    FROM yourTable t1
)

SELECT t.date, t.workday,
       CASE WHEN t.w_sum = 3 THEN 1 ELSE 0 END AS flag
FROM cte t

Note that this answer assumes that you have continuous data, day by day.  If not, then we have to consider how to even handle breaks in a sequence of days.


text:
Q: Django Rest Framework: Using destroy with other params than pk I was wondering if it's possible to use destroy with other params on a GenericViewSet.
Like this : curl DELETE https://localhost/api/custom-url?first_param=123&second_param=1
instead of this : curl DELETE https://localhost/api/custom-url/1
I tried overriding destroy method but it didn't work:
class ExampleViewSet(mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         mixins.CreateModelMixin,
                         mixins.DestroyModelMixin,
                         viewsets.GenericViewSet):

queryset = My_model.objects.all()
serializer_class = MySerializerSerializer

def destroy(self, request, *args, **kwargs):
    first_param = kwargs.get('user_id')
    second_param = kwargs.get('season_id')

    try:
        instance = My_model.objects.get(first_field=first_param, second_field=second_param)
    except ObjectDoesNotExist:
        return Response(status=status.HTTP_304_NOT_MODIFIED)
    self.perform_destroy(instance)
    return Response({'message':'yes!!!'}, status=status.HTTP_200_OK)


text:
Q: How to clear the command line in Octave? In Octave, when typing command in the command line, sometimes I need to erase the whole line and restart a new command. In Matlab, erasing the text would be done with the ESC key. In Octave this does not work. The only way I found to discard the input text is using Ctrl-C. This works, but it is ugly, as it leaves remains on the screen.
Is there a key combination to clear the line in Octave?

A: There are several clearing shortcuts defined:

*

*Meta-D: clear the next word1

*Ctrl-K: clear to the end of the line

*Ctrl-U: clear the whole line

*Ctrl-L: clear the line and the screen

See more examples in the octave command-line-editing section of the manual.
For historical reasons Ctrl-U is usually controlled by your terminal rather than octave, although octave also supports it. You can test this with stty kill undef (restore with stty kill '^U').
1 Meta is often bound to the Win key or the Alt key. If not hit the Esc key first and then the character that needs to be "metaified".

A: to clear the command window type:
clc

A: Ctrl-A: go to beginning of line.
Ctrl-K: kill all characters starting at the cursor.


text:
Q: Angular 8 Kendo Grid: Dropdown not showing selected Item in Edit mode Here's a gif showing the issue:

You can see when the 'Edit' button is hit, it enables edit mode. However the dropdown is not displaying the selected value. The dropdown has items, they can be selected, and then the selected item is displayed.
Here's the html structure for the single cell:
<kendo-grid-column field="Status" title="Status" width="100">
              <ng-template kendoGridCellTemplate let-dataItem>
                {{ statusGrid(dataItem.Status)?.text }}
              </ng-template>
              <ng-template kendoGridEditTemplate
                  let-dataItem="dataItem"
                  let-formGroup="formGroup">
                <kendo-dropdownlist
                    [data]="statusDropdown"
                    (valueChange)="onStatusChange($event, formGroup)"
                    textField="text"
                    valueField="value"
                    [valuePrimitive]="true"
                    [formControl]="formGroup.get('Status')">
                    <ng-template kendoDropDownListItemTemplate let-dataItem>
                      {{ dataItem.text }}
                    </ng-template>
                </kendo-dropdownlist>
            </ng-template>
        </kendo-grid-column>

The Javascript behind it was copy/pasted from
Online Demo


text:
Q: Different behavior of the Klein-Gordon equation By Fourier transform, it is well known that the Klein-Gordon, wave and Schrödinger flows are $e^{it\sqrt{1-\Delta}}$, $e^{it \sqrt{-\Delta}}$ and $e^{it\Delta}$, respectively.
I saw a phrase "the Klein-Gordon flow behaves like the wave flow at high frequency and the Schrödinger flow at low frequency."
I guess it is true at high frequency because its Fourier transform, $e^{it\sqrt{1+|\xi|^2}}$ and $e^{it|\xi|}$ are similar when $|\xi|$ is large (so we can ignore $1$). But, at low frequency, $|\xi|^2$ and $\sqrt{1+|\xi|^2}$ approach to $0$ and $1$, respectively ($e^{it|\xi|^2}$ and $e^{it\sqrt{1+|\xi|}}$).
Hence I can't understand why it behaves like Schrödinger flow.
Could you explain exactly what it means?


text:
Q: macro extract defined function name I have two functions
funcA(x::AbstractMatrix;subd=nothing)=funcA(x[1,:],x[2,:],subd) # format transformer
funcA(a::AbstractVector,b::AbstractVector;subd=nothing)
    babalah
end

and
funcB(x::AbstractMatrix)=funcB(x[1,:],x[2,:]) # format transformer
funcB(a::AbstractVector,b::AbstractVector)
    babalah
end

I wish a macro can easily help me to add the "format transformer" automatically to the funcA and funcB and it can add arguments.
What should I do?


text:
Q: How to find all textboxes in a gridview row? I have a GridView on a website, that have different controls in each row (eg.: textbox, label, dropdownlist). I need to find all textboxes and set the enabled property to false, so the user won't be able to edit them. I tried the code below, but it dosn't work, 'c' never recognised as a textbox, so it never changes the property.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (a)
    {
        foreach (Control c in e.Row.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)(c)).Enabled = false;
            }
        }
    }
}

A: I think you should try like this:
TextBox tb = e.Row.FindControl("textbox_name") as TextBox;
tb.Enabled = false;

A: Your textboxes must be nested within other controls, most likely cells inside the row. That is why you cannot find them just iterating through immediate children.
If you have a list of IDs of the text boxes, you should use FindControl:
((TextBox)e.Row.FindControl("TextBoxID")).Enabled = false;

Otherwise you will need to recursively find your controls of necessary type. See this thread for code sample.
One more option, if a is relatively easy to calculate, is to use in the markup directly, like so:
<asp:TextBox ... Enabled='<%# a %>' />

This depends a lot on the details of how a is derived. If it is a protected or public field of the page class, just the code above should work. If it is calculated based on row, you may need to turn it into protected method and pass params into it:
Enabled='<%# GetEnabled(Eval("Prop1"), Eval("Prop2")) %>'

A: And also want to put some updation.
There are different types of rows in gridview (header,footer,datarow,etc)
so for making little faster for the control find.
Try below (check the if condition)
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Find the TextBox control.
                TextBox txtName = (e.Row.FindControl("txtName") as TextBox);
                txtName.Enabled = false;

                //or
                TextBox txtName1 = (TextBox)e.Row.FindControl("txtName");
                txtName1.Enabled = false;
            }
        }

A: You should search controls inside the cell instead of Row.
foreach (TableCell cell in e.Row.Cells)
{
     foreach (Control c in cell.Controls)
     {
           if (c is TextBox)
           {
                  ((TextBox)(c)).Enabled = false;
           }
     }
}


text:
Q: Convert non-uniform pseudorandom generation to uniform? Lets say I have a function which is non uniform and generates elements in the set A. I have a set B that has the probability of generation of each element in A. Is there any way I can make the non uniform pseudorandom function behave like a uniform pseudorandom function.

A: Sure.  An easy way to generate an element from A with uniform probability:

*

*Assign a number to each element of A

*For each element of A, generate a corresponding random element, and note its corresponding number

*Select the element of A with the smallest random number.  If there's a tie, repeat with the elements that are tied for first.

An efficient way is to encode a stream of random (non-uniform) elements with a range coder according to the given probabilities.  This will generate a stream of uniform random bits.  You can then decode this assuming equal probabilities for all symbols to get uniformly distributed elements of A.  See: https://en.wikipedia.org/wiki/Range_encoding
Another way to generate the uniform random stream of bits is to calculate the entropy of your random source, and then divide the output into chunks and hash with a cryptographic hash function like SHA-1.  The chunks should be big enough to provide more bits of entropy than the bit length of the hash function.  This method could be safer in real life, because it works even if you are wrong about the symbol distribution produced by your generator.  See: https://en.wikipedia.org/wiki/Entropy_(information_theory)

A: Let me suggest a simple algorithm, where you don't need to know the probabilities that each element in A is chosen (set B in your question).  I assume that each element in A has a known order (for example, each element is a number).
There are two parts to the algorithm.  The first is an algorithm to generate unbiased random bits.  We'll call it "RandomBit()" (Morina et al. 2019).

*

*Draw one independent element from A, call it X, and then draw another independent element from A, call it Y.

*If X is less than Y, return 0.  If Y is less than X, return 1.  If neither is the case, go to step 1.

This works because independent pairs of independent draws from A are statistically indifferent (Montes Gutiérrez 2014, De Schuymer et al. 2003); see the appendix to my Note on Randomness Extraction for details.
Next is an algorithm to generate a uniform random number in [0, 1].  All you have to do is "juxtapose enough random binary digits" (von Neumann 1951):  Add RandomBit()/2 + RandomBit()/4 + RandomBit()/8 + ....
If your non-uniform distribution is the normal distribution, see the following question on Cross Validated for further tricks: https://stats.stackexchange.com/questions/117689
REFERENCES:

*

*Von Neumann, J., "Various techniques used in connection with random digits", J. Res. Nat. Bur. Stand. Appl. Math. Series 3, 36-38 (1951).

*Morina, G., Łatuszyński, K., et al., "From the Bernoulli Factory to a Dice Enterprise via Perfect Sampling of Markov Chains", arXiv:1912.09229 [math.PR], 2019.

*Montes Gutiérrez, I., "Comparison of alternatives under uncertainty and imprecision", doctoral thesis, Universidad de Oviedo, 2014.

*De Schuymer, Bart, Hans De Meyer, and Bernard De Baets. "A fuzzy approach to stochastic dominance of random variables", in International Fuzzy Systems Association World Congress 2003.


text:
Q: Test server side git-hooks in --dry-run mode We enabled server-side git hooks to enforce GIT based integration policy where we check for commit message format that is pushed. When 'git push' is invoked in the --dry-run mode, the git hooks are not invoked. How can I test the git hooks without actually pushing the code into the repository?

A: You can either have a test repo on the server side, for you to push.
But for a true local test, you might want to use a client-side commit-msg hook, where your commit message validation function can be tested.
That supposes said function can be externalized in its own script, in order to be called from:

*

*the local client-side commit-msg hook

*the server-side pre-receive hook


text:
Q: Displaying shopping cart in table Think I've done this completely wrong but I am trying to display the values of the items when added to the shopping cart into a table. My code looks like this:
<?php
function minicart() {
    foreach($_SESSION as $name => $value) {
        if ($value > 0) {
            if (substr($name, 0, 5)=='cart_') {
                $id = substr($name, 5, (strlen($name) -5));
                $get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
                while ($get_row = mysql_fetch_assoc($get)) {
                    $sub = $get_row['price']*$value;
                    '
'
                    '
'
                    ''<echo $get_row['name'].' x '.$value.' @ £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).' [-] [+] [Delete]
''
';
                    '
'
                    '
'
                }
            }
            $total += $sub;
        }
    }
    if ($total==0) {
        echo "Your cart is empty";
    }
    else {
        echo '
Total: £'.number_format($total, 2);

    ?>

A: I tried to re write your table to correct format:
echo '
';
while ($get_row = mysql_fetch_assoc($get)) {
    $sub = $get_row['price']*$value;
    echo '

    '.
    $get_row['name'].' x '.$value.' @ £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'
    [-]
    [+]
    [Delete]

    ';
}
echo '
';

Please see PHP Strings

A: I think you want to replace the if-statement with the following.
This will give you 1 table with a row per item, probably what you're looking for.
        if (substr($name, 0, 5)=='cart_') {
            $id = substr($name, 5, (strlen($name) -5));
            $get = mysql_query('SELECT id, name, price FROM products WHERE  id='.mysql_real_escape_string((int)$id));
            echo '
';
            echo '
';
            while ($get_row = mysql_fetch_assoc($get)) {
                $sub = $get_row['price']*$value;
                echo '';
                echo $get_row['name'].' x '.$value.' @ &pound';
                echo number_format($get_row['price'], 2).' = &pound';
                echo number_format($sub, 2);
                echo '[-] ';
                echo '[+] ';
                echo '[Delete]
';
            }
            echo'
';
            echo'
';
        }

A: Try this:
function minicart()
{
    $items = 0;
    $tbl = array();
    foreach($_SESSION as $name => $value)
    {
        if ($value > 0) {
            if (substr($name, 0, 5)=='cart_')
            {
                $id = substr($name, 5, (strlen($name) -5));
                $get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
                $tbl[] = '

'
                  . 'Item	'
                  . 'Quantity	'
                  . 'Unit Price	'
                  . 'SubTotal	'
                  . 'Action	'
                  . '

'
                ;
                while ($get_row = mysql_fetch_assoc($get)) {
                    $items++;
                    $sub = $get_row['price'] * $value;
                    $tbl[] = '
'
                      . '' . $get_row['name'] . '	'
                      . '' . $value . '	'
                      . '£' . number_format( $get_row['price'], 2 ) . '	'
                      . '$pound;' . number_format( $sub, 2) . '	'
                      . ''
                      . ' [-] '
                      . ' [+] '
                      . ' [Delete]'
                      . '	'
                      . '
'
                    ;
                }
                $tbl[] = '
';
            }
            $total += $sub;
        }
    }
    if ($items==0)
    {
        echo "Your cart is empty";
    }
    else
    {
        $tbl[] = '

'
               . 'Total:	'
               . '£' . number_format($total, 2) . '

';
        echo implode( "\n", $tbl );

    }
}

I changed the logic so that if the item count is zero, it displays the "empty cart" message, allowing for zero-cost items.


text:
Q: About the Stirling number of the second kind
Find the exponential generating function for $s_{n,r}$, the number of ways to distribute $r$ distinct objects into $n$ distinct boxes with no empty box, and determine $s_{n,r}$.

My solution is
$$\left(x+\frac{x^2}{2!}+\frac{x^3}{3!}+\cdots\right)^n=(e^x-1)^n$$
$$=\sum_{k=0}^n(-1)^k\binom{n}{k}e^{kx}=\sum_{k=0}^n(-1)^k\binom{n}{k}\sum_{r=0}^{\infty}k^r\frac{x^r}{r!}$$
Thus, $s_{n,r}$ is the coef. of $\frac{x^r}{r!}$, which is $\sum_{k=0}^n(-1)^k\binom{n}{k}k^r$.
However, I found it in another book that $s_{m,n}=\frac{1}{n!}\sum_{k=0}^{n}(-1)^k\binom{n}{k}(n-k)^m$, where $s_{m,n}$ denotes the  Stirling number of the second kind.
I was wondering what's wrong with my solution.

A: There are a couple of things going on here.

*

*You should have $\sum_{k=0}^n(-1)^{n-k}\binom{n}{k}k^r$ as the final answer.  This is because you should have had $\sum_{k=0}^n(-1)^{n-k}\binom{n}{k}e^{kx}$ when you expanded $(e^x-1)^n$.

*The question as you posed it is not asking about the Stirling numbers of the second kind.  As Michael Hardy points out in a comment, the Stirling numbers of the second kind count the number of ways to distribute $r$ distinct objects into $n$ indistinguishable boxes.  (Often this is phrased as "sets" rather than "indistinguishable boxes," as the former seems clearer.)  Your question involves distinct boxes.

Let's expand on the second issue, as the two problems are clearly related.  Since there's some notational confusion going on, let's let $T(r,n)$ denote the number of ways to distribute $r$ distinct objects into $n$ distinct boxes with no empty box (i.e., your problem), and we'll let $S(r,n)$ denote the number of ways to distribute $r$ distinct objects into $n$ indistinguishable boxes with no empty box.  Then we have the relationship $T(r,n) = n! S(r,n)$.  This is because the indistinguishable boxes can be made distinguishable by applying $n$ different labels to them, and there are $n!$ ways to assign $n$ labels to $n$ boxes.
This fits with your computations above.  Your (corrected) computations have $$T(r,n) = \sum_{k=0}^n(-1)^{n-k}\binom{n}{k}k^r.$$
The formula you cite for the Stirling numbers of the second kind has $$S(r,n) = \frac{1}{n!}\sum_{k=0}^{n}(-1)^k\binom{n}{k}(n-k)^r.$$
Since $\binom{n}{n-k} = \binom{n}{k}$, though, by reindexing the sum we get $$S(r,n) = \frac{1}{n!}\sum_{k=0}^{n}(-1)^{n-k}\binom{n}{k}k^r,$$
in agreement with the argument above that $T(r,n) = n!S(r,n)$.


text:
Q: How to CORRECTLY increase UITableViewCell using UILabel's height There have been so many answers to this question on stack overflow, please know that I have looked but all the solutions do not work for me. I have two UILabels in the cell, one has a definite width and height, the other which will be dynamic, I put the width about <= 250 and the height >=50. I have also set all four margins to the content view and then I tried these two methods below to get the height of the string:
var context: NSStringDrawingContext = NSStringDrawingContext()
        context.minimumScaleFactor = 0.8
        cell?.body.text = msg.body
        var width: CGFloat = (cell?.body.frame.size.width)!
        width = ((UIScreen.main.bounds.width)/320)*width
        let size: CGSize = (cell?.body.text!.boundingRect(with: CGSize(width: width, height: 2000), options:NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: cell?.body.font], context: context).size)!
        print("size.height is \(size.height)")
        return size.height

and this method:
var optimalHeight : CGFloat
{
    get
    {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: CGFloat.greatestFiniteMagnitude))
        //let label = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = self.lineBreakMode
        label.font = self.font
        label.text = self.text

        label.sizeToFit()

        return label.frame.height
    }
}

and for these two, the image attached is what shows as the UILabel, which, as anyone can see, is way off.
I have also tried implementing UITableViewAutomaticDimension in the estimatedHeightForRowAt and heightForRowAt methods, but this did not work, after two lines, it would not expand further.
I tried calling estimatedRowHeight and rowHeight in the viewDidLoad() method like this:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300 //even went as far as using 800

same thing, stopped expanding after 2 lines.
I also saw something about implementing these methods:
tableView.setNeedsLayout()
tableView.layoutIfNeeded()

and yet nothing! I have looked through the raywenderlich tutorial and a lot more. I have no clue what I am doing wrong. This might be a duplicate question but I assure you I have tried every solution and nothing works for me. Please could someone take a look at this and see what I am doing wrong?
these are the screenshots of the constraints for both labels

A: So I wrapped my dequeuing in cellForRowAt on a background thread and this prevented my cells from being dynamic. After I took that statement out, it worked perfectly! Such a waste of code time fixing something that was never broken


text:
Q: Visualize embedded and immersed Klein bottle Answers at How to visualize a 4-dimensional parametric surface? give functions for producing images of 3D projections of 4D embeddings of the Klein bottle.
Is there a way to get such a 3D projection from a 4D embedding of the Klein bottle that is the customary "beer-bottle" surface used to help visualize the Klein bottle?
(For a strictly mathematical version of the question, see: https://math.stackexchange.com/questions/2946505/topological-embedding-of-klein-bottle-into-mathbbr4-that-projects-to-usual.)
Prior posts about 3D immersion of the Klein bottle do not help. I already know how to produce an image of that "standard" 3D immersion of the Klein bottle K. But as I said, I want to start with an explicit embedding function into 4D and then an explicit projection down to 3D whose image is that "beer-bottle" immersed surface.

A: I built a continuous transformation of a Klein bottle from 4D to 3D
x[u_, v_, r_] := r (Cos[u/2] Cos[v] - Sin[u/2] Sin[2 v])
y[u_, v_, r_] := r (Sin[u/2] Cos[v] + Cos[u/2] Sin[2 v])
z[u_, v_, p_, \[Epsilon]_] := p Cos[u] (1 + \[Epsilon] Sin[v])
t[u_, v_, p_, \[Epsilon]_] := p Sin[u] (1 + \[Epsilon] Sin[v])
klein[u_, v_] :=
 Module[{bx = 6 Cos[u] (1 + Sin[u]), by = 16 Sin[u],
   rad = 4 (1 - Cos[u]/2), X, Y, Z},
  X = If[Pi <= u < 2 Pi, bx + rad Cos[v + Pi], bx + rad Cos[u] Cos[v]];
  Y = If[Pi <= u < 2 Pi, by, by + rad Sin[u] Cos[v]];
  Z = rad Sin[v];
  {X, Y, Z}]
KleinBottle4D3D[p_, r_, \[Epsilon]_, \[Alpha]_, m_] :=
 ParametricPlot3D[{(x[u, v, r]), (y[u, v, r]),
     Cos[\[Alpha]]*z[u, v, p, \[Epsilon]] +
      Sin[\[Alpha]]*t[u, v, p, \[Epsilon]]}*(1 - m) +
   m*klein[u, v], {u, 0, 2*Pi}, {v, 0, 2*Pi}, PlotRange -> All,
  Mesh -> None, Exclusions -> None, Boxed -> False, Axes -> False,
  PlotStyle -> Opacity[2/3], ColorFunction -> Hue,
  BoxRatios -> {1, 1, 1}]

L = ListAnimate[
  Table[KleinBottle4D3D[15, 7, -1/2, Pi/4, m], {m, 0, 1, .05}]]


text:
Q: NMON analyze cpu and mem 1 day I tried to analyze one day's worth of CPU and memory using nmon on AIX, but I have an error -- why? I also want to run it in background.
user@host(/home/user)$ nmon -s 900 -c 96 -m 96 -r "nmon report" -f -t -m /home/user
Change Directory failed: No such file or directory
Directory attempted was: 96

A: You've given the -m ("change directory") option twice: once with a value of 96 and a second time with a value of /home/user. Remove -m 96 from your command. To run it in the background, simply append &. The result:
nmon -s 900 -c 96 -r "nmon report" -f -t -m /home/user &


text:
Q: Idempotency in a camel application running in Kubernetes cluster I am using apache camel as integration framework in my microservice. I am deploying it in a Kubernetes cloud as multiple pods. I had written a route for reading file from a directory and write to another. But I am facing an issue as the different pods are picking same file. I need to avoid that. I only want any of the pod to pick the file and process but currently all the pods are picking and processing the file. Can someone help with this. Please suggest some examples available in GitHub or any other.
Thanks in advance.

A: Camel recently introduced some interesting clustering capabilities - see here.
In your particular case, you could model a route which is taking the leadership when starting the directory polling, preventing thereby other nodes from picking the (same or other) files.

Set it up is very easy and all you need is to prefix singleton
endpoints according to the master component syntax:
master:namespace:delegateUri

This would result in something like this:
from("master:mycluster:file://...")
        .routeId("clustered-route")
        .log("Clustered file polling !");


text:
Q: Search only reads one keyword: SQLSTATE[HY093]: Invalid parameter number I'm having an issue with my search feature of my website. It's not handling search terms with more than one word. try a live example of the search bar problem over at http://mobile.mixtapemonkey.com/
search "It's Better This Way"
as soon as you type in B I get an error. other than that it works, what do you think the issue is?
    if (empty($errors)) {
  $name_explode = explode(' ', $name); // explode keywords to get each individual keyword, and put into array
  $name_count = count($name_explode); // count keywords from array
  foreach($name_explode as $name_single) {
    $x++; // increment x each loop

    $keyword = "%".$name_single."%";

    $where .= '`keywords` LIKE :keyword'; // append to where clause
    if ($name_count!=$x) {
      $where .= ' AND '; // as long as keyword isn't the last, append AND.
    }
  }

  $sql = "SELECT `name`, `thumb`, `id`, `title` FROM `mixtapes` WHERE ".$where." ORDER BY `id` DESC LIMIT 40";

  $search = $db->prepare($sql); // perform query

  $search->bindParam(':keyword', $keyword, PDO::PARAM_STR);

  $search->execute();

  $search_num_rows = $search->rowCount(); // get number of rows (results) returned

A: Please check the code I have added.the reason you got that error is due to your foreach loop. In that loop you add :keyword everytime. But that count dont match with the bindParam value count. So I changed you code and posting below
if (empty($errors)) {
$name_explode = explode(' ', $name); // explode keywords to get each individual keyword, and put into array
$name_count = count($name_explode); // count keywords from array
$x = 0;
foreach($name_explode as $name_single) {
$x++; // increment x each loop

$keyword[':keyword'.$x] = "%".$name_single."%";

$where .= '`keywords` LIKE :keyword'.$x; // append to where clause
if ($name_count!=$x) {
  $where .= ' OR '; // as long as keyword isn't the last, append AND.
}
}

$sql = "SELECT `name`, `thumb`, `id`, `title` FROM `mixtapes` WHERE ".$where." ORDER BY `id` DESC LIMIT 40";

$search = $db->prepare($sql); // perform query

$search->execute($keyword);

$search_num_rows = $search->rowCount(); //


text:
Q: Call Apple-specific OpenGL commands through MonoTouch/OpenTK If I understand things correctly, Apple's OpenGL ES 2.0 implementation uses some methods from OpenGL ES 3.0, for example
glBindVertexArrayAPPLE

or
glBindVertexArrayOES

instead of
glBindVertexArray

It seems that the OpenTK compilation that gets delivered with MonoTouch does not include either of these methods, although there exist OpenTK bindings for them, see for example line 229 of http://www.opentk.com/files/doc/_g_l_core_8cs_source.html.
Is there any way I can use these features in MonoTouch? Maybe some way to call them through a P/Invoke?

A: To make things clear, OpenTK-1.0.dll as shipped with MonoTouch since early 2012 (no need to install anything else), supports glBindVertexArrayOES by calling:
GL.Oes.BindVertexArray([u]int);

No additional p/invoke is required in user code. As for glBindVertexArrayAPPLE, which would logically be available as:
GL.Apple.BindVertexArray([u]int);

it is not part of the API since GL_APPLE_vertex_array_object is not defined in the iOS version of glext.h (like it is for OSX version of the same file). Note that GL_OES_vertex_array_object is defined in both iOS and OSX versions of glext.h which is why the Oes API is available.
A quick grep (to find all occurances) did not show the symbols as available in any of the .dylib (so adding it or p/invoking it would fail at runtime).

A: That's it:
[DllImport(Constants.OpenGLESLibrary, EntryPoint="glGenVertexArraysOES")]
public extern static void GenVertexArrays(int n, out int id);

[DllImport(Constants.OpenGLESLibrary, EntryPoint="glBindVertexArrayOES")]
public extern static void BindVertexArray(int id);

There are more functions like these two. @Xamarin, maybe they could be included in the next MonoTouch release?

A: If you reference OpenTK-1.0 instead of OpenTK you will find this API there.


text:
Q: How to select the specific frame with object I am detecting the object from the live camera through feature detection with svm , and it read every frame from camera while predicting which affect its speed , i just want that it should select the frame which contain the object and ignore other frames which have no object like empty street or standing car's , it should only detect the moving object
For example , If the object came into camera in 6th frame , it contain into the camera till many frames until it goes out from camera's range , so it should not recount the same object and ignore that frames.
Explanation :

I am detecting the vehicle from video , i want to ignore the empty frames , but how to ignore them ? i only want to check the frames which contain object like vehicle , but if the vehicle is passing from video it take approximately lets assume 5 sec , than it mean same object take 10 frames , so the program count it as 10 vehicles , one from each frame , i want to count it as 1 , because its the one (SAME) vehicle which use 10 frames
My video is already in background subtraction form
I explore two techniques :
1- Entropy ( Frame subtraction )
2- Keyframe extraction

A: This question is confusingly worded. What output do you want from this analysis? Here's the stages I see:
1) I assume each frame gives you an (x,y) or null for the position of each object in the frame. Can you do this?
2) If you might get multiple objects in a frame, you have to match them with objects in the previous frame. If this is not a concern, skip to (3). Otherwise, assign an index to each object in the first frame they appear. In subsequent frames, match each object to the index in the previous frame based on (x,y) distance. Clumsy, but it might be good enough.
3) Calculating velocity. Look at the difference in (x,y) between this frame and the last one. Of course, you can't do this on the first frame. Maybe apply a low-pass filter to position to smooth out any jittery motion.
4) Missing objects. This is a hard one. If your question is how to treat empty frames with no object in them, then I feel like you just ignore them. But, if you want to track objects that go missing in the middle of a trajectory (like maybe a ball with motion blur) then that is harder. If this is what you're going for, you might want to do object matching by predicting the next position using position, velocity, and maybe even object characteristics (like a histogram of hues).
I hope this was helpful.

A: You need an object tracker (many examples can be found on the web for tracking code). Then what you are looking for is the number of tracks. That's your answer.


text:
Q: In DotA2, why «cannot queue for matchmaking at this time»? In DotA2, I cannot start a game. After pressing the find match button, I get a message:

Cannot queue for matchmaking at this time.

This happens for both normal games or ranked games.
I could not find anything about a hypothetical penalty, neither in the UI for starting a game nor on my profile.

*

*Why does it happen?
It is a penalty? It could have to do with abandoned games.

*Can I see this state anywhere?

*How long can I expect it to last?

My game client is up-to-date.

A: It's a known bug and it occurs when you leave a finished game too early. To fix this, create custom lobby and leave it or type "disconnect" in console. Then you should be able to queue normally.

A: This is actually a penalty for various types of misbehavior, such as disconnecting mid-game.


text:
Q: Associativity of symmetric difference (set theory): $(A\Delta B) \Delta C = A \Delta (B\Delta C)$ I'm reading a proof of why $(A\Delta B) \Delta C = A \Delta (B\Delta C)$, where
$A\Delta B = (A\cup B) \setminus (B\cap A)$.
A bit into the proof is where I stop understanding, here:
$(A\cup B \cup C) \cap (A\cup B^c \cup C^c) \cap (A^c\cup B \cup C^c) \cap(A^c \cup B^c \cup C)$ =
$(B \cup C \cup A) \cap (B \cup C^c \cup A^c) \cap (B^c \cup C^c \cup A^c) \cap (B^c \cup C^c \cup A)$
What kind of rules are used in that equality?

A: It looks like there's a typo. The penultimate factor should probably be $B^c \cup C\cup A^c$. Then what's in work here is only the commutative law of unions and intersections.
You can always check the validity of each step using truth tables.

Another solution is to see that symmetric difference is basically the same as addition modulo $2$ of the characteristic function. That is that we count the number of sets an element is in and if that's odd it's part of the symmetric difference. It alls boils down to the fact that addition is associative.


text:
Q: Convert json to symfony php I'm converting json to larvel php  and I'm wondering how you convert this:

JSON:
"assetList":[
  {
    "name":"https://mobilize-uploads-prod.s3.amazonaws.com/uploads/event/Test-Logo-Small-Black-transparent-1_20180730154641244030.png"
  },
  {
    "name":"https://mobilize-uploads-prod.s3.amazonaws.com/uploads/event/Test-Logo-Small-Black-transparent-1_20180730154641244030.png"
  },
  {
    "name":"https://mobilize-uploads-prod.s3.amazonaws.com/uploads/event/Test-Logo-Small-Black-transparent-1_20180730154641244030.png"
  }
]

larvel php:
'thumbnail' => 'assetList'['name'],

Your answer will look something like this:
 'thumbnail' => 'Your code here',

It is supposed to output an image there is 3 different images I just used one as an example. Right now, it is not outputting anything so it is not working maybe because it is an array and I'm not sure how you write an array like this to work. I think the array is stopping it from working. Any help would be much appreciated.
edit: I just found out that this is larvel php

A: Please see my answer below

*

*First Your Json should be as below

{"assetList":[
  {
    "name":"https://mobilize-uploads-prod.s3.amazonaws.com/uploads/event/Test-Logo-Small-Black-transparent-1_20180730154641244030.png"
  },
  {
    "name":"https://mobilize-uploads-prod.s3.amazonaws.com/uploads/event/Test-Logo-Small-Black-transparent-1_20180730154641244030.png"
  },
  {
    "name":"https://mobilize-uploads-prod.s3.amazonaws.com/uploads/event/Test-Logo-Small-Black-transparent-1_20180730154641244030.png"
  }
] }

*First Do a Json_decode in php for your data.
$json_data = [YOUR_JSON_DATA]
$data_arr['data'] = json_decode($json_data,true);

*Pass the array to twig
// for Symfony php framework
$this->render("app:index.html.twig", $data_arr);

*In your twig you need to update the code as below to show the Image urls
{% for img_data in data.assetList %}
    {{ img_data.name }}
{% endfor %}

Let me know if you face any more issue.

A: If you want to build a similar structure to the JSON inside Twig, you can do this as follows:
{% set thumbnail = { "assetList": [{"name": "http://..."}, {"name": "http://..."}] } %}

If you want to pass a similar structure into the view, e.g. do something like $this->render('my_template', ['thumbnail' => ...] then your php code to generate an array like the one in JSON could look like this:
[
    'assetList' => [
        [
            'name' => 'http://...',
        ],
        [
            'name' => 'http://...',
        ],
    ]
]

edit: Also accessing it in Twig will not be assetList["name"] it will be:
{{ thumbnail["assetList"][0]["name"] }}

Where 0 is the offset of the list entry,i.e. 0-2, if you have 3 images.

A: If you passed that json as an array towards twig, u would need to use a loop to read out the array assetList
{% for asset in assetList %}
    {{ asset.name }}
{% endfor %}


text:
Q: modify function so that control flow constructs use `{...}` AND keep comments at right place I would like to modify an input function, so that the expressions always call
`{`(), and doing so, keep the comments at the right place.
Here is an example :
input_fun <- function(){

  if(TRUE)
    foo
  else
    # bar
    bar

  if(FALSE) {
    this
    # baz
    baz
    that
  }

  repeat
    while(condition)
      # qux
      qux
}

cat(deparse(input_fun, control = "useSource"),sep ="\n")
#> function(){
#>
#>   if(TRUE)
#>     foo
#>   else
#>     # bar
#>     bar
#>
#>   if(FALSE) {
#>     this
#>     # baz
#>     baz
#>     that
#>   }
#>
#>   repeat
#>     while(condition)
#>       # qux
#>       qux
#> }

The output would be the following output_fun or similar, where similar means that
inserting or removing new lines before/after { or } is not important, and nor is
indentation.
I also don't mind losing comments that are not on their own line (though I slightly better to keep them).
output_fun <- function(){
  if(TRUE){
    foo
  } else {
    # bar
    bar
  }

  if(FALSE) {
    this
    # baz
    baz
    that
  }

  repeat {
    while(condition){
    # qux
    qux
    }
  }
}

cat(deparse(output_fun, control = "useSource"),sep ="\n")
#> function(){
#>   if(TRUE){
#>     foo
#>   } else {
#>     # bar
#>     bar
#>   }
#>
#>   if(FALSE) {
#>     this
#>     # baz
#>     baz
#>     that
#>   }
#>
#>   repeat {
#>     while(condition){
#>     # qux
#>     qux
#>     }
#>   }
#> }

Maybe something can be done by keeping a count of control flow constructs and opened brackets, or maybe we should go through the parse tree of the input function, edit to add the { and find a way to plug back the comments from the original srcref at the right place, but I'm a bit stuck, any method will do.

edit :
We might be able to use this :
repair <- function(call){
  if(!is.call(call)) {
    return(call)
  }

  # if
  if(call[[1]] == quote(`if`)) {
    if(!is.call(call[[3]]) || call[[3]][[1]] != quote(`{`)){
      call[[3]] <- as.call(list(quote(`{`), call[[3]]))
    }
    if(length(call) == 4 && (!is.call(call[[4]]) || call[[4]][[1]] != quote(`{`))){
      call[[4]] <- as.call(list(quote(`{`), call[[4]]))
    }
    call[-1] <- lapply(as.list(call[-1]), repair)
    return(call)
  }

  # for
  if(call[[1]] == quote(`for`)) {
    if(!is.call(call[[4]]) || call[[4]][[1]] != quote(`{`)){
      call[[4]] <- as.call(list(quote(`{`), call[[4]]))
    }
    call[-1] <- lapply(as.list(call[-1]), repair)
    return(call)
  }

  # repeat
  if(call[[1]] == quote(`repeat`)) {
    if(!is.call(call[[2]]) || call[[2]][[1]] != quote(`{`)){
      call[[2]] <- as.call(list(quote(`{`), call[[2]]))
    }
    call[-1] <- lapply(as.list(call[-1]), repair)
    return(call)
  }

  # while
  if(call[[1]] == quote(`while`)) {
    if(!is.call(call[[3]]) || call[[3]][[1]] != quote(`{`)){
      call[[3]] <- as.call(list(quote(`{`), call[[3]]))
    }
    call[-1] <- lapply(as.list(call[-1]), repair)
    return(call)
  }

  #
  call[] <- lapply(call, repair)
  call
}

output_fun0 <- input_fun
body(output_fun0) <- repair(body(input_fun))
output_fun0
#> function ()
#> {
#>     if (TRUE) {
#>         foo
#>     }
#>     else {
#>         bar
#>     }
#>     if (FALSE) {
#>         this
#>         baz
#>         that
#>     }
#>     repeat {
#>         while (condition) {
#>             qux
#>         }
#>     }
#> }

A: Disclaimer: this is going to be long and twisted
I provide here an improved example including corner cases, and show the main steps.
The functions I used are at the bottom. They're not very well commented so shoot if you need them edited with clarifications.
data
input_fun <- function(){

  if(TRUE)
    foo
  else
    # bar_com1
    # bar_com2
    bar({
      x({y})
    }) %in% z

  # if
  if(
    FALSE) {
    this
    # baz_com
    baz
    that
  }

  repeat
    while(condition)
      # qux_com
      qux
}

Solution
We nest comment in the code by hiding them in the next call as the first argument of a `#`() function
output_fun <- nest_comments(input_fun)
output_fun
#> function ()
#> {
#>     if (TRUE)
#>         foo
#>     else `#`("    # bar_com1\n    # bar_com2", bar)({
#>         x({
#>             y
#>         })
#>     }) %in% z
#>     `#`("  # if", if (FALSE) {
#>         this
#>         `#`("    # baz_com", baz)
#>         that
#>     })
#>     repeat while (condition) `#`("      # qux_com", qux)
#> }

We "repair" the function, adding explicit { calls where missing in control flow constructs
body(output_fun) <- repair_call(body(output_fun))
output_fun
#> function ()
#> {
#>     if (TRUE) {
#>         foo
#>     }
#>     else {
#>         `#`("    # bar_com1\n    # bar_com2", bar)({
#>             x({
#>                 y
#>             })
#>         }) %in% z
#>     }
#>     `#`("  # if", if (FALSE) {
#>         this
#>         `#`("    # baz_com", baz)
#>         that
#>     })
#>     repeat {
#>         while (condition) {
#>             `#`("      # qux_com", qux)
#>         }
#>     }
#> }

We go back to the new parse tree and extract the #() calls into independent
calls above the "host" call
body(output_fun) <- unnest_comments(body(output_fun))
output_fun
#> function ()
#> {
#>     if (TRUE) {
#>         foo
#>     }
#>     else {
#>         `#`("    # bar_com1\n    # bar_com2")
#>         bar({
#>             x({
#>                 y
#>             })
#>         }) %in% z
#>     }
#>     `#`("  # if")
#>     if (FALSE) {
#>         this
#>         `#`("    # baz_com")
#>         baz
#>         that
#>     }
#>     repeat {
#>         while (condition) {
#>             `#`("      # qux_com")
#>             qux
#>         }
#>     }
#> }

Now we can use regex to set the comments back to their standard form.
output_fun <- regularize_comments(output_fun)
output_fun
#> function ()
#> {
#>     if (TRUE) {
#>         foo
#>     }
#>     else {
#>         # bar_com1
#>     # bar_com2
#>         bar({
#>             x({
#>                 y
#>             })
#>         }) %in% z
#>     }
#>     # if
#>     if (FALSE) {
#>         this
#>         # baz_com
#>         baz
#>         that
#>     }
#>     repeat {
#>         while (condition) {
#>             # qux_com
#>             qux
#>         }
#>     }
#> }

functions
regularize_comments <- function(fun) {
  env <- environment(fun)
  fun <- deparse(fun)
  #fun <- gsub("(\\s*`#`\\(\")(.*?)\\\"\\)$","\\2", fun)
  fun <- gsub("(\\s*)`#`\\(\"(\\s*)(.*?)\\\"\\)$","\\1\\3", fun)
  fun <- gsub("\\\\n","\n",fun)
  eval(parse(text=paste(fun, collapse = "\n"))[[1]],envir = env)
}

unnest_comments <- function(call) {
  if(!is.call(call)) {
    return(call)
  }

  call0 <- lapply(call, function(x) {
    call_str <- paste(deparse(x), collapse ="\n")
    if(startsWith(call_str, "`#`(")){
      #is.call(x) && x[[1]] == quote(`#`) && length(x) == 3){
      # browser()
      x <- list(extract_comment(x),
                clean_call(x))
    }
    x
  })
  call <- as.call(unlist(call0))
  call[] <- lapply(call, unnest_comments)
  call
}

# helper for unnest_comments
extract_comment <- function(call){
  if(!is.call(call)) {
    return(NULL)
  }
  if(identical(call[[1]], quote(`#`))){
    return(call[1:2])
  }
  unlist(lapply(call, extract_comment))[[1]]
}

# helper for unnest_comments
clean_call <- function(call){
  if(!is.call(call)) {
    return(call)
  }
  if(identical(call[[1]], quote(`#`))){
    return(call[[3]])
  }
  call[] <- lapply(call, clean_call)
  call
}

is_syntactic <- function(x){
  tryCatch({str2lang(x); TRUE},
           error = function(e) FALSE)
}

nest_comments <- function(fun){
  src <- deparse(fun, control = "useSource")
  # positions of comments
  commented_lgl <- grepl("^\\s*#",src)
  # positions of 1st comments of comment blocks
  first_comments_lgl <- diff(c(FALSE, commented_lgl)) == 1
  # ids of comment blocks along the lines
  comment_ids <- cumsum(first_comments_lgl) * commented_lgl
  # positions of 1st lines after comment blocks
  first_lines_lgl <- diff(!c(FALSE, commented_lgl)) == 1
  first_lines_ids <- cumsum(first_lines_lgl) * first_lines_lgl

  # we iterate through these ids, taking max from lines so if code ends with a
  # comment it will be ignored
  for(i in seq(max(first_lines_ids))){
    comments <- src[comment_ids == i]
    line_num <- which(first_lines_ids == i)
    line <- src[line_num]
    # we move forward character by character until we get a syntactic replacement
    # the code replacement starts with "`#`(" and we try all positions of 2nd
    # parenthese until something works, then deal with next code block

    j <- 0
    repeat {
      break_ <- FALSE
      j <- j+1
      line <- src[line_num]
      if(j == 1) code <- paste0("`#`('", paste(comments,collapse="\n"),"', ") else code[j] <- ""
      for(n_chr in seq(nchar(src[line_num]))){
        code[j] <- paste0(code[j], substr(line, n_chr, n_chr))
        if (n_chr < nchar(line))
          code_last_line <- paste0(code[j],")", substr(line, n_chr+1, nchar(line)))
        else
          code_last_line <- paste0(code[j],")")
        #print(code_last_line)
        src_copy <- src
        src_copy[(line_num-j+1):line_num] <- c(head(code,-1), code_last_line)
        if (is_syntactic(paste(src_copy,collapse="\n"))){
          src <- src_copy
          break_ <- TRUE
          break}
      }
      if(break_ || j == 7) break
      line_num <- line_num + 1
    }
  }
  eval(str2lang(paste(src, collapse = "\n")),envir = environment(fun))
}

repair_call <- function(call){
  if(!is.call(call)) {
    return(call)
  }
  # if
  if(call[[1]] == quote(`if`)) {
    if(!is.call(call[[3]]) || call[[3]][[1]] != quote(`{`))
      call[[3]] <- as.call(list(quote(`{`), call[[3]]))
    if(length(call) == 4 && (!is.call(call[[4]]) || call[[4]][[1]] != quote(`{`)))
      call[[4]] <- as.call(list(quote(`{`), call[[4]]))
    call[-1] <- lapply(as.list(call[-1]), repair_call)
    return(call)}
  # for
  if(call[[1]] == quote(`for`)) {
    if(!is.call(call[[4]]) || call[[4]][[1]] != quote(`{`))
      call[[4]] <- as.call(list(quote(`{`), call[[4]]))
    call[-1] <- lapply(as.list(call[-1]), repair_call)
    return(call)}
  # repeat
  if(call[[1]] == quote(`repeat`)) {
    if(!is.call(call[[2]]) || call[[2]][[1]] != quote(`{`))
      call[[2]] <- as.call(list(quote(`{`), call[[2]]))
    call[-1] <- lapply(as.list(call[-1]), repair_call)
    return(call)}
  # while
  if(call[[1]] == quote(`while`)) {
    if(!is.call(call[[3]]) || call[[3]][[1]] != quote(`{`)){
      call[[3]] <- as.call(list(quote(`{`), call[[3]]))
    }
    call[-1] <- lapply(as.list(call[-1]), repair_call)
    return(call)}
  call[] <- lapply(call, repair_call)
  call
}


text:
Q: Output network switch configuration txt to csv multiple columns I have a text file that is switch interface configuration. I would like to pull out a few lines from the configuration and output them to a csv. Any help would be appreciated
My code below outputs each letter into its own column. Image of csv after running: http://i.imgur.com/hmndZwQ.png
import csv
import sys

txt_file = r"results.txt"
csv_file = r"testBook.csv"

csv_out = open(csv_file, "w")

in_txt = open(txt_file, "r")

out_csv = csv.writer(csv_out)

arr = []

for line in in_txt:
    arr.append(line)

out_csv.writerows(arr)

csv_out.close()

Text file used:
File name: 172.16.0.11.txt

interface 0/1
traffic-shape 5
description 'testname'
switchport mode trunk
switchport trunk native vlan 20
switchport trunk allowed vlan 2-3,20,52
ip access-group mbps25 in 1
exit
interface 0/2
description 'testname5'
switchport mode trunk
exit
interface 0/3
speed 1000 full-duplex
switchport mode access
switchport access vlan 2
exit
I would like to get an output of something close to this: http://i.imgur.com/1lb9R6D.png
Breakdown:
The Switch IP column would populate from the file name 172.16.0.11.txt
The interface column would populate from the interface number
The description column would populate from that interfaces information (if it has a description)
The traffic-shape column would populate from that interfaces information (if it has a traffic-shape)
The ip access-group column would populate from that interfaces information (if it has a access-group)

A:
Question:  ... pull out a few lines from the configuration and output them to a csv

#                  keyword : (fieldname, from, to)
D = OrderedDict([('_', ('Switch IP',)),
                 ('interface',('Interface', 1, 2)),
                 ('description', ('Description', 1, 2)),
                 ('traffic-shape', ('Traffic-Shape', 1, 2)),
                 ('ip',  ('IP Access-Group', 2, 5))])

with open(filename + ".txt") as txt_file, open('testBook.csv', 'w') as csv_file:
    # Build Fieldnames from D
    fieldnames = [D[d][0] for d in D]
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    # Init CSV Record
    record = {fieldnames[0]: filename}

    while True:
        line = txt_file.readline()[:-1]
        if not line: break

        words = line.split()

        # Write CSV Record if 'exit'
        if words[0] == 'exit':
            writer.writerow(record)
            record = {fieldnames[0]:filename}
        else:
            try:
                # Get Keyword Setting from D
                k = D[words[0]]
                # Update CSV Record 'fieldname' with Slice(from,to)
                record[k[0]] = ' '.join(words[k[1]:k[2]])
            except:
                pass

Output:
Switch IP,Interface,Description,Traffic-Shape,IP Access-Group
172.16.0.11,0/1,'testname',5,mbps25 in 1
172.16.0.11,0/2,'testname5',,
172.16.0.11,0/3,,,

Tested with Python: 3.4.2


text:
Q: US->foreign currency abstraction for US-based payment gateways In the case of payment gateways, if the gateway is US-based and can only charge in dollars, but can charge foreign debit/credit cards, and you want to act on countries where the currency is not USD, and you can't/do not want to apply for a local payment gateway, what could you do, programming-wise?
I was thinking about converting the amount in USD to the the specific currency. Problem is:

*

*I don't know where to get real-time accurate exchange-rate data

*Not sure if I get the data from somewhere, if the client's card processor will actually charge that exact price

Do you guys know any best-practices for that? I think another way would be to just charge in dollars, and then let the client know that approximate amount in his/her local currency, but again, I'm not sure where to get an updated currency conversion.
Does any of you have gone through a similar scenario?
PS.: Paypal is not an option.
Any hints appreciated!

A: Currency conversion takes place by your customer's bank, so there's unfortunately no central market through which you can even make estimates.
There are some APIs that you can use to make an estimate, though it's mostly just a guess. If you use one of these, I would make sure to make it clear to your customers that the price may vary depending on their bank.
Overall, I've found the best practice is just to display your prices in the supported currency (e.g., USD) and mention to your customers that it might vary. As we continue to expand internationally, you can take advantage of our local currency offerings to make more exact charges.


text:
Q: Scala style: for vs foreach, filter, map and others What is the best style in scala for "advanced iteration" over collection of smth. In which cases I should use for-comprehension and when I should look for alternative way(in terms of style) of iteration. In Programming in Scala book there is an example that looks almost as next one:
for{
    file <- filesHere
    if file.getName.endsWith("txt")
    line <- Source.fromFile(file).getLines.toList
    if line.trim.matches(pattern)
  } println("|" + file + ": " + line.trim)

I've tried to rewrite it using internal iteration and got:
filesHere foreach { file =>
  if (file.getName.endsWith("txt")) {
    Source.fromFile(file).getLines.toList foreach {line =>
      if (line.trim.matches(pattern)) println("|" + file + ": " + line.trim)
    }
  }
}

However, on the web(including stackoverflow) I've found a lot of articles/posts persuading to use for-comprehension, I don't find it convenient for me to use it. IMHO, internal iteration is much readable and convenient.
What are the best guidelines on this topic?

A: I think it is great that you are learning Scala. There is a wonderful community behind it, very active, and I think that you'll be more-and-more pleased with your decision as time goes on.
For the moment, at least, I think that you should stick to "Programming in Scala" as it is very well written and a terrific introduction to the language. Then, a good place to look will be the Scala api docs themselves as many of the classes/methods contain sample code. Also, the google group is very active (and, as I said, the people there are very friendly).
Keep in mind that the code you provide as an example returns no value, but rather just gives side-effects (in Java, this would have a void return value). Most of the Scala API is geared around functions with little to no side-effects that return a value (you might have, for example, a side-effect of logging, but idiomatic scala code will minimize side-effects in methods and functions).
Within the Scala API, there are methods that would be the preferred style, if it matches your need. For example, in Scheme you might do an inner loop to iterate, in Scala it might look like this:
val myScores = List(4, 8, 6, 1, 2, 4, 9, 8)

def max(ls: List[Int]): Int = {
  def iter(acc: Int, rem: List[Int]): Int = {
    if (rem.isEmpty) acc
    else if (rem.head > acc) iter(rem.head, rem.tail)
    else iter(acc, rem.tail)
  }
  iter(ls.head, ls)
}

But I don't need to write that function because max is already implemented in the list API:
myScores.max

So, if what you want to do is already implemented by a library, you should use that. max() is a trivial example, but there are much more complex transformations to be found in the Scala API and scalaz
A for-comprehension (the original topic of your post) is a combination of flatMap, map, and filter. If you are doing something fairly simple, then both versions will be just as readable, but if you are doing a long chain of flatMap, map, and filter strung together to create a complex transformation, then a for-comprehension will be more readable.
EDIT:
Specific to your question, I think the for-comprehension version is easier to read:
val filterMapFlatmapVersion: List[String] =
  fileNames.filter(_.endsWith("txt")).flatMap { file =>
    io.Source.fromFile(file).getLines().toList.map(_.trim).filter(_ == pattern)
}

val forVersion: List[String] =
  for {
    fileName <- fileNames
    if fileName.endsWith("txt")
    line <- io.Source.fromFile(fileName).getLines()
    if line.trim().matches(pattern)
  } yield line.trim

A: I would expect for-comprehensions to be the preferred approach in Scala.  It's worth noting that a for-comprehension is really syntactic sugar for a map and filter.


text:
Q: populate dynamic form zend ramework 2 I am bulding a web application using Zend Framework 2. The application retrieve some data from a db and shows it in a custom form. This data includes an array, whose length is variable. For each element of the array I need to show an input text in the form and set its label and value according to the element of the array it represents.
I have already my own custom form class, which extends the form base class, but I do not know where should I perform the operation of adding dynamic element. Should I do it in its constructor? Or in the setData method? Or anywhere else?


text:
Q: ListItem date field is one day off when uploading document I've a service that uploads documents to SharePoint Online and assigns the respective metadata to it.
Everything works fine except the date fields that are always one day off.
Eg: If I assign the date 01/05/2016 while uploading the document, when I see it's properties on SharePoint Online it states 30/04/2016.
For the website my regional settings are the following:

Column settings are simple:

In the background i'm parsing the date like this:
Return DateTime.Parse(strValue).ToUniversalTime().ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo)

Any suggestion on what am I doing wrong?

A: ToUniversalTime() converts your date to UTC format. Remove the section and it should work fine.
Remove the ToUniversalTime(). Use it like :
Return DateTime.Parse(strValue).ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo)

ToUniversalTime converts date to UTC format. So maybe because of that the dates are off.


text: Q: Can i somehow check my iPhone safari browser history with exact time? I'm in court and I need to confirm by law something and the only way I can do it, is to offer the exact time I checked for a particular web page on that day. Can someone give me a software or a trick to uncover that data?


text:
Q: My ubuntu system suddenly got somehow reset One day when I boot up on ubuntu after entering the password (I only have one user) suddenly the display went off for a sec and then everything was like reset to a fresh install! All new sudo commands I have done beforehand was when I was installing WireShark from source, which I guess was 2 days before the incident.
So it was reset, my background, my dock and my favorites. But I had my installed apps and themes for the top bar and windows and all, they were just disabled. So I thought it was all this but then I saw the unsolved problems. The one second blank screen shows up everytime I login to my user. The gsconnect keeps giving me TLS error, after many reinstalls through both the gnome extensions and git
TLS support is not available
Gio.TlsCertificate.new_for_paths@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/__init__.js:352:31
_initCertificate@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/backends/lan.js:177:48
start@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/backends/lan.js:440:18
_loadBackends@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/manager.js:251:25
start@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/manager.js:454:14
vfunc_startup@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/daemon.js:258:22
vfunc_handle_local_options@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/daemon.js:664:18
@/home/adjective/.local/share/gnome-shell/extensions/gsconnect@andyholmes.github.io/service/daemon.js:727:17

Also my laptop ports do not mount automatically. When I connect my external hard drive or my phone, it does not appear in the files window and the dmesg command gives me this:
usb 2-1: new SuperSpeed USB device number 4 using xhci_hcd
usb 2-1: New USB device found, idVendor=1058, idProduct=10b8, bcdDevice=10.07
usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=5
usb 2-1: Product: Elements 10B8
usb 2-1: Manufacturer: Western Digital
usb 2-1: SerialNumber: 5758373145423343454B3230
usb-storage 2-1:1.0: USB Mass Storage device detected
scsi host6: usb-storage 2-1:1.0
scsi 6:0:0:0: Direct-Access     WD       Elements 10B8    1007 PQ: 0 ANSI: 6
sd 6:0:0:0: Attached scsi generic sg1 type 0
sd 6:0:0:0: [sdc] Spinning up disk...
......ready
sd 6:0:0:0: [sdc] 1953458176 512-byte logical blocks: (1.00 TB/931 GiB)
sd 6:0:0:0: [sdc] Write Protect is off
sd 6:0:0:0: [sdc] Mode Sense: 47 00 10 08
sd 6:0:0:0: [sdc] No Caching mode page found
sd 6:0:0:0: [sdc] Assuming drive cache: write through
sdc: sdc1
sd 6:0:0:0: [sdc] Attached SCSI disk
i915 0000:00:02.0: [drm] *ERROR* Atomic update failure on pipe A (start=26667 end=26668) time 280 us, min 1064, max 1079, scanline start 1049, end 1087

I can mount it through commandline though but I rather like it fixed.
It's a long written problem and I really appreciate the time you put in reading this. Thanks in advance.