问:
TableLayout rows don't shrink equally but only last row does on different screen sizes
I have created a table in which i want to display 9 animals and a next arrow button. Each row has 3 animals, so that's 3 rows for the animals and one last row for the next arrow button. My problem is that on different screen sizes, the rows don't shrink equally but only the last row does having as a result, the next arrow button to disappear.

This is how it looks on a Nexus 4

And that's how it looks an a smaller screen that has a 3.2" size

And here is my XML code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_animals"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/background"
tools:context="kidsbook.jok.kidsbook.Animals">

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/ads_text"
    android:weightSum=".9"
    android:id="@+id/animalsPage1"
    android:visibility="visible">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum=".9">

        <Button
            android:background="@drawable/cat"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/catSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/dog"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/dogSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/chicken"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/chickenSounds"
            android:layout_weight=".3"/>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum=".9">

        <Button
            android:background="@drawable/horse"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/horseSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/frog"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/frogSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/pig"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/pigSounds"
            android:layout_weight=".3"/>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum=".9">

        <Button
            android:background="@drawable/cock"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/cockSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/donkey"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/donkeySounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/sheep"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/sheepSounds"
            android:layout_weight=".3"/>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:weightSum="1">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".22"
            android:id="@+id/nextButtonAnimalsTo2"
            android:background="@drawable/next_arrow"
            android:onClick="toPage2from1"/>
    </TableRow>

</TableLayout>

<TextView
    android:text="@string/ads"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:minHeight="50dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="20sp"
    android:id="@+id/ads_text"
    android:layout_alignParentBottom="true"/>

</RelativeLayout>
</code>```

Any suggestions and help would be highly appreciated and thank you all in advance.

答:
@Smolikas, I think your views are overlapping in small screen because you are using RelativeLayout. You can use LinearLayout with orientation vertical inside scrollview. It will work for you.

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:id="@+id/activity_animals"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">
</code>```

Your TableLayout & Textview.

```<code>    </LinearLayout>
</ScrollView>
</code>```

Body:
I have created a table in which i want to display 9 animals and a next arrow button. Each row has 3 animals, so that's 3 rows for the animals and one last row for the next arrow button. My problem is that on different screen sizes, the rows don't shrink equally but only the last row does having as a result, the next arrow button to disappear.

This is how it looks on a Nexus 4

And that's how it looks an a smaller screen that has a 3.2" size

And here is my XML code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_animals"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/background"
tools:context="kidsbook.jok.kidsbook.Animals">

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/ads_text"
    android:weightSum=".9"
    android:id="@+id/animalsPage1"
    android:visibility="visible">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum=".9">

        <Button
            android:background="@drawable/cat"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/catSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/dog"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/dogSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/chicken"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/chickenSounds"
            android:layout_weight=".3"/>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum=".9">

        <Button
            android:background="@drawable/horse"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/horseSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/frog"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/frogSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/pig"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/pigSounds"
            android:layout_weight=".3"/>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum=".9">

        <Button
            android:background="@drawable/cock"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/cockSounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/donkey"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/donkeySounds"
            android:layout_weight=".3"/>

        <Button
            android:background="@drawable/sheep"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/sheepSounds"
            android:layout_weight=".3"/>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:weightSum="1">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".22"
            android:id="@+id/nextButtonAnimalsTo2"
            android:background="@drawable/next_arrow"
            android:onClick="toPage2from1"/>
    </TableRow>

</TableLayout>

<TextView
    android:text="@string/ads"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:minHeight="50dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="20sp"
    android:id="@+id/ads_text"
    android:layout_alignParentBottom="true"/>

</RelativeLayout>

Any suggestions and help would be highly appreciated and thank you all in advance.

Body:
@Smolikas, I think your views are overlapping in small screen because you are using RelativeLayout. You can use LinearLayout with orientation vertical inside scrollview. It will work for you.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:id="@+id/activity_animals"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

Your TableLayout & Textview.

    </LinearLayout>
</ScrollView>


来源: stackexchange

问:
How to Display Current Function in Eclipse
I miss a certain functionality in Eclipse. I would like to know the name of the current function the cursor is currently inside. This is useful when browsing unknown code using the search function, for example.

Any idea how to show it? Maybe a plugin?

答: You can also display the Quick Outline (ctrl+o). This way you see the context quickly without having to have a permanent Outline Window linked to the Editor.</p>

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Java RMI - send Client stubs to other clients
I've got to implement something like P2P in RMI. I've created two Remote intrfaces : server and client. Server is responsible for registering clients and returning client stubs to other clients that request it. How should I accomplish this? The method signature on the server looks like this:

```<code>IClient getClient(String resource) throws RemoteException;
</code>```

The problem is I don't really know how should I implement that regarding the stubs&skeleton issues and that many things is happening behind the scenes.

答: You don't have to worry about it since JDK 1.5. See the preamble to the Javadoc for UnicastRemoteObject. As long as you quote a port number, even zero, when calling super() or exportObject you don't need stubs. And you haven't needed skeletons since 1998.</p>

Body:
I've got to implement something like P2P in RMI. I've created two Remote intrfaces : server and client. Server is responsible for registering clients and returning client stubs to other clients that request it. How should I accomplish this? The method signature on the server looks like this:

IClient getClient(String resource) throws RemoteException;

The problem is I don't really know how should I implement that regarding the stubs&skeleton issues and that many things is happening behind the scenes.


问:
fetch response.json() gives responseData = undefined
When using fetch:

```<code>  fetch(REQUEST_URL, {
      method: 'get',
      dataType: 'json',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then((response) =>
      {
        response.json() // << This is the problem
      })
    .then((responseData) => { // responseData = undefined

        console.log(responseData);
     });
     }).catch(function(err) {
        console.log(err);
      })
     .done();
</code>```

The following works works, do you know why? :

```<code>    JSON.parse(response._bodyText)
</code>```

答:
The chaining response should look more like this, specifically the response.json part.  Then you should get an Object back in console.log.

```<code>.then(response => response.json())
.then(response => {

    console.log(response)

}
</code>```

Body:
When using fetch:

  fetch(REQUEST_URL, {
      method: 'get',
      dataType: 'json',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then((response) =>
      {
        response.json() // << This is the problem
      })
    .then((responseData) => { // responseData = undefined

        console.log(responseData);
     });
     }).catch(function(err) {
        console.log(err);
      })
     .done();

The following works works, do you know why? :

    JSON.parse(response._bodyText)

Body:
The chaining response should look more like this, specifically the response.json part.  Then you should get an Object back in console.log.

.then(response => response.json())
.then(response => {

    console.log(response)

}

ContentLicense: CC BY-SA 4.0


问:
How to save/backup amazon instance local
I would like to lower the cost paying to Amazon.
There are stopped instances that I want to backup and save on my local server, on-prem.

After creating an image from the instance, is there any way I can copy AMI to my local server and remove it from Amazon. So in a day, I will need back, it can transfer back from my local server to Amazon to use it again?

The instance first created on Amazon.
I rather a way to save instance on-premise as a file and not as a virtual server.

The main issue is: How can I transfer and save the image of an instance, that created on Amazon, as a file to the local server and how I can return it back to be in  Amazon, in case I need to build the instance again.

Is there any way to do it?

Thanks a lot!

答:
You would need to use the VM Import/Export Tool for that. Read the docs to make sure you know how to upload again.

As to the cost, I am not sure how Amazon configures the cost, that is something you have to check out from your account. Once you create the image it is on your account. Even after you download it, not sure when AWS charges you or not.


问:
Button aligned to bottom of RelativeLayout is cut off
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
</code>```

答:
You have given layout padding in your main container .i.e

```<code>android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
</code>```

Adding margin instead of padding will solve your problem.Give a try to below code

```<code>android:marginBottom="@dimen/activity_vertical_margin"
android:marginLeft="@dimen/activity_horizontal_margin"
android:marginRight="@dimen/activity_horizontal_margin"
android:marginTop="@dimen/activity_vertical_margin"
</code>```

Body:
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

Body:
You have given layout padding in your main container .i.e

android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

Adding margin instead of padding will solve your problem.Give a try to below code

android:marginBottom="@dimen/activity_vertical_margin"
android:marginLeft="@dimen/activity_horizontal_margin"
android:marginRight="@dimen/activity_horizontal_margin"
android:marginTop="@dimen/activity_vertical_margin"


问:
Format bokeh table widget
I am currently running an app displaying the table widget from the bokeh library. The python library creates a html file containing interactive js elements such as graphs and tables.

Whereas with graphs there seem to be lots of options to customize colors etc, this is not the case with the table which comes in the form of a 'widget'.

A slightly changed code example from the doc for a Jupyter notebook is

```<code># coding: utf-8

# In[1]:

from bokeh.io import output_notebook
output_notebook()

# In[2]:

from datetime import date
from random import randint
from bokeh.io import show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        number=[randint(-100, 100) for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="number", title="Number"),
    ]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

show(widgetbox(data_table))
</code>```

Is it possible to format the output in such a way that negative values are assigned color = red, high values are printed bold etc?

Is such a task maybe easier with other libraries such as plotly (no experience yet)?

答:
Someone asked this a few weeks ago. bokeh DataTable with conditionally coloured cells

You can use that example to perform most of the formatting you would need.

Title: Format bokeh table widget

Body:
I am currently running an app displaying the table widget from the bokeh library. The python library creates a html file containing interactive js elements such as graphs and tables.

Whereas with graphs there seem to be lots of options to customize colors etc, this is not the case with the table which comes in the form of a 'widget'.

A slightly changed code example from the doc for a Jupyter notebook is

# coding: utf-8

# In[1]:

from bokeh.io import output_notebook
output_notebook()

# In[2]:

from datetime import date
from random import randint
from bokeh.io import show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        number=[randint(-100, 100) for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="number", title="Number"),
    ]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

show(widgetbox(data_table))

Is it possible to format the output in such a way that negative values are assigned color = red, high values are printed bold etc?

Is such a task maybe easier with other libraries such as plotly (no experience yet)?


问:
Creating a separate log for each Passenger process in a Rails app
I'm trying to determine the cause of high app server instance memory usage and to do so I need a separate log for each running Passenger process (e.g., production_18204.log). Is there a simple way to configure this in a Rails app? Thanks.</p>

答:
To log memory used by process in each request use the following code.

```<code>def log_memory_usage
  mem_usage = `ps -o rss= -p #{ Process.pid }`.to_i
  if logger
    logger.info("[MEMORY USAGE]: #{ number_to_human_size(mem_usage) } | PID: #{ Process.pid } | CONTROLLER: #{ controller_name } | ACTION: #{ action_name }")
  end
end
</code>```

Use this as before action in your base or application controller. Do include ActionView::Helpers::NumberHelper to make number_to_human_size work.

Courtesy: https://github.com/binarylogic/memorylogic

Body:
To log memory used by process in each request use the following code.

def log_memory_usage
  mem_usage = `ps -o rss= -p #{ Process.pid }`.to_i
  if logger
    logger.info("[MEMORY USAGE]: #{ number_to_human_size(mem_usage) } | PID: #{ Process.pid } | CONTROLLER: #{ controller_name } | ACTION: #{ action_name }")
  end
end

Use this as before action in your base or application controller. Do include ActionView::Helpers::NumberHelper to make number_to_human_size work.

Courtesy: https://github.com/binarylogic/memorylogic


问:
Create an array with Twig
I have this in PHP:

```<code>$units = array();
foreach ($popPorts as $port) {
$units[$port->getFrameNo()][$port->getSlotNo()][$port->getPortNo()] = $port->getPortNo();
}
</code>```

How can I achieve the same in twig?

I have tried this so far:

```<code>{% set frames = [] %}
{% for row in object.popPorts %}
    {% set frames[row.frameNo][row.slotNo][row.portNo] = row.portNo %}
{% endfor %}
{{ dump(frames) }}
</code>```

But then I get an error:

Unexpected token "punctuation" of value "[" ("end of statement block"
  expected).

The output should be like this:

```<code>array (size=3)
  (frame) 1 =>
    array (size=2)
      (slot) 1 =>
        array (size=4)
          0 => (port) 26
          1 => (port) 27
          2 => (port) 28
          3 => (port) 29
      (slot) 5 =>
        array (size=2)
          0 => (port) 31
          1 => (port) 34
  (frame) 2 =>
    array (size=1)
      (slot) 3 =>
        array (size=1)
          0 => (port) 32
  (frame) 3 =>
    array (size=1)
      (slot) 6 =>
        array (size=1)
          0 => (port) 33
</code>```

答:
I'm afraid you can't create arrays like that in Twig. Even appending new items to an array is complicated because you need to create an array for the new element and concatenate it with the existing array. Example:

```<code>{% set array = [] %}
{% for item in items %}
    {% set array = array|merge([{ title: item.title, ... }]) %}
{% endfor %}
</code>```

I know this looks awful, but all this inconvenience is done on purpose. Twig is meant to create templates, so the features available to create or process information are limited on purpose. The idea is that heavy data processing should be done with PHP.

Title: Create an array with Twig

Body:
I have this in PHP:

$units = array();
foreach ($popPorts as $port) {
$units[$port->getFrameNo()][$port->getSlotNo()][$port->getPortNo()] = $port->getPortNo();
}

How can I achieve the same in twig?

I have tried this so far:

{% set frames = [] %}
{% for row in object.popPorts %}
    {% set frames[row.frameNo][row.slotNo][row.portNo] = row.portNo %}
{% endfor %}
{{ dump(frames) }}

But then I get an error:

Unexpected token "punctuation" of value "[" ("end of statement block"
  expected).

The output should be like this:

array (size=3)
  (frame) 1 =>
    array (size=2)
      (slot) 1 =>
        array (size=4)
          0 => (port) 26
          1 => (port) 27
          2 => (port) 28
          3 => (port) 29
      (slot) 5 =>
        array (size=2)
          0 => (port) 31
          1 => (port) 34
  (frame) 2 =>
    array (size=1)
      (slot) 3 =>
        array (size=1)
          0 => (port) 32
  (frame) 3 =>
    array (size=1)
      (slot) 6 =>
        array (size=1)
          0 => (port) 33

Body:
I'm afraid you can't create arrays like that in Twig. Even appending new items to an array is complicated because you need to create an array for the new element and concatenate it with the existing array. Example:

{% set array = [] %}
{% for item in items %}
    {% set array = array|merge([{ title: item.title, ... }]) %}
{% endfor %}

I know this looks awful, but all this inconvenience is done on purpose. Twig is meant to create templates, so the features available to create or process information are limited on purpose. The idea is that heavy data processing should be done with PHP.


问:
Taking a score from one activity to another in Android app
I've been trying to work this out but to no avail.

I have a score that is obtained in the GameView class using the int hitCount inside the onTouchEvent method.  This is being calculated fine.  What I need to do is pass the total score to MainMenu class where it says 'Total Number of Hits'.

I have this 'finish' method in the GameActivity class:

```<code>public void finish(){
    Intent returnIntent=new Intent();
    returnIntent.putExtra("GAME_SCORE",gameView.getHitCount());
    setResult(RESULT_OK,returnIntent);
    super.finish();
}
</code>```

GameView class:

```<code>public class GameView extends SurfaceView implements SurfaceHolder.Callback {

    /* Member (state) fields   */
    private GameLoopThread gameLoopThread;
    private Paint paint; //Reference a paint object
    /**
     * The drawable to use as the background of the animation canvas
     */
    private Bitmap mBackgroundImage;
    // For creating the game Sprite
    private Sprite sprite;
    // For recording the number of hits
    private int hitCount;
    // To track if a game is over
    private boolean gameOver;
    // To play sound
    private SoundPlayer sound;
    //int backButtonCount = 0;

    public GameView(Context context) {
        super(context);
        // Focus must be on GameView so that events can be handled.
        this.setFocusable(true);
        // For intercepting events on the surface.
        this.getHolder().addCallback(this);
        // Background image added
        mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.half_moon);
        //sound = new SoundPlayer(this);
    }

    /* Called immediately after the surface created */
    public void surfaceCreated(SurfaceHolder holder) {
        // We can now safely setup the game start the game loop.
        ResetGame();//Set up a new game up - could be called by a 'play again option'
        mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
        gameLoopThread = new GameLoopThread(this.getHolder(), this);
        gameLoopThread.running = true;
        gameLoopThread.start();
    }

    // For the countdown timer
    private long startTime; // Timer to count down from
    private final long interval = 1 * 1000; // 1 sec interval
    private CountDownTimer countDownTimer; // Reference to the class
    private boolean timerRunning = false;
    private String displayTime; // To display the time on the screen

    //To initialise/reset game
    private void ResetGame() {
        /* Set paint details */
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(20);
        sprite = new Sprite(this);
        hitCount = 0;
        // Set timer
        startTime = 10; // Start at 10s to count down
        // Create new object - convert startTime to milliseconds
        countDownTimer = new MyCountDownTimer(startTime * 1000, interval);
        countDownTimer.start(); // Start the time running
        timerRunning = true;
        gameOver = false;
    }

    // Countdown Timer - private class
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }

        public void onFinish() {
            //displayTime = "Time is up!";
            timerRunning = false;
            countDownTimer.cancel();
            gameOver = true;
        }

        public void onTick(long millisUntilFinished) {
            displayTime = " " + millisUntilFinished / 1000;
        }
    }

    //This class updates and manages the assets prior to drawing - called from the Thread
    public void update() {
        sprite.update();
    }

    /**
     * To draw the game to the screen
     * This is called from Thread, so synchronisation can be done
     */
    public void doDraw(Canvas canvas) {
        //Draw all the objects on the canvas
        canvas.drawBitmap(mBackgroundImage, 0, 0, null);
        if (!gameOver) {
            sprite.draw(canvas);
            canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
            canvas.drawText("Number of hits: " + hitCount, 250, 50, paint);
        } else {
            canvas.drawText("Game Over!", 185, 100, paint);
            canvas.drawText("To go back to the main menu, press the 'back' key", 15, 150, paint);
        }
    }

    //To be used if we need to find where screen was touched
    public boolean onTouchEvent(MotionEvent event) {
        if (sprite.wasItTouched(event.getX(), event.getY())) {
            // This just renews the sprite for now
            sprite = new Sprite(this);
            //sound.playZapSound();
            hitCount++;
        }
        return true;
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        gameLoopThread.running = false;

        // Shut down the game loop thread cleanly.
        boolean retry = true;
        while (retry) {
            try {
                gameLoopThread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }

    public void getHitCount() {
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }
}
</code>```

MainMenu class:

```<code>public class MainMenu extends Activity {

    private static final int SCORE_REQUEST_CODE = 1;// The request code for the intent

    TextView tvScore;
    String score;
    Intent gameIntent;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_start);
    }

    public void startGame(View v) {
        gameIntent = new Intent(this, GameActivity.class);
        startActivityForResult(gameIntent, SCORE_REQUEST_CODE);
    }

    /* Create Options Menu */
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    // Respond to item selected on OPTIONS MENU
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            //put data in Intent
            case R.id.easy:
                Toast.makeText(this, "Easy chosen", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.medium:
                Toast.makeText(this, "Medium chosen", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.hard:
                Toast.makeText(this, "Hard chosen", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.other:
                Toast.makeText(this, "Other chosen", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
        // Check which request we're responding to
        if (requestCode == SCORE_REQUEST_CODE) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                if (retIntent.hasExtra("GAME_SCORE")) {
                    int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
                    tvScore.setText(Integer.toString(scoreFromGame));
                }
            }
        }
    }
}
</code>```

Any advice greatly appreciated.

Thanks

UPDATE:

I have added 'return hitCount;' to the 'getHitCount' method in the 'GameView' class and this now just crashes the app when I hit the back key.  One the 'MainMenu' class, I have taken out the last line in the 'onActivityResult' method (tvScore.setText(Integer.toString(scoreFromGame)); and it no longer crashes but obviously doesn't pass the score across.  I don't know where to go from here.

答:
While fetching data from intent you have to use -

```<code>int scoreFromGame = retIntent.getIntExtra("GAME_SCORE", -1);
// -1 is a default value, use accordingly.
</code>```

Instead of trying to get value from extras.

```<code>retIntent.getExtras().getInt("GAME_SCORE");
</code>```

Use extras only when you put some value inside bundle.

Body:
I've been trying to work this out but to no avail.

I have a score that is obtained in the GameView class using the int hitCount inside the onTouchEvent method.  This is being calculated fine.  What I need to do is pass the total score to MainMenu class where it says 'Total Number of Hits'.

I have this 'finish' method in the GameActivity class:

public void finish(){
    Intent returnIntent=new Intent();
    returnIntent.putExtra("GAME_SCORE",gameView.getHitCount());
    setResult(RESULT_OK,returnIntent);
    super.finish();
}

GameView class:

public class GameView extends SurfaceView implements SurfaceHolder.Callback {

    /* Member (state) fields   */
    private GameLoopThread gameLoopThread;
    private Paint paint; //Reference a paint object
    /**
     * The drawable to use as the background of the animation canvas
     */
    private Bitmap mBackgroundImage;
    // For creating the game Sprite
    private Sprite sprite;
    // For recording the number of hits
    private int hitCount;
    // To track if a game is over
    private boolean gameOver;
    // To play sound
    private SoundPlayer sound;
    //int backButtonCount = 0;

    public GameView(Context context) {
        super(context);
        // Focus must be on GameView so that events can be handled.
        this.setFocusable(true);
        // For intercepting events on the surface.
        this.getHolder().addCallback(this);
        // Background image added
        mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.half_moon);
        //sound = new SoundPlayer(this);
    }

    /* Called immediately after the surface created */
    public void surfaceCreated(SurfaceHolder holder) {
        // We can now safely setup the game start the game loop.
        ResetGame();//Set up a new game up - could be called by a 'play again option'
        mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
        gameLoopThread = new GameLoopThread(this.getHolder(), this);
        gameLoopThread.running = true;
        gameLoopThread.start();
    }

    // For the countdown timer
    private long startTime; // Timer to count down from
    private final long interval = 1 * 1000; // 1 sec interval
    private CountDownTimer countDownTimer; // Reference to the class
    private boolean timerRunning = false;
    private String displayTime; // To display the time on the screen

    //To initialise/reset game
    private void ResetGame() {
        /* Set paint details */
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(20);
        sprite = new Sprite(this);
        hitCount = 0;
        // Set timer
        startTime = 10; // Start at 10s to count down
        // Create new object - convert startTime to milliseconds
        countDownTimer = new MyCountDownTimer(startTime * 1000, interval);
        countDownTimer.start(); // Start the time running
        timerRunning = true;
        gameOver = false;
    }

    // Countdown Timer - private class
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }

        public void onFinish() {
            //displayTime = "Time is up!";
            timerRunning = false;
            countDownTimer.cancel();
            gameOver = true;
        }

        public void onTick(long millisUntilFinished) {
            displayTime = " " + millisUntilFinished / 1000;
        }
    }

    //This class updates and manages the assets prior to drawing - called from the Thread
    public void update() {
        sprite.update();
    }

    /**
     * To draw the game to the screen
     * This is called from Thread, so synchronisation can be done
     */
    public void doDraw(Canvas canvas) {
        //Draw all the objects on the canvas
        canvas.drawBitmap(mBackgroundImage, 0, 0, null);
        if (!gameOver) {
            sprite.draw(canvas);
            canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
            canvas.drawText("Number of hits: " + hitCount, 250, 50, paint);
        } else {
            canvas.drawText("Game Over!", 185, 100, paint);
            canvas.drawText("To go back to the main menu, press the 'back' key", 15, 150, paint);
        }
    }

    //To be used if we need to find where screen was touched
    public boolean onTouchEvent(MotionEvent event) {
        if (sprite.wasItTouched(event.getX(), event.getY())) {
            // This just renews the sprite for now
            sprite = new Sprite(this);
            //sound.playZapSound();
            hitCount++;
        }
        return true;
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        gameLoopThread.running = false;

        // Shut down the game loop thread cleanly.
        boolean retry = true;
        while (retry) {
            try {
                gameLoopThread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }

    public void getHitCount() {
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }
}

MainMenu class:

public class MainMenu extends Activity {

    private static final int SCORE_REQUEST_CODE = 1;// The request code for the intent

    TextView tvScore;
    String score;
    Intent gameIntent;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_start);
    }

    public void startGame(View v) {
        gameIntent = new Intent(this, GameActivity.class);
        startActivityForResult(gameIntent, SCORE_REQUEST_CODE);
    }

    /* Create Options Menu */
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    // Respond to item selected on OPTIONS MENU
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            //put data in Intent
            case R.id.easy:
                Toast.makeText(this, "Easy chosen", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.medium:
                Toast.makeText(this, "Medium chosen", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.hard:
                Toast.makeText(this, "Hard chosen", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.other:
                Toast.makeText(this, "Other chosen", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
        // Check which request we're responding to
        if (requestCode == SCORE_REQUEST_CODE) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                if (retIntent.hasExtra("GAME_SCORE")) {
                    int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
                    tvScore.setText(Integer.toString(scoreFromGame));
                }
            }
        }
    }
}

Any advice greatly appreciated.

Thanks

UPDATE:

I have added 'return hitCount;' to the 'getHitCount' method in the 'GameView' class and this now just crashes the app when I hit the back key.  One the 'MainMenu' class, I have taken out the last line in the 'onActivityResult' method (tvScore.setText(Integer.toString(scoreFromGame)); and it no longer crashes but obviously doesn't pass the score across.  I don't know where to go from here.

Body:
While fetching data from intent you have to use -

int scoreFromGame = retIntent.getIntExtra("GAME_SCORE", -1);
// -1 is a default value, use accordingly.

Instead of trying to get value from extras.

retIntent.getExtras().getInt("GAME_SCORE");

Use extras only when you put some value inside bundle.


问:
Fortran 77 conversion to C++
I have a Fortran 77 application that uses Common declarations to "share" memory variables.  Back in the day, when memory was expensive and hard to come by this was the way around it.

The equipment being controlled sets status flags.  These flags reside in these Common variables.

Any suggestions on how to implement the Common functionality in c++?

A class perhaps, with all the common variables being public.  Thus any program instantiating that class will have access to the contents of the Common variables.

Are there any tutorials/guidelines for converting Fortran to C or C++?

Thanks

答:
This Fortran to C/C++ Tutorial suggests:

```<code>      FORTRAN:
           DOUBLE PRECISION X
           INTEGER A, B, C
           COMMON/ABC/ X, A, B, C

      C:
           extern struct{
               double x;
               int a, b, c;
           } abc_;

      C++:
         extern "C" {
           extern struct{
               double x;
               int a, b, c;
           } abc_;
         }
</code>```

You put the extern struct into an .h file which the C / C++ files refer to with #include, and in exactly one .c or .cpp file you put exactly what was in the .h file but without the "extern" word.

My assumption is that what you have to start with is relatively terse and borderline incomprehensible, and that you want to translate it into C++ in a way that preserves a near one-to-one correspondence to the original.

Title: Fortran 77 conversion to C++

Body:
This Fortran to C/C++ Tutorial suggests:

      FORTRAN:
           DOUBLE PRECISION X
           INTEGER A, B, C
           COMMON/ABC/ X, A, B, C

      C:
           extern struct{
               double x;
               int a, b, c;
           } abc_;

      C++:
         extern "C" {
           extern struct{
               double x;
               int a, b, c;
           } abc_;
         }

You put the extern struct into an .h file which the C / C++ files refer to with #include, and in exactly one .c or .cpp file you put exactly what was in the .h file but without the "extern" word.

My assumption is that what you have to start with is relatively terse and borderline incomprehensible, and that you want to translate it into C++ in a way that preserves a near one-to-one correspondence to the original.


问:
Python: Finding length of the repeating sequence of numbers in a string of floats
I am trying to write a function which takes in a list of floats and determines whether or not there is a repeating sequence of number within that list. If there is a repeating sequence then it counts the numbers in that sequence.

These examples are what I want my function to do

Example 1:

```<code>function = '1.0 8.0 4.0 2.0 1.0 8.0 4.0 2.0 1.0 8.0 4.0 2.0 1.0 8.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 8.0, 4.0, 2.0
# so result should equal 4 in this case
</code>```

Example 2:

```<code>function = '1.0 8.0 4.0 1.0 2.0 1.0 8.0 4.0 1.0 2.0 1.0 8.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 8.0, 4.0, 1.0, 2.0
# so result should equal 5 in this case
</code>```

Example 3:

```<code>function = '1.0 8.0 4.0 2.0 1.0 7.0 6.0 3.0 2.0 5.0 9.0'
result = find_repeating_sequence(function)
# repeating sequence doesn't exist
# so result should equal None in this case
</code>```

Example 4:

```<code>function = '1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 11.0
# so result should equal 2 in this case
</code>```

So far what I have got is:

```<code>def find_repeating_sequence(function):
        regex = re.compile(r'(.+ .+)( \1)+')
        match = regex.search(function)
        result = match

       if result == None:
            print "There was no repeating sequence found!"
        else:
            print "Repeating sequence found!"
            print match.group(1)
            result = match.group(1)

       return result
</code>```

This works for all examples in the sense that match.group(1) gives the repeating sequence. However for some reason len(match.group(1)) does not return the correct number.

Like for Example 1:

print match.group(1) gives 1.0 8.0 4.0 2.0

But print len(match.group(1)) gives 15

Also it does not return the correct value for Example 4:
print match.group(1) gives 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0

And print len(match.group(1)) gives 35

What am I doing wrong?

UPDATE:

Thanks to one of the answers below I have solved the print len(match.group(1)) issue by using len(match.group(1).split())

However for some reason if
function = 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0
print match.group(1) gives 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0
and not 1.0 2.0 4.0 8.0

答:
match.group() returns a string and in this case len() returns the number of characters in the string.

you could split your string by space, and then count the number of elements

Answer to the update:
your expression is greedy, it tries to find the longest match. Try (.+? .+?)( \1)+?. The questionmark after a qualifier makes the regex lazy:

https://regex101.com/r/1w7nxD/1

Body:
I am trying to write a function which takes in a list of floats and determines whether or not there is a repeating sequence of number within that list. If there is a repeating sequence then it counts the numbers in that sequence.

These examples are what I want my function to do

Example 1:

function = '1.0 8.0 4.0 2.0 1.0 8.0 4.0 2.0 1.0 8.0 4.0 2.0 1.0 8.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 8.0, 4.0, 2.0
# so result should equal 4 in this case

Example 2:

function = '1.0 8.0 4.0 1.0 2.0 1.0 8.0 4.0 1.0 2.0 1.0 8.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 8.0, 4.0, 1.0, 2.0
# so result should equal 5 in this case

Example 3:

function = '1.0 8.0 4.0 2.0 1.0 7.0 6.0 3.0 2.0 5.0 9.0'
result = find_repeating_sequence(function)
# repeating sequence doesn't exist
# so result should equal None in this case

Example 4:

function = '1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 11.0
# so result should equal 2 in this case

So far what I have got is:

def find_repeating_sequence(function):
        regex = re.compile(r'(.+ .+)( \1)+')
        match = regex.search(function)
        result = match

       if result == None:
            print "There was no repeating sequence found!"
        else:
            print "Repeating sequence found!"
            print match.group(1)
            result = match.group(1)

       return result

This works for all examples in the sense that match.group(1) gives the repeating sequence. However for some reason len(match.group(1)) does not return the correct number.

Like for Example 1:

print match.group(1) gives 1.0 8.0 4.0 2.0

But print len(match.group(1)) gives 15

Also it does not return the correct value for Example 4:
print match.group(1) gives 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0

And print len(match.group(1)) gives 35

What am I doing wrong?

UPDATE:

Thanks to one of the answers below I have solved the print len(match.group(1)) issue by using len(match.group(1).split())

However for some reason if
function = 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0
print match.group(1) gives 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0
and not 1.0 2.0 4.0 8.0


问:
Authorization in Facebook, Swift 3, FBSDK
I am trying to create an API for login user on facebook, but I have this error:

Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

on this line:

```<code>self.accessToken = jsonData["access_token"].string!
</code>```

Console shows:

My Code:

fatal error: unexpectedly found nil while unwrapping an Optional value
      (lldb)

```<code>func login(userType: String, completionHandler: @escaping (NSError?) -> Void) {

        let path = "api/social/convert-token/"
        let url = baseURL!.appendingPathComponent(path)
        let params: [String: Any] = [
            "grant_type": "convert_token",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "backend": "facebook",
            "token": FBSDKAccessToken.current().tokenString,
            "user_type": userType
        ]

        Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response) in

            switch response.result {
            case .success(let value):

                let jsonData = JSON(value)

                self.accessToken = jsonData["access_token"].string!
                self.refreshToken = jsonData["refresh_token"].string!
                self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!))

                completionHandler(nil)
                break

            case .failure(let error):
                completionHandler(error as NSError?)
                break
            }
        }
    }
</code>```

答:
The problem was the app info in Constants.swift</p>

```<code>let BASE_URL: String = ""
let CLIENT_ID: String = ""
let CLIENT_SECRET: String = ""
</code>```

Body:
I am trying to create an API for login user on facebook, but I have this error:

Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

on this line:

self.accessToken = jsonData["access_token"].string!

Console shows:

My Code:

fatal error: unexpectedly found nil while unwrapping an Optional value
      (lldb)

func login(userType: String, completionHandler: @escaping (NSError?) -> Void) {

        let path = "api/social/convert-token/"
        let url = baseURL!.appendingPathComponent(path)
        let params: [String: Any] = [
            "grant_type": "convert_token",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "backend": "facebook",
            "token": FBSDKAccessToken.current().tokenString,
            "user_type": userType
        ]

        Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response) in

            switch response.result {
            case .success(let value):

                let jsonData = JSON(value)

                self.accessToken = jsonData["access_token"].string!
                self.refreshToken = jsonData["refresh_token"].string!
                self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!))

                completionHandler(nil)
                break

            case .failure(let error):
                completionHandler(error as NSError?)
                break
            }
        }
    }

Body:
The problem was the app info in Constants.swift

let BASE_URL: String = ""
let CLIENT_ID: String = ""
let CLIENT_SECRET: String = ""


问:
Copy data from python lists into postgresql tables
I have a python list cve_id, pkg_name & vuln_status. I'd like to import the data from these lists int a postgresql table

What I have tried:

```<code>from scanner import *
import psycopg2

try:
    conn = psycopg2.connect(database="test", user="postgres",password="something", host="127.0.0.1", port="5432")

except:
    print "Database un-successfull"
    quit()

cur = conn.cursor()

cur.execute("INSERT into vuln_data(cve_id, pkg_name, status) VALUES (%s,%s, %s)", (cve_id, pkg_name, vuln_status))

conn.commit()
conn.close()
</code>```

I get an error saying

psycopg2.DataError: multidimensional arrays must have array expressions with matching dimensions

```<code>                                                         ^
</code>```

Would love if someone could point out what can be done, here.

Thanks

答:
If your data is in the form:

```<code>[
    (val, val, val),
    (val, val, val),
    (val, val, val),
]
</code>```

Then the answer is cursor.executemany( sql, data ):

psycopg2: insert multiple rows with one query

If your data is not in this form, then put it in this form with zip() or list comprehensions.

There are HUGE performance implications.

If Autocommit is ON, you get one COMMIT per query, which will be slow as hell.

Solution 1: BEGIN, then executemany(), then COMMIT.

Solution 2: see link above, create a multi-value INSERT and do it as a single query.

Body:
I have a python list cve_id, pkg_name & vuln_status. I'd like to import the data from these lists int a postgresql table

What I have tried:

from scanner import *
import psycopg2

try:
    conn = psycopg2.connect(database="test", user="postgres",password="something", host="127.0.0.1", port="5432")

except:
    print "Database un-successfull"
    quit()

cur = conn.cursor()

cur.execute("INSERT into vuln_data(cve_id, pkg_name, status) VALUES (%s,%s, %s)", (cve_id, pkg_name, vuln_status))

conn.commit()
conn.close()

I get an error saying

psycopg2.DataError: multidimensional arrays must have array expressions with matching dimensions

                                                         ^

Would love if someone could point out what can be done, here.

Thanks

Body:
If your data is in the form:

[
    (val, val, val),
    (val, val, val),
    (val, val, val),
]

Then the answer is cursor.executemany( sql, data ):

psycopg2: insert multiple rows with one query

If your data is not in this form, then put it in this form with zip() or list comprehensions.

There are HUGE performance implications.

If Autocommit is ON, you get one COMMIT per query, which will be slow as hell.

Solution 1: BEGIN, then executemany(), then COMMIT.

Solution 2: see link above, create a multi-value INSERT and do it as a single query.


问:
AWS Elastic Beanstalk: setting up X virtual framebuffer (Xvfb)
I'm trying to get a Selenium script running on an Elastic Beanstalk server, to achieve this I am using pyvirtualdisplay package following this answer. However, for the Display driver to run xvfb also needs to be installed on the system. I'm getting this error message:

```<code>OSError=[Errno 2] No such file or directory: 'Xvfb'
</code>```

Is there any way to manually install this on EB? I have also set up an EC2 server as suggested here, but the whole process seems unnecessary for this task.

答:
You can create a file in .ebextensions/ like: .ebextensions/xvfb.config with the following content:

```<code>packages:
  yum:
    xorg-x11-server-Xvfb: []
</code>```

Body:
I'm trying to get a Selenium script running on an Elastic Beanstalk server, to achieve this I am using pyvirtualdisplay package following this answer. However, for the Display driver to run xvfb also needs to be installed on the system. I'm getting this error message:

OSError=[Errno 2] No such file or directory: 'Xvfb'

Is there any way to manually install this on EB? I have also set up an EC2 server as suggested here, but the whole process seems unnecessary for this task.

Body:
You can create a file in .ebextensions/ like: .ebextensions/xvfb.config with the following content:

packages:
  yum:
    xorg-x11-server-Xvfb: []


问:
React : setState in componentDidMount not causing infinite loop
I am new to ReactJS. When i am reading ReactJS Blueprint book author had specified that

"but take care to never run setState in here, as that will trigger an
  endless update loop."

So, i have created a below simple component but i did not see any such infinite loop happening.

```<code>'use strict';
import React from 'react';
import { render } from 'react-dom';
const App = React.createClass({
    displayName : "SG",
    getDefaultProps() {
        return {
            age : "24"
        }
    },
    getInitialState() {
        return {
            date : ""
        }
    },
    componentDidMount() {
        debugger;
        var d = new Date();
        this.setState({date: d.getMilliseconds().toString()});
    },
    render() {
        return (
            <section>
                <h1>Demo App</h1>
                <p>Name : {this.props.name}</p>
                <p>Age : {this.props.age}</p>
                <p>date : {this.state.date}</p>
            </section>
        );
    }
});
render (<App name='Gowtham S'/>, document.getElementById('container'));
</code>```

I kept debugger in componentDidMount but it is hitting only once. Whats wrong with my code can anyone help me?

Thanks

答:
He is talking about componentDidUpdate, not componentDidMount.

When you setState in componentDidUpdate, the latter is being called again because the component should update, which results in endless recursion. On the other hand, componentDidMount is only called on the initial render.

Body:
I am new to ReactJS. When i am reading ReactJS Blueprint book author had specified that

"but take care to never run setState in here, as that will trigger an
  endless update loop."

So, i have created a below simple component but i did not see any such infinite loop happening.

'use strict';
import React from 'react';
import { render } from 'react-dom';
const App = React.createClass({
    displayName : "SG",
    getDefaultProps() {
        return {
            age : "24"
        }
    },
    getInitialState() {
        return {
            date : ""
        }
    },
    componentDidMount() {
        debugger;
        var d = new Date();
        this.setState({date: d.getMilliseconds().toString()});
    },
    render() {
        return (

Demo App

Name : {this.props.name}

Age : {this.props.age}

date : {this.state.date}

        );
    }
});
render (<App name='Gowtham S'/>, document.getElementById('container'));

I kept debugger in componentDidMount but it is hitting only once. Whats wrong with my code can anyone help me?

Thanks


问:
Gradle incremental build for my task: what's wrong?
I'm struggling with Gradle 3.3 in Android Studio 2.3. I have assets generating task for which I specify inputs.dir and outputs.dir in cfg section:

```<code>task compileAssets{

inputs.dir 'src/main/assets_src'
outputs.dir 'src/main/assets'

def proj_src = 'src/main/'
def abs_proj_src = project.projectDir.getAbsolutePath() + '/' + 'src/main/'
abs_proj_src = abs_proj_src.replace('\\','/')

doLast {
    delete(proj_src + 'assets')
    mkdir(proj_src + 'assets')

    copy
        {
            from proj_src + 'assets_src'
            include 'xml/**'
            include 'fonts/**'
            include 'shaders/**'
            into proj_src + 'assets'
        }

    javaexec{
        main = '-jar'
        args = [
            "../../utils/encoder.jar",
            abs_proj_src + 'assets_src/bin/levels',
            abs_proj_src + 'assets/bin/levels',
            '-rewrite'
        ]
    }
}
</code>```

I expect Gradle will check contents of input folder changes and if some files were added, removed or changed it will allow to execute task, else it will print 'UP-TO-DATE'. But it is so only when only delete(...) and mkdir(...). Otherwise it is executed every time. Maybe I understand the term 'incremental build' in a wrong way? Or maybe there is task size limit, or javaexec or copy are forbidden in incremental build?

PS. I tried to launch task with make command and directly from AS Gradle projects pane.

答:
It was my own error. Below is defined cleanAssets task, where I forgot to add << or doLast:

```<code>task cleanAssets{
        delete(proj_src + 'assets')
        mkdir(proj_src + 'assets')
}
</code>```

So every build in configure phase assets folder was deleted. Funny!

Body:
I'm struggling with Gradle 3.3 in Android Studio 2.3. I have assets generating task for which I specify inputs.dir and outputs.dir in cfg section:

task compileAssets{

inputs.dir 'src/main/assets_src'
outputs.dir 'src/main/assets'

def proj_src = 'src/main/'
def abs_proj_src = project.projectDir.getAbsolutePath() + '/' + 'src/main/'
abs_proj_src = abs_proj_src.replace('\\','/')

doLast {
    delete(proj_src + 'assets')
    mkdir(proj_src + 'assets')

    copy
        {
            from proj_src + 'assets_src'
            include 'xml/**'
            include 'fonts/**'
            include 'shaders/**'
            into proj_src + 'assets'
        }

    javaexec{
        main = '-jar'
        args = [
            "../../utils/encoder.jar",
            abs_proj_src + 'assets_src/bin/levels',
            abs_proj_src + 'assets/bin/levels',
            '-rewrite'
        ]
    }
}

I expect Gradle will check contents of input folder changes and if some files were added, removed or changed it will allow to execute task, else it will print 'UP-TO-DATE'. But it is so only when only delete(...) and mkdir(...). Otherwise it is executed every time. Maybe I understand the term 'incremental build' in a wrong way? Or maybe there is task size limit, or javaexec or copy are forbidden in incremental build?

PS. I tried to launch task with make command and directly from AS Gradle projects pane.

Body:
It was my own error. Below is defined cleanAssets task, where I forgot to add << or doLast:

task cleanAssets{
        delete(proj_src + 'assets')
        mkdir(proj_src + 'assets')
}

So every build in configure phase assets folder was deleted. Funny!


问:
Angular2 Animation for simple hover, without any state change
I need help with ng2 animate. I need to prepare simple hover effect based on this:

```<code>@Component({
    selector: 'category',
    template : require('./category.component.html'),
    styleUrls: ['./category.component.scss'],
    animations: [
        trigger('albumState', [
            state('inactive', style({
                bottom: '0px'
            })),
            state('active', style({
                bottom: '200px'
            })),
            transition('inactive => active', animate('100ms ease-in')),
            transition('active => inactive', animate('100ms ease-in'))
        ])
    ]
})
</code>```

I need a hint how can I assign that to the template? On Ng2 Docs, we have implementation base on object parameter. I don't need to change any parameter of my

```<code>item/object/album
</code>```

from the category, just want assign animation to template.

Regards!
Greg

答:
If you need to override a property being set by the Angular animation you could always use !important.

```<code>.album:hover {
  bottom: 20px !important;
}
</code>```

Using the important flag is not the most desirable solution, but it will work until we get support for pseudo classes in Angular animation.

Body:
I need help with ng2 animate. I need to prepare simple hover effect based on this:

@Component({
    selector: 'category',
    template : require('./category.component.html'),
    styleUrls: ['./category.component.scss'],
    animations: [
        trigger('albumState', [
            state('inactive', style({
                bottom: '0px'
            })),
            state('active', style({
                bottom: '200px'
            })),
            transition('inactive => active', animate('100ms ease-in')),
            transition('active => inactive', animate('100ms ease-in'))
        ])
    ]
})

I need a hint how can I assign that to the template? On Ng2 Docs, we have implementation base on object parameter. I don't need to change any parameter of my

item/object/album

from the category, just want assign animation to template.

Regards!
Greg

Body:
If you need to override a property being set by the Angular animation you could always use !important.

.album:hover {
  bottom: 20px !important;
}

Using the important flag is not the most desirable solution, but it will work until we get support for pseudo classes in Angular animation.


问:
Libtool versioning of a library that depends on other libraries
I have a framework that uses Boost and CgiCC in the core application and in its interface.

How should I version the library binary interface (a.k.a. libtool -version-info)?

I have no problems tracking the changes in library itself when I make various changes. As it
is clear for me how should I version.

But...

Both Boost and CgiCC libraries do not provide any backward compatible API/ABI and my library may be linked with quite arbitrary versions Boost and CgiCC so I can't provide any promise about the interfaces, so I can't really specify -version-info because even the
same library compiled against different versions of Boost and CgiCC would not be compatible.

So... What should I do? How should I version library?

I know that I should not depend on Boost and CgiCC interfaces in first place, but this is what I get so far for existing stable version. This issue is addressed in next major release but I still have and want to maintain current release as it is very valuable.

答: -version-info does not bluntly take some major-minor-patch version you made up (that's what -release is for), but has to adhere to the numbering scheme described in http://www.gnu.org/software/libtool/manual/html_node/Versioning.html (the entire chapter) .