问:
OnItemClickListener for spinner item, issue with setOnItemSelectedListener
I want to create a time and date selection dialog, like the one in the goolgle keep app, shown when one wants to be reminded about an event in the future.

The dialog has two spinner fields for the date and the time of day.
The first few fields are verbal descriptions like Today, Tomorrow etc. The last element is a manual selection of the date. Clicking it opens a Time/Date picker.

My current solution uses two custom adapter for each of these Spinners. The adapters are analogous so I will further only describe the time selection part.

My TimeSelection example implements both the getView and getDropDownView methods. The getDropDownView method isn't interesting it set the values to be displayed in the spinner items as you usually would in this situation.

```<code>@Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolderDropDown holder;
        TimeSelectionModel model = getItem(position);
        if (convertView == null) {
            holder = new ViewHolderDropDown();
            convertView = inflater.inflate(R.layout.time_spinner_drop_down_item, parent, false);
            holder.verbalTimeTextView = (TextView) convertView.findViewById(R.id.verbal_time_text_view);
            holder.timeTextView = (TextView) convertView.findViewById(R.id.time_text_view);
            convertView.setTag(R.layout.time_spinner_drop_down_item, holder);
        } else {
            holder = (ViewHolderDropDown) convertView.getTag(R.layout.time_spinner_drop_down_item);
        }

        holder.timeTextView.setText(model.time);
        holder.verbalTimeTextView.setText(model.verbalTime);

        return convertView;
    }
</code>```

The only non standard thing is that it populates two TextViews for a verbal description Morning, Evening etc. and an exact one 8:00.

The getView method is different instead of populating its members by usig the regular data array it takes the value from a field selectedTime. In a moment I will come back to how this field is set.

```<code>@NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.time_spinner_item, parent, false);
            holder.timeTextView = (TextView) convertView.findViewById(R.id.time_text_view);
            convertView.setTag(R.layout.time_spinner_item, holder);
        } else {
            holder = (ViewHolder) convertView.getTag(R.layout.time_spinner_item);
        }

        holder.timeTextView.setText(selectedTime);

        return convertView;
    }
</code>```

The DateTimeSelectionDialog which holds both these views implements a setOnItemSelectedListener for both these spinners which are again analogous.

```<code>timeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, "onItemSelected");
        if (position == POSITION_MORNING) {
            timeAdpater.setTime(8, 0);
        } else if (position == POSITION_AFTERNOON) {
            timeAdpater.setTime(13, 0);
        } else if (position == POSITION_EVENING) {
            timeAdpater.setTime(18, 0);
        } else if (position == POSITION_NIGHT) {
            timeAdpater.setTime(20, 0);
        } else {
            dateTimeDialogCallbacks.selectTimeManually();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});
</code>```

It is here where I set the label. The one exception is the last field where I call dateTimeDialogCallbacks.selectTimeManually(); implemented by the underling activity. After selecting the time from a TimePicker I call this method implemented by the DateTimeSelectionDialog.

```<code>public void setTime(int hour, int minute) {
        this.hour = hour;
        this.minute = minute;
        timeAdpater.setTime(hour, minute);
    }
</code>```

timeAdapter.setTime(hour, minute) will set the field and notify the adapter about a data change.

Everything seemed to be working great.
The problem is setOnItemSelectedListener isn't really the same thing like a normal click listener. Because it will only be called if the clicked field is different than the previously selected one.
So once the user selects the time manually he can't select it a second time manually. This is of course a bug.

So my question is what is the workaround for this? The people at google obviously found a way, so it can be done.

答: Well , within the context of your code, you can add checks in onNothingSelected(AdapterView parent) which is not ideal but a workaround!</p>

Body:
I want to create a time and date selection dialog, like the one in the goolgle keep app, shown when one wants to be reminded about an event in the future.

The dialog has two spinner fields for the date and the time of day.
The first few fields are verbal descriptions like Today, Tomorrow etc. The last element is a manual selection of the date. Clicking it opens a Time/Date picker.

My current solution uses two custom adapter for each of these Spinners. The adapters are analogous so I will further only describe the time selection part.

My TimeSelection example implements both the getView and getDropDownView methods. The getDropDownView method isn't interesting it set the values to be displayed in the spinner items as you usually would in this situation.

@Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolderDropDown holder;
        TimeSelectionModel model = getItem(position);
        if (convertView == null) {
            holder = new ViewHolderDropDown();
            convertView = inflater.inflate(R.layout.time_spinner_drop_down_item, parent, false);
            holder.verbalTimeTextView = (TextView) convertView.findViewById(R.id.verbal_time_text_view);
            holder.timeTextView = (TextView) convertView.findViewById(R.id.time_text_view);
            convertView.setTag(R.layout.time_spinner_drop_down_item, holder);
        } else {
            holder = (ViewHolderDropDown) convertView.getTag(R.layout.time_spinner_drop_down_item);
        }

        holder.timeTextView.setText(model.time);
        holder.verbalTimeTextView.setText(model.verbalTime);

        return convertView;
    }

The only non standard thing is that it populates two TextViews for a verbal description Morning, Evening etc. and an exact one 8:00.

The getView method is different instead of populating its members by usig the regular data array it takes the value from a field selectedTime. In a moment I will come back to how this field is set.

@NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.time_spinner_item, parent, false);
            holder.timeTextView = (TextView) convertView.findViewById(R.id.time_text_view);
            convertView.setTag(R.layout.time_spinner_item, holder);
        } else {
            holder = (ViewHolder) convertView.getTag(R.layout.time_spinner_item);
        }

        holder.timeTextView.setText(selectedTime);

        return convertView;
    }

The DateTimeSelectionDialog which holds both these views implements a setOnItemSelectedListener for both these spinners which are again analogous.

timeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG, "onItemSelected");
        if (position == POSITION_MORNING) {
            timeAdpater.setTime(8, 0);
        } else if (position == POSITION_AFTERNOON) {
            timeAdpater.setTime(13, 0);
        } else if (position == POSITION_EVENING) {
            timeAdpater.setTime(18, 0);
        } else if (position == POSITION_NIGHT) {
            timeAdpater.setTime(20, 0);
        } else {
            dateTimeDialogCallbacks.selectTimeManually();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});

It is here where I set the label. The one exception is the last field where I call dateTimeDialogCallbacks.selectTimeManually(); implemented by the underling activity. After selecting the time from a TimePicker I call this method implemented by the DateTimeSelectionDialog.

public void setTime(int hour, int minute) {
        this.hour = hour;
        this.minute = minute;
        timeAdpater.setTime(hour, minute);
    }

timeAdapter.setTime(hour, minute) will set the field and notify the adapter about a data change.

Everything seemed to be working great.
The problem is setOnItemSelectedListener isn't really the same thing like a normal click listener. Because it will only be called if the clicked field is different than the previously selected one.
So once the user selects the time manually he can't select it a second time manually. This is of course a bug.

So my question is what is the workaround for this? The people at google obviously found a way, so it can be done.


来源: stackexchange

问:
Variable value is not displaying in Jquery Graph
I am trying to use spark-line graph. I am passing values to graph as a JavaScript variable. But it is not displaying. But I surprised when I give same value as constant/static. It displays Correctly. Here is the my code :-

```<code> r("#sp-tristate-bar-total-revenue").sparkline([1,21,31,12], {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
</code>```

}

This above code working fine but If I take these values in Javascript variable like following code, graph does not work:-

```<code>var graph_val='1,21,31,12';
r("#sp-tristate-bar-total-revenue").sparkline([graph_val], {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
});
</code>```

Please help me to get rid of this.

答:
You want the variable to be an array. So var graph_val = [1,21,31,12] is what you need.

```<code>var graph_val=[1,21,31,12];
r("#sp-tristate-bar-total-revenue").sparkline(graph_val, {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
});
</code>```

UPDATE:
In the comments you mentioned the value coming from $("#id").text() as '2,5,3,6,8'. You can turn the comma delimitered string to an integer array like this:

```<code>graph_val = $("#id").text().split(',');
for (a in graph_val ) {
    graph_val[a] = parseInt(graph_val[a]);
}

r("#sp-tristate-bar-total-revenue").sparkline(graph_val, {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
});
</code>```

Example: https://jsfiddle.net/w49mpetp/2/

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use spark-line graph. I am passing values to graph as a JavaScript variable. But it is not displaying. But I surprised when I give same value as constant/static. It displays Correctly. Here is the my code :-

 r("#sp-tristate-bar-total-revenue").sparkline([1,21,31,12], {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"

}

This above code working fine but If I take these values in Javascript variable like following code, graph does not work:-

var graph_val='1,21,31,12';
r("#sp-tristate-bar-total-revenue").sparkline([graph_val], {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
});

Please help me to get rid of this.

Body:
You want the variable to be an array. So var graph_val = [1,21,31,12] is what you need.

var graph_val=[1,21,31,12];
r("#sp-tristate-bar-total-revenue").sparkline(graph_val, {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
});

UPDATE:
In the comments you mentioned the value coming from $("#id").text() as '2,5,3,6,8'. You can turn the comma delimitered string to an integer array like this:

graph_val = $("#id").text().split(',');
for (a in graph_val ) {
    graph_val[a] = parseInt(graph_val[a]);
}

r("#sp-tristate-bar-total-revenue").sparkline(graph_val, {
    type: "bar",
    width: "100%",
    height: "30px",
    barWidth: 4,
    barSpacing: 6,
    barColor: "#16D39A"
});

Example: https://jsfiddle.net/w49mpetp/2/


问:
Convert byte array to time_t
I have a linux time clock, that sending me the clock with bytes, I have no idea how to get the clock out of it, I do know that it's a type of "time_t" (which is probably the total seconds since 1/1/1970), See below a few examples what I'm receiving from the clock
(I'm not sure if it's sending local or GMT time)

This bytes represents 11/09/2017 16:52(Local time) or 11/09/2017 21:52(GMT)

```<code>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,66,120,53,34,0,0,0
</code>```

This bytes represents 11/10/2017 10:27(Local time) or 11/10/2017 15:27(GMT)

```<code>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,162,111,54,34,0,0,0
</code>```

This bytes represents 11/13/2017 14:20(Local time) or 11/13/2017 19:20(GMT)

```<code>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,160,154,58,34,0,0,0
</code>```

答:
With a little reverse engineering, it's possible to see what the data from your Linux clock is doing.

If you read your lines of data, you can see that the final 7 bytes are an incrementing counter, with the least significant byte in the first position. If you do the maths, the 3 counters give the following totals:

```<code>573929538
573992866
574266016
</code>```

Looking at the differences from the first number to the second and third, you get the following:

```<code>63328
336478
</code>```

... which are the elapsed times between your samples, in seconds.

For some reason, the raw values aren't the time in seconds since the Unix Epoch, but the time in seconds since a day early in September 1999.

Anyway, the following source code shows the basics of how you can convert your data into the local time.

```<code>#include <time.h>

int main(int argc, char* argv[])
{
    const unsigned long localEpoch = 936316800;   // local epoch Sept 1999

    std::vector<std::vector<int>> timeData =
    {
        { 66,  120, 53, 34, 0, 0, 0 },
        { 162, 111, 54, 34, 0, 0, 0 },
        { 160, 154, 58, 34, 0, 0, 0 }
    };

    for (auto& data : timeData)
    {
        // convert to total seconds
        unsigned long total = 0;
        for (std::vector<int>::iterator it = data.begin(); it != data.end(); ++it)
        {
            total += (*it) << (std::distance(data.begin(), it) * 8);
        }
        std::cout << "Seconds: " << total << std::endl;

        // add to local epoch and display
        time_t raw = total + localEpoch;
        struct tm timeinfo;
        localtime_s(&timeinfo, &raw);

        char fmt[100] = { 0 };
        asctime_s(fmt, 100, &timeinfo);
        std::cout << fmt << std::endl;
    }

    return 0;
}
</code>```

And it gives the following outputs:

```<code>Seconds: 573929538
Thu Nov  9 16:52:18 2017

Seconds: 573992866
Fri Nov 10 10:27:46 2017

Seconds: 574266016
Mon Nov 13 14:20:16 2017
</code>```

Hope this is of some help. (NB I did this in VS, so the time formatting functions are of the Windows variety, but you get the idea.)

(Edit): OK as requested, here's some equivalent C# code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        public static void Main(string[] args)
        {
            int[,] timeData = new int[,]
            {
                {  66, 120, 53, 34, 0, 0, 0 },
                { 162, 111, 54, 34, 0, 0, 0 },
                { 160, 154, 58, 34, 0, 0, 0 }
            };

            for (int line = 0; line < timeData.GetLength(0); ++line)
            {
                ulong total = 0;
                for (int i = 0; i < timeData.GetLength(1); ++i)
                {
                    total += (ulong)timeData[line,i] << (8 * i);
                }
                System.Console.WriteLine("Seconds: " + total.ToString());
                DateTime result = FromUnixTime(total + localEpoch);
                System.Console.WriteLine(result.ToString());
            }

            System.Console.ReadKey();
        }

        public static DateTime FromUnixTime(ulong unixTime)
        {
            return epoch.AddSeconds(unixTime);
        }

        private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        private static readonly ulong localEpoch = 936316800;   // local epoch Sept 1999
    }
}
</code>```

(Thanks to this question for the Epoch conversion.)

Title: Convert byte array to time_t

Body:
I have a linux time clock, that sending me the clock with bytes, I have no idea how to get the clock out of it, I do know that it's a type of "time_t" (which is probably the total seconds since 1/1/1970), See below a few examples what I'm receiving from the clock
(I'm not sure if it's sending local or GMT time)

This bytes represents 11/09/2017 16:52(Local time) or 11/09/2017 21:52(GMT)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,66,120,53,34,0,0,0

This bytes represents 11/10/2017 10:27(Local time) or 11/10/2017 15:27(GMT)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,162,111,54,34,0,0,0

This bytes represents 11/13/2017 14:20(Local time) or 11/13/2017 19:20(GMT)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,160,154,58,34,0,0,0

Body:
With a little reverse engineering, it's possible to see what the data from your Linux clock is doing.

If you read your lines of data, you can see that the final 7 bytes are an incrementing counter, with the least significant byte in the first position. If you do the maths, the 3 counters give the following totals:

573929538
573992866
574266016

Looking at the differences from the first number to the second and third, you get the following:

63328
336478

... which are the elapsed times between your samples, in seconds.

For some reason, the raw values aren't the time in seconds since the Unix Epoch, but the time in seconds since a day early in September 1999.

Anyway, the following source code shows the basics of how you can convert your data into the local time.

#include <time.h>

int main(int argc, char* argv[])
{
    const unsigned long localEpoch = 936316800;   // local epoch Sept 1999

    std::vector<std::vector<int>> timeData =
    {
        { 66,  120, 53, 34, 0, 0, 0 },
        { 162, 111, 54, 34, 0, 0, 0 },
        { 160, 154, 58, 34, 0, 0, 0 }
    };

    for (auto& data : timeData)
    {
        // convert to total seconds
        unsigned long total = 0;
        for (std::vector<int>::iterator it = data.begin(); it != data.end(); ++it)
        {
            total += (*it) << (std::distance(data.begin(), it) * 8);
        }
        std::cout << "Seconds: " << total << std::endl;

        // add to local epoch and display
        time_t raw = total + localEpoch;
        struct tm timeinfo;
        localtime_s(&timeinfo, &raw);

        char fmt[100] = { 0 };
        asctime_s(fmt, 100, &timeinfo);
        std::cout << fmt << std::endl;
    }

    return 0;
}

And it gives the following outputs:

Seconds: 573929538
Thu Nov  9 16:52:18 2017

Seconds: 573992866
Fri Nov 10 10:27:46 2017

Seconds: 574266016
Mon Nov 13 14:20:16 2017

Hope this is of some help. (NB I did this in VS, so the time formatting functions are of the Windows variety, but you get the idea.)

(Edit): OK as requested, here's some equivalent C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        public static void Main(string[] args)
        {
            int[,] timeData = new int[,]
            {
                {  66, 120, 53, 34, 0, 0, 0 },
                { 162, 111, 54, 34, 0, 0, 0 },
                { 160, 154, 58, 34, 0, 0, 0 }
            };

            for (int line = 0; line < timeData.GetLength(0); ++line)
            {
                ulong total = 0;
                for (int i = 0; i < timeData.GetLength(1); ++i)
                {
                    total += (ulong)timeData[line,i] << (8 * i);
                }
                System.Console.WriteLine("Seconds: " + total.ToString());
                DateTime result = FromUnixTime(total + localEpoch);
                System.Console.WriteLine(result.ToString());
            }

            System.Console.ReadKey();
        }

        public static DateTime FromUnixTime(ulong unixTime)
        {
            return epoch.AddSeconds(unixTime);
        }

        private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        private static readonly ulong localEpoch = 936316800;   // local epoch Sept 1999
    }
}

(Thanks to this question for the Epoch conversion.)


问:
Android Studio 3.1 Canary 3 - Gradle sync failed
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

```<code>Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)
</code>```

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too

答:
on Windows i just remove  from C:\Users\    folder -

.AndroidStudioPreview3.1

and all cache folders in .android ,.gradle too

and problem is gone)

Body:
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too


问:
Dynamically add subplots in matplotlib with more than one column
How can I dynamically add a new plot to bunch of subplots if I'm using more than one column to display my subplots? This answers this question for one column, but I cant seem to modify the answers there to make it dynamically add to a subplot with x columns

I modified Sadarthrion's answer and attempted the following. Here, for sake of an example, I made number_of_subplots=11 and num_cols = 3.

```<code>import matplotlib.pyplot as plt

def plotSubplots(number_of_subplots,num_cols):
    # Start with one
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot([1,2,3])

    for j in range(number_of_subplots):
        if j > 0:
            # Now later you get a new subplot; change the geometry of the existing
            n = len(fig.axes)
            for i in range(n):
                fig.axes[i].change_geometry(n+1, num_cols, i+1)

            # Add the new
            ax = fig.add_subplot(n+1, 1, n+1)
            ax.plot([4,5,6])

            plt.show()

   plotSubplots(11,3)
</code>```

As you can see this isn't giving me what I want. The first plot takes up all the columns and the additional plots are smaller than they should be

EDIT:

('2.7.6 | 64-bit | (default, Sep 15 2014, 17:36:35) [MSC v.1500 64 bit (AMD64)]'

Also I have matplotlib version 1.4.3:

```<code>import matplotlib as mpl
print mpl.__version__
1.4.3
</code>```

I tried Paul's answer below and get the following error message:

```<code>import math

import matplotlib.pyplot as plt
from matplotlib import gridspec

def do_plot(ax):
    ax.plot([1,2,3], [4,5,6], 'k.')

N = 11
cols = 3
rows = math.ceil(N / cols)

gs = gridspec.GridSpec(rows, cols)
fig = plt.figure()
for n in range(N):
    ax = fig.add_subplot(gs[n])
    do_plot(ax)

fig.tight_layout()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-f74203b1c1bf> in <module>()
     15 fig = plt.figure()
     16 for n in range(N):
---> 17     ax = fig.add_subplot(gs[n])
     18     do_plot(ax)
     19

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.pyc in add_subplot(self, *args, **kwargs)
    962                     self._axstack.remove(ax)
    963
--> 964             a = subplot_class_factory(projection_class)(self, *args, **kwargs)
    965
    966         self._axstack.add(key, a)

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in __init__(self, fig, *args, **kwargs)
     73             raise ValueError('Illegal argument(s) to subplot: %s' % (args,))
     74
---> 75         self.update_params()
     76
     77         # _axes_class is set in the subplot_class_factory

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in update_params(self)
    113         self.figbox, self.rowNum, self.colNum, self.numRows, self.numCols =     114             self.get_subplotspec().get_position(self.figure,
--> 115                                                 return_all=True)
    116
    117     def is_first_col(self):

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\gridspec.pyc in get_position(self, fig, return_all)
    423
    424         figBottoms, figTops, figLefts, figRights = --> 425                     gridspec.get_grid_positions(fig)
    426
    427

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\gridspec.pyc in get_grid_positions(self, fig)
    103             cellHeights = [netHeight*r/tr for r in self._row_height_ratios]
    104         else:
--> 105             cellHeights = [cellH] * nrows
    106
    107         sepHeights = [0] + ([sepH] * (nrows-1))

TypeError: can't multiply sequence by non-int of type 'float'
</code>```

答:
```<code>from math import ceil
from PyQt5 import QtWidgets, QtCore
from matplotlib.gridspec import GridSpec
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

class MplCanvas(FigureCanvas):
    """
    Frontend class. This is the FigureCanvas as well as plotting functionality.
    Plotting use pyqt5.
    """

    def __init__(self, parent=None):
        self.figure = Figure()

        gs = GridSpec(1,1)

        self.figure.add_subplot(gs[0])
        self.axes = self.figure.axes

        super().__init__(self.figure)

        self.canvas = self.figure.canvas
        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.updateGeometry()
        self.setParent(parent)

    def add(self, cols=2):
        N = len(self.axes) + 1
        rows = int(ceil(N / cols))
        grid = GridSpec(rows, cols)

        for gs, ax in zip(grid, self.axes):
            ax.set_position(gs.get_position(self.figure))

        self.figure.add_subplot(grid[N-1])
        self.axes = self.figure.axes
        self.canvas.draw()
</code>```

<p>Was doing some PyQt5 work, but the add method shows how to dynamically add a new subplot. The set_position method of Axes is used to change the old position to new position. Then you add a new subplot with the new position. </p>

Body:
How can I dynamically add a new plot to bunch of subplots if I'm using more than one column to display my subplots? This answers this question for one column, but I cant seem to modify the answers there to make it dynamically add to a subplot with x columns

I modified Sadarthrion's answer and attempted the following. Here, for sake of an example, I made number_of_subplots=11 and num_cols = 3.

import matplotlib.pyplot as plt

def plotSubplots(number_of_subplots,num_cols):
    # Start with one
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot([1,2,3])

    for j in range(number_of_subplots):
        if j > 0:
            # Now later you get a new subplot; change the geometry of the existing
            n = len(fig.axes)
            for i in range(n):
                fig.axes[i].change_geometry(n+1, num_cols, i+1)

            # Add the new
            ax = fig.add_subplot(n+1, 1, n+1)
            ax.plot([4,5,6])

            plt.show()

   plotSubplots(11,3)

As you can see this isn't giving me what I want. The first plot takes up all the columns and the additional plots are smaller than they should be

EDIT:

('2.7.6 | 64-bit | (default, Sep 15 2014, 17:36:35) [MSC v.1500 64 bit (AMD64)]'

Also I have matplotlib version 1.4.3:

import matplotlib as mpl
print mpl.__version__
1.4.3

I tried Paul's answer below and get the following error message:

import math

import matplotlib.pyplot as plt
from matplotlib import gridspec

def do_plot(ax):
    ax.plot([1,2,3], [4,5,6], 'k.')

N = 11
cols = 3
rows = math.ceil(N / cols)

gs = gridspec.GridSpec(rows, cols)
fig = plt.figure()
for n in range(N):
    ax = fig.add_subplot(gs[n])
    do_plot(ax)

fig.tight_layout()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-f74203b1c1bf> in <module>()
     15 fig = plt.figure()
     16 for n in range(N):
---> 17     ax = fig.add_subplot(gs[n])
     18     do_plot(ax)
     19

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.pyc in add_subplot(self, *args, **kwargs)
    962                     self._axstack.remove(ax)
    963
--> 964             a = subplot_class_factory(projection_class)(self, *args, **kwargs)
    965
    966         self._axstack.add(key, a)

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in __init__(self, fig, *args, **kwargs)
     73             raise ValueError('Illegal argument(s) to subplot: %s' % (args,))
     74
---> 75         self.update_params()
     76
     77         # _axes_class is set in the subplot_class_factory

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_subplots.pyc in update_params(self)
    113         self.figbox, self.rowNum, self.colNum, self.numRows, self.numCols =     114             self.get_subplotspec().get_position(self.figure,
--> 115                                                 return_all=True)
    116
    117     def is_first_col(self):

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\gridspec.pyc in get_position(self, fig, return_all)
    423
    424         figBottoms, figTops, figLefts, figRights = --> 425                     gridspec.get_grid_positions(fig)
    426
    427

C:\Users\user\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\gridspec.pyc in get_grid_positions(self, fig)
    103             cellHeights = [netHeight*r/tr for r in self._row_height_ratios]
    104         else:
--> 105             cellHeights = [cellH] * nrows
    106
    107         sepHeights = [0] + ([sepH] * (nrows-1))

TypeError: can't multiply sequence by non-int of type 'float'

Body:
from math import ceil
from PyQt5 import QtWidgets, QtCore
from matplotlib.gridspec import GridSpec
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

class MplCanvas(FigureCanvas):
    """
    Frontend class. This is the FigureCanvas as well as plotting functionality.
    Plotting use pyqt5.
    """

    def __init__(self, parent=None):
        self.figure = Figure()

        gs = GridSpec(1,1)

        self.figure.add_subplot(gs[0])
        self.axes = self.figure.axes

        super().__init__(self.figure)

        self.canvas = self.figure.canvas
        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.updateGeometry()
        self.setParent(parent)

    def add(self, cols=2):
        N = len(self.axes) + 1
        rows = int(ceil(N / cols))
        grid = GridSpec(rows, cols)

        for gs, ax in zip(grid, self.axes):
            ax.set_position(gs.get_position(self.figure))

        self.figure.add_subplot(grid[N-1])
        self.axes = self.figure.axes
        self.canvas.draw()

Was doing some PyQt5 work, but the add method shows how to dynamically add a new subplot. The set_position method of Axes is used to change the old position to new position. Then you add a new subplot with the new position.


问:
Polymorphism with gson
I have a problem deserializing a json string with Gson.
I  receive an array of commands. The command can be start,  stop , some other type of command. Naturally I have polymorphism, and start/stop command inherit from command.

How can I serialize it back to the correct command object using gson?

Seems that I get only the base type, that is the declared type and never the runtime type.

答:
Google has released its own RuntimeTypeAdapterFactory to handle the polymorphism but unfortunately it's not part of the gson core (you must copy and paste the class inside your project).

Example:

```<code>RuntimeTypeAdapterFactory<Animal> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
.of(Animal.class, "type")
.registerSubtype(Dog.class, "dog")
.registerSubtype(Cat.class, "cat");

Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(runtimeTypeAdapterFactory)
    .create();
</code>```

Here I have posted a full working example of it using the models Animal, Dog and Cat.

I think it's better to rely on this adapter rather than reimplement it from scratch.

Title: Polymorphism with gson

Body:
Google has released its own RuntimeTypeAdapterFactory to handle the polymorphism but unfortunately it's not part of the gson core (you must copy and paste the class inside your project).

Example:

RuntimeTypeAdapterFactory<Animal> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
.of(Animal.class, "type")
.registerSubtype(Dog.class, "dog")
.registerSubtype(Cat.class, "cat");

Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(runtimeTypeAdapterFactory)
    .create();

Here I have posted a full working example of it using the models Animal, Dog and Cat.

I think it's better to rely on this adapter rather than reimplement it from scratch.

ContentLicense: CC BY-SA 4.0


问:
SSRS Data always show on third page
I'm new on SSRS and I want to create report, standard report.
When I finish assign my data to textbox on Table, why my data show on the next 2 page?

My sample report.

答:
Check that the report body + margins does not exceed the page width. When this happens, the blank area to the right of the report which will not fit on page one will 'print' on page two but as this is just white space you don't see anything, then the rest of the report will print on page three.

First try to reduce margins as this is the easiest thin to do, if the problem will occurs then you have to make the body contents narrower.

Title: SSRS Data always show on third page


问:
Add style to tag in javascript onclick
I have this working javascript that i would like to one more feature to. I would like so that if i click for example " Fair Trade " the text color should change, and if i now press for example " Toxicfree " it should fade away that style and fade in the new style.

This is to make sure the user knows what Title they have selected and are reading about.

All help is appreciated!

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this)
  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-link {
  width: 100px;
}</code>```

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

```

JSFIDDLE

答:
Add a class to the selected div, and then give a special color to this class.

Use transition in css to animate the fade-in fade-out styling:

```<code>-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
-ms-transition: all .5s ease-in-out;
-o-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
</code>```

.5s means half a second. You can increase or decrease the number depending on your requirements

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}</code>```

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

```

Title: Add style to tag in javascript onclick

Body:
I have this working javascript that i would like to one more feature to. I would like so that if i click for example " Fair Trade " the text color should change, and if i now press for example " Toxicfree " it should fade away that style and fade in the new style.

This is to make sure the user knows what Title they have selected and are reading about.

All help is appreciated!

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this)
  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})

.section-link {
  width: 100px;
}

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

JSFIDDLE

Body:
Add a class to the selected div, and then give a special color to this class.

Use transition in css to animate the fade-in fade-out styling:

-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
-ms-transition: all .5s ease-in-out;
-o-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;

.5s means half a second. You can increase or decrease the number depending on your requirements

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})

.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-link small-solid-circle-p4 fair-d">
  <h2>
    <nobr>FAIR-TRADE</nobr>
  </h2>
</div>
<div class="section-link small-solid-circle-p4 toxic-d">
  <h2>TOXICFREE</h2>
</div>
<div class="section-link small-solid-circle-p4 quality-d">
  <h2>QUALITY</h2>
</div>
<div class="section-link small-solid-circle-p4 organic-d">
  <h2>ORGANIC</h2>
</div>
<div class="section-link small-solid-circle-p4 vegan-d">
  <h2>VEGAN</h2>
</div>
<div class="section-display active info-p4">
  <h2 class="title1">Lorem ipsum</h2>
  <h2 class="text1">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br>
    <br> Tap on the symbols if you want to know more.</h2>
</div>


问:
how to get the first splited part of each index in an array
we have an array like below, length of the array is not constant(may increase/decrease).

```<code>[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]
</code>```

My aim is to achieve only the first part of each index like below.

```<code>[255028AD,261830AD,.........]
</code>```

Please help.

答:
Something like that should work:</p>

```<code>const arr = ['255028AD_ABC_DE_2057','261830AD_ABC_FG_2876'];
const arrModified = arr.map(element =>
    element.substr(0, element.indexOf('_')));
console.log(arrModified)
</code>```

Body:
we have an array like below, length of the array is not constant(may increase/decrease).

[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]

My aim is to achieve only the first part of each index like below.

[255028AD,261830AD,.........]

Please help.

Body:
Something like that should work:

const arr = ['255028AD_ABC_DE_2057','261830AD_ABC_FG_2876'];
const arrModified = arr.map(element =>
    element.substr(0, element.indexOf('_')));
console.log(arrModified)


答:
Use Array.map function so your code will look something like this

```<code>[].map(item => item.split('_')[0])
</code>```

where [] is your array

in ES5 syntax it will look like

```<code>[].map(function(item) {
  return item.split('_')[0];
})
</code>```

Hope that helps

Title: how to get the first splited part of each index in an array

Body:
Use Array.map function so your code will look something like this

[].map(item => item.split('_')[0])

where [] is your array

in ES5 syntax it will look like

[].map(function(item) {
  return item.split('_')[0];
})

Hope that helps


答:
You put the string inside an array as a single element, you need to instead generate the array of create one.

Option 1: Split string into array

```<code>var graph_val='1,21,31,12';
r("#sp-tristate-bar-total-revenue").sparkline(graph_val.split(','), {
</code>```

Option 2: Write the vals as an array

```<code>var graph_val=[1,21,31,12];
r("#sp-tristate-bar-total-revenue").sparkline(graph_val, {
</code>```

Title: Variable value is not displaying in Jquery Graph

Body:
You put the string inside an array as a single element, you need to instead generate the array of create one.

Option 1: Split string into array

var graph_val='1,21,31,12';
r("#sp-tristate-bar-total-revenue").sparkline(graph_val.split(','), {

Option 2: Write the vals as an array

var graph_val=[1,21,31,12];
r("#sp-tristate-bar-total-revenue").sparkline(graph_val, {


问:
Stubbing Chained Queries in Rails 3 and Rspec
I'm trying to test a scope I have that is based upon a chain of other scopes. ("public_stream" below).

```<code>scope :public, where("entries.privacy = 'public'")
scope :completed, where("entries.observation <> '' AND entries.application <> ''")
scope :without_user, lambda { |user| where("entries.user_id <> ?", user.id) }
scope :public_stream, lambda { |user| public.completed.without_user(user).limit(15) }
</code>```

Using a test like this:

```<code>    it "should use the public, without_user, completed, and limit scopes" do
      @chain = mock(ActiveRecord::Relation)
      Entry.should_receive(:public).and_return(@chain)
      @chain.should_receive(:without_user).with(@user).and_return(@chain)
      @chain.should_receive(:completed).and_return(@chain)
      @chain.should_receive(:limit).with(15).and_return(Factory(:entry))

      Entry.public_stream(@user)
    end
</code>```

However, I continue to receive this error:

```<code>Failure/Error: Entry.public_stream(@user)
undefined method `includes_values' for #<Entry:0xd7b7c0>
</code>```

It seems includes_values is an instance variable of the ActiveRecord::Relation object, but when I try to stub it, I still receive the same error. I was wondering if anyone had experience with stubing Rails 3's new chained queries? I can find a bunch of discussion over 2.x's find hash, but nothing on how to test what's current.

答:
I use rspec's stub_chain for this.  You might be able to use something like:

some_model.rb

```<code>scope :uninteresting, :conditions => ["category = 'bad'"],
                      :order => "created_at DESC"
</code>```

Controller

```<code>@some_models = SomeModel.uninteresting.where(:something_else => true)
</code>```

spec

```<code>SomeModel.stub_chain(:uninteresting, :where) {mock_some_model}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to test a scope I have that is based upon a chain of other scopes. ("public_stream" below).

scope :public, where("entries.privacy = 'public'")
scope :completed, where("entries.observation <> '' AND entries.application <> ''")
scope :without_user, lambda { |user| where("entries.user_id <> ?", user.id) }
scope :public_stream, lambda { |user| public.completed.without_user(user).limit(15) }

Using a test like this:

    it "should use the public, without_user, completed, and limit scopes" do
      @chain = mock(ActiveRecord::Relation)
      Entry.should_receive(:public).and_return(@chain)
      @chain.should_receive(:without_user).with(@user).and_return(@chain)
      @chain.should_receive(:completed).and_return(@chain)
      @chain.should_receive(:limit).with(15).and_return(Factory(:entry))

      Entry.public_stream(@user)
    end

However, I continue to receive this error:

Failure/Error: Entry.public_stream(@user)
undefined method `includes_values' for #<Entry:0xd7b7c0>

It seems includes_values is an instance variable of the ActiveRecord::Relation object, but when I try to stub it, I still receive the same error. I was wondering if anyone had experience with stubing Rails 3's new chained queries? I can find a bunch of discussion over 2.x's find hash, but nothing on how to test what's current.

Body:
I use rspec's stub_chain for this.  You might be able to use something like:

some_model.rb

scope :uninteresting, :conditions => ["category = 'bad'"],
                      :order => "created_at DESC"

Controller

@some_models = SomeModel.uninteresting.where(:something_else => true)

spec

SomeModel.stub_chain(:uninteresting, :where) {mock_some_model}


答:
the second piece of code does not initialize an array as the first.

try this:

```<code>var graph_val=[1,21,31,12];
</code>```

Body:
the second piece of code does not initialize an array as the first.

try this:

var graph_val=[1,21,31,12];


问:
How to deploy a java application on tomcat and access it online
I wanna deploy a java app on tomcat 9 to be accessible by typing an address like www.justanormalapp.stuff. Now I have a dedicated server machine on which i'm going to be installing tomcat and deploying the WAR app file but it can be only accessed locally through http://localhost:8080/myapp/ and I don't know how to make it accessible online.

I am not looking for some fancy domain name as anything free will do since the app is only going to be used for 3 - 6 months.

答:
If all your PCs are not in the same net, you have to create an VPN to allow external computers access to your server.

So:

Create your VPN.

Configure VPN in the PCs where you want to access to your application

Use ip:port/myapp

This should be enough.


Body:
Try this:

var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'];
arr = arr.map(el => el.split('_')[0]);
console.log(arr);


问:
How to center a div (CSS loader)
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

How do I centre it horizontally & vertically?

I tried:

```<code>position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
</code>```

But transform:translate(-50%,-50%); do not work

答:
Easiest way to center element using CSS is by using flexbox. No hacks required.

if need to set parent container with display: flex.

```<code><div class="container">
   <div class="item">
      Aligned Item
   <div>
</div>
</code>```

CSS:

```<code>.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.item {
  width: 200px;
  height: 200px;
}
</code>```

All elements with class item will be centrally aligned.

More details can be found at

https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/

Title: How to center a div (CSS loader)

Body:
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

How do I centre it horizontally & vertically?

I tried:

position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);

But transform:translate(-50%,-50%); do not work

Body:
Easiest way to center element using CSS is by using flexbox. No hacks required.

if need to set parent container with display: flex.

<div class="container">
   <div class="item">
      Aligned Item
   <div>
</div>

CSS:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.item {
  width: 200px;
  height: 200px;
}

All elements with class item will be centrally aligned.

More details can be found at

https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/


问:
Avoid double switch case in strategy pattern
I know this is a lot of stuff but please bear with me, I don't know how else to describe the problem comprehensively. Imagine there is a mashine which has 2 devices A & B. Each of the devices has 2 axes that can be turned on and off. (The axes have actually more properties to set, but for the sake of simplicity let's focus only on 1):

```<code>        mashine
           |
      ------------
      |          |
      A          B
    ------    ------
    |    |    |    |
    X    Y    X    Y
   ---  ---  ---  ---
   |||  |||  |||  |||
   ESP  ESP  ESP  ESP

E: Enable(bool) | S: Start(bool) | P: Position(double)
</code>```

The mashine is represented by the following class (which I cannot change!):

// MASHINE

```<code>public static class Mashine
{
    public static bool Enable_B_X { get; set; }
    public static bool Enable_B_Y { get; set; }

    public static bool Enable_A_X { get; set; }
    public static bool Enable_A_Y { get; set; }
    // actually much more properties for each axis and device
}
</code>```

My aim is to program a control class which would provide methods that can be used to set these variables. I tried using a strategy pattern (or at least something similar to this). The pattern of the mashine parts tree lead me to try to apply the pattern twice (since it has 2 split levels). Once in the interchangeable devices and one in the interchangeable axes.   This is the code I have so far:

// Device Control Interface and the 2 Different Device Classes A and B

```<code>public class DeviceControl
{
    public virtual IAxis Axis { get; set; }

    public void Enable()
    {
        Axis.Enable = true;
    }
    public void Disable()
    {
        Axis.Enable = false;
    }
}

public class DeviceControl_A : DeviceControl
{
    public override IAxis Axis
    {
        get { return base.Axis as IAxis_A; }
        set { base.Axis = value as IAxis_A; }
    }
}

public class DeviceControl_B : DeviceControl
{
    public override IAxis Axis
    {
        get { return base.Axis as IAxis_B; }
        set { base.Axis = value as IAxis_B; }
    }
}
</code>```

Axis representation (Interface and Explicit Classes): Basically they are intended to map the variables in the static class Mashine onto the properties of the different axes

```<code>public interface IAxis
{
    bool Enable { get; set; }
}

// These Interfaces are to ensure that Axis_A goes only into Device A
// and Axis_B only with device B
public interface IAxis_A : IAxis { }

public interface IAxis_B : IAxis { }

public class X_Axis_A : IAxis_A
{
    public bool Enable
    {
        get => Mashine.Enable_A_X;
        set => Mashine.Enable_A_X = value;
    }
}

public class Y_Axis_A : IAxis_A
{
    public bool Enable
    {
        get => Mashine.Enable_A_Y;
        set => Mashine.Enable_A_Y = value;
    }
}

public class X_Axis_B : IAxis_B
{
    public bool Enable
    {
        get => Mashine.Enable_B_X;
        set => Mashine.Enable_B_X = value;
    }
}

public class Y_Axis_B : IAxis_B
{
    public bool Enable
    {
        get => Mashine.Enable_B_Y;
        set => Mashine.Enable_B_Y = value;
    }
}
</code>```

And this is the Control Class which provides the methods for the control of the mashine in dependency of the device and the appropriate axis:

```<code>public enum Device { A, B }

public enum Axis { X, Y }

public class Control
{
    public DeviceControl devControl;

    public void Disable(Device dev, Axis dim)
    {
        // initialize
        InitAxisAndDevice(dev, dim);
        devControl.Disable();
    }

    public void Enable(Device dev, Axis dim)
    {
        InitAxisAndDevice(dev, dim);
        devControl.Enable();
    }

    private void InitAxisAndDevice(Device dev, Axis dim)
    {
        switch (dev)
        {
            case Device.A:
                this.devControl = new DeviceControl_A();

                switch (dim)
                {
                    case Axis.X: this.devControl.Axis = new X_Axis_A(); break;
                    case Axis.Y: this.devControl.Axis = new Y_Axis_A(); break;
                    case Axis.Z: this.devControl.Axis = new Z_Axis_A(); break;
                }
                break;
            case Device.B:
                this.devControl = new DeviceControl_B();

                switch (dim)
                {
                    case Axis.X: this.devControl.Axis = new X_Axis_B(); break;
                    case Axis.Y: this.devControl.Axis = new Y_Axis_B(); break;
                    case Axis.Z: this.devControl.Axis = new Z_Axis_B(); break;
                }
                break;
        }
    }
}
</code>```

Question 1

How can I avoid this double switch case in the InitAxisAndDevice method?

Question 2

Is there a better way to make sure that only A-type axes go along with device A ?

I have the strong feeling that I misunderstood something in the application of this pattern. Is there maybe a different approach/pattern which would be more suitable to solve this mapping of control problem?

Any help is greatly appriciated. Thank you in advance.

EDIT

Since I was too vague in explanation, here is a use case.
All axes have an almost identical set of variables that have to be set like:[enable(bool), position(double), start(bool)]

The point of abstraction is to have a single control class which can use one method Enable f.e. to enable any axis dependent on the type of device and on the type of axis.

I hope it became a little clearer

答:
Consider the following code. The idea is to create an abstract representation of device axis, devices and machine as interface. Then use a factory to create concrete devices and axis for the (given not changeable) Mashine.

```<code>public static class Mashine
{
    public static bool Enable_B_X { get; set; }
    public static bool Enable_B_Y { get; set; }

    public static bool Enable_A_X { get; set; }
    public static bool Enable_A_Y { get; set; }
}

/// <summary>
/// Represents a single axis of a single device
/// </summary>
public interface IDeviceAxis
{
    void Enable();
    void Disable();
}
// general device that has two axis, but doesn't care about anything else
public interface IDevice
{
    IDeviceAxis X { get; }
    IDeviceAxis Y { get; }
}
// data model for an alternative Mashine representation
public interface IMachineModel
{
    IDevice A { get; }
    IDevice B { get; }
}
</code>```

Usage:

```<code>public enum Device { A, B }

public enum Axis { X, Y }

// your control class
public class Control
{
    public IMachineModel devControl;

    public Control()
    {
        // MachineFactory see below
        devControl = MachineFactory.GetMachine();
    }

    public void Disable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Disable();
    }

    public void Enable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Enable();
    }

    private IDeviceAxis GetAxis(Device dev, Axis dim)
    {
        var device = GetDevice(dev);
        switch (dim)
        {
            case Axis.X:
                return device.X;
            case Axis.Y:
                return device.Y;
            default:
                throw new ArgumentException("Invalid Axis", "dim");
        }
    }
    private IDevice GetDevice(Device dev)
    {
        switch (dev)
        {
            case Device.A:
                return devControl.A;
            case Device.B:
                return devControl.B;
            default:
                throw new ArgumentException("Invalid Device", "dev");
        }
    }
}
</code>```

The missing part: a concrete implementation of the interfaces and a factory to get the whole machine representation:

```<code>// concrete machine factory
public static class MachineFactory
{
    // factory for the whole Mashine wrapper
    public static IMachineModel GetMachine()
    {
        return new MachineModel
        {
            A = GetDeviceA(),
            B = GetDeviceB(),
        };
    }

    // factory methods specify the connection from the wrapper classes to the Mashine

    private static IDevice GetDeviceA()
    {
        return new MachineDevice(x => Mashine.Enable_A_X = x, y => Mashine.Enable_A_Y = y);
    }
    private static IDevice GetDeviceB()
    {
        return new MachineDevice(x => Mashine.Enable_B_X = x, y => Mashine.Enable_B_Y = y);
    }

    // concrete implementations can be used for the target Mashine

    private class MachineDeviceAxis : IDeviceAxis
    {
        Action<bool> _setterFunction;
        public MachineDeviceAxis(Action<bool> setter)
        {
            _setterFunction = setter;
        }

        public void Enable()
        {
            _setterFunction(true);
        }

        public void Disable()
        {
            _setterFunction(false);
        }
    }

    private class MachineDevice : IDevice
    {
        public MachineDevice(Action<bool> xSetter, Action<bool> ySetter)
        {
            X = new MachineDeviceAxis(xSetter);
            Y = new MachineDeviceAxis(ySetter);
        }
        public IDeviceAxis X { get; private set; }

        public IDeviceAxis Y { get; private set; }
    }

    private class MachineModel : IMachineModel
    {
        public IDevice A { get; set; }

        public IDevice B { get; set; }
    }
}
</code>```

Regarding the usage of the machine abstraction, I think there is no real advantage of using enum Device and enum Axis. Compare the following codes:

```<code>// controllers
Control yourControl;
IMachineModel myMachineModel;
// usage
yourControl.Enable(Device.A, Axis.X);
myMachineModel.A.X.Enable();
</code>```

The advantage of using Control here doesn't really improve the code if you ask me.

Edit regarding other parameters

Maybe the Enable and Disable is already over-engineered? How about some generic Set(value) instead:

```<code>public interface IAxisParameter<TParameter>
{
    void Set(TParameter value);
}

public interface IDeviceAxis
{
    IAxisParameter<bool> Enabled { get; }

    IAxisParameter<double> Position { get; }

    IAxisParameter<bool> Start { get; }
}
</code>```

Usage:

```<code>public class Control
{
    public void Disable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Enabled.Set(false);
    }

    public void Enable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Enabled.Set(true);
    }

    // rest of the code as in the original answer above
}
</code>```

Then change the internal machine implementation accordingly:

```<code>// inside factory

    // added implementation
    private class MachineParameter<TParam> : IAxisParameter<TParam>
    {
        Action<TParam> _setterFunction;
        public MachineParameter(Action<TParam> setter)
        {
            _setterFunction = setter;
        }
        public void Set(TParam value)
        {
            _setterFunction(value);
        }
    }

    // changed implementation
    private class MachineDeviceAxis : IDeviceAxis
    {
        public IAxisParameter<bool> Enabled { get; set; }

        public IAxisParameter<double> Position { get; set; }

        public IAxisParameter<bool> Start { get; set; }
    }

    // changed factory methods

    private static IDeviceAxis GetDeviceAxisA_X()
    {
        return new MachineDeviceAxis
        {
            Enabled = new MachineParameter<bool>(x => Mashine.Enable_A_X = x),
            Position = null, // TODO
            Start = null, // TODO
        };
    }
    private static IDeviceAxis GetDeviceAxisA_Y()
    {
        return new MachineDeviceAxis
        {
            Enabled = new MachineParameter<bool>(y => Mashine.Enable_A_Y = y),
            Position = null, // TODO
            Start = null, // TODO
        };
    }
    private static IDevice GetDeviceA()
    {
        return new MachineDevice
        {
            X = GetDeviceAxisA_X(),
            Y = GetDeviceAxisA_Y(),
        };
    }
    private static IDevice GetDeviceB()
    {
        // TODO same thing for device B
        return null;
    }
</code>```

The concept should be clear... in the end you have to write some code for each property of the actual machine.
Maybe it would be a good idea to re-organize the parameter creation inside the factory to something like @Fildor did in his linked code example.

Edit: keeping the factory code more compact

Instead of bloating the factory with a separate method for each parameter, re-group the creation of parameter setters to create the setters for one parameter type in all devices in one place (eg. CreateEnabledParameterSetters):

```<code>// concrete machine factory
public static class MachineFactory
{
    // factory for the whole Mashine wrapper
    public static IMachineModel GetMachine()
    {
        var enabledSetters = CreateEnabledParameterSetters();
        return new MachineModel
        {
            A = GetDevice(enabledSetters, 0 /*A*/),
            B = GetDevice(enabledSetters, 1 /*B*/),
        };
    }

    // factory methods specify the connection from the wrapper classes to the Mashine

    private static Action<bool>[,] CreateEnabledParameterSetters()
    {
        return new Action<bool>[,]
        {
            { x => Mashine.Enable_A_X = x, x => Mashine.Enable_A_Y = x },
            { x => Mashine.Enable_B_X = x, x => Mashine.Enable_B_Y = x },
        };
    }
    private static IDeviceAxis GetDeviceAxis(Action<bool>[,] enabledSetters, int deviceIndex, int axisIndex)
    {
        return new MachineDeviceAxis
        {
            Enabled = new MachineParameter<bool>(enabledSetters[deviceIndex, axisIndex]),
            Position = null, // TODO
            Start = null, // TODO
        };
    }
    private static IDevice GetDevice(Action<bool>[,] enabledSetters, int deviceIndex)
    {
        return new MachineDevice
        {
            X = GetDeviceAxis(enabledSetters, deviceIndex, 0 /*X*/),
            Y = GetDeviceAxis(enabledSetters, deviceIndex, 1 /*Y*/),
        };
    }

// ...
</code>```

Body:
I know this is a lot of stuff but please bear with me, I don't know how else to describe the problem comprehensively. Imagine there is a mashine which has 2 devices A & B. Each of the devices has 2 axes that can be turned on and off. (The axes have actually more properties to set, but for the sake of simplicity let's focus only on 1):

        mashine
           |
      ------------
      |          |
      A          B
    ------    ------
    |    |    |    |
    X    Y    X    Y
   ---  ---  ---  ---
   |||  |||  |||  |||
   ESP  ESP  ESP  ESP

E: Enable(bool) | S: Start(bool) | P: Position(double)

The mashine is represented by the following class (which I cannot change!):

// MASHINE

public static class Mashine
{
    public static bool Enable_B_X { get; set; }
    public static bool Enable_B_Y { get; set; }

    public static bool Enable_A_X { get; set; }
    public static bool Enable_A_Y { get; set; }
    // actually much more properties for each axis and device
}

My aim is to program a control class which would provide methods that can be used to set these variables. I tried using a strategy pattern (or at least something similar to this). The pattern of the mashine parts tree lead me to try to apply the pattern twice (since it has 2 split levels). Once in the interchangeable devices and one in the interchangeable axes.   This is the code I have so far:

// Device Control Interface and the 2 Different Device Classes A and B

public class DeviceControl
{
    public virtual IAxis Axis { get; set; }

    public void Enable()
    {
        Axis.Enable = true;
    }
    public void Disable()
    {
        Axis.Enable = false;
    }
}

public class DeviceControl_A : DeviceControl
{
    public override IAxis Axis
    {
        get { return base.Axis as IAxis_A; }
        set { base.Axis = value as IAxis_A; }
    }
}

public class DeviceControl_B : DeviceControl
{
    public override IAxis Axis
    {
        get { return base.Axis as IAxis_B; }
        set { base.Axis = value as IAxis_B; }
    }
}

Axis representation (Interface and Explicit Classes): Basically they are intended to map the variables in the static class Mashine onto the properties of the different axes

public interface IAxis
{
    bool Enable { get; set; }
}

// These Interfaces are to ensure that Axis_A goes only into Device A
// and Axis_B only with device B
public interface IAxis_A : IAxis { }

public interface IAxis_B : IAxis { }

public class X_Axis_A : IAxis_A
{
    public bool Enable
    {
        get => Mashine.Enable_A_X;
        set => Mashine.Enable_A_X = value;
    }
}

public class Y_Axis_A : IAxis_A
{
    public bool Enable
    {
        get => Mashine.Enable_A_Y;
        set => Mashine.Enable_A_Y = value;
    }
}

public class X_Axis_B : IAxis_B
{
    public bool Enable
    {
        get => Mashine.Enable_B_X;
        set => Mashine.Enable_B_X = value;
    }
}

public class Y_Axis_B : IAxis_B
{
    public bool Enable
    {
        get => Mashine.Enable_B_Y;
        set => Mashine.Enable_B_Y = value;
    }
}

And this is the Control Class which provides the methods for the control of the mashine in dependency of the device and the appropriate axis:

public enum Device { A, B }

public enum Axis { X, Y }

public class Control
{
    public DeviceControl devControl;

    public void Disable(Device dev, Axis dim)
    {
        // initialize
        InitAxisAndDevice(dev, dim);
        devControl.Disable();
    }

    public void Enable(Device dev, Axis dim)
    {
        InitAxisAndDevice(dev, dim);
        devControl.Enable();
    }

    private void InitAxisAndDevice(Device dev, Axis dim)
    {
        switch (dev)
        {
            case Device.A:
                this.devControl = new DeviceControl_A();

                switch (dim)
                {
                    case Axis.X: this.devControl.Axis = new X_Axis_A(); break;
                    case Axis.Y: this.devControl.Axis = new Y_Axis_A(); break;
                    case Axis.Z: this.devControl.Axis = new Z_Axis_A(); break;
                }
                break;
            case Device.B:
                this.devControl = new DeviceControl_B();

                switch (dim)
                {
                    case Axis.X: this.devControl.Axis = new X_Axis_B(); break;
                    case Axis.Y: this.devControl.Axis = new Y_Axis_B(); break;
                    case Axis.Z: this.devControl.Axis = new Z_Axis_B(); break;
                }
                break;
        }
    }
}

Question 1

How can I avoid this double switch case in the InitAxisAndDevice method?

Question 2

Is there a better way to make sure that only A-type axes go along with device A ?

I have the strong feeling that I misunderstood something in the application of this pattern. Is there maybe a different approach/pattern which would be more suitable to solve this mapping of control problem?

Any help is greatly appriciated. Thank you in advance.

EDIT

Since I was too vague in explanation, here is a use case.
All axes have an almost identical set of variables that have to be set like:[enable(bool), position(double), start(bool)]

The point of abstraction is to have a single control class which can use one method Enable f.e. to enable any axis dependent on the type of device and on the type of axis.

I hope it became a little clearer

Body:
Consider the following code. The idea is to create an abstract representation of device axis, devices and machine as interface. Then use a factory to create concrete devices and axis for the (given not changeable) Mashine.

public static class Mashine
{
    public static bool Enable_B_X { get; set; }
    public static bool Enable_B_Y { get; set; }

    public static bool Enable_A_X { get; set; }
    public static bool Enable_A_Y { get; set; }
}

/// <summary>
/// Represents a single axis of a single device
/// </summary>
public interface IDeviceAxis
{
    void Enable();
    void Disable();
}
// general device that has two axis, but doesn't care about anything else
public interface IDevice
{
    IDeviceAxis X { get; }
    IDeviceAxis Y { get; }
}
// data model for an alternative Mashine representation
public interface IMachineModel
{
    IDevice A { get; }
    IDevice B { get; }
}

Usage:

public enum Device { A, B }

public enum Axis { X, Y }

// your control class
public class Control
{
    public IMachineModel devControl;

    public Control()
    {
        // MachineFactory see below
        devControl = MachineFactory.GetMachine();
    }

    public void Disable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Disable();
    }

    public void Enable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Enable();
    }

    private IDeviceAxis GetAxis(Device dev, Axis dim)
    {
        var device = GetDevice(dev);
        switch (dim)
        {
            case Axis.X:
                return device.X;
            case Axis.Y:
                return device.Y;
            default:
                throw new ArgumentException("Invalid Axis", "dim");
        }
    }
    private IDevice GetDevice(Device dev)
    {
        switch (dev)
        {
            case Device.A:
                return devControl.A;
            case Device.B:
                return devControl.B;
            default:
                throw new ArgumentException("Invalid Device", "dev");
        }
    }
}

The missing part: a concrete implementation of the interfaces and a factory to get the whole machine representation:

// concrete machine factory
public static class MachineFactory
{
    // factory for the whole Mashine wrapper
    public static IMachineModel GetMachine()
    {
        return new MachineModel
        {
            A = GetDeviceA(),
            B = GetDeviceB(),
        };
    }

    // factory methods specify the connection from the wrapper classes to the Mashine

    private static IDevice GetDeviceA()
    {
        return new MachineDevice(x => Mashine.Enable_A_X = x, y => Mashine.Enable_A_Y = y);
    }
    private static IDevice GetDeviceB()
    {
        return new MachineDevice(x => Mashine.Enable_B_X = x, y => Mashine.Enable_B_Y = y);
    }

    // concrete implementations can be used for the target Mashine

    private class MachineDeviceAxis : IDeviceAxis
    {
        Action<bool> _setterFunction;
        public MachineDeviceAxis(Action<bool> setter)
        {
            _setterFunction = setter;
        }

        public void Enable()
        {
            _setterFunction(true);
        }

        public void Disable()
        {
            _setterFunction(false);
        }
    }

    private class MachineDevice : IDevice
    {
        public MachineDevice(Action<bool> xSetter, Action<bool> ySetter)
        {
            X = new MachineDeviceAxis(xSetter);
            Y = new MachineDeviceAxis(ySetter);
        }
        public IDeviceAxis X { get; private set; }

        public IDeviceAxis Y { get; private set; }
    }

    private class MachineModel : IMachineModel
    {
        public IDevice A { get; set; }

        public IDevice B { get; set; }
    }
}

Regarding the usage of the machine abstraction, I think there is no real advantage of using enum Device and enum Axis. Compare the following codes:

// controllers
Control yourControl;
IMachineModel myMachineModel;
// usage
yourControl.Enable(Device.A, Axis.X);
myMachineModel.A.X.Enable();

The advantage of using Control here doesn't really improve the code if you ask me.

Edit regarding other parameters

Maybe the Enable and Disable is already over-engineered? How about some generic Set(value) instead:

public interface IAxisParameter<TParameter>
{
    void Set(TParameter value);
}

public interface IDeviceAxis
{
    IAxisParameter<bool> Enabled { get; }

    IAxisParameter<double> Position { get; }

    IAxisParameter<bool> Start { get; }
}

Usage:

public class Control
{
    public void Disable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Enabled.Set(false);
    }

    public void Enable(Device dev, Axis dim)
    {
        GetAxis(dev, dim).Enabled.Set(true);
    }

    // rest of the code as in the original answer above
}

Then change the internal machine implementation accordingly:

// inside factory

    // added implementation
    private class MachineParameter<TParam> : IAxisParameter<TParam>
    {
        Action<TParam> _setterFunction;
        public MachineParameter(Action<TParam> setter)
        {
            _setterFunction = setter;
        }
        public void Set(TParam value)
        {
            _setterFunction(value);
        }
    }

    // changed implementation
    private class MachineDeviceAxis : IDeviceAxis
    {
        public IAxisParameter<bool> Enabled { get; set; }

        public IAxisParameter<double> Position { get; set; }

        public IAxisParameter<bool> Start { get; set; }
    }

    // changed factory methods

    private static IDeviceAxis GetDeviceAxisA_X()
    {
        return new MachineDeviceAxis
        {
            Enabled = new MachineParameter<bool>(x => Mashine.Enable_A_X = x),
            Position = null, // TODO
            Start = null, // TODO
        };
    }
    private static IDeviceAxis GetDeviceAxisA_Y()
    {
        return new MachineDeviceAxis
        {
            Enabled = new MachineParameter<bool>(y => Mashine.Enable_A_Y = y),
            Position = null, // TODO
            Start = null, // TODO
        };
    }
    private static IDevice GetDeviceA()
    {
        return new MachineDevice
        {
            X = GetDeviceAxisA_X(),
            Y = GetDeviceAxisA_Y(),
        };
    }
    private static IDevice GetDeviceB()
    {
        // TODO same thing for device B
        return null;
    }

The concept should be clear... in the end you have to write some code for each property of the actual machine.
Maybe it would be a good idea to re-organize the parameter creation inside the factory to something like @Fildor did in his linked code example.

Edit: keeping the factory code more compact

Instead of bloating the factory with a separate method for each parameter, re-group the creation of parameter setters to create the setters for one parameter type in all devices in one place (eg. CreateEnabledParameterSetters):

// concrete machine factory
public static class MachineFactory
{
    // factory for the whole Mashine wrapper
    public static IMachineModel GetMachine()
    {
        var enabledSetters = CreateEnabledParameterSetters();
        return new MachineModel
        {
            A = GetDevice(enabledSetters, 0 /*A*/),
            B = GetDevice(enabledSetters, 1 /*B*/),
        };
    }

    // factory methods specify the connection from the wrapper classes to the Mashine

    private static Action<bool>[,] CreateEnabledParameterSetters()
    {
        return new Action<bool>[,]
        {
            { x => Mashine.Enable_A_X = x, x => Mashine.Enable_A_Y = x },
            { x => Mashine.Enable_B_X = x, x => Mashine.Enable_B_Y = x },
        };
    }
    private static IDeviceAxis GetDeviceAxis(Action<bool>[,] enabledSetters, int deviceIndex, int axisIndex)
    {
        return new MachineDeviceAxis
        {
            Enabled = new MachineParameter<bool>(enabledSetters[deviceIndex, axisIndex]),
            Position = null, // TODO
            Start = null, // TODO
        };
    }
    private static IDevice GetDevice(Action<bool>[,] enabledSetters, int deviceIndex)
    {
        return new MachineDevice
        {
            X = GetDeviceAxis(enabledSetters, deviceIndex, 0 /*X*/),
            Y = GetDeviceAxis(enabledSetters, deviceIndex, 1 /*Y*/),
        };
    }

// ...


问:
Flask LDAP3 Auth Blueprint fails with Uninitialized ASN.1 value
I'm trying to put together a flask blueprint for LDAP3 auth. If I use the same code as a standard flask app, everything works as expected, the bind is successful and the user auth also succeeds:

```<code>DEBUG:root:Validating LDAPLoginForm against LDAP
DEBUG:flask_ldap3_login:Opening connection with bind user 'XXXX@XXXX.COM'
DEBUG:flask_ldap3_login:Successfully bound to LDAP as 'XXXX@XXXX.COM' for search_bind method
DEBUG:flask_ldap3_login:Performing an LDAP Search using filter '(&(objectclass=person)(sAMAccountName=YYYY))', base 'ou=Users,ou=XXXX,dc=XXXX,dc=COM', and scope 'SUBTREE'
DEBUG:flask_ldap3_login:Opening connection with bind user 'CN=YYYY,OU=Admin Users,OU=Users,OU=XXXX,DC=XXXX,DC=COM'
DEBUG:flask_ldap3_login:Directly binding a connection to a server with user:'CN=YYYY,OU=Admin Users,OU=Users,OU=XXXX,DC=XXXX,DC=COM'
DEBUG:flask_ldap3_login:Authentication was successful for user 'YYYY'
</code>```

but as soon as I turn it into a blueprint:

```<code>DEBUG:root:Validating LDAPLoginForm against LDAP
DEBUG:flask_ldap3_login:Opening connection with bind user 'XXXX@XXXX.COM'
DEBUG:flask_ldap3_login:Destroying connection at <0x7f181f9ee2b0>
ERROR:flask_ldap3_login:Uninitialized ASN.1 value ("__len__" attribute looked up)
</code>```

My init.py is as follows

```<code>from flask import Flask

app = Flask(__name__)
app.config.from_object('config')

from app.ldauth.views import auth_blueprint
app.register_blueprint(auth_blueprint)
</code>```

And app/ldauth/views.py:

```<code>from flask import Flask, Blueprint, url_for
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager, login_user, UserMixin, current_user
from flask import render_template_string, render_template, redirect
from flask_ldap3_login.forms import LDAPLoginForm
from app import app

auth_blueprint = Blueprint('ldauth',__name__,template_folder='templates')

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager.
login_manager.login_view = "auth.login"
users = {}

class User(UserMixin):
    def __init__(self, dn, username, data):
        self.dn = dn
        self.username = username
        self.data = data

    def __repr__(self):
        return self.dn

    def get_id(self):
        return self.dn

@login_manager.user_loader
def load_user(id):
    if id in users:
        return users[id]
    return None

@ldap_manager.save_user
def save_user(dn, username, data, memberships):
    user = User(dn, username, data)
    users[dn] = user
    return user

@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    template = """
    {{ get_flashed_messages() }}
    {{ form.errors }}
    <form method="POST">
        <label>Username{{ form.username() }}</label>
        <label>Password{{ form.password() }}</label>
        {{ form.submit() }}
        {{ form.hidden_tag() }}
    </form>
    """

    # Instantiate a LDAPLoginForm which has a validator to check if the user
    # exists in LDAP.

    form = LDAPLoginForm()

    if form.validate_on_submit():
        # Successfully logged in, We can now access the saved user object
        # via form.user.
        login_user(form.user)  # Tell flask-login to log them in.

        # TODO: Validate next to ensure it is safe!
        return redirect(next)  # Send them home

    return render_template_string(template,form=form)
</code>```

pip freeze:

```<code>Babel==2.5.1
blinker==1.4
click==6.7
Flask==0.12.2
Flask-BabelEx==0.9.3
flask-ldap3-login==0.9.13
Flask-Login==0.4.0
Flask-Mail==0.9.1
Flask-Principal==0.4.0
Flask-Security==3.0.0
Flask-SQLAlchemy==2.3.2
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.10
ldap3==2.3
MarkupSafe==1.0
passlib==1.7.1
pkg-resources==0.0.0
pyasn1==0.3.7
pyasn1-modules==0.1.5
python3-ldap==0.9.8.4
pytz==2017.3
speaklater==1.3
SQLAlchemy==1.1.15
Werkzeug==0.12.2
WTForms==2.1
</code>```

I'm clearly missing something here, any ideas?

答: Turns out this was some issue with the virtualenv. Created a new virtualenv this morning and moved the code into it, works as expected.</p>

Body:
I'm trying to put together a flask blueprint for LDAP3 auth. If I use the same code as a standard flask app, everything works as expected, the bind is successful and the user auth also succeeds:

DEBUG:root:Validating LDAPLoginForm against LDAP
DEBUG:flask_ldap3_login:Opening connection with bind user 'XXXX@XXXX.COM'
DEBUG:flask_ldap3_login:Successfully bound to LDAP as 'XXXX@XXXX.COM' for search_bind method
DEBUG:flask_ldap3_login:Performing an LDAP Search using filter '(&(objectclass=person)(sAMAccountName=YYYY))', base 'ou=Users,ou=XXXX,dc=XXXX,dc=COM', and scope 'SUBTREE'
DEBUG:flask_ldap3_login:Opening connection with bind user 'CN=YYYY,OU=Admin Users,OU=Users,OU=XXXX,DC=XXXX,DC=COM'
DEBUG:flask_ldap3_login:Directly binding a connection to a server with user:'CN=YYYY,OU=Admin Users,OU=Users,OU=XXXX,DC=XXXX,DC=COM'
DEBUG:flask_ldap3_login:Authentication was successful for user 'YYYY'

but as soon as I turn it into a blueprint:

DEBUG:root:Validating LDAPLoginForm against LDAP
DEBUG:flask_ldap3_login:Opening connection with bind user 'XXXX@XXXX.COM'
DEBUG:flask_ldap3_login:Destroying connection at <0x7f181f9ee2b0>
ERROR:flask_ldap3_login:Uninitialized ASN.1 value ("__len__" attribute looked up)

My init.py is as follows

from flask import Flask

app = Flask(__name__)
app.config.from_object('config')

from app.ldauth.views import auth_blueprint
app.register_blueprint(auth_blueprint)

And app/ldauth/views.py:

from flask import Flask, Blueprint, url_for
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager, login_user, UserMixin, current_user
from flask import render_template_string, render_template, redirect
from flask_ldap3_login.forms import LDAPLoginForm
from app import app

auth_blueprint = Blueprint('ldauth',__name__,template_folder='templates')

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager.
login_manager.login_view = "auth.login"
users = {}

class User(UserMixin):
    def __init__(self, dn, username, data):
        self.dn = dn
        self.username = username
        self.data = data

    def __repr__(self):
        return self.dn

    def get_id(self):
        return self.dn

@login_manager.user_loader
def load_user(id):
    if id in users:
        return users[id]
    return None

@ldap_manager.save_user
def save_user(dn, username, data, memberships):
    user = User(dn, username, data)
    users[dn] = user
    return user

@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    template = """
    {{ get_flashed_messages() }}
    {{ form.errors }}
    <form method="POST">
        Username{{ form.username() }}
        Password{{ form.password() }}
        {{ form.submit() }}
        {{ form.hidden_tag() }}
    </form>
    """

    # Instantiate a LDAPLoginForm which has a validator to check if the user
    # exists in LDAP.

    form = LDAPLoginForm()

    if form.validate_on_submit():
        # Successfully logged in, We can now access the saved user object
        # via form.user.
        login_user(form.user)  # Tell flask-login to log them in.

        # TODO: Validate next to ensure it is safe!
        return redirect(next)  # Send them home

    return render_template_string(template,form=form)

pip freeze:

Babel==2.5.1
blinker==1.4
click==6.7
Flask==0.12.2
Flask-BabelEx==0.9.3
flask-ldap3-login==0.9.13
Flask-Login==0.4.0
Flask-Mail==0.9.1
Flask-Principal==0.4.0
Flask-Security==3.0.0
Flask-SQLAlchemy==2.3.2
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.10
ldap3==2.3
MarkupSafe==1.0
passlib==1.7.1
pkg-resources==0.0.0
pyasn1==0.3.7
pyasn1-modules==0.1.5
python3-ldap==0.9.8.4
pytz==2017.3
speaklater==1.3
SQLAlchemy==1.1.15
Werkzeug==0.12.2
WTForms==2.1

I'm clearly missing something here, any ideas?