问:
Matplotlib annotation arrow with TikZ style path decoration
I have recently switched from making illutrations with TeX (PGF/TikZ) to using Matplotlib for the same purpose. The main reason is that a lot of my scientific code is in python and some of the illustrations should directly use the output of python calculations.

I have been using annotate and the fancy arrow patch, which already does a lot of what I need, such as drawing curved arrows (see e.g. here). Compared to TikZ, there is one particular thing I have been missing: path decorations (see e.g. https://tex.stackexchange.com/a/193451/96546 for an easy TikZ example). My question is if there is a way to do such TikZ-style path decorations in matplotlib?

Since this is rather broad I will set a particular task (taken from the TeX.SE question https://tex.stackexchange.com/questions/193444/sketching-simple-arrows-with-different-direction): How would I draw the following picture in Matplotlib?

I am aware of this question, but the implementation is not really a decoration of a line between endpoints, but rather a plotted function.

答:
I created this in matplotlib with the help of the feynman package by GkAntonius (docs). This has capabilities for neat plotting of various arrow types using vertices and lines, including a style='wiggly' line style. I also added a straight start and end segment to these wiggly lines, as in the example diagram in the OP. In addition, given the comments/bounty asks for a curved/arch wiggly line, I have also included a demonstration of this functionality.

Diagram in question

Code:

```<code>import matplotlib.pyplot as plt
from feynman import Diagram

# Set up diagram
fig = plt.figure(figsize=(10.,10.))
ax = fig.add_axes([0,0,1,1], frameon=False)
diagram = Diagram(ax)

# Mirror line
m1 = diagram.vertex(xy=(.1,.5), marker='')
m2 = diagram.vertex(xy=(.9,.5), marker='')
mirror = diagram.line(m1, m2, arrow=False, style='double')

# Top left P-line
p1 = diagram.vertex(xy=(.2, .8), marker='')
p2 = diagram.vertex(xy=(.5, .5), marker='')
P1 = diagram.line(p1, p2, arrow=True, arrow_param={'t':0.91})
P1.text("$P$", fontsize=60, y=-.1, t=.1)

# Bottom right P-line
p3 = diagram.vertex(xy=(.5, .5), marker='')
p4 = diagram.vertex(xy=(.8, .2), marker='')
P2 = diagram.line(p3, p4, arrow=True, arrow_param={'t':0.91})
P2.text("$P$", fontsize=60, y=.05, t=.9)

# Top right P-line
p5 = diagram.vertex(xy=(.5, .5), marker='')
p6 = diagram.vertex(xy=(.8, .8), marker='')
P3 = diagram.line(p5, p6, arrow=True, arrow_param={'t':0.91})
P3.text("$P$", fontsize=60, y=-.05, t=.9)

# Top right SV-line start
sv1_s1 = diagram.vertex(xy=(.5, .5), marker='')
sv1_s2 = diagram.vertex(xy=(.51, .5175), marker='')
SV1_start = diagram.line(sv1_s1, sv1_s2, arrow=False)

# Top right SV-line middle
sv1_1 = diagram.vertex(xy=(.51, .5175), marker='')
sv1_2 = diagram.vertex(xy=(.69, .8325), marker='')
SV1 = diagram.line(sv1_1, sv1_2, arrow=False, style='wiggly', nwiggles=5)
SV1.text("$SV$", fontsize=60, y=.15, t=.9)

# Top right SV-line end
sv1_e1 = diagram.vertex(xy=(.69, .8325), marker='')
sv1_e2 = diagram.vertex(xy=(.7, .85), marker='')
SV1_end = diagram.line(sv1_e1, sv1_e2, arrow=True, arrow_param={'t':0.91})

# Bottom right SV-line start
sv2_s1 = diagram.vertex(xy=(.5, .5), marker='')
sv2_s2 = diagram.vertex(xy=(.51, .4825), marker='')
SV2_start = diagram.line(sv2_s1, sv2_s2, arrow=False)

# Bottom right SV-line middle
sv2_1 = diagram.vertex(xy=(.51, .4825), marker='')
sv2_2 = diagram.vertex(xy=(.69, .1675), marker='')
SV2 = diagram.line(sv2_1, sv2_2, arrow=False, style='wiggly', nwiggles=5)
SV2.text("$SV$", fontsize=60, y=-.15, t=.9)

# Bottom right SV-line end
sv2_e1 = diagram.vertex(xy=(.69, .1675), marker='')
sv2_e2 = diagram.vertex(xy=(.7, .15), marker='')
SV2_end = diagram.line(sv2_e1, sv2_e2, arrow=True, arrow_param={'t':0.91})

diagram.plot()
plt.show()
</code>```

Curved/arched lines

Code

```<code>import matplotlib.pyplot as plt
from feynman import Diagram

# Set up diagram
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0,0,1,1], frameon=False)
diagram = Diagram(ax)

# Curvy wiggly line
sv1_1 = diagram.vertex(xy=(.205, .205), marker='')
sv1_2 = diagram.vertex(xy=(.79, .79), marker='')
SV1 = diagram.line(sv1_1, sv1_2, arrow=False, style='wiggly elliptic ', nwiggles=8)
SV1.text("$1$", fontsize=50, y=.15, t=.5)

# Curvy wiggly line end
sv1_e1 = diagram.vertex(xy=(.79, .79), marker='')
sv1_e2 = diagram.vertex(xy=(.8, .8), marker='')
SV1_end = diagram.line(sv1_e1, sv1_e2, arrow=True, arrow_param={'t':0.91})

# Circular wiggly line
sv2_1 = diagram.vertex(xy=(.75, .25), marker='')
SV2 = diagram.line(sv2_1, sv2_1, arrow=False, style='wiggly circular', nwiggles=8)
SV2.text("$2$", fontsize=50, y=.15, t=.5)

diagram.plot()
plt.show()
</code>```

Body:
I created this in matplotlib with the help of the feynman package by GkAntonius (docs). This has capabilities for neat plotting of various arrow types using vertices and lines, including a style='wiggly' line style. I also added a straight start and end segment to these wiggly lines, as in the example diagram in the OP. In addition, given the comments/bounty asks for a curved/arch wiggly line, I have also included a demonstration of this functionality.

Diagram in question

Code:

import matplotlib.pyplot as plt
from feynman import Diagram

# Set up diagram
fig = plt.figure(figsize=(10.,10.))
ax = fig.add_axes([0,0,1,1], frameon=False)
diagram = Diagram(ax)

# Mirror line
m1 = diagram.vertex(xy=(.1,.5), marker='')
m2 = diagram.vertex(xy=(.9,.5), marker='')
mirror = diagram.line(m1, m2, arrow=False, style='double')

# Top left P-line
p1 = diagram.vertex(xy=(.2, .8), marker='')
p2 = diagram.vertex(xy=(.5, .5), marker='')
P1 = diagram.line(p1, p2, arrow=True, arrow_param={'t':0.91})
P1.text("$P$", fontsize=60, y=-.1, t=.1)

# Bottom right P-line
p3 = diagram.vertex(xy=(.5, .5), marker='')
p4 = diagram.vertex(xy=(.8, .2), marker='')
P2 = diagram.line(p3, p4, arrow=True, arrow_param={'t':0.91})
P2.text("$P$", fontsize=60, y=.05, t=.9)

# Top right P-line
p5 = diagram.vertex(xy=(.5, .5), marker='')
p6 = diagram.vertex(xy=(.8, .8), marker='')
P3 = diagram.line(p5, p6, arrow=True, arrow_param={'t':0.91})
P3.text("$P$", fontsize=60, y=-.05, t=.9)

# Top right SV-line start
sv1_s1 = diagram.vertex(xy=(.5, .5), marker='')
sv1_s2 = diagram.vertex(xy=(.51, .5175), marker='')
SV1_start = diagram.line(sv1_s1, sv1_s2, arrow=False)

# Top right SV-line middle
sv1_1 = diagram.vertex(xy=(.51, .5175), marker='')
sv1_2 = diagram.vertex(xy=(.69, .8325), marker='')
SV1 = diagram.line(sv1_1, sv1_2, arrow=False, style='wiggly', nwiggles=5)
SV1.text("$SV$", fontsize=60, y=.15, t=.9)

# Top right SV-line end
sv1_e1 = diagram.vertex(xy=(.69, .8325), marker='')
sv1_e2 = diagram.vertex(xy=(.7, .85), marker='')
SV1_end = diagram.line(sv1_e1, sv1_e2, arrow=True, arrow_param={'t':0.91})

# Bottom right SV-line start
sv2_s1 = diagram.vertex(xy=(.5, .5), marker='')
sv2_s2 = diagram.vertex(xy=(.51, .4825), marker='')
SV2_start = diagram.line(sv2_s1, sv2_s2, arrow=False)

# Bottom right SV-line middle
sv2_1 = diagram.vertex(xy=(.51, .4825), marker='')
sv2_2 = diagram.vertex(xy=(.69, .1675), marker='')
SV2 = diagram.line(sv2_1, sv2_2, arrow=False, style='wiggly', nwiggles=5)
SV2.text("$SV$", fontsize=60, y=-.15, t=.9)

# Bottom right SV-line end
sv2_e1 = diagram.vertex(xy=(.69, .1675), marker='')
sv2_e2 = diagram.vertex(xy=(.7, .15), marker='')
SV2_end = diagram.line(sv2_e1, sv2_e2, arrow=True, arrow_param={'t':0.91})

diagram.plot()
plt.show()

Curved/arched lines

Code

import matplotlib.pyplot as plt
from feynman import Diagram

# Set up diagram
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0,0,1,1], frameon=False)
diagram = Diagram(ax)

# Curvy wiggly line
sv1_1 = diagram.vertex(xy=(.205, .205), marker='')
sv1_2 = diagram.vertex(xy=(.79, .79), marker='')
SV1 = diagram.line(sv1_1, sv1_2, arrow=False, style='wiggly elliptic ', nwiggles=8)
SV1.text("$1$", fontsize=50, y=.15, t=.5)

# Curvy wiggly line end
sv1_e1 = diagram.vertex(xy=(.79, .79), marker='')
sv1_e2 = diagram.vertex(xy=(.8, .8), marker='')
SV1_end = diagram.line(sv1_e1, sv1_e2, arrow=True, arrow_param={'t':0.91})

# Circular wiggly line
sv2_1 = diagram.vertex(xy=(.75, .25), marker='')
SV2 = diagram.line(sv2_1, sv2_1, arrow=False, style='wiggly circular', nwiggles=8)
SV2.text("$2$", fontsize=50, y=.15, t=.5)

diagram.plot()
plt.show()


来源: stackexchange

问:
File verification and validation
So I have this code here made in a more simplified way:

```<code>var reader = new FileReader();
reader.onload = function(progressEvent) {

    // By lines
    var lines = this.result.split('\n');
    let N = /^(N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;

    for (var line = 0; line < lines.length; line++) {
      if (N.test(lines[line])) {
        console.log(lines[line]);
      } else {
        console.log("Invalid register = ", lines[line]);
      }
    }
}

</code>```

What I want is a way that a message can be shown to tell me that the file corresponded to all those requirements and if not that a message can be printed to tell me that the file is not valid, but keep showing me the message at the console. How can I possibly do that? Another question I have is if there is a way to specify that can be only one register called N1

HERE IS A FILE EXAMPLE

```<code>N108258594000135255240708     315370        BLABLA BLABLABL BLAB BLA
N2BLA2222016BLABLA BLABLABLA                                3525.250
N3BLABLABLABL.EXE                                   01BF011351A2B06D7A88048CBDDC53CE
N908234944000135255240708     000016
</code>```

答:
My understanding is that you are processing each line one by one and it is an error if there is more than one "register called N1", i.e. a line that passed the regex test and begins with N1. So you have to keep track of whether you have already seen such a line:</p>

```<code>var reader = new FileReader();
var invalidRegister = false;
var seenN1 = false;
reader.onload = function(progressEvent) {
    // By lines
    var lines = this.result.split('\n');
    let N = /^(N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;

    for (var line = 0; line < lines.length; line++) {
      let s = lines[line];
      if (N.test(s)) {
        if (s.substr(0, 2) == 'N1') {
          if (seenN1) {
             console.log("Repeat N1 register = ", s);
             invalidRegister = true;
             continue;
          }
          seenN1 = true;
        }
        console.log(s);
      } else {
        console.log("Invalid register = ", s);
        invalidRegister = true;
      }
    }
    if (invalidRegister) {
      console.log('The file is not valid.');
    }
};
</code>```

ContentLicense: CC BY-SA 4.0

Title: File verification and validation

Body:
So I have this code here made in a more simplified way:

var reader = new FileReader();
reader.onload = function(progressEvent) {

    // By lines
    var lines = this.result.split('\n');
    let N = /^(N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;

    for (var line = 0; line < lines.length; line++) {
      if (N.test(lines[line])) {
        console.log(lines[line]);
      } else {
        console.log("Invalid register = ", lines[line]);
      }
    }
}

What I want is a way that a message can be shown to tell me that the file corresponded to all those requirements and if not that a message can be printed to tell me that the file is not valid, but keep showing me the message at the console. How can I possibly do that? Another question I have is if there is a way to specify that can be only one register called N1

HERE IS A FILE EXAMPLE

N108258594000135255240708     315370        BLABLA BLABLABL BLAB BLA
N2BLA2222016BLABLA BLABLABLA                                3525.250
N3BLABLABLABL.EXE                                   01BF011351A2B06D7A88048CBDDC53CE
N908234944000135255240708     000016

Body:
My understanding is that you are processing each line one by one and it is an error if there is more than one "register called N1", i.e. a line that passed the regex test and begins with N1. So you have to keep track of whether you have already seen such a line:

var reader = new FileReader();
var invalidRegister = false;
var seenN1 = false;
reader.onload = function(progressEvent) {
    // By lines
    var lines = this.result.split('\n');
    let N = /^(N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;

    for (var line = 0; line < lines.length; line++) {
      let s = lines[line];
      if (N.test(s)) {
        if (s.substr(0, 2) == 'N1') {
          if (seenN1) {
             console.log("Repeat N1 register = ", s);
             invalidRegister = true;
             continue;
          }
          seenN1 = true;
        }
        console.log(s);
      } else {
        console.log("Invalid register = ", s);
        invalidRegister = true;
      }
    }
    if (invalidRegister) {
      console.log('The file is not valid.');
    }
};


问:
ORA-00904: invalid identifier
I tried to write the following inner join query using an Oracle database:

```<code> SELECT Employee.EMPLID as EmpID,
        Employee.FIRST_NAME AS Name,
        Team.DEPARTMENT_CODE AS TeamID,
        Team.Department_Name AS teamname
 FROM PS_TBL_EMPLOYEE_DETAILS Employee
 INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team
 ON Team.DEPARTMENT_CODE = Employee.DEPTID
</code>```

That gives the below error:

```<code> INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team ON Team.DEPARTMENT_CODE = Employee.DEPTID
                                              *
ERROR at line 4:
ORA-00904: "TEAM"."DEPARTMENT_CODE": invalid identifier
</code>```

The DDL of one table is:

```<code>CREATE TABLE "HRMS"."PS_TBL_DEPARTMENT_DETAILS"
(
  "Company Code" VARCHAR2(255),
  "Company Name" VARCHAR2(255),
  "Sector_Code" VARCHAR2(255),
  "Sector_Name" VARCHAR2(255),
  "Business_Unit_Code" VARCHAR2(255),
  "Business_Unit_Name" VARCHAR2(255),
  "Department_Code" VARCHAR2(255),
  "Department_Name" VARCHAR2(255),
  "HR_ORG_ID" VARCHAR2(255),
  "HR_ORG_Name" VARCHAR2(255),
  "Cost_Center_Number" VARCHAR2(255),
  " " VARCHAR2(255)
)
SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS
</code>```

答: DEPARTMENT_CODE is not a column that exists in the table Team. Check the DDL of the table to find the proper column name.</p>

ContentLicense: CC BY-SA 3.0

Title: ORA-00904: invalid identifier

Body:
I tried to write the following inner join query using an Oracle database:

 SELECT Employee.EMPLID as EmpID,
        Employee.FIRST_NAME AS Name,
        Team.DEPARTMENT_CODE AS TeamID,
        Team.Department_Name AS teamname
 FROM PS_TBL_EMPLOYEE_DETAILS Employee
 INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team
 ON Team.DEPARTMENT_CODE = Employee.DEPTID

That gives the below error:

 INNER JOIN PS_TBL_DEPARTMENT_DETAILS Team ON Team.DEPARTMENT_CODE = Employee.DEPTID
                                              *
ERROR at line 4:
ORA-00904: "TEAM"."DEPARTMENT_CODE": invalid identifier

The DDL of one table is:

CREATE TABLE "HRMS"."PS_TBL_DEPARTMENT_DETAILS"
(
  "Company Code" VARCHAR2(255),
  "Company Name" VARCHAR2(255),
  "Sector_Code" VARCHAR2(255),
  "Sector_Name" VARCHAR2(255),
  "Business_Unit_Code" VARCHAR2(255),
  "Business_Unit_Name" VARCHAR2(255),
  "Department_Code" VARCHAR2(255),
  "Department_Name" VARCHAR2(255),
  "HR_ORG_ID" VARCHAR2(255),
  "HR_ORG_Name" VARCHAR2(255),
  "Cost_Center_Number" VARCHAR2(255),
  " " VARCHAR2(255)
)
SEGMENT CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS


问:
how to set initialRouteName dynamically in the react-native
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

```<code>import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);
</code>```

答:
Ok So in your navigation page create state and change its value accordingly AsyncStorage like

```<code>render() {
  const status = get AsyncStorage.getItem('unit');
  if(status != null)
  { setState({ name : 'Home'}) }
  else
  { setState({ name : 'anotherTab'}) }
}
</code>```

then pass that state to tabNavigation

```<code>initialRouteName: this.state.name,
</code>```

and this state , setState functions are classed based so you have to use useState instead to initial state on your page

Body:
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);

Body:
Ok So in your navigation page create state and change its value accordingly AsyncStorage like

render() {
  const status = get AsyncStorage.getItem('unit');
  if(status != null)
  { setState({ name : 'Home'}) }
  else
  { setState({ name : 'anotherTab'}) }
}

then pass that state to tabNavigation

initialRouteName: this.state.name,

and this state , setState functions are classed based so you have to use useState instead to initial state on your page


问:
How to make Android layout activity similar with instagrams image selection?
Am trying to create image selection activity layout similar with Instagram like below image.

But in my case when i add RelativeLayout >> GridView, the image_button and camera_button is will be pushed off the screen.

Please can anyone help how do I arrange the layout to give me expected result?

```<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:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white"
    tools:context=".imageEditClass"
    android:id="@+id/activity_image_edit_class">

        <FrameLayout
            android:id="@+id/top_frame"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.fenchtose.nocropper.CropperView
                android:background="#ff282828"
                android:id="@+id/croppingImagePreview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:nocropper__grid_opacity="0.8"
                app:nocropper__grid_thickness="0.8dp"
                app:nocropper__padding_color="@color/colorAccent"
                app:nocropper__grid_color="@color/colorAccent" />

            <ImageView
                android:id="@+id/snap_button"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_margin="16dp"
                android:padding="8dp"
                android:layout_gravity="start|bottom"
                android:background="@drawable/black_transp_circ_ripple"
                android:scaleType="center"
                android:src="@mipmap/ic_crop_free_white_24dp"
                android:contentDescription="Crop" />

            <ImageView
                android:id="@+id/rotate_button"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:padding="8dp"
                android:layout_margin="16dp"
                android:layout_gravity="end|bottom"
                android:background="@drawable/black_transp_circ_ripple"
                android:scaleType="center"
                android:src="@mipmap/ic_rotate_right_white_24dp"
                android:contentDescription="Rotate" />

        </FrameLayout>

    <GridLayout
        android:id="@+id/bottom_grid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="3"
        android:rowCount="3"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="211dp">

            <GridView
                android:id="@+id/galleryGridView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:columnWidth="280dp"
                android:gravity="center"
                android:horizontalSpacing="1dp"
                android:numColumns="4"
                android:padding="1dp"
                android:stretchMode="columnWidth"
                android:verticalSpacing="2dp">

            </GridView>

        </RelativeLayout>

            <Button
                android:layout_width="125dp"
                android:layout_height="wrap_content"
                android:text="@string/galleryText"
                android:background="@color/white"
                android:textColor="@color/colorPrimary"
                android:id="@+id/image_button"/>

            <Button
                android:layout_width="125dp"
                android:layout_height="wrap_content"
                android:text="@string/photoText"
                android:background="@color/white"
                android:textColor="@color/colorPrimary"
                android:id="@+id/camera_button"/>

            <Button
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:text="@string/saveText"
                android:background="@color/colorPrimary"
                android:layout_gravity="end|bottom"
                android:id="@+id/crop_save_button"/>

        </GridLayout>

    </RelativeLayout>
</code>```

答:
You've defined your GridLayout to have 3 rows and 3 columns. You then provide a RelativeLayout containing a GridView as the first cell (position 0/0). You then provide a Button for "Gallery" which will be occupy position 0/1. You then provide a Button for "Photo" which will occupy position 0/2. Your "Save" `Button' will now occupy the cell at row 1, column 0. This isn't what you want.

Why do you have the RelativeLayout containing the GridView inside the GridLayout? It seems that you only need the GridLayout to evenly space the buttons at the bottom.

An alternative would be to indicate that the RelativeLayout should occupy 3 columns within the GridLayout, which would position the 3 buttons in the 3 cells of row index 1. You can do this by providing the RelativeLayout a ColumnSpec that has columnSpan=3. This tells the GridLayout that the RelativeLayout wants to be 3 cells (ie: the entire width of the row) wide.

Body:
Am trying to create image selection activity layout similar with Instagram like below image.

But in my case when i add RelativeLayout >> GridView, the image_button and camera_button is will be pushed off the screen.

Please can anyone help how do I arrange the layout to give me expected result?

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white"
    tools:context=".imageEditClass"
    android:id="@+id/activity_image_edit_class">

        <FrameLayout
            android:id="@+id/top_frame"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.fenchtose.nocropper.CropperView
                android:background="#ff282828"
                android:id="@+id/croppingImagePreview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:nocropper__grid_opacity="0.8"
                app:nocropper__grid_thickness="0.8dp"
                app:nocropper__padding_color="@color/colorAccent"
                app:nocropper__grid_color="@color/colorAccent" />

            <ImageView
                android:id="@+id/snap_button"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_margin="16dp"
                android:padding="8dp"
                android:layout_gravity="start|bottom"
                android:background="@drawable/black_transp_circ_ripple"
                android:scaleType="center"
                android:src="@mipmap/ic_crop_free_white_24dp"
                android:contentDescription="Crop" />

            <ImageView
                android:id="@+id/rotate_button"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:padding="8dp"
                android:layout_margin="16dp"
                android:layout_gravity="end|bottom"
                android:background="@drawable/black_transp_circ_ripple"
                android:scaleType="center"
                android:src="@mipmap/ic_rotate_right_white_24dp"
                android:contentDescription="Rotate" />

        </FrameLayout>

    <GridLayout
        android:id="@+id/bottom_grid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="3"
        android:rowCount="3"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="211dp">

            <GridView
                android:id="@+id/galleryGridView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:columnWidth="280dp"
                android:gravity="center"
                android:horizontalSpacing="1dp"
                android:numColumns="4"
                android:padding="1dp"
                android:stretchMode="columnWidth"
                android:verticalSpacing="2dp">

            </GridView>

        </RelativeLayout>

            <Button
                android:layout_width="125dp"
                android:layout_height="wrap_content"
                android:text="@string/galleryText"
                android:background="@color/white"
                android:textColor="@color/colorPrimary"
                android:id="@+id/image_button"/>

            <Button
                android:layout_width="125dp"
                android:layout_height="wrap_content"
                android:text="@string/photoText"
                android:background="@color/white"
                android:textColor="@color/colorPrimary"
                android:id="@+id/camera_button"/>

            <Button
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:text="@string/saveText"
                android:background="@color/colorPrimary"
                android:layout_gravity="end|bottom"
                android:id="@+id/crop_save_button"/>

        </GridLayout>

    </RelativeLayout>


问:
Exclude values "starting with" from column in WPF DataGrid
I have DataGrid to display table from Database. I am also collecting properties for filter.

Here is my code:

```<code>private Dictionary<string, string> _conditions = new Dictionary<string, string>();

private void UpdateFilter()
{
    var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
    DataView dv = DataGrid1.ItemsSource as DataView;
    dv.RowFilter = string.Join(" AND ", activeConditions);
}

private void NameSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = NameSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["name"] = null;
    else
        _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
    UpdateFilter();
}

private void CustomerNumberSearch_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = CustomerNumberSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["nro"] = null;
    else
        _conditions["nro"] = string.Format("NRO Like '%{0}'", filter); //this should be "Begins with" not "Like"
    UpdateFilter();
}

private void ActiveCustomer_Click_1(object sender, RoutedEventArgs e)
{
    if (ActiveCustomer.IsChecked == true)
    {
        _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", "1");
        UpdateFilter();
    }
    else
    {
        _conditions["active"] = null;
        UpdateFilter();
    }
}
</code>```

How, instead of one parameter in textbox "NRO Like '%{0}'", filter:

```<code>private void CustomerNumberSearch_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = CustomerNumberSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["nro"] = null;
    else
        _conditions["nro"] = string.Format("NRO Like '%{0}'", filter); //this should be "Begins with" not "Like"
    UpdateFilter();
}
</code>```

I can exclude everything except numbers starting with 2 and 3?

In Column NRO I have like:

```<code>1575
8589445
5465858
3545664
3545688
2894489
2686886
3898984
8978556
6548898
</code>```

I can make a checkbox but what would be the filter criteria to leave only?:

```<code>3545664
3545688
2894489
2686886
3898984
</code>```

答:
If somebody wondering the same. Here is solution I have used in my case:</p>

```<code>   private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        if (CheckBox1.IsChecked == true)
        {
            _conditions["criteria1"] = string.Format("NRO Like '2%' OR NRO Like '3%'");
            UpdateFilter();
        }
        else
        {
            _conditions["criteria1"] = null;
            UpdateFilter();
        }
    }
</code>```

Body:
I have DataGrid to display table from Database. I am also collecting properties for filter.

Here is my code:

private Dictionary<string, string> _conditions = new Dictionary<string, string>();

private void UpdateFilter()
{
    var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
    DataView dv = DataGrid1.ItemsSource as DataView;
    dv.RowFilter = string.Join(" AND ", activeConditions);
}

private void NameSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = NameSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["name"] = null;
    else
        _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
    UpdateFilter();
}

private void CustomerNumberSearch_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = CustomerNumberSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["nro"] = null;
    else
        _conditions["nro"] = string.Format("NRO Like '%{0}'", filter); //this should be "Begins with" not "Like"
    UpdateFilter();
}

private void ActiveCustomer_Click_1(object sender, RoutedEventArgs e)
{
    if (ActiveCustomer.IsChecked == true)
    {
        _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", "1");
        UpdateFilter();
    }
    else
    {
        _conditions["active"] = null;
        UpdateFilter();
    }
}

How, instead of one parameter in textbox "NRO Like '%{0}'", filter:

private void CustomerNumberSearch_TextChanged_1(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    string filter = CustomerNumberSearch.Text;
    if (string.IsNullOrEmpty(filter))
        _conditions["nro"] = null;
    else
        _conditions["nro"] = string.Format("NRO Like '%{0}'", filter); //this should be "Begins with" not "Like"
    UpdateFilter();
}

I can exclude everything except numbers starting with 2 and 3?

In Column NRO I have like:

1575
8589445
5465858
3545664
3545688
2894489
2686886
3898984
8978556
6548898

I can make a checkbox but what would be the filter criteria to leave only?:

3545664
3545688
2894489
2686886
3898984

Body:
If somebody wondering the same. Here is solution I have used in my case:

   private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        if (CheckBox1.IsChecked == true)
        {
            _conditions["criteria1"] = string.Format("NRO Like '2%' OR NRO Like '3%'");
            UpdateFilter();
        }
        else
        {
            _conditions["criteria1"] = null;
            UpdateFilter();
        }
    }


问:
Multiple click on submit button it's submit same form multiple time in Codeigniter
I was work in one codeigniter project, this project have large amount of data, i have one issue in data insert time click multiple time submit button it insert same data multiple time in database.

how it can possible ..?

答:
Your best bet is to do this server-side.

Once the method in your controller or the script has been called, set a session variable stating that the form has been submitted.

For example,

```<code><?php
session_start();
if (!isset($_SESSION['formclicked'])) {
$_SESSION['formclicked'] = true;
//now process form

}

?>
</code>```

This so the attacker won't be able to bypass client-side validation

Body:
Your best bet is to do this server-side.

Once the method in your controller or the script has been called, set a session variable stating that the form has been submitted.

For example,

<?php
session_start();
if (!isset($_SESSION['formclicked'])) {
$_SESSION['formclicked'] = true;
//now process form

}

?>

This so the attacker won't be able to bypass client-side validation


问:
Pandas get value out of list and create new list
I have a list with filmgenres and a id, also I have a second list just with the id. I now try to use the first list to get only the genres in a list. The problem should be easy, but I couldn't find the solution.

The list with the filmgenres is loaded via an csv file. It looks like:

```<code>   Unnamed: 0     id                name
0            0     28              Action
1            1     12           Adventure
2            2     16           Animation
3            3     35              Comedy
4            4     80               Crime
5            5     99         Documentary
6            6     18               Drama
7            7  10751              Family
8            8     14             Fantasy
9            9     36             History
10          10     27              Horror
</code>```

The second list is like:

```<code> filmgenre = [28, 16, 14, 99]
</code>```

My code so far:

```<code>filmgenreslist = pd.read_csv("genrelist.csv") #load csv
cleanfilmlist = filmgenreslist.loc[:,"name"] #tried to reduce the list to necessary informations
filmgenre = [28, 16, 14, 878]
filmgenrenames = [] #tried to save the genres for later
number = 0 #just to test
test = cleanfilmlist.loc[filmgenreslist["id"] == filmgenre[number]] #try to extract only the genrename
print(test)
#print(test[-1])
#to loop through the data, multiple tries but can't solve
for number in range(5):
    try:
        #filmgenrenames.append([cleanfilmlist["name"].where(cleanfilmlist["id"] == filmgenre[number])])
        filmgenrenames.append([cleanfilmlist.loc(cleanfilmlist["id"] == filmgenre[number])])
        #filmgenrenames.append([cleanfilmlist.loc[filmgenreslist["id"] == filmgenre[number]]])
        #print(number, filmgenrenames)
    except:
        filmgenrenames.append(["missing"])

print(filmgenrenames)
</code>```

I tired to get a output like:

```<code>filmgenresname =["Action","Animation","Fantasy","Documentary","missing"]
</code>```

答:
You can make dictionary for id as key and name as value and then map it with list:</p>

```<code>map_id_name = dict(zip(filmgenreslist['id'], filmgenreslist['name']))
list(map(lambda x:map_id_name.get(x, "missing"), filmgenre ))
</code>```

Body:
I have a list with filmgenres and a id, also I have a second list just with the id. I now try to use the first list to get only the genres in a list. The problem should be easy, but I couldn't find the solution.

The list with the filmgenres is loaded via an csv file. It looks like:

   Unnamed: 0     id                name
0            0     28              Action
1            1     12           Adventure
2            2     16           Animation
3            3     35              Comedy
4            4     80               Crime
5            5     99         Documentary
6            6     18               Drama
7            7  10751              Family
8            8     14             Fantasy
9            9     36             History
10          10     27              Horror

The second list is like:

 filmgenre = [28, 16, 14, 99]

My code so far:

filmgenreslist = pd.read_csv("genrelist.csv") #load csv
cleanfilmlist = filmgenreslist.loc[:,"name"] #tried to reduce the list to necessary informations
filmgenre = [28, 16, 14, 878]
filmgenrenames = [] #tried to save the genres for later
number = 0 #just to test
test = cleanfilmlist.loc[filmgenreslist["id"] == filmgenre[number]] #try to extract only the genrename
print(test)
#print(test[-1])
#to loop through the data, multiple tries but can't solve
for number in range(5):
    try:
        #filmgenrenames.append([cleanfilmlist["name"].where(cleanfilmlist["id"] == filmgenre[number])])
        filmgenrenames.append([cleanfilmlist.loc(cleanfilmlist["id"] == filmgenre[number])])
        #filmgenrenames.append([cleanfilmlist.loc[filmgenreslist["id"] == filmgenre[number]]])
        #print(number, filmgenrenames)
    except:
        filmgenrenames.append(["missing"])

print(filmgenrenames)

I tired to get a output like:

filmgenresname =["Action","Animation","Fantasy","Documentary","missing"]

Body:
You can make dictionary for id as key and name as value and then map it with list:

map_id_name = dict(zip(filmgenreslist['id'], filmgenreslist['name']))
list(map(lambda x:map_id_name.get(x, "missing"), filmgenre ))


问:
my express api works in postman but not when calling from react.It gives "TypeError: NetworkError when attempting to fetch resource."
I am creating url shortner using react and nodejs. user inputs url in react and then press submit to triggerpost request. It works fine with postman but doesn't when calling from react. I tried calling post request on different url, it works but it doesn't with work with express url
This is react front end part which calls post after submitting url

```<code>handleSubmit = async (e) => {
    e.preventDefault();
    const url = {
      originalUrl: this.state.originalUrl
    }

    const item = await fetch("http://localhost:5000/api/post", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(url)
    })
    console.log("item",item)
  }
</code>```

This is express part which works fine with postman

```<code>router.post('/post', async (req,res) => {
    const originalUrl = req.body.originalUrl;

    const urlCode = random()

    var newInput = new model({
        originalUrl,
        urlCode
    })

    var item = await newInput.save()

    return res.json({
        originalUrl:originalUrl,
        urlCode:urlCode,

    })
</code>```

答:
This is probably related to Cross-Origin Resource Sharing (CORS).

The Cross-Origin Resource Sharing (CORS) mechanism gives web servers
  cross-domain access controls, which enable secure cross-domain data
  transfers. Modern browsers use CORS in an API container - such as
  XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP
  requests. (Source:
  https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

There are different ways to handle this, and one simple way is you need to install chrome extension Moesif Orign & CORS Changer
and the other way you check your installed extension by disabling one by one from chrome://extensions/ and then check one by one which extension is making this issue.

Body:
I am creating url shortner using react and nodejs. user inputs url in react and then press submit to triggerpost request. It works fine with postman but doesn't when calling from react. I tried calling post request on different url, it works but it doesn't with work with express url
This is react front end part which calls post after submitting url

handleSubmit = async (e) => {
    e.preventDefault();
    const url = {
      originalUrl: this.state.originalUrl
    }

    const item = await fetch("http://localhost:5000/api/post", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(url)
    })
    console.log("item",item)
  }

This is express part which works fine with postman

router.post('/post', async (req,res) => {
    const originalUrl = req.body.originalUrl;

    const urlCode = random()

    var newInput = new model({
        originalUrl,
        urlCode
    })

    var item = await newInput.save()

    return res.json({
        originalUrl:originalUrl,
        urlCode:urlCode,

    })


问:
Angular Form nested objects
I have a form where the user enters some data, then sends a POST. Now I am working on a feature to allow editing of previously entered information. Some of the inputs in the fields have nested objects, as:

```<code>export class Transfer {
    constructor(
        public id: number,
        public destination: string,
        public market: string,
        public project: Project,
        public workstream: Workstream,
        public contact: Contact
    )
}
</code>```

```<code>export class Workstream {
    constructor(
        public id: number,
        public workStream: string
    ) { }
}
</code>```

```<code>export class Contact {
    constructor(
        public id: number,
        public name: string
    ) { }
}
</code>```

When loading the information to the form, fields containing strings or numbers work well, but objects don't show the correct information. The field for Contact gives me a [object Object], while Workstream does not preselect the right option from a drop down.

```<code>            <!-- Workstream -->
            <mat-form-field class="example-full-width">
                <mat-label>Workstream</mat-label>
                <mat-select [(ngModel)]="transfer.workstream" name="workstream" [(value)]="transfer.workstream">
                    <mat-option *ngFor="let workstream of workstreams$ | async" [value]="workstream">
                        {{workstream.workStream}}
                    </mat-option>
                </mat-select>
            </mat-form-field>

            <!-- Contact -->
            <mat-form-field class="example-full-width">
            <input matInput placeholder="Contact" [(ngModel)]="transfer.contact" name="contact" value="transfer.contact.name"
                #contactSearchBox (input)="searchContact(contactSearchBox.value)" [matAutocomplete]="auto">
            </mat-form-field>

            <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let contact of contacts$ | async" [value]="contact.name"
                    (click)="selectContact(contact)">
                    {{contact.name}}
                </mat-option>
            </mat-autocomplete>
</code>```

In the contact field the user is able to search by name, which works.
Any clues on how to implement this? Thanks!

答:
Fixed both issues, thanks to Badis Merabet and Angular Material.

To fix my drop down, I added [compareWith]="compareObjects" to mat-select, and used the same function described in the link.

My search bar was fixed by adding [displayWith]="displayFn" to mat-autocomplete, using the same technique as done in Angular Material.

Title: Angular Form nested objects

Body:
I have a form where the user enters some data, then sends a POST. Now I am working on a feature to allow editing of previously entered information. Some of the inputs in the fields have nested objects, as:

export class Transfer {
    constructor(
        public id: number,
        public destination: string,
        public market: string,
        public project: Project,
        public workstream: Workstream,
        public contact: Contact
    )
}

export class Workstream {
    constructor(
        public id: number,
        public workStream: string
    ) { }
}

export class Contact {
    constructor(
        public id: number,
        public name: string
    ) { }
}

When loading the information to the form, fields containing strings or numbers work well, but objects don't show the correct information. The field for Contact gives me a [object Object], while Workstream does not preselect the right option from a drop down.

            <mat-form-field class="example-full-width">
                <mat-label>Workstream</mat-label>
                <mat-select [(ngModel)]="transfer.workstream" name="workstream" [(value)]="transfer.workstream">
                    <mat-option *ngFor="let workstream of workstreams$ | async" [value]="workstream">
                        {{workstream.workStream}}
                    </mat-option>
                </mat-select>
            </mat-form-field>

            <mat-form-field class="example-full-width">
            <input matInput placeholder="Contact" [(ngModel)]="transfer.contact" name="contact" value="transfer.contact.name"
                #contactSearchBox (input)="searchContact(contactSearchBox.value)" [matAutocomplete]="auto">
            </mat-form-field>

            <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let contact of contacts$ | async" [value]="contact.name"
                    (click)="selectContact(contact)">
                    {{contact.name}}
                </mat-option>
            </mat-autocomplete>

In the contact field the user is able to search by name, which works.
Any clues on how to implement this? Thanks!


问:
What is the swift way of converting this string into PGN notation?
I have the following string

```<code>let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
</code>```

and want to convert this to PGN notation so the final result should be

```<code>result = "r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/"
</code>```

The PGN notation converts the zeros to counts found.  Normally in python, I would just use

import chess.pgn

Before deep diving into python library, is there is a succinct and 'Swift' way to do this?

答:
There is no direct function for that but I just created a program for fun. You can check this out:- </p>

```<code>let str = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
   var newStr = ""
   var flag = 0

    // Do any additional setup after loading the view.

    for char in str {
        if flag == 0 {
            if char == "0" {
                flag += 1
            }
            else {
                newStr.append(char)
            }
        }
        else {
            if char == "0" {
                flag += 1
            }
            else {
                newStr.append("\(flag)")
                flag = 0
                if char == "0" {
                    flag += 1
                }
                else {
                    newStr.append(char)
                }
            }
        }
    }
    print(newStr)
</code>```

Body:
I have the following string

let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"

and want to convert this to PGN notation so the final result should be

result = "r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/"

The PGN notation converts the zeros to counts found.  Normally in python, I would just use

import chess.pgn

Before deep diving into python library, is there is a succinct and 'Swift' way to do this?

Body:
There is no direct function for that but I just created a program for fun. You can check this out:-

let str = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
   var newStr = ""
   var flag = 0

    // Do any additional setup after loading the view.

    for char in str {
        if flag == 0 {
            if char == "0" {
                flag += 1
            }
            else {
                newStr.append(char)
            }
        }
        else {
            if char == "0" {
                flag += 1
            }
            else {
                newStr.append("\(flag)")
                flag = 0
                if char == "0" {
                    flag += 1
                }
                else {
                    newStr.append(char)
                }
            }
        }
    }
    print(newStr)


问:
How is this javascript object destructuring working?
I am trying to understand this React redux example on : https://codesandbox.io/s/f2ded

In reducer.js, the initial state is :

```<code>const initialState = {
  taskName: "",
  tasks: []
};
</code>```

In App.js, we have :

```<code>const mapStateToProps = state => {
  return {
    ...state.list
  };
};
</code>```

The state does not have a property list and it state.list should be an empty object {}. But, it actually holds

Appreciate any help in understanding how exactly this works. Thank you.

答:
It's because of the combineReducers at the bottom

```<code>const reds = combineReducers({ list });

export default reds;
</code>```

That means that everything in that part of the Redux state is state.list.taskName or state.list.tasks etc.

[edit] just wanted to add some clarity from the official docs, https://redux.js.org/api/combinereducers/

```<code>rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
  potato: {
    // ... potatoes, and other state managed by the potatoReducer ...
  },
  tomato: {
    // ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
  }
}
</code>```

Body:
I am trying to understand this React redux example on : https://codesandbox.io/s/f2ded

In reducer.js, the initial state is :

const initialState = {
  taskName: "",
  tasks: []
};

In App.js, we have :

const mapStateToProps = state => {
  return {
    ...state.list
  };
};

The state does not have a property list and it state.list should be an empty object {}. But, it actually holds

Appreciate any help in understanding how exactly this works. Thank you.

Body:
It's because of the combineReducers at the bottom

const reds = combineReducers({ list });

export default reds;

That means that everything in that part of the Redux state is state.list.taskName or state.list.tasks etc.

[edit] just wanted to add some clarity from the official docs, https://redux.js.org/api/combinereducers/

rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
  potato: {
    // ... potatoes, and other state managed by the potatoReducer ...
  },
  tomato: {
    // ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
  }
}


问:
Is there a way to target an element that gets added dynamically to the page in React?
I'm trying to hack a solution to an iframe that gets added dynamically to my page in order to change its CSS. I have the iframe's id. Is there a way of doing this with React?

Edit: I'm using React. I don't have access to the source code of the iframe (an embedded checkout as part of an online shop) so can only make changes to its CSS once it's been dynamically added to the page.

答:
I think you can use React refs
https://reactjs.org/docs/refs-and-the-dom.html</p>


问:
Maximum Size List in Java
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

```<code>public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}
</code>```

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

答:
If you extend the LinkedList class you will have direct access to all it's methods. Instead of having to write stuff like

```<code>fixedList.getList().pop()
</code>```

you could just write

```<code>fixedList.pop()
</code>```

You could then override the methods where you need to add the maxSize criteria.

Title: Maximum Size List in Java

Body:
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

Body:
If you extend the LinkedList class you will have direct access to all it's methods. Instead of having to write stuff like

fixedList.getList().pop()

you could just write

fixedList.pop()

You could then override the methods where you need to add the maxSize criteria.


问:
Start and Stop a flask app multiple times within a process using gevents Wsgi server
I have a flask app which I need to start and then shut down within the same process and repeat this multiple times. I am using gevents in my application so I'm using gevents.pywsgi as my WSGI server. Now I'm trying to gracefully shutdown the server so I can restart it in the same process after I do a few other things.

So the following code creates a basic flask app, which when receives a POST request with any valid data on /hit endpoint populates the data field. A greenlet is running in parallel with this app and when it sees that the data field is populated, it shuts down the server.

```<code>    def func():
    global data
    data = None

    app = Flask(__name__)

    @app.route('/hit', methods=['POST'])
    def hit():
        global data
        data = request.json

        if data is not None:
            return "Input Recieved, Server closed "
        else:
            return "Invalid Input, Try again"

    def shutdown_server(_server):
        global data
        while data is None:
            sleep(0.5)
        _server.stop()
        _server.close()

    server = WSGIServer(('0.0.0.0',5100), app)

    start = spawn(server.start)
    stop = spawn(shutdown_server, request, server)

    joinall([start, stop])

    return True
</code>```

Now this code is running fine if I run the server once, but if I try to run the server again within the same process it throws the following error:

```<code>Traceback (most recent call last):
  File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
  File "/home/batman/Documents/genisys/lib/python3.6/site-packages/gevent/baseserver.py", line 308, in start
    self.start_accepting()
  File "/home/batman/Documents/genisys/lib/python3.6/site-packages/gevent/baseserver.py", line 160, in start_accepting
    self._watcher = self.loop.io(self.socket.fileno(), 1)
AttributeError: 'WSGIServer' object has no attribute 'socket'
</code>```

I'm not sure if this is even possible, or if I have to run the server in a separate process if I want to run it multiple times. Can anybody tell me why I'm facing this error and is there a better and cleaner way to shutdown the server so I don't face this error?

EDIT : I give IP and port as arguments to func, so I have tried call func with a different port multiple times and with the same port multiple times, I still get the same error.

答: I think problem is you already running the server on port 5100 so again you can't run process on same port , so you have to dynamically change the port numbers when you want start the process </p>

Body:
I have a flask app which I need to start and then shut down within the same process and repeat this multiple times. I am using gevents in my application so I'm using gevents.pywsgi as my WSGI server. Now I'm trying to gracefully shutdown the server so I can restart it in the same process after I do a few other things.

So the following code creates a basic flask app, which when receives a POST request with any valid data on /hit endpoint populates the data field. A greenlet is running in parallel with this app and when it sees that the data field is populated, it shuts down the server.

    def func():
    global data
    data = None

    app = Flask(__name__)

    @app.route('/hit', methods=['POST'])
    def hit():
        global data
        data = request.json

        if data is not None:
            return "Input Recieved, Server closed "
        else:
            return "Invalid Input, Try again"

    def shutdown_server(_server):
        global data
        while data is None:
            sleep(0.5)
        _server.stop()
        _server.close()

    server = WSGIServer(('0.0.0.0',5100), app)

    start = spawn(server.start)
    stop = spawn(shutdown_server, request, server)

    joinall([start, stop])

    return True

Now this code is running fine if I run the server once, but if I try to run the server again within the same process it throws the following error:

Traceback (most recent call last):
  File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
  File "/home/batman/Documents/genisys/lib/python3.6/site-packages/gevent/baseserver.py", line 308, in start
    self.start_accepting()
  File "/home/batman/Documents/genisys/lib/python3.6/site-packages/gevent/baseserver.py", line 160, in start_accepting
    self._watcher = self.loop.io(self.socket.fileno(), 1)
AttributeError: 'WSGIServer' object has no attribute 'socket'

I'm not sure if this is even possible, or if I have to run the server in a separate process if I want to run it multiple times. Can anybody tell me why I'm facing this error and is there a better and cleaner way to shutdown the server so I don't face this error?

EDIT : I give IP and port as arguments to func, so I have tried call func with a different port multiple times and with the same port multiple times, I still get the same error.


问:
Bootstrap 4 carousel-fade animation not working properly
So I was working on my web project where I used form over carousel using css. It's working perfectly with sliding animation but when I am adding class carousel-fade the form at the center is also fading with the carousel but I want to prevent that. Here, In example instead of that big form I used a simple
 tag for demonstration. How can I solve this issue ?

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

I am at center

```

答: Remove this class 'carousel-fade' from first div and if you want to add any extra class then used your own class name instead of default carousel class name.</p>


问:
get particular value by key from Hashmap in velocity template
i have a java code like below

```<code>  public static void main(String args[]) throws Exception {
    VelocityEngine engine = new VelocityEngine();
    engine.init();

    Template template = engine.getTemplate("userinfo.vm");

    VelocityContext vc = new VelocityContext();

    Map<String, Object> jsonResponse = new HashMap<String, Object>();

    jsonResponse.put("44", "United Kingdom");
    jsonResponse.put("33", "France");
    jsonResponse.put("49", null);

    vc.put("userList", jsonResponse);
    StringWriter writer = new StringWriter();
    template.merge(vc, writer);

    System.out.println(writer);
}
</code>```

in .vm file

```<code>#foreach ($mapEntry in $userList.entrySet())
$!{mapEntry.get("44")}
#end
</code>```

Here i am trying to get particular value using above code, but its not giving expected output

My expected output is

```<code> United Kingdom
</code>```

答:
Per https://velocity.apache.org/engine/1.7/user-guide.html#set:

You could access the first element above using
  $monkey.Map.get("banana") to return a String 'good', or even
  $monkey.Map.banana to return the same value.

Per https://velocity.apache.org/engine/1.7/user-guide.html#index-notation

$foo["bar"]   ## Passing a string where $foo may be a Map

Body:
i have a java code like below

  public static void main(String args[]) throws Exception {
    VelocityEngine engine = new VelocityEngine();
    engine.init();

    Template template = engine.getTemplate("userinfo.vm");

    VelocityContext vc = new VelocityContext();

    Map<String, Object> jsonResponse = new HashMap<String, Object>();

    jsonResponse.put("44", "United Kingdom");
    jsonResponse.put("33", "France");
    jsonResponse.put("49", null);

    vc.put("userList", jsonResponse);
    StringWriter writer = new StringWriter();
    template.merge(vc, writer);

    System.out.println(writer);
}

in .vm file

#foreach ($mapEntry in $userList.entrySet())
$!{mapEntry.get("44")}
#end

Here i am trying to get particular value using above code, but its not giving expected output

My expected output is

 United Kingdom


问:
2 iOS app with different with bundle identifier in 1 onesignal app
We are working on the On-demand Photography app.
So basically we have.
2 android apps (user and photographer)
2 iOS apps (user and photographer)

android push configured with firebase and firebase allows us to configure 2 android apps against one firebase key. So multiple android apps are working on 1 one signal app id.

but iOS side doest not allow us to do so, we need to configure 2 iOS apps with 1 one signal app id.

How we can make this possible?

答:
Unfortunately this is not possible. You would need to create an OneSignal app for each of these two apps. A single OneSignal App can include 1 of each platform (Website, Android App, iOS App, Email, etc.).

Refer this, https://documentation.onesignal.com/docs/dashboard


问:
Calculate coordinates of a point after zooming in JavaScript
I have a requirement to make some annotations on an image. This image is scalable (can be zoomed in and out). Now the challenge is that the annotations should also move with the scaling. How can I achieve this? I understand that 'direction' of zooming depends on the point considered as 'centre' when zooming, so assuming that this 'centre' is the absolute centre of the iamge container (width/2, height/2), how do I get the coordinates of the same point on image after zooming?

As an example, consider the following two images:

Image-1 (Normal scale):

Image-2 (Zoomed-in):

If I know the coordinates of the red point in Image-1 (which is at normal scale), how do I get the coordinates (x,y) of the same red point in Image-2? Note that the image container's width and height will remain same throughout the zooming process.

答:
First, you'd want to determine the coordinates of the annotation with respect to the center of the image.

So for example on an image of 200 x 100, the point (120,60) with the origin in the left top corner would be (20,-10) when you take the center of the image as your origin.

If you scale the image 150%, your new coordinates would be those coordinates multiplied by 1,5 (=150%).
In our example that would be 30, -15.

Than you can calculate that back to absolute values, with the original point of origin


问:
Convert an array which contains strings into key value pairs
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

```<code>let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);
</code>```

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}

答:
Actually, I figured a better which gives out a Map with exact key-value pairs. All I need is to pass a Map and My array to it and it spits out the map with the key-values.</p>

```<code>const myString = '101-2000-10-102-2000-15';
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
const compartmentMap = (someMap, someArray) => (someArray.map(x => { console.log(x)
const [a, b, c] = x.split("-");
someMap.set(a, {b,c});
}));
const x = new Map();
compartmentMap(x, strArray);
console.log(x);
</code>```

Body:
I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:

let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);

My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}

Body:
Actually, I figured a better which gives out a Map with exact key-value pairs. All I need is to pass a Map and My array to it and it spits out the map with the key-values.

const myString = '101-2000-10-102-2000-15';
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
const compartmentMap = (someMap, someArray) => (someArray.map(x => { console.log(x)
const [a, b, c] = x.split("-");
someMap.set(a, {b,c});
}));
const x = new Map();
compartmentMap(x, strArray);
console.log(x);


问:
which is a better approach for fibonacci series generation
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

```<code>#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}
</code>```

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

答:
I'm not sure what this function is really supposed to do.  It
only works in the exact loop you present, and as others have
pointed out, it only works once.  (And there's probably a typo
in your loop, since your complete program outputs "0", and
nothing else.)  What advantage does it offer over:

```<code>int y = 0;
int x = 1;
for ( int i = 0; i < count; ++ i ) {
    std::cout << y <<std::endl;
    y = x + y;
    x = y - x;
}
</code>```

? It's more complex, far less robust, and far less useful.

Body:
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

Body:
I'm not sure what this function is really supposed to do.  It
only works in the exact loop you present, and as others have
pointed out, it only works once.  (And there's probably a typo
in your loop, since your complete program outputs "0", and
nothing else.)  What advantage does it offer over:

int y = 0;
int x = 1;
for ( int i = 0; i < count; ++ i ) {
    std::cout << y <<std::endl;
    y = x + y;
    x = y - x;
}

? It's more complex, far less robust, and far less useful.


问:
weak_ptr, shared_ptr in lambda capture list and std::queue<T,Container>::emplace
I have a function which enqueue lambda using std::queue's build-in emplace. I created shared_ptr object (task), which later I would capture in lambda.

```<code>    template<typename Func, typename... Args>
    auto submit(Func&& f, Args&&... args)
    {
        using result_type = std::result_of_t<Func(Args...)>;
        using pckg_task_type = std::packaged_task<result_type()>;

        auto task = std::make_shared< pckg_task_type >(
                    std::bind(std::forward<Func>(f), std::forward<Args>(args)...) );
        ...
    }
</code>```

This is the part which is creating confusion:

Case 1: Which works perfectly

```<code>            tasks.emplace(
                [task](){
                    auto wptr = std::weak_ptr<pckg_task_type>(task);
                    if( auto p = wptr.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );
</code>```

Case 2: Which immediately throws an exception

```<code>                tasks.emplace(
                [wc = std::weak_ptr<pckg_task_type>(task)](){
                    if( auto p = wc.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );
</code>```

With tasks defined as

```<code>std::queue< std::function<void()> > tasks;
</code>```

Calling lambda from case 2 without emplace it into queue doesn't throw exception.

Can anyone explain the difference between cases above? Where is the problem?

答:
Your first case copies the shared pointer into the lambda and will therefore keep it alive for the lifetime of the lambda, the weak pointer inside the lambda is pointless as you create a weak pointer then immediately lock it which will never fail.

The second case is only capturing a weak pointer, the shared pointer goes out of scope at the end of submit and presumably there are no other references to it so the pointer is deleted. This would only work if your lambda starts executing and locks the pointer before the end of submit.

Body:
I have a function which enqueue lambda using std::queue's build-in emplace. I created shared_ptr object (task), which later I would capture in lambda.

    template<typename Func, typename... Args>
    auto submit(Func&& f, Args&&... args)
    {
        using result_type = std::result_of_t<Func(Args...)>;
        using pckg_task_type = std::packaged_task<result_type()>;

        auto task = std::make_shared< pckg_task_type >(
                    std::bind(std::forward<Func>(f), std::forward<Args>(args)...) );
        ...
    }

This is the part which is creating confusion:

Case 1: Which works perfectly

            tasks.emplace(
                [task](){
                    auto wptr = std::weak_ptr<pckg_task_type>(task);
                    if( auto p = wptr.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );

Case 2: Which immediately throws an exception

                tasks.emplace(
                [wc = std::weak_ptr<pckg_task_type>(task)](){
                    if( auto p = wc.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );

With tasks defined as

std::queue< std::function<void()> > tasks;

Calling lambda from case 2 without emplace it into queue doesn't throw exception.

Can anyone explain the difference between cases above? Where is the problem?


问:
Java default constructor
What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?</p>

```<code>public Module() {
   this.name = "";
   this.credits = 0;
   this.hours = 0;
}

public Module(String name, int credits, int hours) {
   this.name = name;
   this.credits = credits;
   this.hours = hours;
}
</code>```

答:
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.

Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.

Title: Java default constructor

Body:
What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?

public Module() {
   this.name = "";
   this.credits = 0;
   this.hours = 0;
}

public Module(String name, int credits, int hours) {
   this.name = name;
   this.credits = credits;
   this.hours = hours;
}


问:
Calculating average of list from certain point in list?
I have a question, I know that it is possible to calculate the average of a list but is it possible to calculate average but from a certain point?

For example:

```<code>def Average(lst):
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst)
</code>```

Printing average of the list:

```<code>print("Average of the list =", round(average, 2))
</code>```

Output:
    Average of the list = 4.14

Say we want to keep the first 3 values and average the rest to have only 4 values in the list

So my new list is:

```<code>list = [2, 8, 6, 7, 3, 2, 1]
new_list = [2, 8, 6, 12.25]
</code>```

Edit 1

Thank you all for your answers. I have another question, say, I don't know the length of my list and I just want 4 elements in my new list. How could I tackle this?

答:
if you want to calculate a list elements average for a specific region from the list and create a new list with the rest of elements and the specific region average you can use:

```<code>import statistics

l = [2, 8, 6, 7, 3, 2, 1]

start = 3
end = 5

new_list = [*l[:start], statistics.mean(l[start: end]), *l[end:]]
new_list
</code>```

output:

```<code>[2, 8, 6, 5, 2, 1]
</code>```

Body:
I have a question, I know that it is possible to calculate the average of a list but is it possible to calculate average but from a certain point?

For example:

def Average(lst):
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst)

Printing average of the list:

print("Average of the list =", round(average, 2))

Output:
    Average of the list = 4.14

Say we want to keep the first 3 values and average the rest to have only 4 values in the list

So my new list is:

list = [2, 8, 6, 7, 3, 2, 1]
new_list = [2, 8, 6, 12.25]

Edit 1

Thank you all for your answers. I have another question, say, I don't know the length of my list and I just want 4 elements in my new list. How could I tackle this?

Body:
if you want to calculate a list elements average for a specific region from the list and create a new list with the rest of elements and the specific region average you can use:

import statistics

l = [2, 8, 6, 7, 3, 2, 1]

start = 3
end = 5

new_list = [*l[:start], statistics.mean(l[start: end]), *l[end:]]
new_list

output:

[2, 8, 6, 5, 2, 1]


问:
C++ runtime type switching with multiple enums
This is a magic switch problem, the solution was described here. However, I was wondering if it was possible to make it 3-dimensional, i.e. let it switch based on three given enums. In the ideal case, n-dimensional would be preferred of course. I tried first to make it 2-dimensional as shown below, but I run into double variadic unpacking, and I cannot find out how that would work.

template<class Enum, class Enum2, template<Enum, Enum2>class Z>
struct magic_switch {
  // return value of a call to magic_switch(Args...)
  template<class...Args>
  using R = std::result_of_t<Z<Enum(0), Enum2(0)>(Args...)>;
  // A function pointer for a jump table:
  template<class...Args>
  using F = R<Args...>(*)(Args&&...);
  // Produces a single function pointer for index I and args Args...
  template<size_t I, size_t I2, class...Args>
  F<Args...> f() const {
    using ret = R<Args...>;
    return +[](Args&&...args)->ret{
      using Invoke=Z<Enum(I), Enum(I2)>;
      return Invoke{}(std::forward<Args>(args)...);
    };
  }
  // builds a jump table:
  template<class...Args, size_t...Is, size_t ...Is2>
  std::array<F<Args...>,size_t(Enum::COUNT)>
  table( std::index_sequence<Is...>, std::index_sequence<Is2...> ) const {
    return {{
      f<Is, Is2, Args...>()... ... // << -- 2d expansion not working
    }};
  }
  template<class...Args>
  R<Args...> operator()(Enum n, Enum2 n2, Args&&...args) {
    // a static jump table for this case of Args...:
    static auto jump=table<Args...>(std::make_index_sequence<size_t(Enum::COUNT)>{}, std::make_index_sequence<size_t(Enum2::COUNT)>{});
    // Look up the nth entry in the jump table, and invoke it:
    return jump[size_t(n) + size_t(Enum::COUNT) * size_t(n2)](std::forward<Args>(args)...);
  }
};
```

<p>Calling this code would be as follows </p>

<pre class="lang-cpp prettyprint-override"><code>enum class abc_enum { a, b, c, COUNT };
enum class defg_enum { d, e, f, g, COUNT };

template<abc_enum e, defg_enum f>
struct stuff {
  void operator()() const {
    std::cout << (int)e << '\n';
    std::cout << (int)f << '\n';
  }
};
magic_switch<abc_enum, defg_enum, stuff>{}(abc_enum::b, defg_enum::f);
</code>```

However, above does not compile due to the double variadic pack expansion. For more dimensions, even more variadic packs would have to be unpacked. Is there a solution for the n-dimensional magic switch problem?

答:
Instead of creating a single std::array with all possible function pointers, you can split the problem into smaller parts and create an N-D std::array instead.

Here's a quick and dirty example for the 2D problem you asked about:

```<code>template<class Enum, class Enum2, template <Enum, Enum2> class Z>
struct magic_switch {
  // return value of a call to magic_switch(Args...)
  template <class...Args>
  using R = std::result_of_t<Z<Enum(0), Enum2(0)>(Args...)>;

  // A function pointer for a jump table:
  template <class...Args>
  using F = R<Args...>(*)(Args&&...);

  // Produces a single function pointer for index I and args Args...
  template<size_t I, size_t I2, class...Args>
  F<Args...> f() const {
    using ret = R<Args...>;
    return +[](Args&&...args)->ret{
      using Invoke=Z<Enum(I), Enum2(I2)>;
      return Invoke{}(std::forward<Args>(args)...);
    };
  }

  // builds a jump table:
  // Table for fixed Enum value
  template <class... Args>
  using InnerArray = std::array<F<Args...>, size_t(Enum2::COUNT)>;

  template <size_t I, class... Args, size_t... Is2>
  InnerArray<Args...> innerTable (std::index_sequence<Is2...>) const {
    return {{ f<I, Is2, Args...>()... }}; // Expand Is2.
  }

  // Nested (2D) table
  template<class... Args, size_t... Is>
  std::array<InnerArray<Args...>, size_t(Enum::COUNT)> table (std::index_sequence<Is...>) const {
    return {{ innerTable<Is, Args...>(std::make_index_sequence<size_t(Enum2::COUNT)>{})... }}; // Expand Is.
  }

  template<class...Args>
  R<Args...> operator()(Enum n, Enum2 n2, Args&&...args) {
    // a static jump table for this case of Args...:
    static auto jump=table<Args...>(std::make_index_sequence<size_t(Enum::COUNT)>{});
    // Look up the nth entry in the jump table, and invoke it:
    return jump[size_t(n)][size_t(n2)](std::forward<Args>(args)...);
  }
};
</code>```

And actually using it with your example:

```<code>enum class abc_enum { a, b, c, COUNT };
enum class defg_enum { d, e, f, g, COUNT };

template<abc_enum e, defg_enum f>
struct stuff {
  void operator()() const {
    std::cout << (int)e << '\n';
    std::cout << (int)f << '\n';
  }
};

int main () {
  magic_switch<abc_enum, defg_enum, stuff>{}(abc_enum::b, defg_enum::f);
}
</code>```

I haven't tried making this automatically handle N different enums. Let's say that's left as an exercise for the reader :).

Body:
This is a magic switch problem, the solution was described here. However, I was wondering if it was possible to make it 3-dimensional, i.e. let it switch based on three given enums. In the ideal case, n-dimensional would be preferred of course. I tried first to make it 2-dimensional as shown below, but I run into double variadic unpacking, and I cannot find out how that would work.

template<class Enum, class Enum2, template<Enum, Enum2>class Z>
struct magic_switch {
  // return value of a call to magic_switch(Args...)
  template<class...Args>
  using R = std::result_of_t<Z<Enum(0), Enum2(0)>(Args...)>;
  // A function pointer for a jump table:
  template<class...Args>
  using F = R<Args...>(*)(Args&&...);
  // Produces a single function pointer for index I and args Args...
  template<size_t I, size_t I2, class...Args>
  F<Args...> f() const {
    using ret = R<Args...>;
    return +[](Args&&...args)->ret{
      using Invoke=Z<Enum(I), Enum(I2)>;
      return Invoke{}(std::forward<Args>(args)...);
    };
  }
  // builds a jump table:
  template<class...Args, size_t...Is, size_t ...Is2>
  std::array<F<Args...>,size_t(Enum::COUNT)>
  table( std::index_sequence<Is...>, std::index_sequence<Is2...> ) const {
    return {{
      f<Is, Is2, Args...>()... ... // << -- 2d expansion not working
    }};
  }
  template<class...Args>
  R<Args...> operator()(Enum n, Enum2 n2, Args&&...args) {
    // a static jump table for this case of Args...:
    static auto jump=table<Args...>(std::make_index_sequence<size_t(Enum::COUNT)>{}, std::make_index_sequence<size_t(Enum2::COUNT)>{});
    // Look up the nth entry in the jump table, and invoke it:
    return jump[size_t(n) + size_t(Enum::COUNT) * size_t(n2)](std::forward<Args>(args)...);
  }
};

Calling this code would be as follows

enum class abc_enum { a, b, c, COUNT };
enum class defg_enum { d, e, f, g, COUNT };

template<abc_enum e, defg_enum f>
struct stuff {
  void operator()() const {
    std::cout << (int)e << '\n';
    std::cout << (int)f << '\n';
  }
};
magic_switch<abc_enum, defg_enum, stuff>{}(abc_enum::b, defg_enum::f);

However, above does not compile due to the double variadic pack expansion. For more dimensions, even more variadic packs would have to be unpacked. Is there a solution for the n-dimensional magic switch problem?

Body:
Instead of creating a single std::array with all possible function pointers, you can split the problem into smaller parts and create an N-D std::array instead.

Here's a quick and dirty example for the 2D problem you asked about:

template<class Enum, class Enum2, template <Enum, Enum2> class Z>
struct magic_switch {
  // return value of a call to magic_switch(Args...)
  template <class...Args>
  using R = std::result_of_t<Z<Enum(0), Enum2(0)>(Args...)>;

  // A function pointer for a jump table:
  template <class...Args>
  using F = R<Args...>(*)(Args&&...);

  // Produces a single function pointer for index I and args Args...
  template<size_t I, size_t I2, class...Args>
  F<Args...> f() const {
    using ret = R<Args...>;
    return +[](Args&&...args)->ret{
      using Invoke=Z<Enum(I), Enum2(I2)>;
      return Invoke{}(std::forward<Args>(args)...);
    };
  }

  // builds a jump table:
  // Table for fixed Enum value
  template <class... Args>
  using InnerArray = std::array<F<Args...>, size_t(Enum2::COUNT)>;

  template <size_t I, class... Args, size_t... Is2>
  InnerArray<Args...> innerTable (std::index_sequence<Is2...>) const {
    return {{ f<I, Is2, Args...>()... }}; // Expand Is2.
  }

  // Nested (2D) table
  template<class... Args, size_t... Is>
  std::array<InnerArray<Args...>, size_t(Enum::COUNT)> table (std::index_sequence<Is...>) const {
    return {{ innerTable<Is, Args...>(std::make_index_sequence<size_t(Enum2::COUNT)>{})... }}; // Expand Is.
  }

  template<class...Args>
  R<Args...> operator()(Enum n, Enum2 n2, Args&&...args) {
    // a static jump table for this case of Args...:
    static auto jump=table<Args...>(std::make_index_sequence<size_t(Enum::COUNT)>{});
    // Look up the nth entry in the jump table, and invoke it:
    return jump[size_t(n)][size_t(n2)](std::forward<Args>(args)...);
  }
};

And actually using it with your example:

enum class abc_enum { a, b, c, COUNT };
enum class defg_enum { d, e, f, g, COUNT };

template<abc_enum e, defg_enum f>
struct stuff {
  void operator()() const {
    std::cout << (int)e << '\n';
    std::cout << (int)f << '\n';
  }
};

int main () {
  magic_switch<abc_enum, defg_enum, stuff>{}(abc_enum::b, defg_enum::f);
}

I haven't tried making this automatically handle N different enums. Let's say that's left as an exercise for the reader :).