text:
Q: EditText is getting cut off in ViewHolder of RecyclerView I have a custom ViewHolder inside of a RecyclerView inside of a LinearLayout in an Activity. I'm trying to get the EditText inside of the ViewHolder to show all of the text inside of it. It keeps getting clipped off from the rest of the view:

Here's the relevant XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:paddingTop="8dp"
android:paddingBottom="8dp">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">
    <CheckBox
        android:id="@+id/add_existing_creature_add_this_creature"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"/>

    <!-- Name of the creature -->
    <TextView
        android:id="@+id/add_existing_creature_list_item_creature_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:textAlignment="center"
        android:textSize="24sp"/>

    <!-- Copies of the creature -->
    <LinearLayout
        android:id="@+id/existing_creature_list_item_copies_group"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:visibility="visible"
        android:padding="4dp" >
        <TextView
            android:labelFor="@+id/add_existing_creature_number_of_copies"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/x"/>
        <EditText
            android:id="@id/add_existing_creature_number_of_copies"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_gravity="bottom"
            android:gravity="bottom"
            android:padding="4dp"/>
    </LinearLayout>
    ....
    <!-- More XML enter code here--->

How do I get the clipping to stop?

A: You are limited height of your layout ( existing_creature_list_item_copies_group)
by other childe of parent LinearLayout (sec linear)
test below code and I fixed this problem by padding 2dp text view (add_existing_creature_list_item_creature_name) and fixed child gravity layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom"
    android:paddingTop="8dp"
    android:paddingBottom="8dp">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">
        <CheckBox
            android:id="@+id/add_existing_creature_add_this_creature"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"/>

        <!-- Name of the creature -->
        <TextView
            android:id="@+id/add_existing_creature_list_item_creature_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:text="5"
            android:padding="2dp"
            android:textAlignment="center"
            android:textSize="24sp"/>

        <!-- Copies of the creature -->
        <LinearLayout
            android:id="@+id/existing_creature_list_item_copies_group"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:visibility="visible"
            android:layout_gravity="center"
            android:gravity="center"
            >
            <TextView
                android:labelFor="@+id/add_existing_creature_number_of_copies"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="x"/>
            <EditText
                android:id="@id/add_existing_creature_number_of_copies"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:layout_gravity="bottom"
                android:gravity="bottom"
                android:text="2"
                android:padding="8dp"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>


text:
Q: Ошибка в запросе к БД "Column 'day_reports_id' cannot be null" - хотя это внешний ключ Получаю ошибку:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'day_reports_id' cannot be null (SQL: insert into `elementary_reports` (`type`, `project`, `subproject`, `report`, `time`, `day_reports_id`, `updated_at`, `created_at`) values (Рабочее время, Рабочее время, Рабочее время, Рабочее время, 5, , 2018-08-20 21:04:51, 2018-08-20 21:04:51))

Суть ее ясна, но почему-то автоматически не подставляется нужный id из связанной таблицы..
Миграции (для id установлен increments, а также используется ключ foreign и references):
Schema::create('day_reports', function (Blueprint $table) {
        $table->increments('id');
        $table->text('username');
        $table->timestamps();
    });

Schema::create('elementary_reports', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('day_reports_id')->unsigned();
        $table->foreign('day_reports_id')->references('id')->on('day_reports');
        $table->text('type');
        $table->text('project');
        $table->text('subproject')->nullable();
        $table->text('report');
        $table->double('time');
        $table->timestamps();
    });

Контроллер (сделал как в документации):
  $dayReport = new DayReport();
    $dayReport -> username = Auth::user()->name;

    $dayReport->elementaryReports()->saveMany([
        new ElementaryReport(['type' => 'Рабочее время', 'project' => 'Рабочее время', 'subproject' => 'Рабочее время', 'report' => 'Рабочее время', 'time' => 5]),
        new ElementaryReport(['type' => 'Рабочее врем2', 'project' => 'Рабочее врем2', 'subproject' => 'Рабочее врем2', 'report' => 'Рабочее врем2', 'time' => 6]),
    ]);

Модель (указал привязку между двумя таблицами через внешний ключ day_reports_id):
class DayReport extends Model{
public function elementaryReports()
{
    return $this->hasMany('App\ElementaryReport', 'day_reports_id', 'id');
}

Что здесь может быть не так?

A: У вас в коде вы написали
$dayReport = new DayReport();

Это просто экземпляр объекта, он не вставлен в бд!
Это значить что $dayReport не имеет id. А как будет работать saveMany которому надои id для day_reports_id?
Попробуйте так:
$dayReport = DayReport::create([
    'username' => auth()->user()->name
]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find an maxima such that $\sqrt a+\sqrt b$, when $27a^2+b^2=27$ (In high-school level!) How to get a maximum value of $\sqrt a+\sqrt b$, when $27a^2+b^2=27$?

I know that using Lagrange multiplier is easiest way in college-level math, but I believe there is a elementary and elegant way to prove that in high-school level.

I made $a=\cos\theta$ and $b=3\sqrt3\sin\theta$, but in that case, the process of finding the maximum value becomes too messy.

I need your help.

A: Here's an entirely elementary solution, although it may not be very satisfying. We have, using the power-mean inequality,
\begin{align*}
\frac{\sqrt a + \sqrt b}4
&=\frac{\sqrt a + \sqrt{\frac b9} + \sqrt{\frac b9} + \sqrt{\frac b9}}4\\
&\leq \left(\frac{(\sqrt a)^4+\left(\sqrt{\frac b9}\right)^4+\left(\sqrt{\frac b9}\right)^4+\left(\sqrt{\frac b9}\right)^4}{4}\right)^{1/4}\\
&=\left(\frac{a^2+\frac{b^2}{81}+\frac{b^2}{81}+\frac{b^2}{81}}{4}\right)^{1/4}\\
&=\left(\frac{\frac{27a^2+b^2}{27}}{4}\right)^{1/4}=\frac1{4^{1/4}}=\frac1{\sqrt 2}.
\end{align*}
As a result, $\sqrt a+\sqrt b\leq 2\sqrt 2$. Equality is reached at $a=1/2$ and $b=9/2$, as can be traced through the application of the power-mean inequality.
The power-mean inequality is the statement that
$$\left(\frac{\sum_{i=1}^n a_i^p}{n}\right)^{1/p}$$
is an increasing function in $p$. This can be proven for the necessary exponents ($1$ and $4$) in four variables by first showing it for two variables:
$$\frac{x+y}{2}\leq \left(\frac{x^4+y^4}2\right)^{1/4}$$
since
$$\frac{x^4+y^4}2-\left(\frac{x+y}2\right)^4=\frac{(x+y)^4(7x^2+10xy+7y^2)}{16},$$
and then using this to show
$$\frac{w+x+y+z}{4}\leq \frac{\left(\frac{w^4+x^4}2\right)^{1/4}+\left(\frac{y^4+z^4}2\right)^{1/4}}2\leq \left(\frac{w^4+x^4+y^4+z^4}{4}\right)^{1/4}.$$
(These techniques are similar to the proof of the AM-GM inequality.)

It's probably easier to simply use differential calculus: letting $x=\sqrt a$, we wish to maximize
$$f(x) = x+(27-27x^4)^{1/4}.$$
We compute
$$f'(x)=1-\frac{27x^3}{(27-27x^4)^{3/4}}; f''(x)=-\frac{3^{7/4}x^2}{(1-x^4)^{7/4}}<0,$$
so the function has a unique maximum where
$$1=\frac{27x^3}{(27-27x^4)^{3/4}} \implies x=\frac{\sqrt 2}2.$$

A: Let $x = \sqrt{a}$ and $y = \sqrt{b}$, so we are aiming
\begin{align*}
\max_{\substack{x, y \ge 0 \\ 27x^4 + y^4 = 27}} (x + y)
\end{align*}
We can find the max via two applications of Cauchy-Schwarz:
\begin{align*}
x + y = \left\langle \left(x, \frac{y}{\sqrt{3}}\right), (1, \sqrt{3}) \right\rangle \le \sqrt{x^2 + \frac{y^2}{3}}\sqrt{4} \\
x^2 + \frac{y^2}{3} = \left\langle \left(x^2, \frac{y^2}{3\sqrt{3}}\right), (1, \sqrt{3}) \right\rangle \le \sqrt{x^4 + \frac{y^4}{27}}\sqrt{4} = \sqrt{4}
\end{align*}
In order words
\begin{align*}
x + y \le \sqrt{\sqrt{4}} \sqrt{4} = 2\sqrt{2}
\end{align*}
To show this bound is attainable, plug in $(x, y) = (\frac{1}{\sqrt{2}}, \frac{3}{\sqrt{2}})$.

A: You can homogeneise a bit the coefficients by setting $\begin{cases}a=A^2\\b=9B^2\end{cases}$ to get to $\begin{cases}A^4+3B^4=1\\\min(A+3B)\end{cases}$
In fact substituting $A=(1-3B^4)^{\frac 14}$ does not lead to such a mess for the derivative :
$\dfrac{\partial(A+3B)}{\partial B}=3-3\dfrac{B^3}{(1-3B^4)^{\frac 34}}=0\iff (1-3B^4)^{\frac 34}=B^3\implies B^{12}=(1-3B^4)^3$
This simplifies to $$28B^{12}-27B^8+9B^4-1=\underbrace{(2B^2+1)}_\text{>0}(2B^2-1)\underbrace{(7B^8-5B^4+1)}_{>0}$$
Note: the last one behaves as $7x^2-5x+1$, which is a quadratic with no real roots.
So in the end, only $B^2=\frac 12$ which leads to $A^2=\frac 12$ too are critical values.

A: Alternately, using Hölder's Inequality,
$$\sqrt{a}+\sqrt{b} \leqslant \left(27a^2+b^2 \right)^{1/4} \left(\tfrac13+1 \right)^{3/4} =2\sqrt2 $$
Equality is possible when $27a^2:b^2=\frac13:1 \implies (a, b) = (\frac12, \frac92)$, so this gives a maximum.


text:
Q: Cannot connect to RabbitMQ in Cloudfoundry Micro Instance I have an application I have been running on cloudfoundry.com for a while and everything works great when deployed to api.cloudfoundry.com.  I recently set up a CF Micro instance to do local testing in a cloud environment and when my application is deployed to the micro instance, it cannot connect to my rabbit service. I get the following exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.integration.MessageHandlingException: error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
...
org.springframework.integration.MessageHandlingException: error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]
    org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:79)
    org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115)
    org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102)
...
org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection timed out
    org.springframework.amqp.rabbit.connection.RabbitUtils.convertRabbitAccessException(RabbitUtils.java:109)
    org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:163)
    org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:228)
    org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils$1.createConnection(ConnectionFactoryUtils.java:119)
    org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.doGetTransactionalResourceHolder(ConnectionFactoryUtils.java:163)
    org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.getTransactionalResourceHolder(ConnectionFactoryUtils.java:109)
    org.springframework.amqp.rabbit.connection.RabbitAccessor.getTransactionalResourceHolder(RabbitAccessor.java:100)
    org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:591)
    org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:329)
    org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:385)
    org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint.send(AmqpOutboundEndpoint.java:200)
    org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint.handleRequestMessage(AmqpOutboundEndpoint.java:192)

I'm not sure what to look at (i'm sure there is something in the micro instance I can look at, but not sure what), so I thought I'd ask here.
I have verified that the service exists:
vmc services
Getting services... OK

name                    service    version
xxx-mongo    mongodb    2.0
xxx-mysql    mysql      5.1
xxx-rabbit   rabbitmq   2.4

I have verified that the service is bound to my application:
vmc app myapp
myapp: running
  platform: spring on java
  usage: 512M × 1 instance
  urls: mydomain.cloudfoundry.me
  services: xxx-mysql, xxx-rabbit, xxx-mongo

I even tried to rebind it but it says it is bound:
vmc bind-service xxx-rabbit myapp
Binding xxx-rabbit to myapp... SKIPPED
App myapp already binds xxx-rabbit.

My app is a Spring application.  The config for the rabbit service is set up like so:
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:cloud="http://schema.cloudfoundry.org/spring"
        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
        xmlns:rabbit="http://www.springframework.org/schema/rabbit"
        xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd
          http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
          http://www.springframework.org/schema/jdbc
          http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
          http://schema.cloudfoundry.org/spring
          http://schema.cloudfoundry.org/spring/cloudfoundry-spring.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
          http://www.springframework.org/schema/util
          http://www.springframework.org/schema/util/spring-util-3.1.xsd">

    <!-- MongoDB setup -->
    <mongo:db-factory
        id="mongoDbFactory"
        dbname="xxx"
        host="127.0.0.1"
        port="27017"
        username="test_user"
        password="test_pass"  />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory" />
    </bean>

    <!-- Set up the AmqpTemplate/RabbitTemplate: -->
    <rabbit:connection-factory id="rabbitConnectionFactory"/>
    <rabbit:template id="rabbitTemplate" connection-factory="rabbitConnectionFactory"/>

    <bean id="jdbcDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
        <property name="username" value="spring" />
        <property name="password" value="spring" />
    </bean>

    <jdbc:initialize-database data-source="jdbcDataSource">
        <jdbc:script location="classpath:oauthTokenStoreSchema.sql"/>
    </jdbc:initialize-database>
</beans>

This config relies on the Spring auto-reconfig, which is working fine as far as I can tell.  It doesn't complain as startup, only when I actually try to send a message to the queue like so:
org.springframework.integration.Message<Message> msg = MessageBuilder.withPayload(m).build();
messagesChannel.send(msg);

Lastly, I logged into the micro instance to see if rabbit is actually running and it appears to be:
vcap@micro:~$ ps -ef | grep rabbit
root      1492     1  0 Jan14 ?        00:17:00 ruby /var/vcap/packages/rabbit_node/services/rabbit/bin/rabbit_node -c /var/vcap/jobs/rabbit_node/config/rabbit_node.yml
root      1509     1  0 Jan14 ?        00:14:48 ruby /var/vcap/packages/rabbit_gateway/services/ng/rabbit/bin/rabbit_gateway -c /var/vcap/jobs/rabbit_gateway/config/rabbit_gateway.yml
root      1771  1492  0 Jan14 ?        00:14:36 /var/vcap/data/packages/erlang/3/lib/erlang/erts-5.8.2/bin/beam -W w -K true -A30 -P 1048576 -- -root /var/vcap/data/packages/erlang/3/lib/erlang -progname erl -- -home /var/vcap/store/rabbit/instances/d55204b5-814c-4c64-bd35-861d77ee927d -- -noshell -noinput -sname d55204b5-814c-4c64-bd35-861d77ee927d@localhost -boot /var/vcap/store/rabbit/instances/d55204b5-814c-4c64-bd35-861d77ee927d/plugins/rabbit -config /var/vcap/store/rabbit/instances/d55204b5-814c-4c64-bd35-861d77ee927d/config/rabbitmq -kernel inet_default_connect_options [{nodelay,true}] -rabbit tcp_listeners [{"10.0.1.21",10001}] -sasl errlog_type error -kernel error_logger {file,"/var/vcap/sys/service-log/rabbit/d55204b5-814c-4c64-bd35-861d77ee927d/d55204b5-814c-4c64-bd35-861d77ee927d@localhost.log"} -sasl sasl_error_logger {file,"/var/vcap/sys/service-log/rabbit/d55204b5-814c-4c64-bd35-861d77ee927d/d55204b5-814c-4c64-bd35-861d77ee927d@localhost-sasl.log"} -os_mon start_cpu_sup true -os_mon start_disksup false -os_mon start_memsup false -mnesia dir "/var/vcap/store/rabbit/instances/d55204b5-814c-4c64-bd35-861d77ee927d/mnesia" -smp disable
vcap     49299 49278  0 02:38 pts/0    00:00:00 grep --color=auto rabbit

Again, when I deploy to api.cloudfoundry.com, the app can connect to the rabbitmq just fine.  I'm running v119 of micro as well if that helps.
Any help you could provide would be great!  Thanks.
EDIT:
Per Hitesh recommendation, I tried to use the cloud profile, but that didn't work.  I also tried this:
<beans profile="default">
        <rabbit:connection-factory
            id="rabbitConnectionFactory"
            host="localhost"
            password="testpwd"
            port="1238"
            username="testuser"
            virtual-host="virthost" />
        <rabbit:template id="rabbitTemplate" connection-factory="rabbitConnectionFactory"/>
    </beans>

    <beans profile="cloud">
        <cloud:rabbit-connection-factory id="rabbitConnectionFactory" />
        <rabbit:template id="rabbitTemplate" connection-factory="rabbitConnectionFactory"/>
    </beans>

What is interesting though, is that I tried this (copied out of the docs):
<rabbit:connection-factory
    id="rabbitConnectionFactory"
    host="localhost"
    password="testpwd"
    port="1238"
    username="testuser"
    virtual-host="virthost" />
<rabbit:template id="rabbitTemplate" connection-factory="rabbitConnectionFactory"/>

And now my sending application works!  But my receiving app still doesn't work.  It gets this error:
ERROR: main org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter#0'; nested exception is org.springframework.amqp.UncategorizedAmqpException: java.util.concurrent.TimeoutException: Timed out waiting for startup
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:170)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$1(DefaultLifecycleProcessor.java:154)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:339)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:143)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:108)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:926)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:467)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1206)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1079)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1002)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:506)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.amqp.UncategorizedAmqpException: java.util.concurrent.TimeoutException: Timed out waiting for startup
    at org.springframework.amqp.rabbit.connection.RabbitUtils.convertRabbitAccessException(RabbitUtils.java:118)
    at org.springframework.amqp.rabbit.connection.RabbitAccessor.convertRabbitAccessException(RabbitAccessor.java:106)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.start(AbstractMessageListenerContainer.java:365)
    at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.doStart(AmqpInboundChannelAdapter.java:85)
    at org.springframework.integration.endpoint.AbstractEndpoint.start(AbstractEndpoint.java:84)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:167)
    ... 39 more
Caused by: java.util.concurrent.TimeoutException: Timed out waiting for startup
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.getStartupException(SimpleMessageListenerContainer.java:512)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doStart(SimpleMessageListenerContainer.java:337)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.start(AbstractMessageListenerContainer.java:363)
    ... 42 more

I've tried all the configurations above, but none work.

A: I would suggest trying out the sample spring app using rabbitmq, it lives here :
https://github.com/rabbitmq/rabbitmq-cloudfoundry-samples/tree/master/spring. Also there is a step by step doc to help you through it. You can compare the config there with your app and if it works, that means something might be missing in the config.
Also if this does not help then you can post a question here "http://support.cloudfoundry.com"
giving us access to your application so we can try deploying it ourselves.
Thanks,

*

*Hitesh

A: I would suggest you try replacing the lines :
<!-- Set up the AmqpTemplate/RabbitTemplate: -->
<rabbit:connection-factory id="rabbitConnectionFactory"/>

with :
<!-- Obtain a connection to the RabbitMQ via cloudfoundry-runtime: -->
<cloud:rabbit-connection-factory id="connectionFactory"/>

The latter case is using the cloud namespace which will read the rabbit-


text:
Q: How to symlink python in Homebrew? For some reason it's no symlinking when I run `brew link python.' I'm getting the following error and I do what it tells me to do but it's not working. I have tried doing what it tells me to do but maybe I'm not putting the formula_name right. Also, when I do 'which python' it doesn't point to the Homebrew python and I need help fixing that as well.
    Linking /usr/local/Cellar/python/2.7.3...Warning: Could not link python.
    Unlinking....

   Error: Could not symlink file: /usr/local/Cellar/python/2.7.3/bin/smtpd.py
   Target /usr/local/bin/smtpd2.py already exists. You may need to delete it.
   To force the link and delete this file, do:
      brew link --overwrite formula_name

A: Did you try brew link --overwrite python?


text:
Q: Asynchronous calls using postgres as an example in NodeJS When implementing this code (example taken directly from https://github.com/brianc/node-postgres):
var pg = require('pg');

var conString = "tcp://postgres:1234@localhost/postgres";

pg.connect(conString, function(err, client) {
  client.query("SELECT NOW() as when", function(err, result) {
      console.log("Row count: %d",result.rows.length);  // 1
      console.log("Current year: %d", result.rows[0].when.getFullYear());
      //Code halts here
  });
});

After the last console.log, node hangs. I think this is because the asynchronous nature, and I suspect at this point, one should call a callback function.
I have two questions:

*

*Is my thinking correct?

*If my thinking is correct, then how does the mechanics work. I know NodeJS is using an event loop, but what is making this event loop halt at this point?

A: It appears to hang because the connection to Postgres is still open. Until it's closed, or "ended"...
client.end(); // Code halts here

Node will continue to wait in idle for another event to be added to the queue.

*

*Not quite. This is a detail of node-postgres and its dependencies, not of Node or of its "asynchronous nature" in general.

*The idling is due to and documented for the generic-pool module that node-postgres uses:

If you are shutting down a long-lived process, you may notice that node fails to exit for 30 seconds or so. This is a side effect of the idleTimeoutMillis behavior -- the pool has a setTimeout() call registered that is in the event loop queue, so node won't terminate until all resources have timed out, and the pool stops trying to manage them.

And, as it explains under Draining:

If you know would like to terminate all the resources in your pool before their timeouts have been reached, you can use destroyAllNow() in conjunction with drain():
pool.drain(function() {
    pool.destroyAllNow();
});

One side-effect of calling drain() is that subsequent calls to acquire() will throw an Error.

Which is what pg.end() does and can certainly be done if your intention is to exit at the end of a serial application, such as unit testing or your given snippet.


text:
Q: Is there a way to export data from S3 to Amazon Aurora serverless with lambda? So I was searching for a solution that could let me export S3 data into Aurora Serverless. I know that the LOAD DATA request is only available for the Aurora cluster not the serverless one.
I've found some documentation about the data injection from S3 to RDS MySQL but I don't know if this still applies to Amazon Aurora MySQL.

A: If you're ok with temporarily putting the data on an ec2 instance, you can do it in two steps:
aws s3 cp s3://path/to/mydatafile /local/path/to/mydatafile
mysql --defaults-file=/path/to/.my.cnf -e "load data local infile '/local/path/to/mydatafile' into table sampletable"
References
StackOverflow discussion on loading data
MySQL "load data" reference
Copying from s3
Using MySQL options files


text:
Q: Inheritance inside Classes Python3 I need something like this
class Parent(object):
    class Base(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

    class Derived(Base):
        def __init__(self, a, b, c):
            super(Derived,self).__init__(a, b)
            self.c = c

        def doit():
            pass

parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()

When I try to run this, i get this following error: NameError: name 'Derived' is not defined
I tried with 'Base' in the place of 'Derived' in super() - didn't help

A: Class inheritance does not change the parent class. In this case your Parent class only contains the original Base class and not the derived class.
You can simply use monkey-patching to solve this problem,
class Parent(object):
    pass

class Base(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

class Derived(Base):
    def __init__(self, a, b, c):
        super(Derived,self).__init__(a, b)
        self.c = c

    def doit(self):
        pass

Parent.Derived = Derived

parent = Parent()
x, y , z = 1, 1, 1
derived = parent.Derived(x,y,z)
derived.doit()

A: Prefixing 'Derived' with 'Parent.', made it. As I already have commented on the question. This is just for experimenting with the 'Derived' class. But I am still wondering how the, 'class Derived(Base):' is fine (without 'Parent.' prefix for 'Base' class)
class Parent(object):
    class Base(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

    class Derived(Base):
        def __init__(self, a, b, c):
            super(Parent.Derived,self).__init__(a, b)
            self.c = c

        def doit():
            pass

parent = Parent()
derived = parent.Derived(x,y,z)
derived.doit()


text:
Q: Method that returns the yield for an object in Ruby Is there a method in Ruby that returns the content of the block passed on to an object?
For example, what if I have an object which I want to put in an array?
In an ideal world, we would do (what I'm looking for):
"string".reverse.upcase.something{ |s| send(s) }

which would return an array with my object, as equivalent to:
send("string".reverse.upcase)

which isn't chainable if I have my object to start with and can get messy in more complex scenarios.
So the something method would return the evaluation of the block, like Array#map, but for one element only.

A: I don't know of such a thing built-in but you can easily do it yourself:
class Object
  def something(&block)
    block.call(self)
  end
end

p "foo".something { | o | [o] }
p 23.something { | x | p x; 42 }

gives
["foo"]      # object "foo" put into an array
23           # object handed to block
42           # something return block's result

A: Six years after the original question, Ruby 2.5.0 introduced Object#yield_self, then shortened in Ruby 2.6 as #then:

 class Object
   def yield_self(*args)
     yield(self, *args)
   end
 end

[...]
It executes the block and returns its output.
(Ruby Feature #6721)

For example:
2.then{ |x| x*x }  # => 4

A: Are you looking for Object.tap ?

A: I sometimes wish for a similar function in the standard library. The name could for example be with or with_it
(Repeating previous code with new name)
class Object
  def with_it(&block)
    block.call(self)
  end
end

Example usage:
x = [1, 2, 3, 4, 5].map {|x| x * x }.with_it do |list|
   head = list.unshift
   list << head * 10
   list.join " / "
end

As opposed to:
list = [1, 2, 3, 4, 5].map {|x| x * x }
head = list.unshift
list << head * 10
x = list.join " / "

While the latter is easier to understand, the former has the benefit of keeping the variables list and head scoped and the assignment to x is more clear in my opinion (the assignment to x has to be inserted into the last line of the code). Scoping would be a benfit if the code was a part of a larger method.
Another option to using with_it would thus be putting the code in a separate method. Eg:
def mult_head_and_join(list)
    head = list.unshift
    list << head * 10
    list.join " / "
end

x = mult_head_and_join [1, 2, 3, 4, 5].map {|x| x * x }

Not sure what to conclude with here, but I guess I'd vote for with_it to be included in the standard library


text:
Q: Problems encountered when writing astronomy/astrodynamic program I am attempting to write a program that will show me the sky from a certain point on the earth with certain solar system bodies using the JPL Horizons Ephemeris. There are two problems I encountered: the astroquery.jplhorizons module will not work, and I do not have a sufficient 3D graphics module that I know how to use. Here is the code from the first problem; it was a test directly from the documentation (https://astroquery.readthedocs.io/en/latest/jplhorizons/jplhorizons.html).
from astroquery.jplhorizons import Horizons
obj = Horizons(id='Ceres', location='568',
            epochs={'start':'2010-01-01', 'stop':'2010-03-01','step':'10d'})
eph = obj.ephemerides()
print(eph)

The docs say I should get this:
targetname    datetime_str   datetime_jd ...   GlxLat  RA_3sigma DEC_3sigma
  ---            ---             d      ...    deg      arcsec    arcsec
---------- ----------------- ----------- ... --------- --------- ----------
   1 Ceres 2010-Jan-01 00:00   2455197.5 ... 24.120057       0.0        0.0
   1 Ceres 2010-Jan-11 00:00   2455207.5 ... 20.621496       0.0        0.0
   1 Ceres 2010-Jan-21 00:00   2455217.5 ... 17.229529       0.0        0.0
   1 Ceres 2010-Jan-31 00:00   2455227.5 ...  13.97264       0.0        0.0
   1 Ceres 2010-Feb-10 00:00   2455237.5 ... 10.877201       0.0        0.0
   1 Ceres 2010-Feb-20 00:00   2455247.5 ...  7.976737       0.0        0.0

However, instead I get this error when I run from my terminal:
Traceback (most recent call last):
 File ".\astrotest.py", line 4, in <module>
    eph = obj.ephemerides()
File "C:\Users\ct_sk\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroquery\utils\class_or_instance.py", line 25, in f
    return self.fn(obj, *args, **kwds)
File "C:\Users\ct_sk\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroquery\utils\process_asyncs.py", line 29, in newmethod
    result = self._parse_result(response, verbose=verbose)
File "C:\Users\ct_sk\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroquery\jplhorizons\core.py", line 946, in _parse_result
    data = self._parse_horizons(response.text)
File "C:\Users\ct_sk\AppData\Local\Programs\Python\Python36-32\lib\site-packages\astroquery\jplhorizons\core.py", line 852, in _parse_horizons
    raise IOError('Cannot parse table column names.')
OSError: Cannot parse table column names.

I don't know what to do about this. For the 3D question, I have dabbled a little in OpenGL and I find it too difficult and I would like something simpler. Usually when I do 3D graphics I use Processing (https://processing.org/), and something like that would be perfect. Thanks for the help.

A: I've tried to look at the source code of this library but the line numbers didn't match yours so you need to check this in your code.
Look at the file core.py and line 852, there's your error. You can print the value/object that is used there and see if it's something you expect. In Python errors are often propagated further, so if the value is wrong you need to check where did you get it from and debug there.
If you show us the line with your error we may be able to help you more.


text:
Q: Xamarin Amazon S3 Uploads Has anyone had any experience using Amazon S3 file uploads on Xamarin? It should be simple, but I am having trouble getting it to work. I'm trying to use https://github.com/xamarin/amazon to do my upload of a file like so:
try
{
    var client = new AmazonS3Client ("REDACTED", "REDACTED");
    var transferUtility = new TransferUtility (client);
    TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
        .WithBucketName("bucketname")
        .WithFilePath(image.LocalPath)
        .WithKey("rodsTest")
        .WithTimeout(5 * 60 * 1000);
    transferUtility.Upload(request);

} catch (Exception ex){
    Console.WriteLine (ex.ToString ());
}

But I'm getting this exception:
System.ObjectDisposedException: The object was used after being disposed. at System.Net.WebConnection.BeginWrite (System.Net.HttpWebRequest request, System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback cb, System.Object state) [0x0001f] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnection.cs:1033 at System.Net.WebConnectionStream.BeginWrite (System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback cb, System.Object state) [0x0026c] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:541
The github repo hasn't been updated in a year so maybe it's just broken? All I want to do is PUT and DELETE files so my next step is to just hit the REST API with RestSharp rather than use a wrapper but surely this is something others have done, can anyone shed some light?

A: Check out: amazon s3 file upload using xamarin  c#
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = serviceUrl; // amazon s3 URL
config.UseHttp = true;
config.RegionEndpoint =Amazon.RegionEndpoint.APNortheast1; // your region

AmazonS3Client client = new AmazonS3Client(accessKey,
    secretAccessKey, config);

TransferUtility transferUtility = new TransferUtility(client);

TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
request.BucketName = s3Bucket;
request.FilePath = filePath; // local file path

// Test that the path is correct
UIImage image = UIImage.FromFile(filePath);

System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken();
await transferUtility.UploadAsync(request, cancellationToken);


text:
Q: Kotlin, вопрос по function reference Долго вчитывался в документацию, но не до конца понял, как оно работает.
Внутренний голос нашептывает, что вот эти две строки должны делать одно и то-же:
private fun makePost(post: Map<String, String>): RequestBody {
    val body = FormBody.Builder()
1:    post.forEach { (k, v) -> body.add(k, v) }
2:    post.forEach { body::add }
    return body.build()
}

Но не делают. первая работает, а вторая нет (body остается пустым, но и ошибок нет)
растолкуйте, пожалуйста, где мой внутренний голос облажался и можно ли(как?) использовать тут function reference?

A: Отлично, что с версией все ясно. Вот мое обьяснение:
Метод forEach для вашей Map оперирует элементами Map.Entry<String, String>, а это не то же самое, что два параметра типа String, необходимые методу body::add.
Но Kotlin вместо того, чтобы ругнуться, делает вид что сможет развернуть элемент, как делает в варианте №1, но что-то не получается.
Думаю, что можете зарепортить им баг. Как минимум на то, что нет ни ошибки, ни предупреждения, но код не работает.
Вот ссылка на имплементацию этой фичи.
https://youtrack.jetbrains.com/issue/KT-6947
Это похоже на специфический кейс для Map, который упустили в тестах новой фичи.

A: Ответ разработчиков:

Your code is incorrect. To pass a method reference to a function, you
  need to enclose it in parentheses, not in curly braces:
  bar.forEach(foo1::add)

При передаче (method)function reference в функцию необходимо использовать обычные скобки, а не фигурные.
Следующие три строки выполняют одно и то же:
post.forEach ({ (k, v) -> body.add(k, v) })
post.forEach { (k, v) -> body.add(k, v) }
post.forEach (body::add)

Обратите внимание, что метод, на который осуществляется ссылка, должен возвращать Unit, иначе даже не скомпилируется.
Если единственным параметром является лямбда, то обычные скобки можно опустить и оставить только фигурные (строки 1 и 2)


text:
Q: In The Rolling Stones, did Heinlein deliberately try to confuse the reader with nicknames? Robert Heinlein's novel The Rolling Stones has two or three unrelated names for six out of the seven main characters.  The narrator and different characters use different names for calling each other.  (The 16 year old twin brothers Castor and Pollux call each other Grandpa and Junior.)
Even though the family nicknames make sense in-universe, no explanation is given to the reader, and this was very confusing to me.  It took me about a quarter of the book until I figured out just how many members the family has and who they are.
Did Heinlein deliberately try to confuse the readers with these names, or am I just too stupid to understand his prose?

A: I think the multiple names for each character may have been used as shorthand to let the reader know not only who was being addressed, but also who was addressing them.

A: The confusion for the reader isn't deliberate, but it reflects the confusion that the Stone family would cause in anyone that visited them - the twins squabbling, Mother and Father having a discussion of what they ought to do, Meade on the phone, the baby crying and Grandma putting her oar in as she pleased. Heinlein did grow up in a large family, so that kind of situation was probably familiar to him.
It's possible that Heinlein was also deliberately emulating a particular style of movie dialogue - full of snappy comebacks and nicknames for characters, rather like a Cary Grant movie.

A: I've read the book many times, and never had any trouble telling who was who.
So, I don't see any cause to assume Heinlein was trying to confuse anyone.


text:
Q: How to find architecture of my PC and Ubuntu? When running uname -a, I get as output
41-Ubuntu SMP Mon Aug 13 17:59:54 UTC 2012 i686 athlon i386 GNU/Linux

Can someone please explain to  me why both i386 & i686 ?
What exactly is my PC architecture and what version of Ubuntu am I using (32bit or 64bit)?

A: Use Anwar's answer to find the architecture.
Now here is the explanation for your second part of the question.
Below is the uname output: In my case I have installed a 32 bit version. Both i386 and i686 refer 32 bit version. uname will return x86_64 in case if it is a 64 bit version.
$ uname -a
Linux devav2 3.2.0-30-generic-pae #48-Ubuntu SMP Fri Aug 24 17:14:09 UTC 2012 i686 i686 i386 GNU/Linux

*

*Linux(-s) - OS/Kernel name

*devav2(-n) - hostname

*3.2.0-30-generic-pae (-r) - kernel release

*48-Ubuntu SMP Fri Aug 24 17:14:09 UTC 2012 (-v) - Kernel version with time and SMP stands for symmetric multiprocessing, which means you have multiprocessor support

*i686(-m) - Machine hardware name

*i686(-p) - processor type

*i386(-i) - hardware platform

*GNU/LINUX(-o) - Operating System name

Below is grabbed from uname --help page which might help you to understand more about it.
 -a, --all                print all information, in the following order,
                             except omit -p and -i if unknown:
  -s, --kernel-name        print the kernel name
  -n, --nodename           print the network node hostname
  -r, --kernel-release     print the kernel release
  -v, --kernel-version     print the kernel version
  -m, --machine            print the machine hardware name
  -p, --processor          print the processor type or "unknown"
  -i, --hardware-platform  print the hardware platform or "unknown"
  -o, --operating-system   print the operating system

A: If all you want is the architecture you could always try the command called arch.  It is very terse.  It is not POSIX.

A: For debian Linux derived systems, one possible command is dpkg-architecture -q DEB_BUILD_ARCH.
On 64bits systems, it returns :
$ dpkg-architecture -q DEB_BUILD_ARCH
amd64

On 32bits systems, it returns :
$ dpkg-architecture -q DEB_BUILD_ARCH
i386

A: The command is uname -m.
Open a terminal try using uname -m command. This should show you the OS architecture.
If it gives any output like ix86, where x is 3,4,5 or 6, Your OS is 32bit.
You can also see the Ubuntu architecture by Opening "System monitor" and going in the System tab.

Difference between hardware platform and Processor type:
There is a difference between the hardware platform (which is given by -i switch) to the CPU type (given by -p switch).
The hardware platform tells us which architecture the kernel is built for (may be optimized though for later versions). It can be a i386.
However the Processor type refers to the actual processor type of your machine such as i686 (P4 and later builds).
Thanks to Schotty of this this page. Here is an answer from Unix stackexchange site on the same topic, though I didn't find the language enough clear (completely my fault).

A: use syscap from Formake project https://sourceforge.net/projects/formake
syscap allows to probe many system properties and test dependencies. It is a portable shell script.


text:
Q: Does Landscape support Ubuntu derivatives? Can we add an Ubuntu derivative to list of computers to manage in Ubuntu Landscape or just Ubuntu?
At least the official ones (Lubuntu, Xubuntu, etc.).

A: I don't know about support in the commercial sense (as in - will you get paid support from Canonical with them), but landscape technically works fine on derivatives.
I personally run Ubuntu/Xubuntu/Lubuntu and all of them work properly.
Full disclaimer: I'm a Landscape engineer.


text:
Q: Integral Calculus: Plane Areas in Rectangular Coordinates Find the area bounded by the given curves:
$y^2+2x-2y-3=0$ and the $y$-axis
(using horizontal & vertical strip)

A: Finding the points:
$x = 0$ so
$$ y^2+2(0)-2y-3=0 $$
$$ y^2-2y-3=0 $$
$$ (y-3)(y+1)=0 $$
Thus points $P$ are $(0,3),(0,-1)$.
By completing the square
$y^2-2y+1=-2x+3+1$.
$$ (y-1)^2=-2(2x-2) $$
$ y=1, x=2 ,
V = (2,1) $
The parabola opens left.


text:
Q: How to Create MULTIPLE bundles in iPhone Application? Hi I have a situation where my application can be used for different purposes depending on certain inputs.
Ex: I have a Theme.js which will have contents for Type A and another Theme.js will have contents for Type B. Here i will need to create a two bundles so that my application automatically will point to the bundle which will be used and use resources from that particular bundle.
I am not getting where to start with like How do i create a bundle. Is new file >resources> settings.bundle ?
ANY HELP WOULD REALLY BE APPRECIATED :)

A: Step 1) Make new folder on Mac
Step 2) Add files to folder
Step 3) Add .bundle extension to that folder
Step 4) Add the file to XCode
Step 5) ...?
Step 6) PROFIT!


text:
Q: Issue testing spring cloud SQS Listener Environment

*

*Spring Boot: 1.5.13.RELEASE

*Cloud: Edgware.SR3

*Cloud AWS: 1.2.2.RELEASE

*Java 8

*OSX 10.13.4

Problem
I am trying to write an integration test for SQS.
I have a local running localstack docker container with SQS running on TCP/4576
In my test code I define an SQS client with the endpoint set to local 4576 and can successfully connect and create a queue, send a message and delete a queue. I can also use the SQS client to receive messages and pick up the message that I sent.
My problem is that if I remove the code that is manually receiving the message in order to allow another component to get the message nothing seems to be happening. I have a spring component annotated as follows:
Listener
@Component
public class MyListener {
@SqsListener(value = "my_queue", deletionPolicy = ON_SUCCESS)
    public void receive(final MyMsg msg) {
        System.out.println("GOT THE MESSAGE: "+ msg.toString());
    }
}

Test
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyTest {

    @Autowired
    private AmazonSQSAsync amazonSQS;

    @Autowired
    private SimpleMessageListenerContainer container;

    private String queueUrl;

    @Before
    public void setUp() {
        queueUrl = amazonSQS.createQueue("my_queue").getQueueUrl();
    }

    @After
    public void tearDown() {
        amazonSQS.deleteQueue(queueUrl);
    }

    @Test
    public void name() throws InterruptedException {
        amazonSQS.sendMessage(new SendMessageRequest(queueUrl, "hello"));
        System.out.println("isRunning:" + container.isRunning());
        System.out.println("isActive:" + container.isActive());
        System.out.println("isRunningOnQueue:" + container.isRunning("my_queue"));
        Thread.sleep(30_000);
        System.out.println("GOT MESSAGE: " + amazonSQS.receiveMessage(queueUrl).getMessages().size());
    }

    @TestConfiguration
    @EnableSqs
    public static class SQSConfiguration {

        @Primary
        @Bean(destroyMethod = "shutdown")
        public AmazonSQSAsync amazonSQS() {
            final AwsClientBuilder.EndpointConfiguration endpoint = new AwsClientBuilder.EndpointConfiguration("http://127.0.0.1:4576", "eu-west-1");
            return new AmazonSQSBufferedAsyncClient(AmazonSQSAsyncClientBuilder
                    .standard()
                    .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("key", "secret")))
                    .withEndpointConfiguration(endpoint)
                    .build());
        }
    }
}

In the test logs I see:

o.s.c.a.m.listener.QueueMessageHandler   : 1 message handler methods found on class MyListener: {public void MyListener.receive(MyMsg)=org.springframework.cloud.aws.messaging.listener.QueueMessageHandler$MappingInformation@1cd4082a}
  2018-05-31 22:50:39.582  INFO 16329 ---
o.s.c.a.m.listener.QueueMessageHandler   : Mapped "org.springframework.cloud.aws.messaging.listener.QueueMessageHandler$MappingInformation@1cd4082a" onto public void MyListener.receive(MyMsg)

Followed by:

isRunning:true
isActive:true
isRunningOnQueue:false
GOT MESSAGE: 1

This demonstrates that in the 30 second pause between sending the message the container didn't pick it up and when I manually poll for the message it is there on the queue and I can consume it.
My question is, why isn't the listener being invoked and why is the isRunningOnQueue:false line suggesting that it's not auto started for that queue?
Note that I also tried setting my own SimpleMessageListenerContainer bean with autostart set to true explicitly (the default anyway) and observed no change in behaviour. I thought that the org.springframework.cloud.aws.messaging.config.annotation.SqsConfiguration#simpleMessageListenerContainer that is set up by @EnableSqs ought to configure an auto started SimpleMessageListenerContainer that should be polling for me message.
I have also set
logging.level.org.apache.http=DEBUG
logging.level.org.springframework.cloud=DEBUG

in my test properties and can see the HTTP calls create the queue, send a message and delete etc but no HTTP calls to receive (apart from my manual one at the end of the test).

A: I figured this out after some tinkering.
Even if the simple message container factory is set to not auto start, it seems to do its initialisation anyway, which involves determining whether the queue exists.
In this case, the queue is created in my test in the setup method - but sadly this is after the spring context is set up which means that an exception occurs.
I fixed this by simply moving the queue creation to the context creation of the SQS client (which happens before the message container is created). i.e.:
@Bean(destroyMethod = "shutdown")
        public AmazonSQSAsync amazonSQS() {
            final AwsClientBuilder.EndpointConfiguration endpoint = new AwsClientBuilder.EndpointConfiguration("http://localhost:4576", "eu-west-1");
            final AmazonSQSBufferedAsyncClient client = new AmazonSQSBufferedAsyncClient(AmazonSQSAsyncClientBuilder
                    .standard()
                    .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("dummyKey", "dummySecret")))
                    .withEndpointConfiguration(endpoint)
                    .build());
            client.createQueue("test-queue");
            return client;
        }


text:
Q: Tensorflow and masking (labeling) images I'm trying to detect face using Tensorflow and Keras.  Dataset is LFW Parts. Not interested in Open CV.

Example of dataset looks like this

Would like to know the following:

*

*If I understood it correctly, python script takes images and theirs masks, runs them through a model and save that model with weights. After that, if accuracy is high enough, predictor can be used to run totally unknown single image and get proper mask as a result. Right?

*If I want to detect face only, with ears, and use LFW dataset, each mask should be edited, and some of the green part removed?

*If that's the case, are there any tools for the job, that will do this automatically or be easy to use? Manual removal seem like a nightmare.

*What about details of mask? In the example above, mask of hair is pretty rough. Will the machine learn ( pun intended ) to make details and eventually set exact hair, or it will remain like this?

*Lets say object was added in front of face, like beard, glasses or hat. What will happen with detection? Will it simply cut it if beyond face edges, or it will detect that shape also? Do I need proper images and masks of that too?


text:
Q: Activii workflow long running task I am using Activti version 6.0.0.
I want synchronous executions of task in activiti,but I have a long running task which might take 20 minutes to execute.
I wanted to get process instance id quickly in my controller without considering completion of task in bpmn,so I added a intermediate timer event of "0 minute" in my bpmn file.
I  have started executing a process,lets say with processInstanceid p1.At that time only I again start the process,lets say with processInstanceid  p2.
Now both processes arrive till the task where there is a wait event of 20 minutes(I have used while loop for this).Now according to the flow both processes should come till the end task and finish their execution but instead of that none of the process finish its execution and run multiple times from first task to end task.
how to run multiple processes independently and parallaly from start task to end task (one of these tasks have code which will take long time to execute)

A: Likely you tasks are timing out and the the retry logic is kicking in which is causing the multiple run. Ultimately the instances will fail after 3 retries.
To be completely candid, synchronous execution of long running tasks can lead to real problems, especially under load where you can easily exceed available threads, memory or other resources.
You'd be far better served to use an asynchronous model such as documented nicely by Camunda here: https://github.com/camunda/camunda-bpm-examples/tree/master/servicetask/service-invocation-asynchronous
I have successfully used this pattern with all of the Activiti variants and it works nicely.


text:
Q: How to convert comma separated array to rows in hive I try to pull anchorurl summary for each transactionid in my table, so I need convert comma separated array to rows.
This is running in Hive, mostly use sql command. (In DDC of Dbeaver actually)
SELECT      eventdate
            ,transactionid
            ,platform
            ,storeid
            ,StringTokenizerDelim(anchorurls,",")
                over (PARTITION by eventdate,transactionid,platform,storeid)
FROM        scribe.tblscriberelatedsearchresults
order by    1,2,3
;

SELECT      eventdate
            ,transactionid
            ,platform
            ,storeid
            ,url
FROM        scribe.tblscriberelatedsearchresults lateral view explode(split(anchorurls,",")) anchorurls as url
order by    1,2,3
;

SELECT      eventdate
            ,transactionid
            ,platform
            ,storeid
            ,split_part(anchorurls,",")
                over (PARTITION by eventdate,transactionid,platform,storeid)
FROM        scribe.tblscriberelatedsearchresults
order by    1,2,3
;

SELECT      eventdate
            ,transactionid
            ,platform
            ,storeid
            ,split(anchorurls,",")
FROM        scribe.tblscriberelatedsearchresults
order by    1,2,3
;
One more thing is:
I find command "explode" can get those array out perfectly, but I don't know how to also keep the other columns such as transactionid with them (which is the foreign key for joining another table)
Originally it was:
eventdate   transactionid   platform   storeid   "url1","url2","url3"

I expect it to be:
eventdate   transactionid   platform   storeid   url1
eventdate   transactionid   platform   storeid   url2
eventdate   transactionid   platform   storeid   url3

Error message:

Reason: SQL Error [42601]: ERROR: ('HY000', "[HY000]
  [Cloudera][HiveODBC] (35) Error from Hive: error code: '40000' error
  message: 'Error while compiling statement: FAILED: SemanticException
  Failed to breakup Windowing invocations into Groups. At least 1 group
  must only depend on input columns. Also check for circular
  dependencies.\nUnderlying error: Invalid function split_part'. (35)
  (SQLExecDirectW)")   Position: 13

A: You can use lateral view explode to get output you're looking for
Please follow this link explained in detail with the examples


text:
Q: Proving that if $ed ≡ 1 \pmod{\frac12 φ(n)} $, then $y^{ed} ≡ y \pmod{ n}.$ This is actually the third step of the problem. It's preceded by these questions that I'm sure are supposed to lead me to solution.
$n = pq$, p and q distinct odd primes
First I'm supposed to show that $y^{\frac{1}{2}\phi(n)} \equiv 1 \pmod{ p}$ and that $y^{\frac{1}{2}\phi(n)} \equiv 1 \pmod{ q}$. $gcd(y, n) = 1$
Since $\phi(n) = (p-1)(q-1)$, I showed that $y^{\frac{1}{2}(p-1)(q-1)} \equiv [y^{\frac{1}{2}(q-1)}]$$^{(p-1)} \equiv 1 \pmod{ p}$ (by Fermat's Theorem) and did basically the same thing for the other equivalence relation. Does Fermat's theorem apply in this case? I'm hoping that it's safe to assume $gcd(y^{\frac{1}{2}(q-1)}, p-1) =1$
Then I was supposed to show that $y^{\frac12\phi(n)} \equiv 1 \pmod{ n}$ from the previous steps, but I said that $y^{\frac12\phi(n)} \equiv [y^{\frac12}] ^{\phi(n)} \equiv 1 \pmod{ n}$ by Euler's Theorem (again making a similar assumption)
Then comes the question I posted in the title: Proving that if $ed ≡ 1 \pmod{\frac12 φ(n)} $,  then $y^{ed} ≡ y \pmod{ n}.$
I'm not really seeing the connection between these different statements which makes me think that I did the first ones wrong. I'm thrown off by the $\frac12$ because otherwise it's easy to see that $y^{ed} ≡ y \pmod{ n}. \implies ed ≡ 1 \pmod{ φ(n)} $. I'm not seeing how to prove that it still works with the $\frac12$.
Any advice or anyone see where I did something wrong? Thanks!

A: Since $y$ is prime to $n$ (and $p$), so is $y^{\frac12(q-1)}$ amd indeed little Fermat tells us that $y^{\frac12\phi(n)}\equiv 1\pmod p$. By symmetry, also $y^{\frac12\phi(n)}\equiv 1\pmod q$. Then by the Chinese Remainder Theorem, $y^{\frac12\phi(n)}\equiv a\pmod n$.
So finally if $ed=k\cdot\frac12\phi(n)+1$ we find $y^{ed}=\left(y^{\frac12\phi(n)}\right)^k\cdot y\equiv y\pmod n$.

A: Let $n = pq$, p and q distinct odd primes
Claim:  $y^{\frac{1}{2}\phi(n)} \equiv 1 \pmod{ p}$ and $y^{\frac{1}{2}\phi(n)} \equiv 1 \pmod{ q}$.
As $gcd(y, n) = 1$ so $gcd(p, n) = 1$ and $gcd(q, n) = 1$, so by Fermat's theorem,
$y^{\phi(p)} \equiv 1\pmod{ p}$ and $y^{\phi(q)} \equiv 1\pmod{ q}$
As p and q are distinct odd primes, so $2|(p-1)$ and $2|(q-1)$
or rather $2|\phi(p)$ and $2|\phi(q)$.
$y^{\frac{1}{2}(p-1)(q-1)} \equiv [y^{(p-1)}]$$^{\frac{1}{2}(q-1)}\equiv 1 \pmod{ p}$
Hence,$y^{\frac{1}{2}\phi(n)} \equiv 1 \pmod{ p}$ and $y^{\frac{1}{2}\phi(n)} \equiv 1 \pmod{ q}$.
From here can you see why we have $y^{\frac12\phi(n)} \equiv 1 \pmod{ n}$.
You can not safely assume things, you need a proof for anything you claim.
Claim: $ed ≡ 1 \pmod{\frac12 φ(n)} $,  then $y^{ed} ≡ y \pmod{ n}.$
Now, if you have ${\frac12 φ(n)} | (ed-1)$ then $(ed-1) = k{\frac12 φ(n)} $for some $k \in N$
From here, can you see why $y^{ed} ≡ y \pmod{ n}.$
Hope this helps!!


text:
Q: echo input tag with oninput validity in php Others things it seem fine but once it involve function in the element the echo php doesnt work. For example this one
<?php
    $output = '';
    $output .'

                Written Score
                <input class="form-control" placeholder="Written Score" type="number" name="written" id="written" min="0" max="100" oninput="validity.valid||(value='');" />

';

    echo $output;
?>

it seem the oninput="validity.valid||(value='');" is make this code doesn't works.

A: You need to escape those single quotes inside the string assignment. Change ' to \':
"validity.valid||(value=\'\');"


text:
Q: SQL column name period (.) * I read the following query:
SELECT a.* FROM my_table AS a JOIN your_table AS b ON ...

What is a.* and what does it mean/do?

A: It means "all columns from table a", which in your example refers to my_table.
If you want a specific column, you could do something like:
SELECT a.columnName, a.anotherColumn FROM my_table AS a JOIN your_table AS b ON ...
If you wanted all columns from a and b, you would do:
SELECT a.*, b.* FROM my_table AS a JOIN your_table AS b ON ...
Or if you want some from a, and all from b:
SELECT a.columnName, a.anotherColumn, b.* FROM my_table AS a JOIN your_table AS b ON ...


text:
Q: 1.9.3.7 to 1.9.3.8 Upgrade Broke Cart & Checkout for Logged in Customers After Compilation We just upgraded from 1.9.3.7 to 1.9.3.8 and getting a blank page when trying to access the cart or add products to it. This happens for logged in customers only and only when compilation is turned on. No log or PHP errors - just a blank page. We found this but not sure how to properly edit the file. Please help with exact instructions on how and what file to edit.

A: This problem has been fixed within 1.9.3.9.
Please use this newer version.


text:
Q: Making sure only 30 participants enroll I need to make a system in which only a certain amount of participants can enroll into a class.
The problem is that there is a moment that they leave the website to a payment providers portal and after the payment is done, they return to finalize the enrollment process.
So when person A adds the class to their cart and enters the payment portal, there still is 'room' in the class. It fills the class only when they return from the payment system. If person B starts the payment before person A is done, they too can enroll. Resulting in 31 entries.
It seems like this would require a sort of semaphore, but how would I go about implementing this?


text:
Q: Option text position Hi how i can change my text in option to a bit higher using css as is not in centre line

                                      Price Mode
                                      <select class="select-price-mode custom-select-sm col-10" id="select-price-mode"  required>
                                        <option selected disabled value="" >Select ....</option>
                                      </select>

                                        Please select a valid price mode.

                                        Payment Frequency
                                        <select class="select-payment-frequency custom-select-sm col-10" id="select-payment-frequency" required>
                                          <option selected disabled value="">Select ....</option>
                                        </select>

                                            Please select a valid payment frequency.

A:

select{font-size: 30px;}

                                      Price Mode
                                      <select class="select-price-mode custom-select-sm col-10" id="select-price-mode"  required>
                                        <option selected disabled value="" >Select ....</option>
                                      </select>

                                        Please select a valid price mode.

                                        Payment Frequency
                                        <select class="select-payment-frequency custom-select-sm col-10" id="select-payment-frequency" required>
                                          <option selected disabled value="">Select ....</option>
                                        </select>

                                            Please select a valid payment frequency.


text:
Q: Can not extract resource from com.android.aaptcompiler.ParsedResource@67025f4b In android studio, it gives an error when starting the emulator: Can not extract resource from com.android.aaptcompiler.ParsedResource@67025f4b.
How can I remove/fix this error?


text:
Q: Multipole ${\it l}$ value for the second acoustic peak in the CMB power spectrum So according to the Planck paper https://arxiv.org/pdf/1502.01582.pdf page 20, the first peak is  ${\it l}$=220, but the second peak is ${\it l}$=537. Not quite the double of the first peak, why? If the fundamental wave vs harmonics analogy were to hold with the sound wave, shouldn't it be doubled? Is it because of the non exact relation between l and angular size? Is the /angular size/ of the second peak 1/2 of that of the first peak?

A: There are a few reasons why the CMB angular power spectrum is more complicated than the spectrum for "waves on a string." To give a few examples:

*

*First, the waves exist in three dimensional space, but we only observe angular fluctuations on our sky. There is a projection that occurs while passing from three dimensional modes with a "wavenumber" $k$, to two dimensional modes with an "angular quantum number" $\ell$. Angular mode $\ell$ will therefore contain information from a range of different 3d modes with different values of $k$.

*Second, the primordial plasma had a mix of different components, that were not all in equilibrium. In particular, there was the relativistic primordial plasma -- consisting mostly of electrons, protons, and photons -- as well as dark matter. The primordial plasma will oscillate due to sound waves, creating the peak-like structure in the CMB. However, the dark matter does not oscillate, and only falls into local gravitational wells. This will tend to enhance the amplitude of plasma oscillations that "fall into" the wells, and decrease the amplitude of plasma oscillations that "climb out of" the wells (the relative heights of the second and third peaks is one piece of evidence for dark matter).

*The dispersion relationship for the plasma (which controls the wavelengths of each mode) will likely not be as simple as what you would get for a wave on a string, because of underlying interactions in the plasma.
I am not sure what precisely explains the specific point you brought up -- maybe someone else will be able to give a more detailed answer -- but this is just to say that there is more going on in the CMB than in the toy "waves on a string" problem, so you shouldn't expect the peaks in the CMB to follow a pattern derived for waves on a string.


text:
Q: How to disable the main splitbutton action, but keep enabled the arrow I have a split button and i want, for some cases, to disable main button action but keep the arrow for viewing the menu.
Is there any change to do this? I think that maybe i have to create two buttons,

A: You simply need to check if the action is allowed or not in the button handler, and set it in your flow..
Here is a working fiddle - https://fiddle.sencha.com/#fiddle/bv8
There could be other / better options but this should work.
Hope it helps.


text:
Q: Determining a preimage of the connecting homomorphism of the Mayer Vietoris sequence In this article http://en.wikipedia.org/wiki/Mayer%E2%80%93Vietoris_sequence, and in the section about the  connecting homomorphism associated to a Mayer-Vietoris sequence, the connecting homomorphhism $\partial_*$ is defined by:
$$H_{n}(X) \xrightarrow{\partial_*}\,H_{n-1} (A\cap B)$$
My problem is the following. Suppose we have a class in  $Im(\partial_*)\subset H_{n-1}(A\cap B)$ and we want to determine one of the preimages of this class in $H_{n}(X)$, is there a general way to find this preimage, knowing that the map $\partial:X\rightarrow A\cap B$ from which $\partial_*$ is induced is not known in general or maybe need not exist!!


text:
Q: Is it possible for my app to delete all the device`s data (apps, pictures, etc.)? I want the user to be able to delete all his data from my app.
Is it possible?

A: Yes, you can do a factory reset programmatically, but your app must be enabled as Device Admin.
Read more here: https://developer.android.com/guide/topics/admin/device-admin.html
Once your app is enabled as Device Administrator, you simple call wipe() from DevicePolicyManager (https://developer.android.com/guide/topics/admin/device-admin.html#wipe)
Note: Your app will also be erased! It's a factory reset!


text:
Q: How to access a nested Dictionary<> objects in a foreach loop I have a nested Dictionary structure like this:
Dictionary<string, Dictionary<string, string>> dict;

I'm trying to access the elements using two foreach loops but the compiler won't let me use the following as the loop variable for my inner loop:
Dictionary<string, string>

This is what I have:
foreach (string key in dict.Keys) {
    foreach (Dictionary<string, string> innerDict in dict[key]) {
        // ...
    }
}

The compiler says:
Cannot convert type 'System.Collections.Generic.KeyValuePair<string,string>'
 to 'System.Collections.Generic.Dictionary<string,string>'

I can use KeyValuePair<string,string> in the inner loop, but I would like to access the dictionary object itself as a whole (so that I can do something like this: if (dict.ContainsKey(innerDict)) { ... })

A: The minimum code change to fix it is like this (but see the correct approach in the next code snippet in this answer):
Dictionary<string, Dictionary<string, string>> dict;

foreach (string key in dict.Keys)
{
    foreach (var innerDict in dict[key].Select(k => k.Value))
    {
    }
}

Your problem was that when you enumerate over a dictionary, you get a sequence of Key/Value pairs. In your case, the Value was the inner dictionary, and it is that which you needed.
I'm using the Linq "Select()" operation to convert each key/value pair into just the value part, i.e. the dictionary which is the value in the key/value pair.
However, that's a long-winded and inefficient way to go about getting each inner dictionary along with its key. Here's how it should be done:
foreach (var item in dict)
{
    string key = item.Key;
    Dictionary<string, string> innerDict = item.Value;

    // Do something with key and innerDict.
}

I'm assuming that you are trying to visit each inner dictionary in turn while knowning that inner dictionary's key in the outer dictionary.
Note that I only copied the values from item.Key and item.Value into local variables to illustrate their types. You could just use item.Key and item.Value directly, of course.
If you really only want the inner dictionaries themselves (and you don't need the key for each inner dictionary), you can just do it like so (as Nuffin suggested):
foreach (var innerDict in dict.Values)
{
    // Use inner dictionary
}

A: That's because the value of the string key is not a list. Change the declaration of the Dictionary to Dictionary<string, List<Dictionary<string, string>>> dict; if that's what you want.
Or you could just grab the dictionary inside the first foreach loop like this:
Dictionary<string, string> val = dict[key];

and use it from there. But either way, you're trying to iterate against something that's not enumerable.
I think you may have the Dictionary defined like you want -you just don't need an inner loop.

A: You could just keep it short by using:
foreach (Dictionary<string, string> d in dict.Values) {
}

It works, no complaints from the compiler.
Also notice that your code doesn't work because in that context, dict[key] is not a collection of dictionaries, but a single dictionary.

A: I think you are misunderstanding the underlying Dictionary structure.
Dictionary<string, Dictionary<string, string>>

The above results in a parent containing a single dictionary object.  When you attempt to use foreach over this object the compiler does not know what to do.  It might be easier to understand if you use the following code
Dictionary<string,string> dictionaryObject;
foreach (string item in dictionaryObject)
{ }

The above will also result in the same error.
You can resolve your issue by iterating over the keys or values of the dictionary object, for example,
foreach (string  key in dict.Keys)
{
    foreach (string innerKey in dict[key].Keys)
    {
        System.Diagnostics.Debug.WriteLine(dict[key][innerKey]);
    }
}

A: You will still have the dictionary to reference just like you wish, even when you use the KVP.  Try this:
foreach (var outerKVP in dict {
    foreach (var innerKVP in dict[outerKVP.Key]) {
        var theString = dict[outerKVP.Key][innerKVP.Key];
    }
}

A: foreach (Dictionary<string, string> innerDict in dict[key]) {
        // ...
    }

This fails because dict[key] is a Dictionary<string,string>, so enumerating it with foreach will yield elements of type KeyValuePair<string,string>.
If you want to access the inner dictionary, just do so and drop the foreach loop.
Dictionary<string, string> innerDict = dict[key];

A: Should be not so hard:
Dictionary<string, Dictionary<string, string>> dict = new Dictionary<string,Dictionary<string,string>>();

foreach (var kvp in dict)
{
    var innerDict = kvp.Value;

    foreach (var innerKvp in innerDict)
    {
        Console.WriteLine(kvp.Key + " " + innerKvp.Key + " " + innerKvp.Value);
    }
}


text:
Q: How do I find nodes that are connected with >1 path and return their connecting nodes? I am starting with Neo4j and cypher and tried to play around with the default movie Graph.
I want to find all actors that worked with Tom Hanks in more than one movie and list the movies they worked in together.
Finding the actors and amount of movies works
MATCH p=(a {name:"Tom Hanks"})-[r*2]-(b)
WITH count(p) AS commonMovies, a, b
WHERE commonMovies > 1
RETURN DISTINCT commonMovies, b.name
Order By commonMovies DESC;

Output:
3 | Meg Ryan
2 | Gary Sinise
etc.
Finding the movies they worked in together works for all actors that worked with Tom Hanks:
MATCH p=(a {name:"Tom Hanks"})-[r*2]-(b)
RETURN b.name, extract(n in nodes(p)[1..-1] | n.title);

Output:
Tom Hanks       | That thing you do
Liv Tyler       | That thing you do
Charlize Theron | That thing you do
Nora Ephron     | Zou've got mail
What I would like to have is something like:
Actor | [array of movies]
I think the problem is that I aggregate with count(p) but afterwards I cannot extract the nodes from each path. That's at least what appears to be the problem for me.
Thanks!

A: Your current query may return you Tom Hanks himself, this one do the job :
MATCH (n:Person {name:'Tom Hanks'})-->(m:Movie)<--(other)
WITH other.name as coActor, collect(m.title) as movies
WHERE size(movies) > 1
RETURN coActor, movies


text:
Q: Finding the median of a random variable
Losses under an insurance policy have the density function
$$ f(x) = \begin{cases} 0.25 e^{-0.25x}, \; \;  \; \; x \geq 0 \\ 0,
 \; \; \; \; \text{otherwise} \end{cases} $$
The deductible is $1$ for each loss. Calculate the median amount that
  the insurer pays a policyholder for a loss under the policy.

Attempt
What is confusing me here is the term deductible. I believe this is the amount of money that the policyholder must pay. Since $f(x)$ is the density of the rv $X$ which is the losses. We can make another rv call it $Y$ that is that amount of money the insurer pays. Then,
$$ Y = X - 1 $$
And $F_Y(y) = P(Y \leq y ) = P(X-1 \leq y ) = P(X \leq y + 1 ) = F_X(y+1) $
Therefore, we want want to find $\alpha $ so that
$$ F_Y(\alpha) = 0.5 $$
or in other words,
$$ F_X (\alpha + 1 ) = \int\limits_0^{\alpha+1} 0.25 e^{-0.25x} dx = 0.5 $$
Is this a corect approach?

A: The client's original losses are $X \sim \mathsf{Exp}(rate = 1/4)$ with $E(X) = 4.$ However, only claims exceeding $1$ will result in payouts. So only about 77.9% of client losses will result in payouts. If you find the CDF of $X,$ you will
see that $F_X(1) = P(X \le 1) = 0.2212.$ [Computation in R statistical software.]
1 - pexp(1, 1/4)
## 0.7788008

The distribution of the payouts is $Y= X|X > 1,$ and by the no-memory property of the exponential distribution, the distribution of $Y$ is again $\mathsf{Exp}(rate = 1/4).$  Then, as you say, you seek $\alpha$ such that $F_Y(\alpha) = .5.$
Thus, you can find $\alpha = 2.7726.$
qexp(.5, 1/4)
## 2.772589

Simulation: In the following simulation of a million losses $X$ (first histogram), we
find $X_{adj} = X - 1$ (second histogram), and retain only losses $Y$ resulting
in payouts (third histogram). The first and third histograms show the
density function of $\mathsf{Exp}(\lambda=1/4).$ The vertical red line in
the third is at the median.
set.seed(422);  m = 10^6;  lam=1/4
par(mfrow=c(1,3))
 x = rexp(m, lam); summary(x)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.000   1.153   2.776   4.002   5.547  55.216
 hist(x, prob=T, br=50, col="skyblue2", main="Losses Before Deductible")
  curve(dexp(x, lam), add=T, lwd=2, col="darkgreen")

x.adj = x-1;  summary(x.adj)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 -1.0000  0.1526  1.7764  3.0016  4.5469 54.2163
 hist(x.adj, prob=T, br=50, col="skyblue2", main="Adjusted Losses")
  abline(v=0, col="green2")

 y = x.adj[x.adj > 0];  length(y);  summary(y)
 ## 778879
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.000   1.155   2.775   4.001   5.544  54.216
 hist(y, prob=T, br=50, col="skyblue2", main="Payouts")
  curve(dexp(x, lam), add=T, col="darkgreen")
  abline(v = median(y), col="red", lwd=2)
par(mfrow=c(1,1))


text:
Q: How to pass a list of objects using intent? How can I pass a list of objects to another activity ?
Im trying this and its not working...
Activity A
Intent i = new Intent(this,MainActivity.class);
i.putParcelableArrayListExtra("list",listCsv);
setResult(Activity.RESULT_OK,i);
finish();

Activity B
ArrayList<Contato> lAgenda =
(ArrayList<Contato>) getIntent().getSerializableExtra("lista");

And in my Activity B my list lAgenda doesnt get the list of the Activity A,
I got a NULL value.
My ContatoVO class
public class ContatoVO implements Serializable,Parcelable{
    private static final long serialVersionUID = 1L;
    private long id;
    private String nome;
    private String endereco;
    private String telefone;
    private String estado;
    private int idEstado;

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public int getIdEstado()
        {
            return idEstado;
        }

        public void setIdEstado(int id)
        {
            this.idEstado = id;
        }

        public String getEstado() {
            return estado;
        }

        public void setEstado(String estado) {
            this.estado = estado;
        }

        public String getNome() {
            return nome;
        }

        public void setNome(String value) {
            this.nome = value;
        }

        public String getEndereco() {
            return endereco;
        }

        public void setEndereco(String value) {
            this.endereco = value;
        }

        public String getTelefone() {
            return telefone;
        }

        public void setTelefone(String value) {
            this.telefone = value;
        }
        // Will be used by the ArrayAdapter in the ListView
        @Override
        public String toString() {
            return nome;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {

            dest.writeString(nome);
            dest.writeString(endereco);
            dest.writeString(telefone);
        }

}

Function that sends data intent to Activity
public final void lerCsv(Context context)
    {

        AssetManager assetManager = context.getAssets();
        ArrayList<ContatoVO> listaCsv = new ArrayList<ContatoVO>();

        try
        {
            InputStream iStream = assetManager.open("teste.csv");
            InputStreamReader iStreamReader = new InputStreamReader(iStream);
            CSVReader csvReader = new CSVReader(iStreamReader,';');

            String[] registro = null;

            //pula cabeçalho
            csvReader.readNext();

            while((registro = csvReader.readNext()) != null)
            {

                ContatoVO contato = new ContatoVO();
                contato.setNome(registro[0]);
                contato.setEndereco(registro[1]);
                contato.setTelefone(registro[2]);

                listaCsv.add(contato);

            }

            csvReader.close();

            Intent i = new Intent(this,MainActivity.class);

            i.putParcelableArrayListExtra("lista",listaCsv);
            setResult(Activity.RESULT_OK,i);
            finish();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }

    }

Where i Try to get this data(list)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ArrayList<ContatoVO> lAgendaVO = null;
        try {
            super.onActivityResult(requestCode, resultCode, data);

                lAgendaVO = data.getParcelableArrayListExtra("lista");

                lContatoDAO.open();
                lContatoDAO.InserirListaCsv(lAgendaVO);
                adapter.notifyDataSetChanged();

        } catch (Exception ex) {
            trace("Erro : " + ex.getMessage());
        }
    }

A: The key you are using to retrieve the ArrayList doesn't match the one you are using to write it onto the bundle. You have to be consistent. Use either list or lista. I strongly suggest you to use constants. E.g
ActivityA
public static final String LIST_KEY = "LIST_KEY";
Intent i = new Intent(this,MainActivity.class);
i.putParcelableArrayListExtra(LIST_KEY,listCsv);
setResult(Activity.RESULT_OK,i);
finish();

ActivityB
ArrayList<Contato> lAgenda =
         (ArrayList<Contato>) getIntent(). getParcelableArrayList(ActivityA.LIST_KEY);

if the snippet to retrieve the List is part of onActivityResult, you have to use the former parameter Intent data instead of  getIntent()
As Pointed out by @Sergey, you have to be consistent also on the put*/get* you use. If Contato is Parcelable (highly recommended), use getParcelableArrayList  instead of getSerializableExtra .
Edit:
you need the constructor that takes a Parcel
protected ContatoVO(Parcel in) {
    id = in.readLong();
    nome = in.readString();
    endereco = in.readString();
    telefone = in.readString();
    estado = in.readString();
    idEstado = in.readInt();
}

you writeToParcel is not writing all the field. Change it to:
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeLong(id);
    dest.writeString(nome);
    dest.writeString(endereco);
    dest.writeString(telefone);
    dest.writeString(estado);
    dest.writeInt(idEstado);
}

And you missed Parcelable.Creator
@SuppressWarnings("unused")
public static final Parcelable.Creator<ContatoVO> CREATOR = new Parcelable.Creator<ContatoVO>() {
    @Override
    public ContatoVO createFromParcel(Parcel in) {
        return new ContatoVO(in);
    }

    @Override
    public ContatoVO[] newArray(int size) {
        return new ContatoVO[size];
    }
};

}

A: If you want to return result of startActivityForResult
and you are using putParcelableArrayListExtra which uses ArrayList containing parcelable objects you shoud be consistent and when receiving data use
@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      .... = data.getParcelableArrayListExtra("list")
}


text:
Q: Display Images from raw data on web page This question may have a simple answer and I may be asking it the wrong way.
I have a web application that pulls information from a server via an API (specifically librets and an MLS feed).  Part of the API returns images but in the form of raw binary data.
Currently I am writing this raw binary data to a .jpg file and storing them on my side for access later.  I was wondering if there was a way to display these images on a webpage using the raw data instead of having to save them on my side.

A: I am equally unsure I am on the right track with an answer, so just kindly ignore or say, rather than downvote me if my interpretation of your querstion is in the wrong way like your question!
You can serve an image from PHP rather than from a file - I mean you can have PHP dynamically create an image and serve it rather than having to have a file in your webserver's filesystem and having to refer to it by name in the src field of an <image> tag in your HTML.
So, instead of
<image src="....jpg" alt="..." size="...">

you can use
<img src="/php/thumb.php?param1=$col&param2=$ref"/>

which causes the PHP script at `/php/thumb.php" to be called when the page is rendered. In that script, you can dynamically create the image (using extra parameters if you wish) like this:
<?php
header("Content-type: image/jpeg");
$p1 = $_GET['param1'];
$p2 = $_GET['param2'];

$src = imagecreatefromstring(SOMESTRING);
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagejpeg($dst);
imagedestroy($dst);
?>

I have omitted some code after the first 3 lines so you just see the technique rather than all the gory details of my code. The actual lines you are interested in are:
header(...image/jpeg);

which tells the browser what type of stuff is coming - i.e. an image, and
imagejpeg();

which actually sends the stream of JPEG data to the browser.


text:
Q: Select all rows where rows in another joined table match condition So I want to select all rows where a subset of rows in another table match the given values.
I have following tables:
Main Profile:
+----+--------+---------------+---------+
| id |  name  | subprofile_id | version |
+----+--------+---------------+---------+
|  1 | Main 1 |             4 |       1 |
|  2 | Main 1 |             5 |       2 |
|  3 | Main 2 |           ... |       1 |
+----+--------+---------------+---------+

Sub Profile:
+---------------+----------+
| subprofile_id | block_id |
+---------------+----------+
|             4 |        6 |
|             4 |        7 |
|             5 |        8 |
|             5 |        9 |
+---------------+----------+

Block:
+----------+-------------+
| block_id | property_id |
+----------+-------------+
|        7 |          10 |
|        7 |          11 |
|        7 |          12 |
|        7 |          13 |
|        8 |          14 |
|        8 |          15 |
|        8 |          16 |
|        8 |          17 |
|      ... |         ... |
+----------+-------------+

Property:
+----+--------------------+--------------------------+
| id |        name        |          value           |
+----+--------------------+--------------------------+
| 10 | Description        | XY                       |
| 11 | Responsible person | Mr. Smith                |
| 12 | ...                | ...                      |
| 13 | ...                | ...                      |
| 14 | Description        | XY                       |
| 15 | Responsible person | Mrs. Brown               |
| 16 | ...                | ...                      |
| 17 | ...                | ...                      |
+----+--------------------+--------------------------+

The user can define multiple conditions on the property table. For example:

*

*Description = 'XY'

*Responsible person = 'Mr. Smith'

I need all 'Main Profiles' with the highest version which have ALL matching properties and can have more of course which do not match.
It should be doable in JPA because i would translate it into QueryDSL to build typesafe, dynamic queries with the users input.
I already searched trough all questions regarding similar problems but couldn't project the answer onto my problem.
Also, I've already tried to write a query which worked quite good but retrieved all rows with at least one matching condition. Therefore i need all properties in my set but it only fetched (fetch join, which is missing in my code examplte) the matching ones.
from MainProfile as mainProfile
  left join mainProfile.subProfile as subProfile
  left join subProfile.blocks as block
  left join block.properties as property
where mainProfile.version = (select max(mainProfile2.version)from MainProfile as mainProfile2 where mainProfile2.name = mainProfile.name) and ((property.name = 'Description' and property.value = 'XY') or (property.name = 'Responsible person' and property.value = 'Mr. Smith'))

Running my query i got two rows:

*

*Main 1 with version 2

*Main 2 with version 1

I would have expected to get only one row due to mismatch of 'responsible person' in 'Main 2'

EDIT 1:
So I found a solution which works but could be improved:
select distinct mainProfile
from MainProfile as mainProfile
  left join mainProfile.subProfile as subProfile
  left join subProfile.blocks as block
  left join block.properties as property
where mainProfile.version = (select max(mainProfile2.version)from MainProfile mainProfile2 where mainProfile2.name = mainProfile.name)
and ((property.name = 'Description' and property.content = 'XY') or (property.name = 'Responsible person' and property.content = 'Mr. Smith'))
group by mainProfile.id
having count (distinct property) = 2

It actually retrieves the right 'Main Profiles'. But the problem is, that only the two found properties are getting fetched. I need all properties though because of further processing.


text:
Q: Undefined variable when using rgb2ind I have this simple program where I'm trying to set the number of colors of an image to 1000, but I get the following error: Undefined function or variable 'rgb'. I also tried with uppercase and quotes, although in the examples I found there where no quotes. I am using Matlab R2012a.
clc
clear all

rgbImage = imread('peppers.png');
[rgbImage,map]=rgb2ind(RGB,1000);

A: The variable you're using as the first parameter to rgb2ind is wrong.  You need to do:
[rgbImage, map] = rgb2ind(rgbImage, 1000);

My guess is that you consulted the MATLAB documentation on rgb2ind and you literally took the first parameter to be substituted as RGB.  The documentation clearly says that RGB is an image loaded into MATLAB.  This is not a constant.


text:
Q: How to assign levels to a column based on specific dates and levels in another column? I have an example dataset with 3 columns: JulianDay, Device, and location. See code below.
structure(list(JulianDay = 40:69, Device = structure(c(1L, 2L,
3L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L, 1L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L), .Label = c("a",
"b", "c"), class = "factor"), Location = c(1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
1, 2, 3)), class = "data.frame", row.names = c(NA, -30L))

Looking through the data, you can see that Device a is at location 1 on days 40, 43, 46. However the devices change locations, and location 1 is occupied by device b on days 49, 52, 55 and device c on 61, 64, 67. Similar changes happen for all three devices.
Now imagine that we only have the first two columns, but I know each date that a Device changes locations and which location it goes to. How could I reconstruct column 3 with that information. Obviously with 30 rows, it would be easy to just manually input, but I'm dealing with a real dataframe that has a few hundred thousand rows.
EDIT:
structure(list(JulianDay = c(40, 40, 40, 41, 41, 41, 42, 42,
42, 43, 43, 43, 44, 44, 44, 45, 45, 45), Device = structure(c(1L,
2L, 3L, 1L, 2L, 3L, 2L, 3L, 1L, 2L, 3L, 1L, 3L, 1L, 2L, 3L, 1L,
2L), .Label = c("a", "b", "c"), class = "factor"), Location = c(1,
2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)), class = "data.frame", row.names = c(NA,
-18L))

Here's a similar dataframe that might clear up the question. Each device is active on every day and on every day there are 3 locations. Without the physical Location column (but knowing what should be contained within) I would like to code something like the following:
if(JulianDay < 41 & Device == 'A') { Location == 1}
if(JulianDay > 41 * JulianDay < 44 & Device == 'A') { Location == 3}
if(JulianDay > 44 & Device == 'A') {Location == 2

Such that a third column (Location) is filled out.

A: If you have a set of conditional expectations based on JulianDay and Device that need to be executed in turn to create Location, then you should take look at dplyr::case_when.
From the docs (see ?dplyr::case_when):

This function allows you to vectorise multiple 'if_else()' statements.
  It is an R equivalent of the SQL 'CASE WHEN' statement. If no cases
  match, 'NA' is returned.

For instance, with your example,
data <- structure(list(JulianDay = c(40, 40, 40, 41, 41, 41, 42, 42,
42, 43, 43, 43, 44, 44, 44, 45, 45, 45), Device = structure(c(1L,
2L, 3L, 1L, 2L, 3L, 2L, 3L, 1L, 2L, 3L, 1L, 3L, 1L, 2L, 3L, 1L,
2L), .Label = c("a", "b", "c"), class = "factor"), Location = c(1,
2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)), class = "data.frame", row.names = c(NA,
-18L))

library(dplyr)

data$Location <- case_when(
  data$JulianDay < 41 & data$Device == "a" ~ 1,
  data$JulianDay > 41 & data$JulianDay < 44 & data$Device == "a" ~ 3,
  data$JulianDay > 44 & data$Device == "a" ~ 2
)


text:
Q: custom pages using asdoc Does anyone know if you can write your own pages that asdoc will recognize and use? For instance, I'd like to write some "Getting Started","Support" and "FAQ" kind of pages that will help understanding what my actionscript classes are about.

A: You can override the XSLT/CSS used by asdoc using the -templates-path option. Start by duplicating %FLEX_HOME%\asdoc\templates to a custom directory and then make changes to those files.

A: Since there is apparently no way to write pages without duplicating templates, figuring out how the templates are used and then editing them. I chose the simpler route: Give up trying to merge with asdoc's output and instead 'host' the generated content with pages of my own. That is, I use the following site structure:
www
  \index.html
  \installation.html
  \gettingstarted.html
  \tutorial1.html
  \asdoc\{auto-generated content here}

Each of my helper pages have a navbar that has a link to the asdoc content. Unfortunately, there's no link from the asdoc pages back to the outer ('host') pages.