问:
RuntimeError: No MovieWriters available in Matplotlib animation
The problem I am getting is in code similar to this example:
https://matplotlib.org/examples/animation/basic_example_writer.html

The error:

RuntimeError: No MovieWriters available occurs at Writer = animation.writers['ffmpeg'] in the example above.

I am using mac, I have installed ffmpeg using brew, and even installed it with conda even though I am not using anaconda for this particular code.

I am positive that it is installed - I have used it in terminal to change files but it is not working within the program.

Thanks!

答:
I have found '/usr/local/bin/ffmpeg' not exists in my computer. so i try this:

```<code>import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.writers['pillow']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
</code>```

and it works for me

Body:
I have found '/usr/local/bin/ffmpeg' not exists in my computer. so i try this:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.writers['pillow']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

and it works for me


来源: stackexchange

问:
Render two items (images) side by side in a list view in react native
I'm trying to design something like the below screenshot in react native.
Please note each tile is a Product element fetched from the backend.

But I'm unable to do this using a ListView and its renderRow method which is denying me to use any kind of InfiniteScroll Components.

Currently I'm running a loop with 2 elements at a time and rendering 2 elements inside a scroll view. Below is my Code to explain better.

```<code>render() {
    var elem = [];
    for(var i = 0; i < this.state.products.length; i+=2) {
      var prod = this.state.products[i];
      var prod2 = this.state.products[i + 1];
      elem.push(
        <View style={styles.view} key={i} >
          <ProductTile onPressAction={this._pdpPage} prod={prod} index={i} />
          <ProductTile onPressAction={this._pdpPage} prod={prod2} index={i + 1} />
        </View>
      );
    }
    return (
        <ScrollView>
          {elem}
        </ScrollView>
    )
}
</code>```

And then based on the index prop I'm aligning the elements on left or right.
My View style looks like below:

```<code>view: {
  flex: 1,
  flexDirection: 'row',
},
</code>```

Please suggest a better way to do this.

Thanks in advance.

答:
Using https://facebook.github.io/react-native/docs/flexbox as a baseline I've been able to easily do this in my projects by adding flexWrap: 'wrap' as below.

```<code>        `<View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
            <View style={{height: 150, width: '50%', backgroundColor: 'powderblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'skyblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'steelblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'powderblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'skyblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'steelblue'}} />
        </View>`
</code>```

So in your project

```<code>         render() {
            var elem = [];
            for(var i = 0; i < this.state.products.length; i+=2) {
            var prod = this.state.products[i];
            var prod2 = this.state.products[i + 1];
            elem.push(
                <View style={styles.view} key={i} >
                <ProductTile onPressAction={this._pdpPage} prod={prod} index={i} />
                <ProductTile onPressAction={this._pdpPage} prod={prod2} index={i + 1} />
                </View>
            );
            }

        return (
            <ScrollView>
                <View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
                    {elem}
                </View>
            </ScrollView>
            )
        }

        view: {
          width: '50%',
          height: 150,
        },
</code>```

As far as height goes, it needs to be set but may work with 'auto' if you don't have a set height.  I didn't test otherwise.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to design something like the below screenshot in react native.
Please note each tile is a Product element fetched from the backend.

But I'm unable to do this using a ListView and its renderRow method which is denying me to use any kind of InfiniteScroll Components.

Currently I'm running a loop with 2 elements at a time and rendering 2 elements inside a scroll view. Below is my Code to explain better.

render() {
    var elem = [];
    for(var i = 0; i < this.state.products.length; i+=2) {
      var prod = this.state.products[i];
      var prod2 = this.state.products[i + 1];
      elem.push(
        <View style={styles.view} key={i} >
          <ProductTile onPressAction={this._pdpPage} prod={prod} index={i} />
          <ProductTile onPressAction={this._pdpPage} prod={prod2} index={i + 1} />
        </View>
      );
    }
    return (
        <ScrollView>
          {elem}
        </ScrollView>
    )
}

And then based on the index prop I'm aligning the elements on left or right.
My View style looks like below:

view: {
  flex: 1,
  flexDirection: 'row',
},

Please suggest a better way to do this.

Thanks in advance.

Body:
Using https://facebook.github.io/react-native/docs/flexbox as a baseline I've been able to easily do this in my projects by adding flexWrap: 'wrap' as below.

        `<View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
            <View style={{height: 150, width: '50%', backgroundColor: 'powderblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'skyblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'steelblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'powderblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'skyblue'}} />
            <View style={{height: 150, width: '50%', backgroundColor: 'steelblue'}} />
        </View>`

So in your project

         render() {
            var elem = [];
            for(var i = 0; i < this.state.products.length; i+=2) {
            var prod = this.state.products[i];
            var prod2 = this.state.products[i + 1];
            elem.push(
                <View style={styles.view} key={i} >
                <ProductTile onPressAction={this._pdpPage} prod={prod} index={i} />
                <ProductTile onPressAction={this._pdpPage} prod={prod2} index={i + 1} />
                </View>
            );
            }

        return (
            <ScrollView>
                <View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
                    {elem}
                </View>
            </ScrollView>
            )
        }

        view: {
          width: '50%',
          height: 150,
        },

As far as height goes, it needs to be set but may work with 'auto' if you don't have a set height.  I didn't test otherwise.

ContentLicense: CC BY-SA 4.0


问:
How to properly concatenate string literal to string variable and reassign to variable
I'm trying to concatenate a string literal to a string variable and reassign this value to the same variable.

I've tried the += operator and something like

string = string + "another string"
```

<p>but that doesn't work.</p>

<p>Here is my code.</p>

<pre class="lang-py prettyprint-override"><code>userWord = input("Enter a word: ").upper()

# Prompt the user to enter a word and assign it to the userWord variable

for letter in userWord:
    # Loops through userWord and concatenates consonants to wordWithoutVowels and skips vowels
    if letter == "A" or letter == "E" or letter == "I" or letter == "O" or letter == "U":
        continue
    wordWithoutVowels += userWord # NameError: name "wordWithoutVowels" is not defined

print(wordWithoutVowels)
</code>```

答:
Firstly, I think you intended to do wordWithoutVowels += letter, not the entire userWord. Secondly, that expression is the same as wordWithoutVowels = wordWithoutVowels + userWord, which means that wordWithoutVowels needs to be defined before it.

Simply add the following before the for loop

```<code>wordWithoutVowels = ''
</code>```

Edit:

As @DeveshKumarSingh mentioned, you can further improve the loop by using the following if condition instead of using continue

```<code>if letter not in ['A','E','I','O','U']:
    wordWithoutVowels += letter
</code>```

Body:
I'm trying to concatenate a string literal to a string variable and reassign this value to the same variable.

I've tried the += operator and something like

string = string + "another string"

but that doesn't work.

Here is my code.

userWord = input("Enter a word: ").upper()

# Prompt the user to enter a word and assign it to the userWord variable

for letter in userWord:
    # Loops through userWord and concatenates consonants to wordWithoutVowels and skips vowels
    if letter == "A" or letter == "E" or letter == "I" or letter == "O" or letter == "U":
        continue
    wordWithoutVowels += userWord # NameError: name "wordWithoutVowels" is not defined

print(wordWithoutVowels)

Body:
Firstly, I think you intended to do wordWithoutVowels += letter, not the entire userWord. Secondly, that expression is the same as wordWithoutVowels = wordWithoutVowels + userWord, which means that wordWithoutVowels needs to be defined before it.

Simply add the following before the for loop

wordWithoutVowels = ''

Edit:

As @DeveshKumarSingh mentioned, you can further improve the loop by using the following if condition instead of using continue

if letter not in ['A','E','I','O','U']:
    wordWithoutVowels += letter


问:
Using svg in btimap
This is my splash screen background and this works fine

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/background_splash_screen"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_logo" />
    </item>

</layer-list>
</code>```

But whenever I replaced

```<code> android:src="@drawable/ic_logo" />
</code>```

with

```<code> android:src="@drawable/some svg image" />
</code>```

it gets me error
How can I use svg in src bitmap?

thanks in advance.

答:
Hi Android don't support svg format directly. You can import the svg to the vectorial format supported by Android platform. You can use the Android Studio's Asset Studio plugin:

You can import the asset from svg, you can right clicking over the drawable source directory and chose the new -> Vector Asset  and in this windows with tittle : Asset Studio you can chose the Asset Type: Local ( SVG;PSD )

Warning: Not all standards features of SVG are supported in Android vector language:

You can check the section: support and restrictions for SVG files in this official  page:

https://developer.android.com/studio/write/vector-asset-studio?

And in the xml you can add the vector asset without the bitmap tag:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/background_splash_screen"/>

    <item
        android:src="@drawable/ic_vector_logo"/>

</layer-list>

```

Title: Using svg in btimap

Body:
This is my splash screen background and this works fine

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/background_splash_screen"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_logo" />
    </item>

</layer-list>

But whenever I replaced

 android:src="@drawable/ic_logo" />

with

 android:src="@drawable/some svg image" />

it gets me error
How can I use svg in src bitmap?

thanks in advance.


问:
Compare two equal arrays but isequal() function return 0 in Matlab
I have two videos and convert them to arrays in Matlab. Then convert them to three separate arrays for each color as follows:

```<code> v = VideoReader('d:\movie_1.avi');
 while hasFrame(v)
       A = readFrame(v);
       r = A(:,:,1);
       g = A(:,:,2);
       b = A(:,:,3);
 end;

v_2 = VideoReader('d:\movie_2.avi');
while hasFrame(v_2)
   A_2 = readFrame(v_2);
   r_2 = A_2(:,:,1);
   g_2 = A_2(:,:,2);
   b_2 = A_2(:,:,3);
end;
</code>```

Then I compared them by isequal function:

```<code>comp_r = isequal(r,r_2)
comp_g = isequal(g,g_2)
comp_b = isequal(b,b_2)
</code>```

All three results are zero that means false:

```<code>comp_r =
     0

comp_g =
     0

comp_b =

     0
</code>```

But when I took differences between them I didn't get anything:

```<code>diff_r = setdiff(r,r_2)
diff_g = setdiff(g,g_2)
diff_b = setdiff(b,b_2)
</code>```

and the result was:

```<code>diff_r =
   Empty matrix: 0-by-1

diff_g =
   Empty matrix: 0-by-1

diff_b =
   Empty matrix: 0-by-1
</code>```

I can't understand the behavior of this test. The isequal function return false but setdiff function doesn't return any differences.

答:
According to setdiff it is possible for isequal to return 0 and setdiff to return empty.

C = setdiff(A,B) returns the data in A that is not in B, with no repetitions. C is in sorted order.

Example:

setdiff([1,2,3], [3,2,1]) returns empty

isequal([1,2,3], [3,2,1]) returns 0

You may try the following for finding the difference:

```<code>r_max_abs_diff = max(abs(double(r(:)) - double(r_2(:))));
disp(['r_max_abs_diff = ', num2str(r_max_abs_diff)]);

%Display the differences of r and r_2 (with false colors):
figure;imagesc(double(r) - double(r_2));impixelinfo;title('r - r\_2');
</code>```

Body:
I have two videos and convert them to arrays in Matlab. Then convert them to three separate arrays for each color as follows:

 v = VideoReader('d:\movie_1.avi');
 while hasFrame(v)
       A = readFrame(v);
       r = A(:,:,1);
       g = A(:,:,2);
       b = A(:,:,3);
 end;

v_2 = VideoReader('d:\movie_2.avi');
while hasFrame(v_2)
   A_2 = readFrame(v_2);
   r_2 = A_2(:,:,1);
   g_2 = A_2(:,:,2);
   b_2 = A_2(:,:,3);
end;

Then I compared them by isequal function:

comp_r = isequal(r,r_2)
comp_g = isequal(g,g_2)
comp_b = isequal(b,b_2)

All three results are zero that means false:

comp_r =
     0

comp_g =
     0

comp_b =

     0

But when I took differences between them I didn't get anything:

diff_r = setdiff(r,r_2)
diff_g = setdiff(g,g_2)
diff_b = setdiff(b,b_2)

and the result was:

diff_r =
   Empty matrix: 0-by-1

diff_g =
   Empty matrix: 0-by-1

diff_b =
   Empty matrix: 0-by-1

I can't understand the behavior of this test. The isequal function return false but setdiff function doesn't return any differences.

Body:
According to setdiff it is possible for isequal to return 0 and setdiff to return empty.

C = setdiff(A,B) returns the data in A that is not in B, with no repetitions. C is in sorted order.

Example:

setdiff([1,2,3], [3,2,1]) returns empty

isequal([1,2,3], [3,2,1]) returns 0

You may try the following for finding the difference:

r_max_abs_diff = max(abs(double(r(:)) - double(r_2(:))));
disp(['r_max_abs_diff = ', num2str(r_max_abs_diff)]);

%Display the differences of r and r_2 (with false colors):
figure;imagesc(double(r) - double(r_2));impixelinfo;title('r - r\_2');


问:
How To Use the SHGetKnownFolderPath Function from Vb6
I am currently adding Windows 7 support to an existing Vb6 project and I have ran into a problem with locating special folder paths using SHGetFolderPath which is not supported on Windows versions starting with Vista.  I know I should use SHGetKnownFolderPath but I cannot  find a good example implementing using SHGetKnownFolderPath API call in VB6.</p>

答:
Using SHGetFolderPath from shfolder.dll just works fine under Vista and Win7:

```<code>Private Declare Function SHGetFolderPath Lib "shfolder" Alias "SHGetFolderPathA" (ByVal hWnd As Long, ByVal csidl As Long, ByVal hToken As Long, ByVal dwFlags As Long, ByVal szPath As String) As Long
</code>```

Then declare an enum on those CSIDL_Xxx constants:

```<code>Public Function GetSpecialFolder(ByVal eType As MySpecialFolderType) As String
    GetSpecialFolder = String(1000, 0)
    Call SHGetFolderPath(0, eType, 0, 0, GetSpecialFolder)
    GetSpecialFolder = Left$(GetSpecialFolder, InStr(GetSpecialFolder, Chr$(0)) - 1)
End Function
</code>```

Body:
Using SHGetFolderPath from shfolder.dll just works fine under Vista and Win7:

Private Declare Function SHGetFolderPath Lib "shfolder" Alias "SHGetFolderPathA" (ByVal hWnd As Long, ByVal csidl As Long, ByVal hToken As Long, ByVal dwFlags As Long, ByVal szPath As String) As Long

Then declare an enum on those CSIDL_Xxx constants:

Public Function GetSpecialFolder(ByVal eType As MySpecialFolderType) As String
    GetSpecialFolder = String(1000, 0)
    Call SHGetFolderPath(0, eType, 0, 0, GetSpecialFolder)
    GetSpecialFolder = Left$(GetSpecialFolder, InStr(GetSpecialFolder, Chr$(0)) - 1)
End Function


问:
How to render and return plot to view in flask?
How do I render a plot to the view in flask?

devices.py:

```<code>@devices_blueprint.route('/devices/test/')

def test():
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plot_url = plt.plot(x,y)
    return render_template('devices/test.html', plot_url=plot_url)
</code>```

test.html

```<code><div class="container">
      <h2>Image</h2>
      <img src= {{ resized_img_src('plot_url') }} class="img-rounded" alt="aqui" width="304" height="236">
    </div>
</code>```

Im trying to use seaborn with this, but even with matplolib I couldn’t get any result.

Note: I don’t want to save image and load it after.

答:
I was getting an "Assetion failed" error trying to send the plot using anaconda(python 2.7) on macOS. I managed to fix the bug by explicitly closing plt before returning. Thanks for this piece of code!</p>

```<code>#Imports for Python 2.7.16
from cStringIO import StringIO
import base64

@devices_blueprint.route('/devices/test/')
def test():
    img = StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)
</code>```

Body:
How do I render a plot to the view in flask?

devices.py:

@devices_blueprint.route('/devices/test/')

def test():
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]
    plot_url = plt.plot(x,y)
    return render_template('devices/test.html', plot_url=plot_url)

test.html

Image

Im trying to use seaborn with this, but even with matplolib I couldn’t get any result.

Note: I don’t want to save image and load it after.

Body:
I was getting an "Assetion failed" error trying to send the plot using anaconda(python 2.7) on macOS. I managed to fix the bug by explicitly closing plt before returning. Thanks for this piece of code!

#Imports for Python 2.7.16
from cStringIO import StringIO
import base64

@devices_blueprint.route('/devices/test/')
def test():
    img = StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    plt.close()
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)


问:
Get the name of an overloaded function passed as an argument at run-time
Assume all includes are defined, please go through the code structure defined below.

```<code>std::unordered_map<std::string, void*> callbackReg;

class A
{
public:
    void foo(int a)
    {
        //impl
    }
    void foo(int a, int b)
    {
        //impl
    }
    void foo(int a, double d)
    {
        //impl
    }

};

template<class Instance , typename Function>
void register_func(Instance& obj, Function func)
{
    /* have to store function name as the key and
     - pointer to raw member function pointer as the value,
     - in callbackReg Map */
    // ---> Point B
}

int main(int argc, const char * argv[])
{
    A a;
    register_evt(a, &A::foo); //---> point A
    system("Pause");
}
</code>```

Problems and Discussions

@ Point A how to resolve function name scope resolution issue which means how to call a overloaded function/pointer to such function ? without inline static cast since it makes bit ugly and messy.

@ Point B assume we have fixed overload name resolutuin issue and now we have to store member funtion name and its pointer value in callbackReg map.

I know may this could bad cumbersome approach but, is this feasible in C++? or else is there any way to store raw memeber funtion pointers with some other key-value in order to use them as callbacks.Since at debug time,debugger already knows what is the function name passed as register_func template fucntion argument.
Please look at the image attached.

Therefore,simply, how can we implement callback register/unregister scenario using only raw member/non-member function pointers?

(Please if the solution or methodology is a cross-platform approach that would be grateful, at least Win32 based)

答:
You can use boost backtrace:

boost::stacktrace::frame provides information about functions. You may construct that class from function pointer and get the function name at runtime

Body:
Assume all includes are defined, please go through the code structure defined below.

std::unordered_map<std::string, void*> callbackReg;

class A
{
public:
    void foo(int a)
    {
        //impl
    }
    void foo(int a, int b)
    {
        //impl
    }
    void foo(int a, double d)
    {
        //impl
    }

};

template<class Instance , typename Function>
void register_func(Instance& obj, Function func)
{
    /* have to store function name as the key and
     - pointer to raw member function pointer as the value,
     - in callbackReg Map */
    // ---> Point B
}

int main(int argc, const char * argv[])
{
    A a;
    register_evt(a, &A::foo); //---> point A
    system("Pause");
}

Problems and Discussions

@ Point A how to resolve function name scope resolution issue which means how to call a overloaded function/pointer to such function ? without inline static cast since it makes bit ugly and messy.

@ Point B assume we have fixed overload name resolutuin issue and now we have to store member funtion name and its pointer value in callbackReg map.

I know may this could bad cumbersome approach but, is this feasible in C++? or else is there any way to store raw memeber funtion pointers with some other key-value in order to use them as callbacks.Since at debug time,debugger already knows what is the function name passed as register_func template fucntion argument.
Please look at the image attached.

Therefore,simply, how can we implement callback register/unregister scenario using only raw member/non-member function pointers?

(Please if the solution or methodology is a cross-platform approach that would be grateful, at least Win32 based)


问:
Is it possible to change the thickness of the slider in wxPython?
I have a slider with 2 states that will be used as a switch in a GUI on a touchscreen. I want it to be thicker. The image below shows how it looks. It is a magnified version. In reality, it is ~ 50 pixels tall. I need ~200.

```<code>self.sld = wx.Slider(self.panel, value = 0, minValue = 0, maxValue = 1, size = (300,50),style = wx.SL_HORIZONTAL|wx.SL_LABELS|wx.SL_AUTOTICKS)
</code>```

答: I have checked the documentation for wx.Slider (documentation wx.Python 4.0.7) and there is nothing mentioned about the thickness of the slider.</p>

Body:
I have a slider with 2 states that will be used as a switch in a GUI on a touchscreen. I want it to be thicker. The image below shows how it looks. It is a magnified version. In reality, it is ~ 50 pixels tall. I need ~200.

self.sld = wx.Slider(self.panel, value = 0, minValue = 0, maxValue = 1, size = (300,50),style = wx.SL_HORIZONTAL|wx.SL_LABELS|wx.SL_AUTOTICKS)


问:
How to compare parts of different lengths in the same string?
I need to create a function my_fun that given a string msg made only of the two characters 'o' and 'x', returns the largest n for which there exist n equispaced 'x' at distance n from each other in the string msg.

```<code>print ( my_fun('xox') )
</code>```

output: 2, since there are two x at distance x(2)

```<code>print ( my_fun('ooxoxxxoooxxxoxo') )
</code>```

output: 4, since there are four x at distance x(4)

I'm facing some troubles figuring out how to nest two for loops to analyze the string, storing the numbers representing the distance and then returning the max distance (which is the largest distance).

Note: I can't import any module

答:
Not the smartest way, but it won't have nested for-loop.

try to get the highest n,
and get the positions, if there exists positions that are next to each other, then subtract the repeated x from the total.

```<code>def my_func(msg):

length_dict = {}
pos_dict = {}

split_x = msg.split('x')

for ind, val in enumerate(split_x):

    if val != '' and ind != len(split_x) -1 and ind != 0:
        length_dict[val] = length_dict.get(val, 0) + 1

        if val not in pos_dict.keys():
            pos_dict[val] = [ind]
        else:
            pos_dict[val].append(ind)

# sort dictionary
sorted_dict = sorted(length_dict.items(), key=lambda x: x[1], reverse=True)

maxO = 0

for key, val in length_dict.items():
    if val > maxO:
        maxO = val

# should have same length
topPos = [ pos_dict[i[0]] for i in sorted_dict if i[1] == maxO]
unpack = sorted([j for i in topPos for j in i])

prev = unpack[0]
countgap = 0
for i, v in enumerate(unpack):
    if i != 0:
        if v - prev == 1:
            countgap += 1

    prev = v

count_x = 2*len(unpack) - countgap

return count_x
</code>```

some of the outcome:

```<code>msg1 = 'xox' # 2 x
msg2 = 'ooxoxxxoooxxxoooxoxo' # 7 x
msg3 = 'xooxoooxxoooxoox' # 6 x
msg4 = 'xooxxoox' # 4 x
msg5 = 'xooxoox' # 3 x
msg6 = 'oxoxxo' # 2 x
msg7 = 'oxxoxoxox' # 4 x
msg8 = 'oxoxoxox' # 4 x
msg9 = 'ooxoxxxoooxxxoxo' # 4x
</code>```

Body:
I need to create a function my_fun that given a string msg made only of the two characters 'o' and 'x', returns the largest n for which there exist n equispaced 'x' at distance n from each other in the string msg.

print ( my_fun('xox') )

output: 2, since there are two x at distance x(2)

print ( my_fun('ooxoxxxoooxxxoxo') )

output: 4, since there are four x at distance x(4)

I'm facing some troubles figuring out how to nest two for loops to analyze the string, storing the numbers representing the distance and then returning the max distance (which is the largest distance).

Note: I can't import any module

Body:
Not the smartest way, but it won't have nested for-loop.

try to get the highest n,
and get the positions, if there exists positions that are next to each other, then subtract the repeated x from the total.

def my_func(msg):

length_dict = {}
pos_dict = {}

split_x = msg.split('x')

for ind, val in enumerate(split_x):

    if val != '' and ind != len(split_x) -1 and ind != 0:
        length_dict[val] = length_dict.get(val, 0) + 1

        if val not in pos_dict.keys():
            pos_dict[val] = [ind]
        else:
            pos_dict[val].append(ind)

# sort dictionary
sorted_dict = sorted(length_dict.items(), key=lambda x: x[1], reverse=True)

maxO = 0

for key, val in length_dict.items():
    if val > maxO:
        maxO = val

# should have same length
topPos = [ pos_dict[i[0]] for i in sorted_dict if i[1] == maxO]
unpack = sorted([j for i in topPos for j in i])

prev = unpack[0]
countgap = 0
for i, v in enumerate(unpack):
    if i != 0:
        if v - prev == 1:
            countgap += 1

    prev = v

count_x = 2*len(unpack) - countgap

return count_x

some of the outcome:

msg1 = 'xox' # 2 x
msg2 = 'ooxoxxxoooxxxoooxoxo' # 7 x
msg3 = 'xooxoooxxoooxoox' # 6 x
msg4 = 'xooxxoox' # 4 x
msg5 = 'xooxoox' # 3 x
msg6 = 'oxoxxo' # 2 x
msg7 = 'oxxoxoxox' # 4 x
msg8 = 'oxoxoxox' # 4 x
msg9 = 'ooxoxxxoooxxxoxo' # 4x


问:
PrimeNg expanded row full width of container
I have a PrimeNg table with an expanded row for every item in the table.

The expanded row should contain a table with data

here is the code of the template.

```<code><div class="primeng-datatable-container" [busyIf]="primengTableHelper.isLoading">
<div class="col-12 text-right mb-2">
    <button class="btn btn-primary" (click)="createOrEditLandlordPropertyPortfolioModal.show()">
        <i class="fa fa-plus"></i> {{ l('Add') }}
    </button>
</div>
<p-table
    #dataTable
    (onLazyLoad)="getLandlordPropertyPortfolios($event)"
    [value]="primengTableHelper.records"
    rows="{{ primengTableHelper.defaultRecordsCountPerPage }}"
    [paginator]="false"
    [lazy]="true"
    dataKey="id"
    [scrollable]="true"
    ScrollWidth="100%"
    [responsive]="primengTableHelper.isResponsive"
    [resizableColumns]="primengTableHelper.resizableColumns"
>
    <ng-template pTemplate="header">
        <tr>
            <th style="width: 20px"></th>
            <th style="width: 130px">
                {{ l('Actions') }}
            </th>
            <th style="width: 130px" pSortableColumn="id">
                {{ l('Id') }}
                <p-sortIcon field="id"></p-sortIcon>
            </th>
            <th style="width: 150px" pSortableColumn="name">
                {{ l('Name') }}
                <p-sortIcon field="name"></p-sortIcon>
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-record let-expanded="expanded">
        <tr>
            <td style="width: 10px">
                <a [pRowToggler]="record">
                    <i [ngClass]="expanded ? 'pi pi-chevron-down' : 'pi pi-chevron-right'"></i>
                </a>
            </td>
            <td
                style="width: 130px"
                [hidden]="
                    !isGrantedAny(
                        'Pages.LandlordPropertyPortfolios.Edit',
                        'Pages.LandlordPropertyPortfolios.Delete'
                    )
                "
            >
                <div class="btn-group dropdown" dropdown container="body">
                    <button class="dropdown-toggle btn btn-sm btn-primary" dropdownToggle>
                        <i class="fa fa-cog"></i><span class="caret"></span> {{ l('Actions') }}
                    </button>
                    <ul class="dropdown-menu" *dropdownMenu>
                        <li>
                            <a
                                href="javascript:;"
                                (click)="createOrEditLandlordPropertyPortfolioModal.show(record.id)"
                                >{{ l('Edit') }}</a
                            >
                        </li>
                        <li>
                            <a href="javascript:;" (click)="deleteReasonModal.show(record)">{{ l('Delete') }}</a>
                        </li>
                    </ul>
                </div>
            </td>
            <td style="width: 130px">
                <span class="ui-column-title"> {{ l('Id') }}</span>
                {{ record.id }}
            </td>
            <td style="width: 150px">
                <span class="ui-column-title"> {{ l('Name') }}</span>
                {{ record.name }}
            </td>
        </tr>
    </ng-template>

    <!--Nested table for property portfolios-->
    <ng-template pTemplate="rowexpansion">
        <div class="ui-g ui-fluid" style="font-size:16px;padding:20px">
            <p-table
                #nestedTable
                [value]="primengTableHelper.records"
                rows="{{ primengTableHelper.defaultRecordsCountPerPage }}"
                [paginator]="false"
                [lazy]="true"
                dataKey="id"
                [scrollable]="true"
                ScrollWidth="100%"
                [responsive]="primengTableHelper.isResponsive"
                [resizableColumns]="primengTableHelper.resizableColumns"
            >
                <ng-template pTemplate="header">
                    <tr>

                        <th style="width: 130px" pSortableColumn="id">
                            {{ l('PropertyAddress') }}
                            <p-sortIcon field="id"></p-sortIcon>
                        </th>
                        <th style="width: 150px" pSortableColumn="name">
                            {{ l('PostalCode') }}
                            <p-sortIcon field="name"></p-sortIcon>
                        </th>
                        <th style="width: 150px" pSortableColumn="name">
                            {{ l('AgentName') }}
                            <p-sortIcon field="name"></p-sortIcon>
                        </th>
                        <th style="width: 150px" pSortableColumn="name">
                            {{ l('Tenant') }}
                            <p-sortIcon field="name"></p-sortIcon>
                        </th>
                        <th style="width: 150px" pSortableColumn="name">
                            {{ l('Status') }}
                            <p-sortIcon field="name"></p-sortIcon>
                        </th>
                    </tr>
                </ng-template>
                <ng-template pTemplate="body" let-record let-expanded="expanded">
                    <tr>
                        <td style="width: 130px">
                            {{ record.properties.id}}
                        </td>
                        <td style="width: 150px">
                            {{ record.properties.postalCode }}
                        </td>
                        <td style="width: 150px">
                            {{ record.properties.agentName }}
                        </td>
                        <td style="width: 150px">
                            {{ record.properties.tenant }}
                        </td>
                        <td style="width: 150px">
                            {{ record.properties.status }}
                        </td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    </ng-template>
</p-table>
</code>```

My problem is that p-table, that in an expanded row, have not 100% width of the container

Here is how it's like

How I can make it fit 100% width of parent container?

答:
I was able to solve it like this
Using colspan="4" attribute

Here is the code of answer

```<code> <ng-template let-rowData pTemplate="rowexpansion" let-columns="columns">
        <tr>
            <td colspan="4">
                <p-table
                    #nestedTable
                    [value]="rowData.properties"
                    [tableStyle]="{ 'width.%': 100 }"
                    [scrollable]="true"
                    ScrollWidth="100%"
                >
                    <ng-template pTemplate="header">
                        <tr>
                            <th style="width: 130px" pSortableColumn="propertyAddress">
                                {{ l('PropertyAddress') }}
                                <p-sortIcon field="propertyAddress"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="postalCode">
                                {{ l('PostalCode') }}
                                <p-sortIcon field="postalCode"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="agentName">
                                {{ l('AgentName') }}
                                <p-sortIcon field="agentName"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="tenant">
                                {{ l('Tenant') }}
                                <p-sortIcon field="tenant"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="status">
                                {{ l('Status') }}
                                <p-sortIcon field="status"></p-sortIcon>
                            </th>
                        </tr>
                    </ng-template>
                    <ng-template pTemplate="body" let-record let-expanded="expanded">
                        <tr>
                            <td style="width: 130px">
                                {{ record.propertyAddress }}
                            </td>
                            <td style="width: 150px">
                                {{ record.postalCode }}
                            </td>
                            <td style="width: 150px">
                                {{ record.agentName }}
                            </td>
                            <td style="width: 150px">
                                {{ record.tenant }}
                            </td>
                            <td style="width: 150px">
                                {{ record.status }}
                            </td>
                        </tr>
                    </ng-template>
                </p-table>
            </td>
        </tr>
    </ng-template>
</code>```

Body:
I have a PrimeNg table with an expanded row for every item in the table.

The expanded row should contain a table with data

here is the code of the template.

    <button class="btn btn-primary" (click)="createOrEditLandlordPropertyPortfolioModal.show()">
         {{ l('Add') }}
    </button>

    <ng-template pTemplate="header">

                {{ l('Actions') }}

                {{ l('Id') }}

                {{ l('Name') }}

    </ng-template>
    <ng-template pTemplate="body" let-record let-expanded="expanded">

                    <button class="dropdown-toggle btn btn-sm btn-primary" dropdownToggle>
                         {{ l('Actions') }}
                    </button>

                            {{ l('Edit') }}

                            {{ l('Delete') }}

                 {{ l('Id') }}
                {{ record.id }}

                 {{ l('Name') }}
                {{ record.name }}

    </ng-template>

    <ng-template pTemplate="rowexpansion">

                <ng-template pTemplate="header">

                            {{ l('PropertyAddress') }}

                            {{ l('PostalCode') }}

                            {{ l('AgentName') }}

                            {{ l('Tenant') }}

                            {{ l('Status') }}

                </ng-template>
                <ng-template pTemplate="body" let-record let-expanded="expanded">

                            {{ record.properties.id}}

                            {{ record.properties.postalCode }}

                            {{ record.properties.agentName }}

                            {{ record.properties.tenant }}

                            {{ record.properties.status }}

                </ng-template>

    </ng-template>

My problem is that p-table, that in an expanded row, have not 100% width of the container

Here is how it's like

How I can make it fit 100% width of parent container?

Body:
I was able to solve it like this
Using colspan="4" attribute

Here is the code of answer

 <ng-template let-rowData pTemplate="rowexpansion" let-columns="columns">
        <tr>
            <td colspan="4">
                <p-table
                    #nestedTable
                    [value]="rowData.properties"
                    [tableStyle]="{ 'width.%': 100 }"
                    [scrollable]="true"
                    ScrollWidth="100%"
                >
                    <ng-template pTemplate="header">
                        <tr>
                            <th style="width: 130px" pSortableColumn="propertyAddress">
                                {{ l('PropertyAddress') }}
                                <p-sortIcon field="propertyAddress"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="postalCode">
                                {{ l('PostalCode') }}
                                <p-sortIcon field="postalCode"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="agentName">
                                {{ l('AgentName') }}
                                <p-sortIcon field="agentName"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="tenant">
                                {{ l('Tenant') }}
                                <p-sortIcon field="tenant"></p-sortIcon>
                            </th>
                            <th style="width: 150px" pSortableColumn="status">
                                {{ l('Status') }}
                                <p-sortIcon field="status"></p-sortIcon>
                            </th>
                        </tr>
                    </ng-template>
                    <ng-template pTemplate="body" let-record let-expanded="expanded">
                        <tr>
                            <td style="width: 130px">
                                {{ record.propertyAddress }}
                            </td>
                            <td style="width: 150px">
                                {{ record.postalCode }}
                            </td>
                            <td style="width: 150px">
                                {{ record.agentName }}
                            </td>
                            <td style="width: 150px">
                                {{ record.tenant }}
                            </td>
                            <td style="width: 150px">
                                {{ record.status }}
                            </td>
                        </tr>
                    </ng-template>
                </p-table>
            </td>
        </tr>
    </ng-template>


问:
Change the color of a character-pointtype in gnuplot
I am trying to set the color of a character-defined point type in gnuplot. Although I can select the desire color of a system defined point type, I cannot do the same with the character-defined one. Below I present a minimal example.

```<code>set samples 5
set term pdf
set o "mwe.pdf"

p x with points lt rgb "violet" pt "V",\
  x with points lt rgb "violet" pt 2

set o
</code>```

The result looks like this:

I also tried to set the color with the lc variable method and feeding the keyword using with a column ("#005893"), buit it still doesn't change the color.

Question

How can I set the color of the letter to achieve something like this:

答: You should use textcolor instead of linecolor or linetype to change the point type defined by a character, as others pointed out already. See the gnuplot documentation.

Body:
I am trying to set the color of a character-defined point type in gnuplot. Although I can select the desire color of a system defined point type, I cannot do the same with the character-defined one. Below I present a minimal example.

set samples 5
set term pdf
set o "mwe.pdf"

p x with points lt rgb "violet" pt "V",\
  x with points lt rgb "violet" pt 2

set o

The result looks like this:

I also tried to set the color with the lc variable method and feeding the keyword using with a column ("#005893"), buit it still doesn't change the color.

Question

How can I set the color of the letter to achieve something like this:


问:
React: Is useEffect not guaranteed to run before the component renders?
I am trying to update some components in Gatsby.js, based on what url path I am on.

I am using useEffect() to make sure the components only update when location.pathname (the part of the url after the domain) changes.

Here is the code: https://codesandbox.io/s/gatsbystarterdefault-290qv

For some reason, useEffect is not using the updated values of the location prop (which is passed to the header component, which in turn wraps every page).

To reproduce, go to the CodeSandbox above and:

Click to page 2, then back again to page 1

See console statements that isHome when re-rendering Header is true while, isHome at NavItemLink is false

Any idea why useEffect does not get the latest value of location?

答:
As stated in the React documentation on useEffect, useEffect is "similar to componentDidMount and componentDidUpdate". Meaning yes, it runs only after the component renders.

You need to rerender the header component after changing navLinks. I recommend you do this by making navLinks part of the component state with the useState hook:

```<code>const [navLinks, setNavLinks] = useState([])

useEffect(() => {
    setNavLinks(
        nav.map((navItem, index) => (
            <NavItemLink
              key={navItem.name}
              name={navItem.name}
              to={navItem.path}
              isHome={location.pathname === withPrefix("/")}
            />
        ))
    )
}, [location.pathname])
</code>```

I've created a fork of your code sandbox with the header component updated to use the useState hook like shown above: https://codesandbox.io/s/gatsbystarterdefault-ftogs

Body:
As stated in the React documentation on useEffect, useEffect is "similar to componentDidMount and componentDidUpdate". Meaning yes, it runs only after the component renders.

You need to rerender the header component after changing navLinks. I recommend you do this by making navLinks part of the component state with the useState hook:

const [navLinks, setNavLinks] = useState([])

useEffect(() => {
    setNavLinks(
        nav.map((navItem, index) => (
            <NavItemLink
              key={navItem.name}
              name={navItem.name}
              to={navItem.path}
              isHome={location.pathname === withPrefix("/")}
            />
        ))
    )
}, [location.pathname])

I've created a fork of your code sandbox with the header component updated to use the useState hook like shown above: https://codesandbox.io/s/gatsbystarterdefault-ftogs


问:
How can I pass props into stackNavigator in React-Native?
I made a login controller Component then I passed my stackNavigator into it, my problem is that I should pass jwt token into the screens but I can't access the "this.state.jwt"

I know there are familiar questions but I just couldn't wrap my head around the answers.

```<code>export default class App extends Component {
  constructor() {
    super();
    this.state = {
      jwt: '',
      loading: true
    }

    this.newJWT = this.newJWT.bind(this);
    this.deleteJWT = deviceStorage.deleteJWT.bind(this);
    this.loadJWT = deviceStorage.loadJWT.bind(this);
    this.loadJWT();
  }

  newJWT(jwt){
    this.setState({
      jwt: jwt
    });
  }

  render() {
    if (this.state.loading) {
      this.deleteJWT()
      return (
        <Loading size={'large'} />
       );
    } else if (!this.state.jwt) {
      return (
        <Auth newJWT={this.newJWT} />
      );
    } else if (this.state.jwt) {
      return (
        <RootNav screenProps={this.state.jwt} />
      );
    }
  }
}

const BottomNaviagtor = createBottomTabNavigator ({

  Home: Home,
  Top: Top,
  Following: {screen: Following},
  LikeD: {screen:Liked}
})

const RootNav = createAppContainer(BottomNaviagtor)
</code>```

Somehow I should do this: Home jwt={this.state.jw} and do this for all others bottomNavigator screens

答:
sorry not enough points to comment, i see your are passing it as a screenProp, if you modify your screenProps to

screenProps={{
                  jwt: this.state.jwt}}

do you have access in your screens doing this.props.screenProps.jwt?

Body:
I made a login controller Component then I passed my stackNavigator into it, my problem is that I should pass jwt token into the screens but I can't access the "this.state.jwt"

I know there are familiar questions but I just couldn't wrap my head around the answers.

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      jwt: '',
      loading: true
    }

    this.newJWT = this.newJWT.bind(this);
    this.deleteJWT = deviceStorage.deleteJWT.bind(this);
    this.loadJWT = deviceStorage.loadJWT.bind(this);
    this.loadJWT();
  }

  newJWT(jwt){
    this.setState({
      jwt: jwt
    });
  }

  render() {
    if (this.state.loading) {
      this.deleteJWT()
      return (
        <Loading size={'large'} />
       );
    } else if (!this.state.jwt) {
      return (
        <Auth newJWT={this.newJWT} />
      );
    } else if (this.state.jwt) {
      return (
        <RootNav screenProps={this.state.jwt} />
      );
    }
  }
}

const BottomNaviagtor = createBottomTabNavigator ({

  Home: Home,
  Top: Top,
  Following: {screen: Following},
  LikeD: {screen:Liked}
})

const RootNav = createAppContainer(BottomNaviagtor)

Somehow I should do this: Home jwt={this.state.jw} and do this for all others bottomNavigator screens


问:
How to load a small css background image before lots of other images (html element in .css file)?
I'm wondering if you can help. I have a small image (46kb) which is currently called in CSS like this:

```<code>html {
background: #000 url(../images/background.jpg) repeat fixed;
}
</code>```

The problem I have with this at the moment is that the background is the last thing to load. On most of my pages I have anywhere from around 50 to 150 small 4kb images (which are content images). Consequently all these images load first before the background image. While this isn't a big deal, as the content is still readable, surely there is a way to load the small background image first?

Ideally I would like to use a CSS solution, but JS is fine, but don't want to use Jquery. I have tried a few methods, but quite a few of these require the image to be placed in the HTML, which is not possible in this case.

Thanks.

Edit: Just to clarify about JQuery, I haven't used it at all in the site so far, so it seems a bit overkill to use it just for loading a small background image. And yes the html {} declaration is at the top of the CSS file (just below some resetting declarations.

答:
You can put

```<code><img style="display:none;" src="../images/background.jpg" />
</code>```

at the top of your  tag to make load it earlier.

Source: https://www.sitepoint.com/community/t/is-there-a-way-i-can-force-my-background-image-to-load-before-the-other-images/4500/5 .

Body:
I'm wondering if you can help. I have a small image (46kb) which is currently called in CSS like this:

html {
background: #000 url(../images/background.jpg) repeat fixed;
}

The problem I have with this at the moment is that the background is the last thing to load. On most of my pages I have anywhere from around 50 to 150 small 4kb images (which are content images). Consequently all these images load first before the background image. While this isn't a big deal, as the content is still readable, surely there is a way to load the small background image first?

Ideally I would like to use a CSS solution, but JS is fine, but don't want to use Jquery. I have tried a few methods, but quite a few of these require the image to be placed in the HTML, which is not possible in this case.

Thanks.

Edit: Just to clarify about JQuery, I haven't used it at all in the site so far, so it seems a bit overkill to use it just for loading a small background image. And yes the html {} declaration is at the top of the CSS file (just below some resetting declarations.

Body:
You can put

<img style="display:none;" src="../images/background.jpg" />

at the top of your <body> tag to make load it earlier.

Source: https://www.sitepoint.com/community/t/is-there-a-way-i-can-force-my-background-image-to-load-before-the-other-images/4500/5 .


问:
I need a helper function to loop through complex object arrays with ngFor
I'm working on setting up a loop in angular and I'm quite new to this. Normally I'd be able to do it no problem but since I was given a weird data object to work with I'm terribly stuck. My code is as follows.

So far I can get the list from "children" at the top of the object but I cant go any further.

Here is my data

```<code>{
   "type": "categoryGroup",
   "children": [
       "Apples",
       "Bananas",
       "Oranges"
   ],
   "Apples": {
       "type": "categorySubgroup",
       "children": [
           "Golden Delicious",
           "Granny Smith",
           "Macintosh"
       ],
       "Golden Delicious": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Granny Smith": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Macintosh": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Bananas": {
       "type": "categorySubgroup",
       "children": [
           "Lady's Finger",
           "Cavendish Bananas"
       ],
       "Lady's Finger": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Cavendish Bananas": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Oranges": {
       "type": "categorySubgroup",
       "children": [
           "Blood Orange"
       ],
       "Blood Orange": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   }
}

</code>```

Here is the HTML part of my code (which is failing miserably)

{{ category }}

{{ categoryGroup }}

{{ categoryItem.name }}

```

I would like some help looping down the object arrays, maybe as a helper function using the "children" array. Any thoughts or help would be greatly appreciated. Thanks!

答:
Try out the following code, please.</p>

```<code><div class="col-md-12"  *ngFor="let category of fruit.children">
  <div class="card">
      <div class="card__header">
          <h4 class="card__title">{{ category }}</h4>
      </div>
      <div class="card__body">
        <div class="row">
          <div class="col-md-4" *ngFor="let categoryGroup of fruit[category].children">
              <div class="subheader">{{ categoryGroup }}</div>
              <div>
                  <ul class="resource-list" *ngFor="let categoryItem of fruit[category].articles">
                      <li>{{ categoryItem.name }}</li>
                  </ul>
                </div>
            </div>
          </div>
      </div>
  </div>
</div>
</code>```

Body:
I'm working on setting up a loop in angular and I'm quite new to this. Normally I'd be able to do it no problem but since I was given a weird data object to work with I'm terribly stuck. My code is as follows.

So far I can get the list from "children" at the top of the object but I cant go any further.

Here is my data

{
   "type": "categoryGroup",
   "children": [
       "Apples",
       "Bananas",
       "Oranges"
   ],
   "Apples": {
       "type": "categorySubgroup",
       "children": [
           "Golden Delicious",
           "Granny Smith",
           "Macintosh"
       ],
       "Golden Delicious": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Granny Smith": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Macintosh": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Bananas": {
       "type": "categorySubgroup",
       "children": [
           "Lady's Finger",
           "Cavendish Bananas"
       ],
       "Lady's Finger": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       },
       "Cavendish Bananas": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   },
   "Oranges": {
       "type": "categorySubgroup",
       "children": [
           "Blood Orange"
       ],
       "Blood Orange": {
           "type": "articleList",
           "articles": [
               {
                   "key": "article-1",
                   "name": "Article 1"
               },
               {
                   "key": "article-2",
                   "name": "Article 2"
               }
           ]
       }
   }
}

Here is the HTML part of my code (which is failing miserably)

{{ category }}

{{ categoryGroup }}

{{ categoryItem.name }}

I would like some help looping down the object arrays, maybe as a helper function using the "children" array. Any thoughts or help would be greatly appreciated. Thanks!

Body:
Try out the following code, please.

<div class="col-md-12"  *ngFor="let category of fruit.children">
  <div class="card">
      <div class="card__header">
          <h4 class="card__title">{{ category }}</h4>
      </div>
      <div class="card__body">
        <div class="row">
          <div class="col-md-4" *ngFor="let categoryGroup of fruit[category].children">
              <div class="subheader">{{ categoryGroup }}</div>
              <div>
                  <ul class="resource-list" *ngFor="let categoryItem of fruit[category].articles">
                      <li>{{ categoryItem.name }}</li>
                  </ul>
                </div>
            </div>
          </div>
      </div>
  </div>
</div>


问:
framework not found RealmSwift
I was installing Realm and imported to my project but when I run the app it shows me an error:

ld: framework not found RealmSwift

  clang: error: linker command failed with exit code 1 (use -v to see invocation)

答:
There can be multiple reasons for this issue.

To get the exact issue you can follow the below step :

Right click on error and select 'Reveal in log'. This will give you more insight about the reason of error.

One of the solution is to setting the 'Enabled Bitcode' to No. For this go to Build settings in your target and search 'Bitcode' in the search field.

I have faced this issue multiple times and one of the below solution may work for you.

After installing the pods make sure that you're opening the workspace instead of Xcode project file.

Restart Xcode

Remove derive data for your application

Reintegrate pods using pod deintegrate and pod install for your project

Reset simulator(If you are viewing the output in simulator)

Ensure proper linking of Framework in your project

Restart simulator

Clean project etc.

Hope this may help you.

Title: framework not found RealmSwift


问:
How can I target a specific column or row in a CSS grid layout?
Is it possible to select a specific grid column or row with CSS?

For example, say I have a 3 row by 2 column CSS grid layout: grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;. How would I select all elements from the 2nd column? For example: grid:nth-child(column:2) (just my idea, not valid code).

I have tried nth-child selectors on the div elements, but this does not allow me to specify row or column when the items are automatically placed by the CSS grid layout engine.

body {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}

.item {
  background: #999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>

<div class="item">
  <p>Right Justify</p>
  <p>Element 1 | Element 2</p>
</div>

<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>

<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>
<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>
<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>
<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div></code>```

答:
There aren't any column or row elements that you can target, but if the grid is uniform (same number of cells in each row), you can select cells. Here are some examples.

1. Columns

Last column in a 5-column grid:

.item:nth-child(5n) { /* ... */ }
```
<p>Fourth (second last) column in a 5-column grid:</p>
<pre class="lang-css prettyprint-override"><code>.item:nth-child(5n-1) { /* ... */ }
</code>```

First (5th last) column in a 5-column grid:

.item:nth-child(5n-4) { /* ... */ }
```
<h2>2. Rows</h2>
<p>First row in a 5-column grid (first five cells):</p>
<pre class="lang-css prettyprint-override"><code>.item:nth-child(-n+5) { /* ... */ }
</code>```

Second row in a 5-column grid (cells from 6 to 10):

.item:nth-child(n+6):nth-child(-n+10) { /* ... */ }
```
<p>Third row in a 5-column grid (cells from 11 to 15):</p>
<pre class="lang-css prettyprint-override"><code>.item:nth-child(n+11):nth-child(-n+15) { /* ... */ }
</code>```

Last row in a 5-column grid with 20 cells (cells from 16 onward):

.item:nth-child(n+16) { /* ... */ }
```

Body:
Is it possible to select a specific grid column or row with CSS?

For example, say I have a 3 row by 2 column CSS grid layout: grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;. How would I select all elements from the 2nd column? For example: grid:nth-child(column:2) (just my idea, not valid code).

I have tried nth-child selectors on the div elements, but this does not allow me to specify row or column when the items are automatically placed by the CSS grid layout engine.

body {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}

.item {
  background: #999;
}

Customer Name

Element 1 | Element 2

Right Justify

Element 1 | Element 2

Customer Name

Element 1 | Element 2

Customer Name

Element 1 | Element 2

Customer Name

Element 1 | Element 2

Customer Name

Element 1 | Element 2

Customer Name

Element 1 | Element 2

Body:
There aren't any column or row elements that you can target, but if the grid is uniform (same number of cells in each row), you can select cells. Here are some examples.

1. Columns

Last column in a 5-column grid:

.item:nth-child(5n) { /* ... */ }

Fourth (second last) column in a 5-column grid:

.item:nth-child(5n-1) { /* ... */ }

First (5th last) column in a 5-column grid:

.item:nth-child(5n-4) { /* ... */ }

2. Rows

First row in a 5-column grid (first five cells):

.item:nth-child(-n+5) { /* ... */ }

Second row in a 5-column grid (cells from 6 to 10):

.item:nth-child(n+6):nth-child(-n+10) { /* ... */ }

Third row in a 5-column grid (cells from 11 to 15):

.item:nth-child(n+11):nth-child(-n+15) { /* ... */ }

Last row in a 5-column grid with 20 cells (cells from 16 onward):

.item:nth-child(n+16) { /* ... */ }


问:
Remove everything after a certain character
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

```<code>/Controller/Action?id=11112&value=4444
</code>```

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

```<code> $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }
</code>```

答:
You can also use the split() function. This seems to be the easiest one that comes to my mind :).

```<code>url.split('?')[0]
</code>```

jsFiddle Demo

One advantage is this method will work even if there is no ? in the string - it will return the whole string.

Body:
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

/Controller/Action?id=11112&value=4444

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }

Body:
You can also use the split() function. This seems to be the easiest one that comes to my mind :).

url.split('?')[0]

jsFiddle Demo

One advantage is this method will work even if there is no ? in the string - it will return the whole string.


问:
Get an alert when a form cant be submitted using ajax
I have a form for a user to request a day off, on my server side i have functionality to check if more than 3 people have asked for that same day off and if they have it wont let the user request that day. I want to display a pop up/alert when they cant request that day

This is in my method in my controller

```<code>if(results.size() >3)
{
   System.out.println("Too many people asked for that day off");
   return new ModelAndView("request");

}
else
{
    Request request = new Request();
    request.setDate(newDate);
    request.setNumDays(numDays);
    request.setReason(reason1);

    ModelAndView mv = new ModelAndView("successRequest");
    mv.addObject("request", request);

    requestService.save(request);
        return mv;
}
</code>```

It return an empty form when there is more than 3 requests for that day but i also want it to have an alert message
Ive tried to do it on my jsp page using ajax

```<code>$('#form').submit(function(e)
{
     $.ajax({
     type:'POST',
     url:"/request",
     data:$(this).serialize(),
     error: function(){
      window.alert("Too many people have asked for that day off");
      console.log("Error");
     }
});
});
</code>```

答:
AJAX is expecting JSON response not ModelAndView Object.

So First things to do is to return JSON Response using @ResponseBody instead of ModelAndView Object.

Then based on the flag value you can show the alert to user.

Body:
I have a form for a user to request a day off, on my server side i have functionality to check if more than 3 people have asked for that same day off and if they have it wont let the user request that day. I want to display a pop up/alert when they cant request that day

This is in my method in my controller

if(results.size() >3)
{
   System.out.println("Too many people asked for that day off");
   return new ModelAndView("request");

}
else
{
    Request request = new Request();
    request.setDate(newDate);
    request.setNumDays(numDays);
    request.setReason(reason1);

    ModelAndView mv = new ModelAndView("successRequest");
    mv.addObject("request", request);

    requestService.save(request);
        return mv;
}

It return an empty form when there is more than 3 requests for that day but i also want it to have an alert message
Ive tried to do it on my jsp page using ajax

$('#form').submit(function(e)
{
     $.ajax({
     type:'POST',
     url:"/request",
     data:$(this).serialize(),
     error: function(){
      window.alert("Too many people have asked for that day off");
      console.log("Error");
     }
});
});


问:
Reducer: Updating an array inside an array
I'm new to Redux, how would I reference the state of a nested array in my reducer?

Here is my state:

```<code>const initState = {
  tabs: [
    { arr: [] },
    { arr: [] }
  ]
};
</code>```

I tried doing something like:

```<code>tabs[0].arr: //do stuff
</code>```

inside my reducer, but I get a parsing error. What is the correct way to reference the array in the first tab?

Edit:
I am adding more code for clarity

```<code>function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {
      return {
          state.tabs[0].arr: [...state.tabs[0].arr, action.arr]
      }
 }
}
//I get this message: 'Parsing error: Unexpected token, expected ","' at the period between 'state' and 'tabs[0]'
</code>```

The rest of my code

```<code>const arrAction = { type: "ADD_ARR", arr: "hello" };
store.dispatch(arrAction);
</code>```

答:
Your syntax is wrong for updating array.</p>

```<code>function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {
     return {
        tabs: [ {
           arr: action.arr
        }, ...state.tabs]
  }
}
</code>```

Body:
I'm new to Redux, how would I reference the state of a nested array in my reducer?

Here is my state:

const initState = {
  tabs: [
    { arr: [] },
    { arr: [] }
  ]
};

I tried doing something like:

tabs[0].arr: //do stuff

inside my reducer, but I get a parsing error. What is the correct way to reference the array in the first tab?

Edit:
I am adding more code for clarity

function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {
      return {
          state.tabs[0].arr: [...state.tabs[0].arr, action.arr]
      }
 }
}
//I get this message: 'Parsing error: Unexpected token, expected ","' at the period between 'state' and 'tabs[0]'

The rest of my code

const arrAction = { type: "ADD_ARR", arr: "hello" };
store.dispatch(arrAction);

Body:
Your syntax is wrong for updating array.

function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {
     return {
        tabs: [ {
           arr: action.arr
        }, ...state.tabs]
  }
}


问:
Elasticsearch custom analyser
Is it possible to create custom elasticsearch analyser which can split index by space and then create two tokens? One, with everything before space and second, with everything.
For example: I have stored record with field which has following text: '35 G'.
Now I want to receive that record by typing only '35' or '35 G' query to that field.
So elastic should create two tokens: ['35', '35 G'] and no more.

If it's possible, how to achieve it ?

答:
Doable using path_hierarchy tokenizer.

```<code>PUT test
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "my_tokenizer"
        }
      },
      "tokenizer": {
        "my_tokenizer": {
          "type": "path_hierarchy",
          "delimiter": " "
        }
      }
    }
  }
  ...
}
</code>```

And now

```<code>POST test/_analyze
{
  "analyzer": "my_analyzer",
  "text": "35 G"
}
</code>```

outputs

```<code>{
  "tokens": [
    {
      "token": "35",
      "start_offset": 0,
      "end_offset": 2,
      "type": "word",
      "position": 0
    },
    {
      "token": "35 G",
      "start_offset": 0,
      "end_offset": 4,
      "type": "word",
      "position": 0
    }
  ]
}
</code>```

Title: Elasticsearch custom analyser

Body:
Doable using path_hierarchy tokenizer.

PUT test
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "my_tokenizer"
        }
      },
      "tokenizer": {
        "my_tokenizer": {
          "type": "path_hierarchy",
          "delimiter": " "
        }
      }
    }
  }
  ...
}

And now

POST test/_analyze
{
  "analyzer": "my_analyzer",
  "text": "35 G"
}

outputs

{
  "tokens": [
    {
      "token": "35",
      "start_offset": 0,
      "end_offset": 2,
      "type": "word",
      "position": 0
    },
    {
      "token": "35 G",
      "start_offset": 0,
      "end_offset": 4,
      "type": "word",
      "position": 0
    }
  ]
}


问:
How can I run a Python script in HTML?
Currently I have some Python files which connect to an SQLite database for user inputs and then perform some calculations which set the output of the program. I'm new to Python web programming and I want to know: What is the best method to use Python on the web?

Example: I want to run my Python files when the user clicks a button on the web page. Is it possible?

I started with Django. But it needs some time for the learning. And I also saw something called CGI scripts. Which option should I use?

答:
You are able to run a Python file using HTML using PHP.

Add a PHP file as index.php:

```<code><html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>
</code>```

Passing the parameter to Python

Create a Python file as test.py:

```<code>import sys
input=sys.argv[1]
print(input)
</code>```

Print the parameter passed by PHP.

Title: How can I run a Python script in HTML?

Body:
You are able to run a Python file using HTML using PHP.

Add a PHP file as index.php:

<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>

Passing the parameter to Python

Create a Python file as test.py:

import sys
input=sys.argv[1]
print(input)

Print the parameter passed by PHP.


问:
Difference between HFP 1.7 and HFP 1.6?
Can someone please tell me the difference between HFP 1.7 and HFP 1.6 ? I am looking for differences in addition to what already mentioned in Wikipedia. Any link or document would be highly appreciated.</p>

答: Version 1.6 adds optional support for wide band speech with the mSBC codec, a 16 kHz monaural configuration of the SBC codec mandated by the A2DP profile. Version 1.7 adds indicator support to report such things as headset battery level.</p>

Title: Difference between HFP 1.7 and HFP 1.6?


问:
Regex Replace A Variable Within Brackets, Including Brackets
How do I get rid of a variable within square brackets, including the brackets themselves? E.g. [152] or [153] or [154]. I am using Yahoo Pipes.</p>

答:
I am unsure if the variables will always be numbers my solutions works by removing all occurrences of [anything]

replace

```<code>\[[^\]]*\] with ""
</code>```

javascript example

```<code>var s = "[152] xxx [153]zzz [154] i";

s = s.replace(/\[[^\]]*\]/g,'')

s ; //# =>  xxx zzz  i
</code>```

Body:
I am unsure if the variables will always be numbers my solutions works by removing all occurrences of [anything]

replace

\[[^\]]*\] with ""

javascript example

var s = "[152] xxx [153]zzz [154] i";

s = s.replace(/\[[^\]]*\]/g,'')

s ; //# =>  xxx zzz  i


问:
How to extract numbers from a string and add to an array?
I want to convert this string:

```<code><5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>
</code>```

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

```<code>$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");
</code>```

Response: String could not be parsed as XML

I expect an array like this:

```<code>[5=>20825.24,7=>0.0,8=>0.0]
</code>```

答:
As long as your output has numbers at the start of the XML tag name, it won't be valid XML.  You may have to resort to using a regex to do the job.

This uses <(\d*)>(.*?)</~ which looks for a < followed by digits, then the > and captures everything up till the next </.  It then combines the values from capture group 1 (the tag name) and 2 (the value)...

```<code>$data = "<5>20825.24</5><7>0.0</ 7><8>0.0</8>";

preg_match_all("~<(\d*)>(.*?)</~", $data, $matches);
$output = array_combine($matches[1], $matches[2]);
print_r($output);
</code>```

gives...

```<code>Array
(
    [5] => 20825.24
    [7] => 0.0
    [8] => 0.0
)
</code>```

Body:
I want to convert this string:

<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");

Response: String could not be parsed as XML

I expect an array like this:

[5=>20825.24,7=>0.0,8=>0.0]

Body:
As long as your output has numbers at the start of the XML tag name, it won't be valid XML.  You may have to resort to using a regex to do the job.

This uses <(\d*)>(.*?)</~ which looks for a < followed by digits, then the > and captures everything up till the next </.  It then combines the values from capture group 1 (the tag name) and 2 (the value)...

$data = "<5>20825.24</5><7>0.0</ 7><8>0.0</8>";

preg_match_all("~<(\d*)>(.*?)</~", $data, $matches);
$output = array_combine($matches[1], $matches[2]);
print_r($output);

gives...

Array
(
    [5] => 20825.24
    [7] => 0.0
    [8] => 0.0
)


问:
Is there a possibility that I'll make the Stripe payment in my app less secured due to wrong implementation?
I am trying to implement stripe in my app, and currently having a bit of a hard time. Like anything else I believe that eventually I'd be able to make it work, but my main concern is that I won't implement it properly, and as a result I'll make the payment less secure that it should be.

Is there a base to my concerns? The last thing I want is to compromise my users credit cards.

I am trying to use the standard implementation and collect the card details with their card input widget.

答:
If you're using Stripe's preferred integrations such as Elements or Checkout, raw card details are always handled within an iframe controlled by Stripe. As such they will never touch your server or be accessible to your code.

That said, there are other potential vulnerabilities in a web application to consider and mitigate (XSS, SQL injection, sanitation of user inputs, server mis-configs or outdated packages) but these aren't specific to collecting card details through Stripe.


问:
how to flatten a df?
I have that schema DF in spark , I want to flat it by using “def flatten_df” function but output still same do you have any idea ?

My data frame schema is like below

```<code> Selected_duration_df.printSchema()
</code>```

output

```<code>  root
   |-- Duration: long (nullable = true)
   |-- event_end_date: timestamp (nullable = true)
   |-- event_start_date: timestamp (nullable = true)
   |-- location_id: long (nullable = true)
   |-- location_name: string (nullable = true)
   |-- product_id: string (nullable = true)
   |-- sensor_id: long (nullable = true)
   |-- sensor_name: string (nullable = true)
   |-- fault_fault_code: string (nullable = true)
   |-- fault_fault_description: string (nullable = true)
   |-- product_model_features: array (nullable = true)
   |    |-- element: struct (containsNull = true)
   |    |    |-- key: string (nullable = true)
   |    |    |-- value: string (nullable = true)
</code>```

I tried "def flatten_df" function

```<code> def flatten_df(nested_df, layers):
     flat_cols = []
     nested_cols = []
     flat_df = []

     flat_cols.append([c[0] for c in nested_df.dtypes if c[1][:6] != 'struct'])
     nested_cols.append([c[0] for c in nested_df.dtypes if c[1][:6] == 'struct'])

     flat_df.append(nested_df.select(flat_cols[0] +
                           [col(nc+'.'+c).alias(nc+'_'+c)
                            for nc in nested_cols[0]
                            for c in nested_df.select(nc+'.*').columns])
              )
     for i in range(1, layers):
         print (flat_cols[i-1])
         flat_cols.append([c[0] for c in flat_df[i-1].dtypes if c[1][:6] != 'struct'])
         nested_cols.append([c[0] for c in flat_df[i-1].dtypes if c[1][:6] == 'struct'])

         flat_df.append(flat_df[i-1].select(flat_cols[i] +
                            [col(nc+'.'+c).alias(nc+'_'+c)
                                for nc in nested_cols[i]
                                for c in flat_df[i-1].select(nc+'.*').columns])
    )

     return flat_df[-1]

  my_flattened_df = flatten_df(Selected_duration_df, 3)
</code>```

the output is same
      my_flattened_df.printSchema()
output

```<code> root
  |-- Duration: long (nullable = true)
  |-- event_end_date: timestamp (nullable = true)
  |-- event_start_date: timestamp (nullable = true)
  |-- location_id: long (nullable = true)
  |-- location_name: string (nullable = true)
  |-- product_id: string (nullable = true)
  |-- sensor_id: long (nullable = true)
  |-- sensor_name: string (nullable = true)
  |-- fault_fault_code: string (nullable = true)
  |-- fault_fault_description: string (nullable = true)
  |-- product_model_features: array (nullable = true)
  |    |-- element: struct (containsNull = true)
  |    |    |-- key: string (nullable = true)
  |    |    |-- value: string (nullable = true)
</code>```

答:
You can simplify this using spark explode function.

See the example below:

import pandas
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode

spark = SparkSession \
    .Builder() \
    .appName('stackoverflow') \
    .getOrCreate()

data = {
    'location_id': [1, 2, 3],
    'product_model_features': [
        [{'key': 'A', 'value': 'B'}, {'key': 'C', 'value': 'D'}, {'key': 'E', 'value': 'F'}],
        [{'key': 'G', 'value': 'H'}, {'key': 'I', 'value': 'J'}, {'key': 'K', 'value': 'L'}],
        [{'key': 'M', 'value': 'N'}, {'key': 'O', 'value': 'P'}, {'key': 'Q', 'value': 'R'}]
    ]
}
df = pandas.DataFrame(data)
df = spark.createDataFrame(df)
df = df.withColumn('p', explode('product_model_features')) \
    .select('location_id', 'p.key', 'p.value')
df.show()
```

<p>Output:</p>

```+-----------+---+-----+
|location_id|key|value|
+-----------+---+-----+
|          1|  A|    B|
|          1|  C|    D|
|          1|  E|    F|
|          2|  G|    H|
|          2|  I|    J|
|          2|  K|    L|
|          3|  M|    N|
|          3|  O|    P|
|          3|  Q|    R|
+-----------+---+-----+
```

Title: how to flatten a df?

Body:
I have that schema DF in spark , I want to flat it by using “def flatten_df” function but output still same do you have any idea ?

My data frame schema is like below

 Selected_duration_df.printSchema()

output

  root
   |-- Duration: long (nullable = true)
   |-- event_end_date: timestamp (nullable = true)
   |-- event_start_date: timestamp (nullable = true)
   |-- location_id: long (nullable = true)
   |-- location_name: string (nullable = true)
   |-- product_id: string (nullable = true)
   |-- sensor_id: long (nullable = true)
   |-- sensor_name: string (nullable = true)
   |-- fault_fault_code: string (nullable = true)
   |-- fault_fault_description: string (nullable = true)
   |-- product_model_features: array (nullable = true)
   |    |-- element: struct (containsNull = true)
   |    |    |-- key: string (nullable = true)
   |    |    |-- value: string (nullable = true)

I tried "def flatten_df" function

 def flatten_df(nested_df, layers):
     flat_cols = []
     nested_cols = []
     flat_df = []

     flat_cols.append([c[0] for c in nested_df.dtypes if c[1][:6] != 'struct'])
     nested_cols.append([c[0] for c in nested_df.dtypes if c[1][:6] == 'struct'])

     flat_df.append(nested_df.select(flat_cols[0] +
                           [col(nc+'.'+c).alias(nc+'_'+c)
                            for nc in nested_cols[0]
                            for c in nested_df.select(nc+'.*').columns])
              )
     for i in range(1, layers):
         print (flat_cols[i-1])
         flat_cols.append([c[0] for c in flat_df[i-1].dtypes if c[1][:6] != 'struct'])
         nested_cols.append([c[0] for c in flat_df[i-1].dtypes if c[1][:6] == 'struct'])

         flat_df.append(flat_df[i-1].select(flat_cols[i] +
                            [col(nc+'.'+c).alias(nc+'_'+c)
                                for nc in nested_cols[i]
                                for c in flat_df[i-1].select(nc+'.*').columns])
    )

     return flat_df[-1]

  my_flattened_df = flatten_df(Selected_duration_df, 3)

the output is same
      my_flattened_df.printSchema()
output

 root
  |-- Duration: long (nullable = true)
  |-- event_end_date: timestamp (nullable = true)
  |-- event_start_date: timestamp (nullable = true)
  |-- location_id: long (nullable = true)
  |-- location_name: string (nullable = true)
  |-- product_id: string (nullable = true)
  |-- sensor_id: long (nullable = true)
  |-- sensor_name: string (nullable = true)
  |-- fault_fault_code: string (nullable = true)
  |-- fault_fault_description: string (nullable = true)
  |-- product_model_features: array (nullable = true)
  |    |-- element: struct (containsNull = true)
  |    |    |-- key: string (nullable = true)
  |    |    |-- value: string (nullable = true)

Body:
You can simplify this using spark explode function.

See the example below:

import pandas
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode

spark = SparkSession \
    .Builder() \
    .appName('stackoverflow') \
    .getOrCreate()

data = {
    'location_id': [1, 2, 3],
    'product_model_features': [
        [{'key': 'A', 'value': 'B'}, {'key': 'C', 'value': 'D'}, {'key': 'E', 'value': 'F'}],
        [{'key': 'G', 'value': 'H'}, {'key': 'I', 'value': 'J'}, {'key': 'K', 'value': 'L'}],
        [{'key': 'M', 'value': 'N'}, {'key': 'O', 'value': 'P'}, {'key': 'Q', 'value': 'R'}]
    ]
}
df = pandas.DataFrame(data)
df = spark.createDataFrame(df)
df = df.withColumn('p', explode('product_model_features')) \
    .select('location_id', 'p.key', 'p.value')
df.show()

Output:

+-----------+---+-----+
|location_id|key|value|
+-----------+---+-----+
|          1|  A|    B|
|          1|  C|    D|
|          1|  E|    F|
|          2|  G|    H|
|          2|  I|    J|
|          2|  K|    L|
|          3|  M|    N|
|          3|  O|    P|
|          3|  Q|    R|
+-----------+---+-----+


问:
Java8 ScheduledExecutorService.scheduleAtFixedRate()
I'm reading a java8 book and come across the difference between scheduleAtFixedRate and scheduleWithFixedDelay methods from ScheduledExecutorService.

I understand the difference between these two methods on the book, however when I tried to write a simple code. It's not so clear why scheduleAtFixedRate behaves synchronously.

As you can see, I'm allocating 100 threads in the pool. And the scheduler will submit a new task every 1ms, and per task, there's a delay of 1s.

```<code>    ScheduledExecutorService s = Executors.newScheduledThreadPool(100);
    s.scheduleAtFixedRate(() -> {
        int num = new Random().nextInt(100);
        System.out.println("Hello World" + num);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finished" + num);
    }, 0, 1, TimeUnit.MILLISECONDS);
</code>```

But why am I getting this output ? A new task will run only after the other.

```<code>Hello World94
Finished94
Hello World14
Finished14
Hello World90
Finished90
Hello World26
Finished26
</code>```

答:
Take a look at the javadoc for ScheduledThreadPoolExecutor#scheduleAtFixedRate

If any execution of this task takes longer than its period, then
    subsequent executions may start late, but will not concurrently
    execute.

So do not await for it to execute concurrently, it will always execute sequentially..

Body:
I'm reading a java8 book and come across the difference between scheduleAtFixedRate and scheduleWithFixedDelay methods from ScheduledExecutorService.

I understand the difference between these two methods on the book, however when I tried to write a simple code. It's not so clear why scheduleAtFixedRate behaves synchronously.

As you can see, I'm allocating 100 threads in the pool. And the scheduler will submit a new task every 1ms, and per task, there's a delay of 1s.

    ScheduledExecutorService s = Executors.newScheduledThreadPool(100);
    s.scheduleAtFixedRate(() -> {
        int num = new Random().nextInt(100);
        System.out.println("Hello World" + num);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finished" + num);
    }, 0, 1, TimeUnit.MILLISECONDS);

But why am I getting this output ? A new task will run only after the other.

Hello World94
Finished94
Hello World14
Finished14
Hello World90
Finished90
Hello World26
Finished26


问:
How to chunk shell script input by time, not by size?
In a bash script I am using a many-producer single-consumer pattern. Producers are background processes writing lines into a fifo (via GNU Parallel). The consumer reads all lines from the fifo, then sorts, filters, and prints the formatted result to stdout.

However, it could take a long time until the full result is available. Producers are usually fast on the first few results but then would slow down. Here I am more interested to see chunks of data every few seconds, each sorted and filtered individually.

mkfifo fifo
parallel ... >"$fifo" &
while chunk=$(read with timeout 5s and at most 10s <"$fifo"); do
  process "$chunk"
done
```

<p>The loop would run until all producers are done and all input is read. Each chunk is read until there has been no new data for 5s, or until 10s have passed since the chunk was started. A chunk may also be empty if there was no new data for 10s.</p>

<p>I tried to make it work like this:</p>

<pre class="lang-sh prettyprint-override"><code>output=$(mktemp)
while true; do
  wasTimeout=0 interruptAt=$(( $(date '+%s') + 10 ))
  while true; do
    IFS= read -r -t5 <>"${fifo}"
    rc="$?"
    if [[ "${rc}" -gt 0 ]]; then
      [[ "${rc}" -gt 128 ]] && wasTimeout=1
      break
    fi
    echo "$REPLY" >>"${output}"
    if [[ $(date '+%s') -ge "${interruptAt}" ]]; then
      wasTimeout=1
      break
    fi
  done
  echo '---' >>"${output}"
  [[ "${wasTimeout}" -eq 0 ]] && break
done
</code>```

Tried some variations of this. In the form above it reads the first chunk but then loops forever. If I use <"${fifo}" (no read/write as above) it blocks after the first chunk. Maybe all of this could be simplified with buffer and/or stdbuf? But both of them define blocks by size, not by time.

答:
I would consider writing a safe multi-threaded program with queues.

I know Java better, but there might be more modern suitable languages like Go and Kotlin.

Body:
In a bash script I am using a many-producer single-consumer pattern. Producers are background processes writing lines into a fifo (via GNU Parallel). The consumer reads all lines from the fifo, then sorts, filters, and prints the formatted result to stdout.

However, it could take a long time until the full result is available. Producers are usually fast on the first few results but then would slow down. Here I am more interested to see chunks of data every few seconds, each sorted and filtered individually.

mkfifo fifo
parallel ... >"$fifo" &
while chunk=$(read with timeout 5s and at most 10s <"$fifo"); do
  process "$chunk"
done

The loop would run until all producers are done and all input is read. Each chunk is read until there has been no new data for 5s, or until 10s have passed since the chunk was started. A chunk may also be empty if there was no new data for 10s.

I tried to make it work like this:

output=$(mktemp)
while true; do
  wasTimeout=0 interruptAt=$(( $(date '+%s') + 10 ))
  while true; do
    IFS= read -r -t5 <>"${fifo}"
    rc="$?"
    if [[ "${rc}" -gt 0 ]]; then
      [[ "${rc}" -gt 128 ]] && wasTimeout=1
      break
    fi
    echo "$REPLY" >>"${output}"
    if [[ $(date '+%s') -ge "${interruptAt}" ]]; then
      wasTimeout=1
      break
    fi
  done
  echo '---' >>"${output}"
  [[ "${wasTimeout}" -eq 0 ]] && break
done

Tried some variations of this. In the form above it reads the first chunk but then loops forever. If I use <"${fifo}" (no read/write as above) it blocks after the first chunk. Maybe all of this could be simplified with buffer and/or stdbuf? But both of them define blocks by size, not by time.


问:
Python JSON Google Translator parsing with Simplejson problem
I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception.

```<code>Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)
</code>```

This is my json object looks like

```<code>{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
</code>```

could anyone tell me what is the problem here?

答:
The issue is that simplejson supports json with double quote encoded strings and not single quote encoded strings, so a naive solution might be</p>

```<code>json.loads(jsonstring.replace("'", '"'))
</code>```

Body:
I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception.

Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)

This is my json object looks like

{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}

could anyone tell me what is the problem here?

Body:
The issue is that simplejson supports json with double quote encoded strings and not single quote encoded strings, so a naive solution might be

json.loads(jsonstring.replace("'", '"'))