问:
DataFrame dynamic columns from embedded lists in dataFrame

Ok so I am a relative noob to Python. I have a need for a transformation of the following dataframe

bd, date

```<code>[[None]], 2017-11-01 09:00:00

[[Sulphur], [Green Tea]], 2017-11-02 09:00:00

[[Green Tea], [Jasmine]], 2017-11-03 09:00:00
</code>```

.....

to be transformed to

date, None, Sulphur, Green Tea, Jasmine...

```<code>2017-11-01 09:00:00, 1, 0, 0, 0...

2017-11-02 09:00:00, 0, 1, 1, 0...

2017-11-03 09:00:00, 0, 0, 1, 1...
</code>```

The items in the embedded list in column BD are dynamic and cannot be predefined columns in the new dataFrame.

I tried the following through another helpful post Create new columns in pandas from python nested lists but could not adapt it successfully

```<code>suppDF1 = suppDF.bd.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)
</code>```

Using the code above I only see 5 columns with incorrect 1s so I am clearly out of my depth.

Update

I tried Max's suggestion but I guess I may have something erroneous in my attempt at using pivot:

```<code>suppDF1 = suppDF.pivot(index="date", columns="bd")["bd"]
</code>```

I get the following error

```<code>unhashable type: 'list'
</code>```

答:
I am sure there are more elegant, functional, pythonic ways to do this... and I would love to know what they are.

```<code>import numpy as np
import pandas as pd

# define dataframe
df = pd.DataFrame(columns = ['bd', 'date'])
df.loc[0, 'bd'] = [[None]]
df.loc[0, 'date'] = '2017-11-01 09:00:00'
df.loc[1, 'bd'] = [['Sulphur'], ['Green Tea']]
df.loc[1, 'date'] = '2017-11-02 09:00:00'
df.loc[2, 'bd'] = [['Green Tea'], ['Jasmine']]
df.loc[2, 'date'] = '2017-11-03 09:00:00'
print(df)

# set the index
df.set_index('date', inplace = True)

# df['bd'] contains doubly nested lists
# for item in column, for list in item, for string in list, add string to list
cols = []
for ls2 in df['bd']:
    for ls1 in ls2:
        for string in ls1:
            if string not in cols:
                cols.append(string)

# make a column for every string in df['bd']
for tea in cols:
    df[tea] = 0

# manual one-hot encoding; couldn't get pd.get_dummies() to work
for row in df.iterrows():
    for ls in row[1][0]:
        for el in ls:
            if el in df.columns:
                df.loc[row[0], el] = 1
df.drop('bd', axis = 1, inplace = True)
df.fillna(0)
</code>```

I spent some time on this; here's some stuff that didn't totally work:

I wasn't able to get this recursive function to work for me (blame me, not the function)...
Flatten (an irregular) list of lists

I tried get_dummies, but it can't hash a list, let alone a doubly nested list...
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

I tried pivoting and pivot_table...
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html

I tried converting the list into a string, but that ended up being a dead end as well...
Converting a Panda DF List into a string

Body:
Ok so I am a relative noob to Python. I have a need for a transformation of the following dataframe

bd, date

[[None]], 2017-11-01 09:00:00

[[Sulphur], [Green Tea]], 2017-11-02 09:00:00

[[Green Tea], [Jasmine]], 2017-11-03 09:00:00

.....

to be transformed to

date, None, Sulphur, Green Tea, Jasmine...

2017-11-01 09:00:00, 1, 0, 0, 0...

2017-11-02 09:00:00, 0, 1, 1, 0...

2017-11-03 09:00:00, 0, 0, 1, 1...

The items in the embedded list in column BD are dynamic and cannot be predefined columns in the new dataFrame.

I tried the following through another helpful post Create new columns in pandas from python nested lists but could not adapt it successfully

suppDF1 = suppDF.bd.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)

Using the code above I only see 5 columns with incorrect 1s so I am clearly out of my depth.

Update

I tried Max's suggestion but I guess I may have something erroneous in my attempt at using pivot:

suppDF1 = suppDF.pivot(index="date", columns="bd")["bd"]

I get the following error

unhashable type: 'list'

Body:
I am sure there are more elegant, functional, pythonic ways to do this... and I would love to know what they are.

import numpy as np
import pandas as pd

# define dataframe
df = pd.DataFrame(columns = ['bd', 'date'])
df.loc[0, 'bd'] = [[None]]
df.loc[0, 'date'] = '2017-11-01 09:00:00'
df.loc[1, 'bd'] = [['Sulphur'], ['Green Tea']]
df.loc[1, 'date'] = '2017-11-02 09:00:00'
df.loc[2, 'bd'] = [['Green Tea'], ['Jasmine']]
df.loc[2, 'date'] = '2017-11-03 09:00:00'
print(df)

# set the index
df.set_index('date', inplace = True)

# df['bd'] contains doubly nested lists
# for item in column, for list in item, for string in list, add string to list
cols = []
for ls2 in df['bd']:
    for ls1 in ls2:
        for string in ls1:
            if string not in cols:
                cols.append(string)

# make a column for every string in df['bd']
for tea in cols:
    df[tea] = 0

# manual one-hot encoding; couldn't get pd.get_dummies() to work
for row in df.iterrows():
    for ls in row[1][0]:
        for el in ls:
            if el in df.columns:
                df.loc[row[0], el] = 1
df.drop('bd', axis = 1, inplace = True)
df.fillna(0)

I spent some time on this; here's some stuff that didn't totally work:

I wasn't able to get this recursive function to work for me (blame me, not the function)...
Flatten (an irregular) list of lists

I tried get_dummies, but it can't hash a list, let alone a doubly nested list...
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

I tried pivoting and pivot_table...
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html

I tried converting the list into a string, but that ended up being a dead end as well...
Converting a Panda DF List into a string


来源: stackexchange

问:
devise 5: How do I modify the Flash messages from Devise to match my css for flash messages?
I'm running the latest version of devise 5 in my Rails 5.1 application. I have the following CSS code for flash messages in my stylesheet.

```<code>div.alert.alert-danger, .alert-danger { background-color: #ff0000; }
div.alert.alert-info, .alert-info { background-color: #99d7ea; }
div.alert.alert-success, .alert-success { background-color: #a3da2f; }
div.alert.alert-warning , .alert-warning { background-color: #e6c856; }
</code>```

The original code only had the first class. It works just fine. After reading some older answers regarding this I added the second one attempting to change the css for the flash messages in devise. The messages from devise show up with my default font size and color but a transparent background. I want them to match what I have defined for my flash messages. The ones I issue use my defined CSS.

Where/how can I override the devise CSS for flash messages to match mine?

答:
You probably really want to modify the markup to match your flash message structure.

The devise_error_messages! method defines the markup for devise error messages. You can override that method in your ApplicationHelper to accommodate the markup you need.

ContentLicense: CC BY-SA 3.0

Body:
I'm running the latest version of devise 5 in my Rails 5.1 application. I have the following CSS code for flash messages in my stylesheet.

div.alert.alert-danger, .alert-danger { background-color: #ff0000; }
div.alert.alert-info, .alert-info { background-color: #99d7ea; }
div.alert.alert-success, .alert-success { background-color: #a3da2f; }
div.alert.alert-warning , .alert-warning { background-color: #e6c856; }

The original code only had the first class. It works just fine. After reading some older answers regarding this I added the second one attempting to change the css for the flash messages in devise. The messages from devise show up with my default font size and color but a transparent background. I want them to match what I have defined for my flash messages. The ones I issue use my defined CSS.

Where/how can I override the devise CSS for flash messages to match mine?


问:
matplotlib heatmap, customize y axis
Right now my code looks like this:

```<code>#generate 262*20 elements
values = np.random.random(262*20).tolist()
# convert the list to a 2D NumPy array
values = np.array(values).reshape((262, 20))
h, w = values.shape
#h=262, w=20
fig = plt.figure(num=None, dpi=80,figsize=(9, 7), facecolor='w', edgecolor='k')
ax = fig.add_subplot(111)
#fig, ax = plt.subplots()
plt.imshow(values)
plt.colorbar()
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))
ax.set_aspect(w/h)
plt.show()
</code>```

The plot looks like this:

As you can see, the range of y axis is 0-261.

But I want my y axis to go from 26 to 290, missing 57, 239, and 253. So still 262 in total. I tried to generate a list like this:

```<code>mylist =[26, 27, ......missing 57, 239, 253, ....290]
plt.yticks(np.arange(h), mylist)
</code>```

The Y axis just looks like everything squished together.

So I tried:

```<code>pylab.ylim([26, 290])
</code>```

And It looks like this:

So it just feels like the data in first row always corresponds to [0], not to [26]

答:
Suggest you use pcolormesh.  If you want gaps, then use an numpy.ma.masked array for the area with gaps.

```<code>import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

values = np.random.rand(290,20)
values[:26, :] = np.NaN
values[ [57, 239, 253], :] = np.NaN
values = np.ma.masked_invalid(values)

h, w = values.shape
fig, ax = plt.subplots(figsize=(9,7))
# Make one larger so these values represent the edge of the data pixels.
y = np.arange(0, 290.5)
x = np.arange(0, 20.5)

pcm = ax.pcolormesh(x, y, values, rasterized=True) # you don't need rasterized=True
fig.colorbar(pcm)
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))
plt.show()
</code>```

Result

EDIT:  If you want to just work w/ a 262x20 array:

```<code>values = np.random.rand(262,20)

h, w = values.shape
fig, ax = plt.subplots(figsize=(9,7))
# Make one larger so these values represent the edge of the data pixels.
y = np.arange(0, 290.5)
y = np.delete(y, [57, 239, 253])
y = np.delete(y, range(26))

x = np.arange(0, 20.5)

pcm = ax.pcolormesh(x, y, values, rasterized=True) # you don't need rasterized=True
fig.colorbar(pcm)
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))

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

Note that this doesn't put a blank line at 57, 239 and 253.  If you want that, you need to do:

```<code>values = np.random.rand(262,20)
Z = np.ones((290, 20)) * np.NaN
inds = set(range(290)) - set(list(range(26)) + [57, 239, 253])
for nn, ind in enumerate(inds):
    Z[ind, :] = values[nn,:]

h, w = values.shape
fig, ax = plt.subplots(figsize=(9,7))
# Make one larger so these values represent the edge of the data pixels.
y = np.arange(0, 290.5)

x = np.arange(0, 20.5)

pcm = ax.pcolormesh(x, y, Z, rasterized=True) # you don't need rasterized=True
fig.colorbar(pcm)
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))

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

Title: matplotlib heatmap, customize y axis

Body:
Right now my code looks like this:

#generate 262*20 elements
values = np.random.random(262*20).tolist()
# convert the list to a 2D NumPy array
values = np.array(values).reshape((262, 20))
h, w = values.shape
#h=262, w=20
fig = plt.figure(num=None, dpi=80,figsize=(9, 7), facecolor='w', edgecolor='k')
ax = fig.add_subplot(111)
#fig, ax = plt.subplots()
plt.imshow(values)
plt.colorbar()
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))
ax.set_aspect(w/h)
plt.show()

The plot looks like this:

As you can see, the range of y axis is 0-261.

But I want my y axis to go from 26 to 290, missing 57, 239, and 253. So still 262 in total. I tried to generate a list like this:

mylist =[26, 27, ......missing 57, 239, 253, ....290]
plt.yticks(np.arange(h), mylist)

The Y axis just looks like everything squished together.

So I tried:

pylab.ylim([26, 290])

And It looks like this:

So it just feels like the data in first row always corresponds to [0], not to [26]

Body:
Suggest you use pcolormesh.  If you want gaps, then use an numpy.ma.masked array for the area with gaps.

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

values = np.random.rand(290,20)
values[:26, :] = np.NaN
values[ [57, 239, 253], :] = np.NaN
values = np.ma.masked_invalid(values)

h, w = values.shape
fig, ax = plt.subplots(figsize=(9,7))
# Make one larger so these values represent the edge of the data pixels.
y = np.arange(0, 290.5)
x = np.arange(0, 20.5)

pcm = ax.pcolormesh(x, y, values, rasterized=True) # you don't need rasterized=True
fig.colorbar(pcm)
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))
plt.show()

Result

EDIT:  If you want to just work w/ a 262x20 array:

values = np.random.rand(262,20)

h, w = values.shape
fig, ax = plt.subplots(figsize=(9,7))
# Make one larger so these values represent the edge of the data pixels.
y = np.arange(0, 290.5)
y = np.delete(y, [57, 239, 253])
y = np.delete(y, range(26))

x = np.arange(0, 20.5)

pcm = ax.pcolormesh(x, y, values, rasterized=True) # you don't need rasterized=True
fig.colorbar(pcm)
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))

plt.show()

Note that this doesn't put a blank line at 57, 239 and 253.  If you want that, you need to do:

values = np.random.rand(262,20)
Z = np.ones((290, 20)) * np.NaN
inds = set(range(290)) - set(list(range(26)) + [57, 239, 253])
for nn, ind in enumerate(inds):
    Z[ind, :] = values[nn,:]

h, w = values.shape
fig, ax = plt.subplots(figsize=(9,7))
# Make one larger so these values represent the edge of the data pixels.
y = np.arange(0, 290.5)

x = np.arange(0, 20.5)

pcm = ax.pcolormesh(x, y, Z, rasterized=True) # you don't need rasterized=True
fig.colorbar(pcm)
plt.xticks(np.arange(w), list('PNIYLKCVFWABCDEFGHIJ'))

plt.show()


问:
How to set dynamic url in React Native 'Share' function

I'm referencing one of my props, a url (but in plain object form), in the Share component of React Native.  I've tried several different ways to get Share to actual be able to read it.  None have worked.  And they should....anyone see what I'm missing?

Here's the code:

```<code>onShareButtonPress() {
   const { image } = this.props.employee;
   const test = JSON.stringify(image);
     //console.log(test);
   Share.share({
      message: 'Here\'s your image:',
      url: test,
      title: 'Dealerslist Image'
   }, {
      // Android only:
      dialogTitle: 'Share Dealerslist goodness',
      // iOS only:
      excludedActivityTypes: [
       'com.apple.UIKit.activity.PostToTwitter'
     ]
   })
</code>```

This won't work either:

```<code> url: 'image',
</code>```

If I log 'test' I get the url as the expected string.  But Share still can't recognize it.  But if I copy the string straight from the console and hardcode/paste it in as the url, it works perfectly.

This code works:

```<code>Share.share({
message: 'Here\'s your image:',
url: "https://firebasestorage.googleapis.com/v0/b/ag-equipment-
      southwest.appspot.com/o/1512760876838.4595.jpg?
      alt=media&token=1bfeba0d-d788-4774-91a7-7801c8084b30",
title: 'Dealerslist Image'
</code>```

}

And 'test' logs exactly as:

```<code>"https://firebasestorage.googleapis.com/v0/b/ag-equipment-
southwest.appspot.com/o/1512760876838.4595.jpg?
alt=media&token=1bfeba0d-d788-4774-91a7-7801c8084b30"
</code>```

All of these I've tried with sharing to ios mail. And the dynamic link won't work with the mail.

However, if I just share to the ios clipboard, I get this:

```<code> Here's your image:%22https://firebasestorage....and so on
</code>```

I'm new to web and mobile development, so I'm not totally sure if the expected behavior is to copy '%22' as possibly a break in the line.  Regardless, the ios mail share isn't getting any of the url.

Any help would be appreciated! Thanks!

答:
You are doing a JSON.stringify on a string which will add two quotes at the start and end.

" = %22 which probably is the reason for the extra %22 codes

```<code>onShareButtonPress() {
   const { image } = this.props.employee;
   Share.share({
      message: 'Here\'s your image:',
      url: image,
      title: 'Dealerslist Image'
   }
   .
   .
   .
)
</code>```

But ideally you would want to try encodeURI and decodeURI if you don't want to deal with unexpected characters during the request flight.

URL ENCODING LIST

ENCODE URI

DECODE URI

const url = "https://google.com"

console.log(url);

console.log(JSON.stringify(url));```

Body:
I'm referencing one of my props, a url (but in plain object form), in the Share component of React Native.  I've tried several different ways to get Share to actual be able to read it.  None have worked.  And they should....anyone see what I'm missing?

Here's the code:

onShareButtonPress() {
   const { image } = this.props.employee;
   const test = JSON.stringify(image);
     //console.log(test);
   Share.share({
      message: 'Here\'s your image:',
      url: test,
      title: 'Dealerslist Image'
   }, {
      // Android only:
      dialogTitle: 'Share Dealerslist goodness',
      // iOS only:
      excludedActivityTypes: [
       'com.apple.UIKit.activity.PostToTwitter'
     ]
   })

This won't work either:

 url: 'image',

If I log 'test' I get the url as the expected string.  But Share still can't recognize it.  But if I copy the string straight from the console and hardcode/paste it in as the url, it works perfectly.

This code works:

Share.share({
message: 'Here\'s your image:',
url: "https://firebasestorage.googleapis.com/v0/b/ag-equipment-
      southwest.appspot.com/o/1512760876838.4595.jpg?
      alt=media&token=1bfeba0d-d788-4774-91a7-7801c8084b30",
title: 'Dealerslist Image'

}

And 'test' logs exactly as:

"https://firebasestorage.googleapis.com/v0/b/ag-equipment-
southwest.appspot.com/o/1512760876838.4595.jpg?
alt=media&token=1bfeba0d-d788-4774-91a7-7801c8084b30"

All of these I've tried with sharing to ios mail. And the dynamic link won't work with the mail.

However, if I just share to the ios clipboard, I get this:

 Here's your image:%22https://firebasestorage....and so on

I'm new to web and mobile development, so I'm not totally sure if the expected behavior is to copy '%22' as possibly a break in the line.  Regardless, the ios mail share isn't getting any of the url.

Any help would be appreciated! Thanks!

Body:
You are doing a JSON.stringify on a string which will add two quotes at the start and end.

" = %22 which probably is the reason for the extra %22 codes

onShareButtonPress() {
   const { image } = this.props.employee;
   Share.share({
      message: 'Here\'s your image:',
      url: image,
      title: 'Dealerslist Image'
   }
   .
   .
   .
)

But ideally you would want to try encodeURI and decodeURI if you don't want to deal with unexpected characters during the request flight.

URL ENCODING LIST

ENCODE URI

DECODE URI

const url = "https://google.com"

console.log(url);

console.log(JSON.stringify(url));


问:
Parallel updating RGBW LED strip; fast memory shuffle (with inline assembler?)
I am trying to parallel update four RGBW LED strips with an Arduino Nano.
The strips are wired to digital pins 0-3 which equals bit 0-3 of I/O register PORTD. (Image: LEDs wired to Arduino)

The strip type is SK6812 RGBW but i don't think this is a very important information. (Datasheet)

The important thing is that in order to update one LED you need to give it 32 bit of data in quick succession as described in the datasheet.
I've managed to do that by preparing an array of 32 bits ( named LED[32] ) which hold the information for one LED of each strip. Than load these values in I/O register PORTD to drive the pins high and low.
The LED[32] array looks like this:

(From LSB to MSB order:
w (white)
b (blue)
r (red)
g (green)

pins 4-7 were saved at the beginning and will be loaded in every frame (X) to keep them as they were)

<table border="1"

  bit7
  bit6
  bit5
  bit4
  bit3
  bit2
  bit1
  bit0

    X
    X
    X
    X
    W3_0
    W2_0
    W1_0
    W0_0

    X
    X
    X
    X
    W3_1
    W2_1
    W1_1
    W0_1

    X
    X
    X
    X
    W3_2
    W2_2
    W1_2
    W0_2

    X
    X
    X
    X
    W3_3
    W2_3
    W1_3
    W0_3

    ...
    ...
    ...
    ...
    ...
    ...
    ...
    ...

    X
    X
    X
    X
    r3_4
    r2_4
    r1_4
    r0_4

    X
    X
    X
    X
    r3_5
    r2_5
    r1_5
    r0_5

    X
    X
    X
    X
    r3_6
    r2_6
    r1_6
    r0_6

    X
    X
    X
    X
    r3_7
    r2_7
    r1_7
    r0_7

```
</div>
</div>
</p>

<p>This information needs to be calculated prior to the writing process of an LED.
The time between two writing processes must be less than 80uS!
For the 16 MHz Arduino that is 1280 cycles.</p>

<p>At this point my calculation is not fast enough.</p>

<p>The information of the LEDs is stored in an array named LEDs"Number of LEDs"4
One dimension of the array for each LED, the second one for the four colors, and the last one for the four different strips.</p>

<p>My code to write to all LEDs:</p>

```static inline __attribute__ ((always_inline)) void showPixel() {
  // Send the 32 Bits down every row. Remember that each pixel is 32 bits wide (8 bits each for R,G, B & W)
  uint8_t bit;
  uint8_t onPixel,offPixel; //output of PORTD when high or low is being written
  cli(); //no interrupts
  offPixel = PIXEL_PORT;  //safe output of Port D
  offPixel &= 0xf0; //create Bitmask for setting bit 4-7 of Port D to original value and leds off 0bxxxx0000
  onPixel = offPixel | 0x0f;  //led pins high plus IO pins as they were 0bxxxx1111

  for(uint8_t ledNr=0; ledNr < NUM_LEDS; ledNr++)  {

    shuffle(0,LEDs[ledNr][3][0],LEDs[ledNr][3][1],LEDs[ledNr][3][2],LEDs[ledNr][3][3],offPixel);//white
    shuffle(8,LEDs[ledNr][2][0],LEDs[ledNr][2][1],LEDs[ledNr][2][2],LEDs[ledNr][2][3],offPixel);//blue
    shuffle(16,LEDs[ledNr][0][0],LEDs[ledNr][0][1],LEDs[ledNr][0][2],LEDs[ledNr][0][3],offPixel);//red
    shuffle(24,LEDs[ledNr][1][0],LEDs[ledNr][1][1],LEDs[ledNr][1][2],LEDs[ledNr][1][3],offPixel);//green

    bit=32;
    while (bit--) { //send out the 32 bytes
      sendBitX4_lower( LED[bit] ,onPixel,offPixel);
    }
  }
  sei(); //activate interrupts
}
```

<p>My shuffle function:</p>

```static inline  __attribute__ ((always_inline)) void shuffle(uint8_t bit, uint8_t v0, uint8_t v1,uint8_t v2, uint8_t v3,uint8_t IOpins){
  uint8_t  res,pos,mask=8;
  pos=bit+8;
    //LED[bit]=0; EDIT: this was a test
    //LED[bit++]=0; to see if decreasing the resolution
    //LED[bit++]=0; speeds it up enough to work
    //bit++;        at 5 bit resolution it was barely fast enough
  while(bit<pos){
    if(v3 & mask) res=8;
    else res=0;
    if(v2 & mask) res|=4;
    if(v1 & mask) res|=2;
    if(v0 & mask) res|=1;
    mask<<=1;
    res|=IOpins;      //Set bits 0-3 to the output that was present
    LED[bit]=res;
    bit++;
  }
```

<p>It can be a bit hard to understand what needs to be done in the suffle function. I've tried to draw it so maybe you can understand it easier (attachment shuffle.pdf).
Essentially the calculation is split up in 4 parts for each color. Each shuffle will write to 8 bytes of the LED[32] array. This process looks a bit like a matrix that is being inverted. Each byte of the LED[32] has elements of 4 different bytes of the LEDs array. Starting with the LSB for LED[0] and moving up to the MSB for LED[8] and so on.</p>

<p>I've tried different examples of this. Some with bit shifting, some with pointers going through the arrays, but this was the fastest.</p>

<p>My question is: is it physically possible to do this calculation in this many cycles? And if yes, how?
Probably with inline assembler but i'm just getting into that...
Thanks for your help. If your interested we could refine this and make it accessible to everyone :)</p>

<p>Update:
I don't think it is possible to get around the shuffle, because the timing of output of 32 bit information per LED is critical. In my code the sendBitX4_lower() function is called 32 times to do that.
The time for sending one bit of information is 1.25µs±600ns lets say 1.9µs that is 30 cycles at max.</p>

<p>If you are interested this is the code:</p>

```static inline __attribute__ ((always_inline)) void sendBitX4_lower( uint8_t bits ,uint8_t onBits,uint8_t offBits ) {
    asm volatile (
      "out %[port], %[onBits] \n\t"           // 1st step - send T0H high

      ".rept %[T0HCycles] \n\t"               // Execute NOPs to delay exactly the specified number of cycles
        "nop \n\t"
      ".endr \n\t"

      "out %[port], %[bits] \n\t"             // set the output bits to thier values for T0H-T1H
      ".rept %[dataCycles] \n\t"               // Execute NOPs to delay exactly the specified number of cycles
      "nop \n\t"
      ".endr \n\t"

      "out %[port],%[offBits]  \n\t"        // last step - T1L all bits low

      // Don't need an explicit delay here since the overhead that follows will always be long enough
      ::
      [port]    "I" (_SFR_IO_ADDR(PIXEL_PORT)),
      [bits]   "d" (bits),
      [onBits]   "d" (onBits),
      [offBits]  "d" (offBits),
      [T0HCycles]  "I" (NS_TO_CYCLES(T0H) - 2),           // 1-bit width less overhead  for the actual bit setting, note that this delay could be longer and everything would still work
      [dataCycles]   "I" (NS_TO_CYCLES((T1H-T0H)) - 2)// Minimum interbit delay. Note that we probably don't need this at all since the loop overhead will be enough, but here for correctness
    );
    // Note that the inter-bit gap can be as long as you want as long as it doesn't exceed the reset timeout (which is A long time)
}
```

I guess a bit of time each frame could be used to do a part of the calculation but doubt all of it. That would be 960 cycles. It might work because the memory saving part is now unnecessary but on the other hand the writing to the port needs to be done.
So all calculation for one frame would need to find time in this sequence:Timing Overview That would involve load from RAM as well as four "if"s that would probably result in a conditional jump (sbrc 1-2 cycles).
I've had a look at the library from Adafruit (https://github.com/adafruit/Adafruit_NeoPixel) to get inspiration.

答:
How about (a blind try, as I don't have arduino IDE, neither did I try to compile with any C compiler, so you may need to fix syntax maybe):

static void showPixel() {
    const uint8_t colorOffsets[4] = { 1, 0, 2, 3 };     // move somewhere into constants?
    ... set up "offPixel" here
    cli(); //no interrupts
    for(uint8_t ledNr=0; ledNr < NUM_LEDS; ++ledNr)  {
        for (uint8_t colorIdx = 0; colorIdx < 4; ++colorIdx) {
            const uint8_t* v_ptr = LEDs[ledNr][colorOffsets[colorIdx]];
            uint8_t bitMask = 0x80;
            do {
                uint8_t toSend = offPixel;  // upper 4 bits preserved PORTD, lower 4 bits cleared
                // set lower 4 bits by the colour values
                if (v_ptr[0] & bitMask) toSend |= 1;
                if (v_ptr[1] & bitMask) toSend |= 2;
                if (v_ptr[2] & bitMask) toSend |= 4;
                if (v_ptr[3] & bitMask) toSend |= 8;

                //TODO send "toSend" to PORTD
                ???
                PIXEL_PORT = toSend;  // guessing it

                bitMask >>= 1;              // next bit of values
            } while (bitMask); // all 8 bits of color value
        }
    }
    sei(); //activate interrupts
}
```

<p>And I wouldn't inline that one, why? It sends data over all LEDs, sounds like big-enough unit to have it just once in code memory.</p>

<p>It should scan Green, Red, Blue, White from top bit for each stripe, build the byte to be sent to PORTD (pins 0-3 from LEDs data, pines 4-7 kept from <code>offPixel</code>). And then you should just send it. No shuffling in memory, reading the correct bits in the pattern in which they should be emitted.</p>

<p>Also it does send full 8 bits of colour, if you want to set certain bits to zero by force, you can probably change <code>while (bitMask)</code> to some particular bit test, and then emit <code>offPixel</code> value remaining times to emit 8 bits in total.</p>

<hr>

<p>EDIT:</p>

<p>I tried this source for a while in godbolt set to AVR gcc, and I have these observations...</p>

<p>First the inner source used (full source on godbolt link above. I was not sure how Arduino defines PORTD, so I put there some volatile memory absolute address, should be close enough):</p>

<pre class="lang-c prettyprint-override"><code>for(uint8_t ledNr=0; ledNr < NUM_LEDS; ++ledNr)  {
    for (uint8_t colorIdx = 0; colorIdx < 4; ++colorIdx) {
        const uint8_t* v_ptr = LEDs[ledNr][colorOffsets[colorIdx]];
        const uint8_t v0 = v_ptr[0];
        const uint8_t v1 = v_ptr[1];
        const uint8_t v2 = v_ptr[2];
        const uint8_t v3 = v_ptr[3];
        uint8_t bitMask = 0x80;
        do {
            PIXEL_PORT = offPixel;      // set the LED bits to low
            asm volatile("": : :"memory");
            // uint8_t toSend = offPixel;  // upper 4 bits preserved PORTD, lower 4 bits cleared
            // // set lower 4 bits by the colour values
            // if (v0 & bitMask) toSend |= 1;
            uint8_t toSend = offPixel | ((v0 & bitMask) ? 1 : 0);
            if (v1 & bitMask) toSend |= 2;
            if (v2 & bitMask) toSend |= 4;
            if (v3 & bitMask) toSend |= 8;

            PIXEL_PORT = toSend;        // set the LED bits to high
            asm volatile("": : :"memory");

            bitMask >>= 1;              // next bit of values
        } while (bitMask); // all 8 bits of color value
    } //for (uint8_t colorIdx = 0; colorIdx < 4; ++colorIdx) {
} //for(uint8_t ledNr=0; ledNr < NUM_LEDS; ++ledNr)
</code>```

The resulting assembly looks like a possible base to work upon, it unrolls the loop 8 times (for bitMask) and turns the bitMask test into specific sbrc + ori pairs, which makes sense to me. The problem is, that the off+on bit set on port will be too short (it switches bits ON and then immediately starts next bit by switching them OFF in the next instruction, and there's not much to do to slow it down, except adding nop delay loop).

And the major problem is, that to get fixed timing across all 32 LEDs, you would need to have to prepare the initial state ahead of unrolled loop, and keep preparing next state toward end of the 7/8th bit test in the delays, so the next LED would start in fixed time just like next bit does.

The C output directly doesn't look to be usable, but may be reasonable template for your own unrolled loop (if you are good enough in assembly, I don't want to write full showPixels() routine, because I never did AVR assembly, plus I don't know how reading/writing to port should be done, plus it's quite tedious to write unrolled loops of this size.

The core code (commented by me) (in this part the 4th bit is tested, i.e. bitMask == 0x10):

```<code>    out 52-0x20,r20    // PORTD = offPixel
    ldi r23,lo8(1)
    sbrs r24,4         // 4th bit (the number goes from 7 to 0)
    ldi r23,lo8(0)     // toSend = 0/1 (? (v0 & bitMask))
    or r23,r20         // toSend |= offPixel
    sbrc r25,4
    ori r23,lo8(2)     // if (v1 & bitMask) toSend |= 2
    sbrc r21,4
    ori r23,lo8(4)     // if (v2 & bitMask) toSend |= 4
    sbrc r22,4
    ori r23,lo8(8)     // if (v3 & bitMask) toSend |= 8
    out 52-0x20,r23    // PORTD = toSend
</code>```

I would write by hand the initial part in the same way as the remaining bit tests, i.e. (makes it much easier for reading by human to have all bits handled by the same fashion code):

```<code>    out 52-0x20,r20    //1c // PORTD = offPixel
    mov r23,r20        //1c // toSend = offPixel
    sbrc r24,4         //1/2c // 4th bit (the number goes from 7 to 0)
    ori r23,lo8(1)     //1c // if (v0 & bitMask) toSend |= 1
    sbrc r25,4         //1/2c
    ori r23,lo8(2)     //1c // if (v1 & bitMask) toSend |= 2
    sbrc r21,4         //1/2c
    ori r23,lo8(4)     //1c // if (v2 & bitMask) toSend |= 4
    sbrc r22,4         //1/2c
    ori r23,lo8(8)     //1c // if (v3 & bitMask) toSend |= 8
    out 52-0x20,r23    //1c // PORTD = toSend
</code>```

(I tried to modify C to suggest that, but the gcc instead inserts two branching rjmp to load the register directly with either offPixel or offPixel+1 value, annoying...)

The sbrc + ori pairs will take fixed 2 clocks for both skip/set condition, so after the offPixel is written to the port, it will take exactly 10 clock cycles to write ON state. That looks to be slightly off the accepted range, if I'm reading your timing overview correctly. So you can move the OFF out somewhere later, like ahead of second sbrc, that will make it 7 clocks between OFF and ON out. (actually hand holding gcc on godbolt works: https://godbolt.org/g/V2vf2X )

Then you have 4+12 for the next loop... that new beginning part (up till second sbrc is already eating 4c, and you have 12c to fill up by housekeeping or artificial delay.

And toward end (bits 2, 1, 0 ...) in the housekeeping/delay part you need to fetch new LED values into v0/v1/v2/v3 registers, for simplicity I would probably use two ranges of registers like r18+ for first pass, r26+ for second pass and do 16 times loop of the two (may need careful register usage design to fit within available spare registers).

Thinking about it, the load of vX values for stripes can also move ahead the pointer, i.e. ldd rX,Z+, that's about 2 cycles (I'm not sure which clocks to apply, on XMEGA not accessing SRAM you can be 1 cycle, but I think you are accessing SRAM with that LEDs?), i.e. 4x2 = 8 cycles. That can wholly fit into 12c delay with spare cycles to adjust Z (going from green [1] to red [0] and from red [0] to blue [2], i.e. sub v_ptr,8 in first case and add v_ptr,4 in second, and then the Z should already point to white [3] after blue [2] is finished. Also if you have LEDs aligned well, you can sub/add just the low part of Z).

So the total code architecture would be like:

prepare pointer ledptr into LEDs[0][1] (Z reg)

cli()

read offPixel (fixed reg for whole code)

{ // loop 32 times this

2c Y = pointer into nextColorPtr table { -8, +4, +0, +0 }

{ // loop 4 times this

8c read v0, v1, v2, v3 with Z+

1c toSend = offPixel

2c if (v0 & 0x80) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 14c)

6c 3x if (v1/2/3 & 0x80) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

~4-8c Z += [Y+] (add -8/+4/0/0 to Z from table at Y) (too lazy to try on my own to see what exact clocks that will be) (also depends whether you have LEDs aligned, so it's enough to adjust lower Z part, or you need to do proper 16b add to whole Z).

~8-4c artificial nop delay to fill up remaining time to 12c total

// second bit starts here

1c toSend = offPixel

2c if (v0 & 0x40) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x40) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

12c nop delay

// third bit starts here

1c toSend = offPixel

2c if (v0 & 0x20) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x20) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

12c nop delay

...

test if Y points beyond nextColorPtr and if this is last from main 32 loops and have branch into 3 variants of last bit code, one variant is loop to "// loop 4 times" continuing (must delay plus branch to loop in 4c to have 16c total till OFF state), second variant is looping back to "// loop 32 times" to proceed next LED, must be done in 2c to have total 16c till OFF state (i.e. just branch == 2c), third variant is to continue toward exit of the procedure (32 LEDs were processed), start each variant by nop delay filling it up to 12c total

// example of last bit variant for valid Y

// last bit starts here

1c toSend = offPixel

2c if (v0 & 0x01) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x01) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

2c nop nop

2c branch to // loop 4 times

...

// example of last bit variant for invalid Y, but valid Z pointer (or counter < 32)

// last bit starts here

1c toSend = offPixel

2c if (v0 & 0x01) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x01) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

2c branch to // loop 32 times

I'm not going to try to write inline ASM for gcc, because I'm completely lost at specifying the clobbered registers/etc.. i.e. making it valid gcc inline. Plus this took me way more time than I expected. (If I would do this for myself, I would write it rather in stand-alone assembly)

But it looks doable, if I understood your timing drawing correctly. So-so, but doable for 4 strips. If you would need more than 4 strips, there's still some delaying here and there to bump it probably to 8 strips at max, but that would require to unroll/interleave the start/end of loops much more aggressively, over several bits (for 8 strips it would probably need to interleave the housekeeping over whole 8 bits code, i.e. no copy/paste at all, each delay formed by tiny piece of next-LED preparation code, and it would need 2 sets of working regs).

If I didn't overlook anything, this should produce fixed 7 clock of OFF state with 16 clocks of ON state (23 clocks total between two bits) for whole 32 LEDs x 4 colors (128 bytes send to port).

The currently suggested source will be already well over 100 lines of code, very tedious to write, debug and maintain, but as you need fixed timing, looks like most reasonable approach.

Body:
I am trying to parallel update four RGBW LED strips with an Arduino Nano.
The strips are wired to digital pins 0-3 which equals bit 0-3 of I/O register PORTD. (Image: LEDs wired to Arduino)

The strip type is SK6812 RGBW but i don't think this is a very important information. (Datasheet)

The important thing is that in order to update one LED you need to give it 32 bit of data in quick succession as described in the datasheet.
I've managed to do that by preparing an array of 32 bits ( named LED[32] ) which hold the information for one LED of each strip. Than load these values in I/O register PORTD to drive the pins high and low.
The LED[32] array looks like this:

(From LSB to MSB order:
w (white)
b (blue)
r (red)
g (green)

pins 4-7 were saved at the beginning and will be loaded in every frame (X) to keep them as they were)

<table border="1"

  bit7
  bit6
  bit5
  bit4
  bit3
  bit2
  bit1
  bit0

    X
    X
    X
    X
    W3_0
    W2_0
    W1_0
    W0_0

    X
    X
    X
    X
    W3_1
    W2_1
    W1_1
    W0_1

    X
    X
    X
    X
    W3_2
    W2_2
    W1_2
    W0_2

    X
    X
    X
    X
    W3_3
    W2_3
    W1_3
    W0_3

    ...
    ...
    ...
    ...
    ...
    ...
    ...
    ...

    X
    X
    X
    X
    r3_4
    r2_4
    r1_4
    r0_4

    X
    X
    X
    X
    r3_5
    r2_5
    r1_5
    r0_5

    X
    X
    X
    X
    r3_6
    r2_6
    r1_6
    r0_6

    X
    X
    X
    X
    r3_7
    r2_7
    r1_7
    r0_7

This information needs to be calculated prior to the writing process of an LED.
The time between two writing processes must be less than 80uS!
For the 16 MHz Arduino that is 1280 cycles.

At this point my calculation is not fast enough.

The information of the LEDs is stored in an array named LEDs"Number of LEDs"4
One dimension of the array for each LED, the second one for the four colors, and the last one for the four different strips.

My code to write to all LEDs:

static inline __attribute__ ((always_inline)) void showPixel() {
  // Send the 32 Bits down every row. Remember that each pixel is 32 bits wide (8 bits each for R,G, B & W)
  uint8_t bit;
  uint8_t onPixel,offPixel; //output of PORTD when high or low is being written
  cli(); //no interrupts
  offPixel = PIXEL_PORT;  //safe output of Port D
  offPixel &= 0xf0; //create Bitmask for setting bit 4-7 of Port D to original value and leds off 0bxxxx0000
  onPixel = offPixel | 0x0f;  //led pins high plus IO pins as they were 0bxxxx1111

  for(uint8_t ledNr=0; ledNr < NUM_LEDS; ledNr++)  {

    shuffle(0,LEDs[ledNr][3][0],LEDs[ledNr][3][1],LEDs[ledNr][3][2],LEDs[ledNr][3][3],offPixel);//white
    shuffle(8,LEDs[ledNr][2][0],LEDs[ledNr][2][1],LEDs[ledNr][2][2],LEDs[ledNr][2][3],offPixel);//blue
    shuffle(16,LEDs[ledNr][0][0],LEDs[ledNr][0][1],LEDs[ledNr][0][2],LEDs[ledNr][0][3],offPixel);//red
    shuffle(24,LEDs[ledNr][1][0],LEDs[ledNr][1][1],LEDs[ledNr][1][2],LEDs[ledNr][1][3],offPixel);//green

    bit=32;
    while (bit--) { //send out the 32 bytes
      sendBitX4_lower( LED[bit] ,onPixel,offPixel);
    }
  }
  sei(); //activate interrupts
}

My shuffle function:

static inline  __attribute__ ((always_inline)) void shuffle(uint8_t bit, uint8_t v0, uint8_t v1,uint8_t v2, uint8_t v3,uint8_t IOpins){
  uint8_t  res,pos,mask=8;
  pos=bit+8;
    //LED[bit]=0; EDIT: this was a test
    //LED[bit++]=0; to see if decreasing the resolution
    //LED[bit++]=0; speeds it up enough to work
    //bit++;        at 5 bit resolution it was barely fast enough
  while(bit<pos){
    if(v3 & mask) res=8;
    else res=0;
    if(v2 & mask) res|=4;
    if(v1 & mask) res|=2;
    if(v0 & mask) res|=1;
    mask<<=1;
    res|=IOpins;      //Set bits 0-3 to the output that was present
    LED[bit]=res;
    bit++;
  }

It can be a bit hard to understand what needs to be done in the suffle function. I've tried to draw it so maybe you can understand it easier (attachment shuffle.pdf).
Essentially the calculation is split up in 4 parts for each color. Each shuffle will write to 8 bytes of the LED[32] array. This process looks a bit like a matrix that is being inverted. Each byte of the LED[32] has elements of 4 different bytes of the LEDs array. Starting with the LSB for LED[0] and moving up to the MSB for LED[8] and so on.

I've tried different examples of this. Some with bit shifting, some with pointers going through the arrays, but this was the fastest.

My question is: is it physically possible to do this calculation in this many cycles? And if yes, how?
Probably with inline assembler but i'm just getting into that...
Thanks for your help. If your interested we could refine this and make it accessible to everyone :)

Update:
I don't think it is possible to get around the shuffle, because the timing of output of 32 bit information per LED is critical. In my code the sendBitX4_lower() function is called 32 times to do that.
The time for sending one bit of information is 1.25µs±600ns lets say 1.9µs that is 30 cycles at max.

If you are interested this is the code:

static inline __attribute__ ((always_inline)) void sendBitX4_lower( uint8_t bits ,uint8_t onBits,uint8_t offBits ) {
    asm volatile (
      "out %[port], %[onBits] \n\t"           // 1st step - send T0H high

      ".rept %[T0HCycles] \n\t"               // Execute NOPs to delay exactly the specified number of cycles
        "nop \n\t"
      ".endr \n\t"

      "out %[port], %[bits] \n\t"             // set the output bits to thier values for T0H-T1H
      ".rept %[dataCycles] \n\t"               // Execute NOPs to delay exactly the specified number of cycles
      "nop \n\t"
      ".endr \n\t"

      "out %[port],%[offBits]  \n\t"        // last step - T1L all bits low

      // Don't need an explicit delay here since the overhead that follows will always be long enough
      ::
      [port]    "I" (_SFR_IO_ADDR(PIXEL_PORT)),
      [bits]   "d" (bits),
      [onBits]   "d" (onBits),
      [offBits]  "d" (offBits),
      [T0HCycles]  "I" (NS_TO_CYCLES(T0H) - 2),           // 1-bit width less overhead  for the actual bit setting, note that this delay could be longer and everything would still work
      [dataCycles]   "I" (NS_TO_CYCLES((T1H-T0H)) - 2)// Minimum interbit delay. Note that we probably don't need this at all since the loop overhead will be enough, but here for correctness
    );
    // Note that the inter-bit gap can be as long as you want as long as it doesn't exceed the reset timeout (which is A long time)
}

I guess a bit of time each frame could be used to do a part of the calculation but doubt all of it. That would be 960 cycles. It might work because the memory saving part is now unnecessary but on the other hand the writing to the port needs to be done.
So all calculation for one frame would need to find time in this sequence:Timing Overview That would involve load from RAM as well as four "if"s that would probably result in a conditional jump (sbrc 1-2 cycles).
I've had a look at the library from Adafruit (https://github.com/adafruit/Adafruit_NeoPixel) to get inspiration.

Body:
How about (a blind try, as I don't have arduino IDE, neither did I try to compile with any C compiler, so you may need to fix syntax maybe):

static void showPixel() {
    const uint8_t colorOffsets[4] = { 1, 0, 2, 3 };     // move somewhere into constants?
    ... set up "offPixel" here
    cli(); //no interrupts
    for(uint8_t ledNr=0; ledNr < NUM_LEDS; ++ledNr)  {
        for (uint8_t colorIdx = 0; colorIdx < 4; ++colorIdx) {
            const uint8_t* v_ptr = LEDs[ledNr][colorOffsets[colorIdx]];
            uint8_t bitMask = 0x80;
            do {
                uint8_t toSend = offPixel;  // upper 4 bits preserved PORTD, lower 4 bits cleared
                // set lower 4 bits by the colour values
                if (v_ptr[0] & bitMask) toSend |= 1;
                if (v_ptr[1] & bitMask) toSend |= 2;
                if (v_ptr[2] & bitMask) toSend |= 4;
                if (v_ptr[3] & bitMask) toSend |= 8;

                //TODO send "toSend" to PORTD
                ???
                PIXEL_PORT = toSend;  // guessing it

                bitMask >>= 1;              // next bit of values
            } while (bitMask); // all 8 bits of color value
        }
    }
    sei(); //activate interrupts
}

And I wouldn't inline that one, why? It sends data over all LEDs, sounds like big-enough unit to have it just once in code memory.

It should scan Green, Red, Blue, White from top bit for each stripe, build the byte to be sent to PORTD (pins 0-3 from LEDs data, pines 4-7 kept from offPixel). And then you should just send it. No shuffling in memory, reading the correct bits in the pattern in which they should be emitted.

Also it does send full 8 bits of colour, if you want to set certain bits to zero by force, you can probably change while (bitMask) to some particular bit test, and then emit offPixel value remaining times to emit 8 bits in total.

EDIT:

I tried this source for a while in godbolt set to AVR gcc, and I have these observations...

First the inner source used (full source on godbolt link above. I was not sure how Arduino defines PORTD, so I put there some volatile memory absolute address, should be close enough):

for(uint8_t ledNr=0; ledNr < NUM_LEDS; ++ledNr)  {
    for (uint8_t colorIdx = 0; colorIdx < 4; ++colorIdx) {
        const uint8_t* v_ptr = LEDs[ledNr][colorOffsets[colorIdx]];
        const uint8_t v0 = v_ptr[0];
        const uint8_t v1 = v_ptr[1];
        const uint8_t v2 = v_ptr[2];
        const uint8_t v3 = v_ptr[3];
        uint8_t bitMask = 0x80;
        do {
            PIXEL_PORT = offPixel;      // set the LED bits to low
            asm volatile("": : :"memory");
            // uint8_t toSend = offPixel;  // upper 4 bits preserved PORTD, lower 4 bits cleared
            // // set lower 4 bits by the colour values
            // if (v0 & bitMask) toSend |= 1;
            uint8_t toSend = offPixel | ((v0 & bitMask) ? 1 : 0);
            if (v1 & bitMask) toSend |= 2;
            if (v2 & bitMask) toSend |= 4;
            if (v3 & bitMask) toSend |= 8;

            PIXEL_PORT = toSend;        // set the LED bits to high
            asm volatile("": : :"memory");

            bitMask >>= 1;              // next bit of values
        } while (bitMask); // all 8 bits of color value
    } //for (uint8_t colorIdx = 0; colorIdx < 4; ++colorIdx) {
} //for(uint8_t ledNr=0; ledNr < NUM_LEDS; ++ledNr)

The resulting assembly looks like a possible base to work upon, it unrolls the loop 8 times (for bitMask) and turns the bitMask test into specific sbrc + ori pairs, which makes sense to me. The problem is, that the off+on bit set on port will be too short (it switches bits ON and then immediately starts next bit by switching them OFF in the next instruction, and there's not much to do to slow it down, except adding nop delay loop).

And the major problem is, that to get fixed timing across all 32 LEDs, you would need to have to prepare the initial state ahead of unrolled loop, and keep preparing next state toward end of the 7/8th bit test in the delays, so the next LED would start in fixed time just like next bit does.

The C output directly doesn't look to be usable, but may be reasonable template for your own unrolled loop (if you are good enough in assembly, I don't want to write full showPixels() routine, because I never did AVR assembly, plus I don't know how reading/writing to port should be done, plus it's quite tedious to write unrolled loops of this size.

The core code (commented by me) (in this part the 4th bit is tested, i.e. bitMask == 0x10):

    out 52-0x20,r20    // PORTD = offPixel
    ldi r23,lo8(1)
    sbrs r24,4         // 4th bit (the number goes from 7 to 0)
    ldi r23,lo8(0)     // toSend = 0/1 (? (v0 & bitMask))
    or r23,r20         // toSend |= offPixel
    sbrc r25,4
    ori r23,lo8(2)     // if (v1 & bitMask) toSend |= 2
    sbrc r21,4
    ori r23,lo8(4)     // if (v2 & bitMask) toSend |= 4
    sbrc r22,4
    ori r23,lo8(8)     // if (v3 & bitMask) toSend |= 8
    out 52-0x20,r23    // PORTD = toSend

I would write by hand the initial part in the same way as the remaining bit tests, i.e. (makes it much easier for reading by human to have all bits handled by the same fashion code):

    out 52-0x20,r20    //1c // PORTD = offPixel
    mov r23,r20        //1c // toSend = offPixel
    sbrc r24,4         //1/2c // 4th bit (the number goes from 7 to 0)
    ori r23,lo8(1)     //1c // if (v0 & bitMask) toSend |= 1
    sbrc r25,4         //1/2c
    ori r23,lo8(2)     //1c // if (v1 & bitMask) toSend |= 2
    sbrc r21,4         //1/2c
    ori r23,lo8(4)     //1c // if (v2 & bitMask) toSend |= 4
    sbrc r22,4         //1/2c
    ori r23,lo8(8)     //1c // if (v3 & bitMask) toSend |= 8
    out 52-0x20,r23    //1c // PORTD = toSend

(I tried to modify C to suggest that, but the gcc instead inserts two branching rjmp to load the register directly with either offPixel or offPixel+1 value, annoying...)

The sbrc + ori pairs will take fixed 2 clocks for both skip/set condition, so after the offPixel is written to the port, it will take exactly 10 clock cycles to write ON state. That looks to be slightly off the accepted range, if I'm reading your timing overview correctly. So you can move the OFF out somewhere later, like ahead of second sbrc, that will make it 7 clocks between OFF and ON out. (actually hand holding gcc on godbolt works: https://godbolt.org/g/V2vf2X )

Then you have 4+12 for the next loop... that new beginning part (up till second sbrc is already eating 4c, and you have 12c to fill up by housekeeping or artificial delay.

And toward end (bits 2, 1, 0 ...) in the housekeeping/delay part you need to fetch new LED values into v0/v1/v2/v3 registers, for simplicity I would probably use two ranges of registers like r18+ for first pass, r26+ for second pass and do 16 times loop of the two (may need careful register usage design to fit within available spare registers).

Thinking about it, the load of vX values for stripes can also move ahead the pointer, i.e. ldd rX,Z+, that's about 2 cycles (I'm not sure which clocks to apply, on XMEGA not accessing SRAM you can be 1 cycle, but I think you are accessing SRAM with that LEDs?), i.e. 4x2 = 8 cycles. That can wholly fit into 12c delay with spare cycles to adjust Z (going from green [1] to red [0] and from red [0] to blue [2], i.e. sub v_ptr,8 in first case and add v_ptr,4 in second, and then the Z should already point to white [3] after blue [2] is finished. Also if you have LEDs aligned well, you can sub/add just the low part of Z).

So the total code architecture would be like:

prepare pointer ledptr into LEDs[0][1] (Z reg)

cli()

read offPixel (fixed reg for whole code)

{ // loop 32 times this

2c Y = pointer into nextColorPtr table { -8, +4, +0, +0 }

{ // loop 4 times this

8c read v0, v1, v2, v3 with Z+

1c toSend = offPixel

2c if (v0 & 0x80) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 14c)

6c 3x if (v1/2/3 & 0x80) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

~4-8c Z += [Y+] (add -8/+4/0/0 to Z from table at Y) (too lazy to try on my own to see what exact clocks that will be) (also depends whether you have LEDs aligned, so it's enough to adjust lower Z part, or you need to do proper 16b add to whole Z).

~8-4c artificial nop delay to fill up remaining time to 12c total

// second bit starts here

1c toSend = offPixel

2c if (v0 & 0x40) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x40) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

12c nop delay

// third bit starts here

1c toSend = offPixel

2c if (v0 & 0x20) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x20) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

12c nop delay

...

test if Y points beyond nextColorPtr and if this is last from main 32 loops and have branch into 3 variants of last bit code, one variant is loop to "// loop 4 times" continuing (must delay plus branch to loop in 4c to have 16c total till OFF state), second variant is looping back to "// loop 32 times" to proceed next LED, must be done in 2c to have total 16c till OFF state (i.e. just branch == 2c), third variant is to continue toward exit of the procedure (32 LEDs were processed), start each variant by nop delay filling it up to 12c total

// example of last bit variant for valid Y

// last bit starts here

1c toSend = offPixel

2c if (v0 & 0x01) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x01) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

2c nop nop

2c branch to // loop 4 times

...

// example of last bit variant for invalid Y, but valid Z pointer (or counter < 32)

// last bit starts here

1c toSend = offPixel

2c if (v0 & 0x01) toSend |= 1

1c PORTD = offPixel   // OFF state send here (after 16c since ON state)

6c 3x if (v1/2/3 & 0x01) toSend |= 2/4/8

1c PORTD = toSend     // ON state send here (after 7c)

2c branch to // loop 32 times

I'm not going to try to write inline ASM for gcc, because I'm completely lost at specifying the clobbered registers/etc.. i.e. making it valid gcc inline. Plus this took me way more time than I expected. (If I would do this for myself, I would write it rather in stand-alone assembly)

But it looks doable, if I understood your timing drawing correctly. So-so, but doable for 4 strips. If you would need more than 4 strips, there's still some delaying here and there to bump it probably to 8 strips at max, but that would require to unroll/interleave the start/end of loops much more aggressively, over several bits (for 8 strips it would probably need to interleave the housekeeping over whole 8 bits code, i.e. no copy/paste at all, each delay formed by tiny piece of next-LED preparation code, and it would need 2 sets of working regs).

If I didn't overlook anything, this should produce fixed 7 clock of OFF state with 16 clocks of ON state (23 clocks total between two bits) for whole 32 LEDs x 4 colors (128 bytes send to port).

The currently suggested source will be already well over 100 lines of code, very tedious to write, debug and maintain, but as you need fixed timing, looks like most reasonable approach.


问:
How do I create a slideshow images with more pageviews on wordpress
I want to make users click one forward/backward button and increase one pageview. For example, 20 slide images will have 20 pageviews.
Now I have follow W3 sample to make this slideshow (https://www.w3schools.com/howto/howto_js_slideshow.asp). However, this will not crease a pageviews. </p>

答:
To send a page view (assuming Google Analytics is loaded):

ga('send', 'pageview', location.pathname);

More on that here: https://developers.google.com/analytics/devguides/collection/analyticsjs/pages

Could add the ga('send', 'pageview', location.pathname); code within the onClick handler for the forward/backward buttons, or within the slider code transitions to the next/previous slide.


问:
Performance issue with Admob banners in multiple fragments
I have an app that has one main activity with FrameLayout. Many fragments are created according to users' input. Every fragment has one admob banner ad using Adview.

I add fragments using the code;

```<code>getSupportFragmentManager().beginTransaction()
                           .add(R.id.container, Constants.frg1, Constants.frgTag1)
                           .addToBackStack(Constants.frgTag1)
                           .commit();
</code>```

I don't want to use transaction.replace() method because I don't want my previous fragment to be recreated when backpressed that all fragments are getting data from a remote server.

So when I add new fragment a new Adview is created inside the new fragment in onCreateView method.

After get around 10 fragments my app starts to get laggy. When I dont use Adview there is no problem with the performance.

You can say that I can use only one Adview inside the MainActivity that contains the fragments but I dont want that because I have a BottomNavigationView that is visible along the application. BottomNavigationBar + Adview = very little place remains for my app content in the screen.

So is there any idea to optimize my app performance using many fragment and each has its own AdView?

答:
After get around 10 fragments my app starts to get laggy. When I dont
  use Adview there is no problem with the performance.

If you are adding multiple Fragments to the backStack, your app will require more resources to store this elements, now adding an advertisement on every Fragment the result will be a high resource consumption, fast battery drainage,  slow application, etc.

The use of Fragments in an application is intended to represent a portion of an UI in an Activity, in fact you will use a complete Fragment to change all the UI in an Activity.

Keeping several Fragments in the backstack is almost like keeping several Activies in the stack, this aproach is incorrect an will cause problems in your application!

How optimize your app with multiple Fragments/ads

1)Use the method onPause() of your activity to destroy the Ad and onResume() to recreate it if you are using the Activity

How to solve adview CPU consuming.

2) Implement Admob via java code:

AdMob banners cause high CPU usage

3) Enable hardware Acceleration:

Enable to your activity:

```<code> <activity android:hardwareAccelerated="true" />
</code>```

or in all your application:

```<code><application android:hardwareAccelerated="true">
</code>```

4) And the most important, try to change your aproach, if you are using fragments you will make transactions to have only one in memory.

Body:
I have an app that has one main activity with FrameLayout. Many fragments are created according to users' input. Every fragment has one admob banner ad using Adview.

I add fragments using the code;

getSupportFragmentManager().beginTransaction()
                           .add(R.id.container, Constants.frg1, Constants.frgTag1)
                           .addToBackStack(Constants.frgTag1)
                           .commit();

I don't want to use transaction.replace() method because I don't want my previous fragment to be recreated when backpressed that all fragments are getting data from a remote server.

So when I add new fragment a new Adview is created inside the new fragment in onCreateView method.

After get around 10 fragments my app starts to get laggy. When I dont use Adview there is no problem with the performance.

You can say that I can use only one Adview inside the MainActivity that contains the fragments but I dont want that because I have a BottomNavigationView that is visible along the application. BottomNavigationBar + Adview = very little place remains for my app content in the screen.

So is there any idea to optimize my app performance using many fragment and each has its own AdView?

Body:
After get around 10 fragments my app starts to get laggy. When I dont
  use Adview there is no problem with the performance.

If you are adding multiple Fragments to the backStack, your app will require more resources to store this elements, now adding an advertisement on every Fragment the result will be a high resource consumption, fast battery drainage,  slow application, etc.

The use of Fragments in an application is intended to represent a portion of an UI in an Activity, in fact you will use a complete Fragment to change all the UI in an Activity.

Keeping several Fragments in the backstack is almost like keeping several Activies in the stack, this aproach is incorrect an will cause problems in your application!

How optimize your app with multiple Fragments/ads

1)Use the method onPause() of your activity to destroy the Ad and onResume() to recreate it if you are using the Activity

How to solve adview CPU consuming.

2) Implement Admob via java code:

AdMob banners cause high CPU usage

3) Enable hardware Acceleration:

Enable to your activity:

 <activity android:hardwareAccelerated="true" />

or in all your application:

<application android:hardwareAccelerated="true">

4) And the most important, try to change your aproach, if you are using fragments you will make transactions to have only one in memory.


问:
Why is my position:sticky not working?
I want my navigation bar to be sticky, but it's not working. I'm also using some basic jQuery to toggle slidedown for class "dropmenu". I also tried position sticky for  element and still it wouldn't work.
This is HTML and CSS :

.dropmenu {
  display: block;
  height: 65px;
  width: 100%;
  background: url("images/menuicon.png") no-repeat 98% center;
  background-color: #404040;
  cursor: pointer;
}

nav ul {
  padding: 0;
  overflow: hidden;
  background: #505050;
  display: none;
}

nav ul li {
  display: block;
  float: none;
  text-align: left;
  width: 100%;
  margin: 0;
}

nav ul li a {
  color: white;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin: 0;
}

div.sticky {
  position: sticky;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="center">
        <header>
            <img class="headerImage" src="images/header.png"/>
            <hr class="menu">
            <div class="sticky">

                <nav class="desktop">
                    <ul>
                        <li>Sertet</li>
                        <li>Rtretrti</li>
                        <li>ertettterli</li>
                        <li>retemi</li>
                        <li>Kerterti</li>
                    </ul>
                </nav>
            </div>
            </header>
        <hr class="menu">
   <p>content goes here</p>
</div></code>```

So what would be the problem?

答:
When you place a position:sticky element inside another element things can get tricky. The sticky element will only travel the height of the parent element so you need to have space in your parent element for the sticky element to move because position: sticky is scoped to the parent element and not the page. The parents overflow and display property can also have an effect. You can try to set the display property of your parent elements to display: intital.

try adding the following:

```<code>.center, header{
  display:initial;
}
</code>```

You can probably set it to inline or inline-block as well depending on your needs.

Here is your snippet with that added along with a couple of other things just for display purposes:

body{
  height:200vh;
}

.center, header{
  display:initial;
}

.dropmenu {
  display: block;
  height: 65px;
  width: 100%;
  background: url("images/menuicon.png") no-repeat 98% center;
  background-color: #404040;
  cursor: pointer;
}

nav ul {
  padding: 0;
  overflow: hidden;
  background: #505050;
  display: none;
}

nav ul li {
  display: block;
  float: none;
  text-align: left;
  width: 100%;
  margin: 0;
}

nav ul li a {
  color: white;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin: 0;
}

div.sticky {
  position: sticky;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="height:100px; background:green;"></div>

    <div class="center">
        <header>
            <img class="headerImage" src="images/header.png"/>
            <hr class="menu">
            <div class="sticky">

                <nav class="desktop">
                    <ul>
                        <li>Sertet</li>
                        <li>Rtretrti</li>
                        <li>ertettterli</li>
                        <li>retemi</li>
                        <li>Kerterti</li>
                    </ul>
                </nav>
            </div>
            </header>
        <hr class="menu">
   <p>content goes here</p>
</div></code>```

Title: Why is my position:sticky not working?

Body:
I want my navigation bar to be sticky, but it's not working. I'm also using some basic jQuery to toggle slidedown for class "dropmenu". I also tried position sticky for  element and still it wouldn't work.
This is HTML and CSS :

.dropmenu {
  display: block;
  height: 65px;
  width: 100%;
  background: url("images/menuicon.png") no-repeat 98% center;
  background-color: #404040;
  cursor: pointer;
}

nav ul {
  padding: 0;
  overflow: hidden;
  background: #505050;
  display: none;
}

nav ul li {
  display: block;
  float: none;
  text-align: left;
  width: 100%;
  margin: 0;
}

nav ul li a {
  color: white;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin: 0;
}

div.sticky {
  position: sticky;
  top: 0;
}

Sertet

Rtretrti

ertettterli

retemi

Kerterti

content goes here

So what would be the problem?

Body:
When you place a position:sticky element inside another element things can get tricky. The sticky element will only travel the height of the parent element so you need to have space in your parent element for the sticky element to move because position: sticky is scoped to the parent element and not the page. The parents overflow and display property can also have an effect. You can try to set the display property of your parent elements to display: intital.

try adding the following:

.center, header{
  display:initial;
}

You can probably set it to inline or inline-block as well depending on your needs.

Here is your snippet with that added along with a couple of other things just for display purposes:

body{
  height:200vh;
}

.center, header{
  display:initial;
}

.dropmenu {
  display: block;
  height: 65px;
  width: 100%;
  background: url("images/menuicon.png") no-repeat 98% center;
  background-color: #404040;
  cursor: pointer;
}

nav ul {
  padding: 0;
  overflow: hidden;
  background: #505050;
  display: none;
}

nav ul li {
  display: block;
  float: none;
  text-align: left;
  width: 100%;
  margin: 0;
}

nav ul li a {
  color: white;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin: 0;
}

div.sticky {
  position: sticky;
  top: 0;
}

<div style="height:100px; background:green;"></div>

    <div class="center">
        <header>
            <img class="headerImage" src="images/header.png"/>
            <hr class="menu">
            <div class="sticky">
                <a class="dropmenu"></a>
                <nav class="desktop">
                    <ul>
                        <li><a href="index.php">Sertet</a></li>
                        <li><a href="index.php">Rtretrti</a></li>
                        <li><a href="photos.php">ertettterli</a></li>
                        <li><a href="index.php">retemi</a></li>
                        <li><a href="index.php">Kerterti</a></li>
                    </ul>
                </nav>
            </div>
            </header>
        <hr class="menu">
   <p>content goes here</p>
</div>

ContentLicense: CC BY-SA 4.0


问:
Spring: Redirect depending the view
I have 2 indentical forms (View A and View B) that use the same controller. I would like it when I do the post of view A, redirect me to a url x and when I do post view B redirects me to another url (y). Is this possible in this function

```<code>@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    CloseCaseFrom sendCloseCaseFrom = new CloseCaseFrom();
    sendCloseCaseFrom.setDetail(closeCaseFrom.getDetail());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdPanic(closeCaseFrom.getIdPanic());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdStaff(user.getIdStaff());
    sendCloseCaseFrom.setIdUserSession(user.getIdUser());
    sendCloseCaseFrom.setSessionToken(user.getToken());

    panic.mClosePanicCase(sendCloseCaseFrom);

    return "redirect:/alerts";

}
</code>```

How can I know, which view trigger the controller?

答:
You could add a hidden input element in each view with the same name but a different value. You then get that value in your controller and redirect based on that.

This input is in ViewA

```<code><input type="hidden" name="destination" value="a" />
</code>```

This input is in ViewB

```<code><input type="hidden" name="destination" value="b" />
</code>```

And in your controller

```<code>@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@RequestParam destination, @ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    //..
    if (destination.equals("a")) {
        // a goes to urlx
        return "redirect:/urlx";
    if (destination.equals("b")) { // or just else {
        // b goes to urly
        return "redirect:/urly";

}
</code>```

Or instead of values a or b you could have the actual destination as a value in the input fields and avoid using if, just plug that destination in your redirect.

Title: Spring: Redirect depending the view

Body:
I have 2 indentical forms (View A and View B) that use the same controller. I would like it when I do the post of view A, redirect me to a url x and when I do post view B redirects me to another url (y). Is this possible in this function

@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    CloseCaseFrom sendCloseCaseFrom = new CloseCaseFrom();
    sendCloseCaseFrom.setDetail(closeCaseFrom.getDetail());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdPanic(closeCaseFrom.getIdPanic());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdStaff(user.getIdStaff());
    sendCloseCaseFrom.setIdUserSession(user.getIdUser());
    sendCloseCaseFrom.setSessionToken(user.getToken());

    panic.mClosePanicCase(sendCloseCaseFrom);

    return "redirect:/alerts";

}

How can I know, which view trigger the controller?

Body:
You could add a hidden input element in each view with the same name but a different value. You then get that value in your controller and redirect based on that.

This input is in ViewA

<input type="hidden" name="destination" value="a" />

This input is in ViewB

<input type="hidden" name="destination" value="b" />

And in your controller

@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@RequestParam destination, @ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    //..
    if (destination.equals("a")) {
        // a goes to urlx
        return "redirect:/urlx";
    if (destination.equals("b")) { // or just else {
        // b goes to urly
        return "redirect:/urly";

}

Or instead of values a or b you could have the actual destination as a value in the input fields and avoid using if, just plug that destination in your redirect.


问:
pyspark split csv with spaces in string - jupyter notebook
I do not want to read a text file, I want to perform the action over an existing Dataframe

my DataFrame has only one column text, like a file, "tabSeparator".

It is a structured file, with 3 columns, separator is a tab.
In case the column has an embedded tab, it is enclosed in double quotes ("xxx xx")

Example:

```<code>-------------------------
col_0
-------------------------
c11   c12    c13
c21 c22 c23
"c 31" "c 32" c33
</code>```

I am using this regular expression:
I am using pyspark with Jupyter Notebook

```<code>myre = '([\\t ]?(\\".*?\\"|[^\\t ]+))'

df = textDF.withColumn("tmp", split( col("_c0"), myre))\
      .select(\
        col("tmp").getItem(0).alias("col_1"),\
        col("tmp").getItem(1).alias("col_2"),\
        col("tmp").getItem(2).alias("col_3")
      )
</code>```

Not sure if the problem is with the regular expression or my way to parse the file but I cannot create a new DataFrame with the 3 columns parsed, resulting on:

```<code>-------------------
|col_1|col_2|col_3|
------+-----+------
| c11 | c12 | c13 |
| c21 | c22 | c23 |
| c 31| c 32| c 33|
-------------------
</code>```

答:
Obviously the problem that you have is that there are two possible separators.

With DataFrames it is very simple to load files with only one separator, for example tab separators, they are considered like CSV files but instead of a comma, it is just a tab.

In this particular scenario you would read them like this:

yourDF = spark.read.option("delimiter", "\t").csv('/tabSeparator/')

But if you have multiple, I believe the only option is to use a regex. You could use RDDs too and write a longer function and use map.

Body:
I do not want to read a text file, I want to perform the action over an existing Dataframe

my DataFrame has only one column text, like a file, "tabSeparator".

It is a structured file, with 3 columns, separator is a tab.
In case the column has an embedded tab, it is enclosed in double quotes ("xxx xx")

Example:

-------------------------
col_0
-------------------------
c11   c12    c13
c21 c22 c23
"c 31" "c 32" c33

I am using this regular expression:
I am using pyspark with Jupyter Notebook

myre = '([\\t ]?(\\".*?\\"|[^\\t ]+))'

df = textDF.withColumn("tmp", split( col("_c0"), myre))\
      .select(\
        col("tmp").getItem(0).alias("col_1"),\
        col("tmp").getItem(1).alias("col_2"),\
        col("tmp").getItem(2).alias("col_3")
      )

Not sure if the problem is with the regular expression or my way to parse the file but I cannot create a new DataFrame with the 3 columns parsed, resulting on:

-------------------
|col_1|col_2|col_3|
------+-----+------
| c11 | c12 | c13 |
| c21 | c22 | c23 |
| c 31| c 32| c 33|
-------------------


问:
Check if an argument is a double
Iḿ developing a program and I need to check if one of the char arrays passed by the argv are numbers, the problem comes when I have parameters like 2_two or 2-2 , what I've tryed doesn't works cause catch the number 2 and keeps the program running when it should exit.
I have tryed with atrof(), sprintf(), but didn work.

```<code>double from;
double to;
double jump;
switch (argc){
    case 2: to = atof(argv [1]); from =10; jump =1; break;
    case 3: to = atof(argv [1]); from = atof(argv[2]); jump = 1; break;
    case 4: to = atof(argv [1]); from = atof(argv[2]); jump =atof(argv [3]); break;
    default: from=1; to = 10; jump =1;
}
if (from == 0.0){
    char message []= "The parameter \"from\" is not a valid number";
    Error(EX_USAGE,message);
}else if (to==0.0){
    char message []= "The parameter \"to\" is not a valid number";
    Error(EX_USAGE,message);
}else if (jump==0.0){
    char message []= "The parameter \"jump\" is not a valid number";
    Error(EX_USAGE,message);
}
</code>```

The method Error is an auxiliar that exit the program with the code error and the message

So what I need is the program exit when I get a parameter that is not just number.

答:
Use strtod (include <stdlib.h>)

```<code>double strtod(const char *nptr, char **endptr);
</code>```

From the man

If endptr is not NULL, a pointer to the character after the last  character  used  in  the
         conversion is stored in the location referenced by endptr.

Example of use

```<code>char *endptr;

double d = strtod(argv[1], &endptr);

int ok = endptr == argv[1] + strlen(argv[1]);
</code>```

If endptr points to the trailing \0 in argv[1], that means the whole string was converted.

ok is 1 meaning the conversion was done up to the end of argv[1].

```<code>if (ok) {
    // use `d`, the converted number
}
</code>```

Title: Check if an argument is a double

Body:
Iḿ developing a program and I need to check if one of the char arrays passed by the argv are numbers, the problem comes when I have parameters like 2_two or 2-2 , what I've tryed doesn't works cause catch the number 2 and keeps the program running when it should exit.
I have tryed with atrof(), sprintf(), but didn work.

double from;
double to;
double jump;
switch (argc){
    case 2: to = atof(argv [1]); from =10; jump =1; break;
    case 3: to = atof(argv [1]); from = atof(argv[2]); jump = 1; break;
    case 4: to = atof(argv [1]); from = atof(argv[2]); jump =atof(argv [3]); break;
    default: from=1; to = 10; jump =1;
}
if (from == 0.0){
    char message []= "The parameter \"from\" is not a valid number";
    Error(EX_USAGE,message);
}else if (to==0.0){
    char message []= "The parameter \"to\" is not a valid number";
    Error(EX_USAGE,message);
}else if (jump==0.0){
    char message []= "The parameter \"jump\" is not a valid number";
    Error(EX_USAGE,message);
}

The method Error is an auxiliar that exit the program with the code error and the message

So what I need is the program exit when I get a parameter that is not just number.

Body:
Use strtod (include <stdlib.h>)

double strtod(const char *nptr, char **endptr);

From the man

If endptr is not NULL, a pointer to the character after the last  character  used  in  the
         conversion is stored in the location referenced by endptr.

Example of use

char *endptr;

double d = strtod(argv[1], &endptr);

int ok = endptr == argv[1] + strlen(argv[1]);

If endptr points to the trailing \0 in argv[1], that means the whole string was converted.

ok is 1 meaning the conversion was done up to the end of argv[1].

if (ok) {
    // use `d`, the converted number
}


问:
Checking a private value in another class [C#]
I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:

User lands in a menu

User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)

Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.

When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.

UML diagram for class structure context: https://i.imgur.com/bL5pZV5.png

Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.

My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.

Pseudo-code:

```<code>FOREACH (var player in player_list)
  IF (is_CPU == TRUE)
    THEN Assign random values
  ELSE
    THEN Manually enter values
</code>```

I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.

I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.

EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.

答:
Redesign your app like this:

```<code>   Class Game
          List<IPlayer> Players
          ShowMenu()
          AddPlayer()
          StartGame()
          IsGameOver(): boolean

   Interface IPlayer
          Turn() : Score

   CpuPlayer: IPlayer
   Player: IPlayer
</code>```

Split your logic into two different classes: you dont need to check. Treat every player the same in the game. Later if you come up with 'NetworkPlayer', 'AIPlayer', 'SuperPlayer' you can easily add to your system.

In your menu:

```<code>    switch (userInput) {
          case AddUser:
                 AddPlayer(new Player());
                 break;
          case AddCpuPlayer:
                 AddPlayer(new CpuPlayer());
                 break;
</code>```

In your gameplay:

```<code>    while (!IsGameOver)
    {
          var nextPlayer = ... next player
          nextPlayer.Turn() ...
    }
</code>```

Body:
I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:

User lands in a menu

User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)

Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.

When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.

UML diagram for class structure context: https://i.imgur.com/bL5pZV5.png

Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.

My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.

Pseudo-code:

FOREACH (var player in player_list)
  IF (is_CPU == TRUE)
    THEN Assign random values
  ELSE
    THEN Manually enter values

I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.

I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.

EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.

Body:
Redesign your app like this:

   Class Game
          List<IPlayer> Players
          ShowMenu()
          AddPlayer()
          StartGame()
          IsGameOver(): boolean

   Interface IPlayer
          Turn() : Score

   CpuPlayer: IPlayer
   Player: IPlayer

Split your logic into two different classes: you dont need to check. Treat every player the same in the game. Later if you come up with 'NetworkPlayer', 'AIPlayer', 'SuperPlayer' you can easily add to your system.

In your menu:

    switch (userInput) {
          case AddUser:
                 AddPlayer(new Player());
                 break;
          case AddCpuPlayer:
                 AddPlayer(new CpuPlayer());
                 break;

In your gameplay:

    while (!IsGameOver)
    {
          var nextPlayer = ... next player
          nextPlayer.Turn() ...
    }


问:
No files found in archive when renaming files
This program reads a list of files from the directory specified on the command line, creates an array of hashes, where each file has key path, size, and sha256sum.

I am trying to create a gzipped tarball of the files, where each files is name the checksum appended with the file's original extension.

I create a gzipped tarball of the files successfully. However, when I try to use Archive::Tar's rename method, I am met with this error:

No such file in archive: '/path/to/file1.txt' at ./program.pl line 62. This error repeats for each file in the archive.

```<code>use strict;
use warnings;
use Data::Dumper qw(Dumper);
use File::Spec qw(catfile rel2abs);
use Digest::SHA qw(sha256_hex);
use Archive::Tar;
use Archive::Tar::File;

my $dir = $ARGV[0];
my $url = $ARGV[1];
my @AoH;
my @checksumfiles;
my $tar = Archive::Tar->new;
my $archive = "archive.tar.gz";

opendir DIR, $dir or die "cannot open dir $dir: $!\n";
chdir $dir or die "cannot navigate to dir $dir: $!\n";

while(my $file = readdir DIR) {
    next unless(-f File::Spec->catfile($dir, $file));
    next if($file =~ m/^\./);

    my $fullpath = File::Spec->rel2abs($file);
    my $fullsize = -s File::Spec->catfile($dir, $file);
    my $fullid   = sha256_hex($fullpath);

    my %hash = (
        path    =>  $fullpath,
        size    =>  $fullsize,
        id      =>  $fullid,
    );

    push(@AoH, \%hash);
}
my @array;
for my $i(0..$#AoH) {
    no warnings 'uninitialized';
    my ($ext) = $AoH[$i]{path} =~ (/(\.[^.]+)$/);
    my $idext = $AoH[$i]{id} . $ext;
    push(@checksumfiles, $idext);
    push(@array, $AoH[$i]{path});
}

Archive::Tar->create_archive($archive, COMPRESS_GZIP, @array);
#print Archive::Tar->list_archive($archive, COMPRESS_GZIP), "\n";

for my $i(0..$#array) {
    $tar->rename($array[$i], $checksumfiles[$i]);
}

print Dumper sort \@array;
print Dumper sort \@checksumfiles;
#print Dumper sort \@AoH;
</code>```

答:
The archive is created with the Class method create_archive, while the rename method is called on the object to (my emphasis)

Rename the file of the in-memory archive to $new_name.

Alas, since the object was never used to write/read the archive there is no in-memory archive.

In general, you can read an archive from disk into memory, where you get Archive::Tar::File objects. Then rename the files and write out a new archive.

```<code>my @file_objs = $tar->read($archive);

for my $i (0..$#file_objs) {
    $file_objs[$i]->rename($checksumfiles[$i]);
}
$tar->write('RENAMED_' . $archive, COMPRESS_GZIP);
</code>```

This worked in my tests.

But this is terribly wasteful if you are indeed first creating the archive, with an extra write-and-read. A suitable way to build the archive in-memory is with add_files

```<code># In a sub to make sure that renaming stays in order in which files are added
sub archive_renamed {
    my ($archive_name, $orig, $new) = @_;
    if (@$orig != @$new) {
        warn "Unequal length of filename lists";
        return;
    }
    my $tar = Archive::Tar->new;

    for my $file (@$orig) {
        if (not $tar->add_files($file)) {
            warn "Error adding $file: ", $tar->error;
            return;
        }
    }
    my @file_objs = $tar->get_files;

    for my $i (0..$#file_objs) {
        $file_objs[$i]->rename($new->[$i]);
    }

    $tar->write($archive_name, COMPRESS_GZIP);
    if (my $error = $tar->error) {
        warn "Error writing $archive_name: $error";
        return;
    }
    return 1;
}

archive_renamed('RENAMED_'.$archive, \@array, \@checksumfiles);
</code>```

Files are renamed in the same order as they were added so all files must have been indeed added or we can end up with wrong names. Thus we abort on any error in adding files. That is why this needs to  be in a sub, too, so that changes can't slip in so to end up renaming files out of order.

If this ends up in a module use Carp::carp instead of warn. If the main code shouldn't proceed on errors use die (or Carp::croak in a module) instead.

If particular properties mentioned in the docs for this method pose a problem (they shouldn't), you can even first copy the files with the new names and form the archive with those (then delete them).  That is also extra work but incomparably more efficient than extra reading and writing of archives.

Body:
This program reads a list of files from the directory specified on the command line, creates an array of hashes, where each file has key path, size, and sha256sum.

I am trying to create a gzipped tarball of the files, where each files is name the checksum appended with the file's original extension.

I create a gzipped tarball of the files successfully. However, when I try to use Archive::Tar's rename method, I am met with this error:

No such file in archive: '/path/to/file1.txt' at ./program.pl line 62. This error repeats for each file in the archive.

use strict;
use warnings;
use Data::Dumper qw(Dumper);
use File::Spec qw(catfile rel2abs);
use Digest::SHA qw(sha256_hex);
use Archive::Tar;
use Archive::Tar::File;

my $dir = $ARGV[0];
my $url = $ARGV[1];
my @AoH;
my @checksumfiles;
my $tar = Archive::Tar->new;
my $archive = "archive.tar.gz";

opendir DIR, $dir or die "cannot open dir $dir: $!\n";
chdir $dir or die "cannot navigate to dir $dir: $!\n";

while(my $file = readdir DIR) {
    next unless(-f File::Spec->catfile($dir, $file));
    next if($file =~ m/^\./);

    my $fullpath = File::Spec->rel2abs($file);
    my $fullsize = -s File::Spec->catfile($dir, $file);
    my $fullid   = sha256_hex($fullpath);

    my %hash = (
        path    =>  $fullpath,
        size    =>  $fullsize,
        id      =>  $fullid,
    );

    push(@AoH, \%hash);
}
my @array;
for my $i(0..$#AoH) {
    no warnings 'uninitialized';
    my ($ext) = $AoH[$i]{path} =~ (/(\.[^.]+)$/);
    my $idext = $AoH[$i]{id} . $ext;
    push(@checksumfiles, $idext);
    push(@array, $AoH[$i]{path});
}

Archive::Tar->create_archive($archive, COMPRESS_GZIP, @array);
#print Archive::Tar->list_archive($archive, COMPRESS_GZIP), "\n";

for my $i(0..$#array) {
    $tar->rename($array[$i], $checksumfiles[$i]);
}

print Dumper sort \@array;
print Dumper sort \@checksumfiles;
#print Dumper sort \@AoH;

Body:
The archive is created with the Class method create_archive, while the rename method is called on the object to (my emphasis)

Rename the file of the in-memory archive to $new_name.

Alas, since the object was never used to write/read the archive there is no in-memory archive.

In general, you can read an archive from disk into memory, where you get Archive::Tar::File objects. Then rename the files and write out a new archive.

my @file_objs = $tar->read($archive);

for my $i (0..$#file_objs) {
    $file_objs[$i]->rename($checksumfiles[$i]);
}
$tar->write('RENAMED_' . $archive, COMPRESS_GZIP);

This worked in my tests.

But this is terribly wasteful if you are indeed first creating the archive, with an extra write-and-read. A suitable way to build the archive in-memory is with add_files

# In a sub to make sure that renaming stays in order in which files are added
sub archive_renamed {
    my ($archive_name, $orig, $new) = @_;
    if (@$orig != @$new) {
        warn "Unequal length of filename lists";
        return;
    }
    my $tar = Archive::Tar->new;

    for my $file (@$orig) {
        if (not $tar->add_files($file)) {
            warn "Error adding $file: ", $tar->error;
            return;
        }
    }
    my @file_objs = $tar->get_files;

    for my $i (0..$#file_objs) {
        $file_objs[$i]->rename($new->[$i]);
    }

    $tar->write($archive_name, COMPRESS_GZIP);
    if (my $error = $tar->error) {
        warn "Error writing $archive_name: $error";
        return;
    }
    return 1;
}

archive_renamed('RENAMED_'.$archive, \@array, \@checksumfiles);

Files are renamed in the same order as they were added so all files must have been indeed added or we can end up with wrong names. Thus we abort on any error in adding files. That is why this needs to  be in a sub, too, so that changes can't slip in so to end up renaming files out of order.

If this ends up in a module use Carp::carp instead of warn. If the main code shouldn't proceed on errors use die (or Carp::croak in a module) instead.

If particular properties mentioned in the docs for this method pose a problem (they shouldn't), you can even first copy the files with the new names and form the archive with those (then delete them).  That is also extra work but incomparably more efficient than extra reading and writing of archives.


问:
Google Places API: The Places API could not find the user's location
In AppDelegate, I have the following code to allow location tracking:

```<code>    let locationManager = CLLocationManager()
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestAlwaysAuthorization()
</code>```

In my ViewController, I make a Google Places request:

```<code>    placesClient = GMSPlacesClient.shared()
    placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
        if let error = error {
            print("Pick Place error: \(error.localizedDescription)")
            return
        }

        if let placeLikelihoodList = placeLikelihoodList {
            let place = placeLikelihoodList.likelihoods.first?.place
            if let place = place {
                print("Place:\(place.name)")
            }
        }
    })
</code>```

The error message is:

[0] (null)  "NSLocalizedFailureReason" : "The Places API could not find the user\'s location. This may be because the user has not allowed the application to access location information."

答:
Be sure to add the NSLocationWhenInUseUsageDescription key to your Info.plist file.

```<code><key>NSLocationWhenInUseUsageDescription</key>
<string>Show your location on the map</string>
</code>```

In addition, choose a location for your simulator. Go to your simulator, Debug -> Location -> Custom Location

Body:
In AppDelegate, I have the following code to allow location tracking:

    let locationManager = CLLocationManager()
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestAlwaysAuthorization()

In my ViewController, I make a Google Places request:

    placesClient = GMSPlacesClient.shared()
    placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
        if let error = error {
            print("Pick Place error: \(error.localizedDescription)")
            return
        }

        if let placeLikelihoodList = placeLikelihoodList {
            let place = placeLikelihoodList.likelihoods.first?.place
            if let place = place {
                print("Place:\(place.name)")
            }
        }
    })

The error message is:

[0] (null)  "NSLocalizedFailureReason" : "The Places API could not find the user\'s location. This may be because the user has not allowed the application to access location information."

Body:
Be sure to add the NSLocationWhenInUseUsageDescription key to your Info.plist file.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Show your location on the map</string>

In addition, choose a location for your simulator. Go to your simulator, Debug -> Location -> Custom Location


问:
How to implement 3 stacks with one array?
Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.</p>

答:
A variant on an earlier answer:  stack #1 grows from the left, and stack #2 grows from the right.

Stack #3 is in the center, but the elements grow in alternate order to the left and right.  If N is the center index, the stack grows as: N, N-1, N+1, N-2, N+2, etc.  A simple function converts the stack index to an array index.

ContentLicense: CC BY-SA 2.5