问:
drop all rows in a dataframe that have an empty list in a specified column in R
I am relatively new to R, so I apologize if this is a very basic question.

I am hoping to drop all rows in a dataframe that have empty lists in a particular column. To be specific, I have some sf geometries which are empty lists that I need removed from the df for later analysis steps.

Here is an example of the data I have (where I have removed content from the lists in column geometry in rows 6:8 to illustrate).

```<code>library(tigris)
#> To enable
#> caching of data, set `options(tigris_use_cache = TRUE)` in your R script or .Rprofile.
state<-states()
#>   |                                                                              |                                                                      |   0%  |                                                                              |                                                                      |   1%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |===                                                                   |   5%  |                                                                              |====                                                                  |   5%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |=======                                                               |  11%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  16%  |                                                                              |============                                                          |  17%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |====================                                                  |  28%  |                                                                              |=====================                                                 |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |========================                                              |  34%  |                                                                              |=========================                                             |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  39%  |                                                                              |============================                                          |  40%  |                                                                              |============================                                          |  41%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |===============================                                       |  45%  |                                                                              |================================                                      |  45%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  63%  |                                                                              |==============================================                        |  66%  |                                                                              |==========================================================            |  83%  |                                                                              |==========================================================            |  84%  |                                                                              |===========================================================           |  84%  |                                                                              |===========================================================           |  85%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |=============================================================         |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |======================================================================| 100%
state[6:8,15] <- NULL
state
#> Simple feature collection with 56 features and 14 fields (with 3 geometries empty)
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -179.2311 ymin: -14.60181 xmax: 179.8597 ymax: 71.43979
#> Geodetic CRS:  NAD83
#> First 10 features:
#>    REGION DIVISION STATEFP  STATENS GEOID STUSPS           NAME LSAD MTFCC
#> 1       3        5      54 01779805    54     WV  West Virginia   00 G4000
#> 2       3        5      12 00294478    12     FL        Florida   00 G4000
#> 3       2        3      17 01779784    17     IL       Illinois   00 G4000
#> 4       2        4      27 00662849    27     MN      Minnesota   00 G4000
#> 5       3        5      24 01714934    24     MD       Maryland   00 G4000
#> 6       1        1      44 01219835    44     RI   Rhode Island   00 G4000
#> 7       4        8      16 01779783    16     ID          Idaho   00 G4000
#> 8       1        1      33 01779794    33     NH  New Hampshire   00 G4000
#> 9       3        5      37 01027616    37     NC North Carolina   00 G4000
#> 10      1        1      50 01779802    50     VT        Vermont   00 G4000
#>    FUNCSTAT        ALAND      AWATER    INTPTLAT     INTPTLON
#> 1         A  62266231560   489271086 +38.6472854 -080.6183274
#> 2         A 138947364717 31362872853 +28.4574302 -082.4091477
#> 3         A 143779863817  6215723896 +40.1028754 -089.1526108
#> 4         A 206230065476 18942261495 +46.3159573 -094.1996043
#> 5         A  25151726296  6979340970 +38.9466584 -076.6744939
#> 6         A   2677787140  1323663210 +41.5974187 -071.5272723
#> 7         A 214049897859  2391604238 +44.3484222 -114.5588538
#> 8         A  23189198255  1026903434 +43.6726907 -071.5843145
#> 9         A 125925929633 13463401534 +35.5397100 -079.1308636
#> 10        A  23874197924  1030383955 +44.0685773 -072.6691839
#>                          geometry
#> 1  MULTIPOLYGON (((-81.74725 3...
#> 2  MULTIPOLYGON (((-86.38865 3...
#> 3  MULTIPOLYGON (((-91.18529 4...
#> 4  MULTIPOLYGON (((-96.78438 4...
#> 5  MULTIPOLYGON (((-77.45881 3...
#> 6              MULTIPOLYGON EMPTY
#> 7              MULTIPOLYGON EMPTY
#> 8              MULTIPOLYGON EMPTY
#> 9  MULTIPOLYGON (((-82.41674 3...
#> 10 MULTIPOLYGON (((-73.31328 4...
```
```

I want to remove these rows that have empty lists. My actual data is several thousand rows long, so manually searching would not be possible.

I found a posting on this in python, but was wondering if anyone has similar simple code to do the same thing in r?

Thank you for your time and thoughts.

答:
For the specific case of empty geometries, sf has a function st_is_empty to check for this sort of situation that returns a boolean value. Either of the following subset the data easily:

```<code>dplyr::filter(state, !sf::st_is_empty(geometry))

state[!sf::st_is_empty(state$geometry), ]
</code>```

Body:
I am relatively new to R, so I apologize if this is a very basic question.

I am hoping to drop all rows in a dataframe that have empty lists in a particular column. To be specific, I have some sf geometries which are empty lists that I need removed from the df for later analysis steps.

Here is an example of the data I have (where I have removed content from the lists in column geometry in rows 6:8 to illustrate).

library(tigris)
#> To enable
#> caching of data, set `options(tigris_use_cache = TRUE)` in your R script or .Rprofile.
state<-states()
#>   |                                                                              |                                                                      |   0%  |                                                                              |                                                                      |   1%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |===                                                                   |   5%  |                                                                              |====                                                                  |   5%  |                                                                              |=====                                                                 |   7%  |                                                                              |=====                                                                 |   8%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |=======                                                               |  11%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |===========                                                           |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  16%  |                                                                              |============                                                          |  17%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  22%  |                                                                              |================                                                      |  23%  |                                                                              |=================                                                     |  24%  |                                                                              |=================                                                     |  25%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |====================                                                  |  28%  |                                                                              |=====================                                                 |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |========================                                              |  34%  |                                                                              |=========================                                             |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |==========================                                            |  38%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  39%  |                                                                              |============================                                          |  40%  |                                                                              |============================                                          |  41%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |===============================                                       |  45%  |                                                                              |================================                                      |  45%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  63%  |                                                                              |==============================================                        |  66%  |                                                                              |==========================================================            |  83%  |                                                                              |==========================================================            |  84%  |                                                                              |===========================================================           |  84%  |                                                                              |===========================================================           |  85%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |=============================================================         |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |======================================================================| 100%
state[6:8,15] <- NULL
state
#> Simple feature collection with 56 features and 14 fields (with 3 geometries empty)
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -179.2311 ymin: -14.60181 xmax: 179.8597 ymax: 71.43979
#> Geodetic CRS:  NAD83
#> First 10 features:
#>    REGION DIVISION STATEFP  STATENS GEOID STUSPS           NAME LSAD MTFCC
#> 1       3        5      54 01779805    54     WV  West Virginia   00 G4000
#> 2       3        5      12 00294478    12     FL        Florida   00 G4000
#> 3       2        3      17 01779784    17     IL       Illinois   00 G4000
#> 4       2        4      27 00662849    27     MN      Minnesota   00 G4000
#> 5       3        5      24 01714934    24     MD       Maryland   00 G4000
#> 6       1        1      44 01219835    44     RI   Rhode Island   00 G4000
#> 7       4        8      16 01779783    16     ID          Idaho   00 G4000
#> 8       1        1      33 01779794    33     NH  New Hampshire   00 G4000
#> 9       3        5      37 01027616    37     NC North Carolina   00 G4000
#> 10      1        1      50 01779802    50     VT        Vermont   00 G4000
#>    FUNCSTAT        ALAND      AWATER    INTPTLAT     INTPTLON
#> 1         A  62266231560   489271086 +38.6472854 -080.6183274
#> 2         A 138947364717 31362872853 +28.4574302 -082.4091477
#> 3         A 143779863817  6215723896 +40.1028754 -089.1526108
#> 4         A 206230065476 18942261495 +46.3159573 -094.1996043
#> 5         A  25151726296  6979340970 +38.9466584 -076.6744939
#> 6         A   2677787140  1323663210 +41.5974187 -071.5272723
#> 7         A 214049897859  2391604238 +44.3484222 -114.5588538
#> 8         A  23189198255  1026903434 +43.6726907 -071.5843145
#> 9         A 125925929633 13463401534 +35.5397100 -079.1308636
#> 10        A  23874197924  1030383955 +44.0685773 -072.6691839
#>                          geometry
#> 1  MULTIPOLYGON (((-81.74725 3...
#> 2  MULTIPOLYGON (((-86.38865 3...
#> 3  MULTIPOLYGON (((-91.18529 4...
#> 4  MULTIPOLYGON (((-96.78438 4...
#> 5  MULTIPOLYGON (((-77.45881 3...
#> 6              MULTIPOLYGON EMPTY
#> 7              MULTIPOLYGON EMPTY
#> 8              MULTIPOLYGON EMPTY
#> 9  MULTIPOLYGON (((-82.41674 3...
#> 10 MULTIPOLYGON (((-73.31328 4...
```

I want to remove these rows that have empty lists. My actual data is several thousand rows long, so manually searching would not be possible.

I found a posting on this in python, but was wondering if anyone has similar simple code to do the same thing in r?

Thank you for your time and thoughts.

Body:
For the specific case of empty geometries, sf has a function st_is_empty to check for this sort of situation that returns a boolean value. Either of the following subset the data easily:

dplyr::filter(state, !sf::st_is_empty(geometry))

state[!sf::st_is_empty(state$geometry), ]


来源: stackexchange

问:
formula to get the average date and set a score
I am trying to create a formula from a table where there are several agents in which column A has a time stamp, I need to create a formula to get the average date of column A of each agent, get the oldest date of the column and the most recent date, and from those 3 information generate a score from 1 to 10, 10 being the average being close the the oldest date, and low score means that the average is close to the newest date.

Link to the sheet

I have a sheet 1 with all the information, and in sheet 2 is where i have a column with the agents name and another value would be the average score.

Any help will be very much appreciated.

答:
use:

```<code>=ARRAYFORMULA(QUERY({VALUE(Sheet1!A1:A), Sheet1!B1:B},
 "select Col2,avg(Col1)
  where Col2 is not null
  group by Col2
  label avg(Col1)'Average'
  format avg(Col1) 'mm/dd/yyyy'", 1))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
use:

=ARRAYFORMULA(QUERY({VALUE(Sheet1!A1:A), Sheet1!B1:B},
 "select Col2,avg(Col1)
  where Col2 is not null
  group by Col2
  label avg(Col1)'Average'
  format avg(Col1) 'mm/dd/yyyy'", 1))


问:
Prevent widget inspector from being launched in VSCode for flutter
How can I prevent widget inspector from launching each time in Visual Studio code. I have seen about 2 to 3 answere online, but either they are not applicable to the latest VSCode OR they are not clear. Please help</p>

答:
I found this on this thread and it worked for me.

open the settings.json file and add "dart.openDevTools": "never"


问:
How to use variable for html attribute in vue?
I'm using vue-router and I want to create navigation bar like this.

```<code>//...
navs: [
   { title: 'Home', router: '/' },
   { title: 'Settings', router: '/settings' }
]

//...

<li v-for='nav in navs' :key="nav.title" class="nav">
   <router-link to='nav.router'>{{nav.title}}</router-link> //nav.router does not return as I expect
</li>

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

But nav.router all navigate to /nav.router not / an /settings

Is there a way to fix this?

答:
Try to bind your routes:</p>
```<code>:to='nav.router'
</code>```

Body:
I'm using vue-router and I want to create navigation bar like this.

//...
navs: [
   { title: 'Home', router: '/' },
   { title: 'Settings', router: '/settings' }
]

//...

   <router-link to='nav.router'>{{nav.title}}</router-link> //nav.router does not return as I expect

//...

But nav.router all navigate to /nav.router not / an /settings

Is there a way to fix this?

Body:
Try to bind your routes:

:to='nav.router'


问:
Redux toolkit store reset automatically in navigating between pages in next js
I'm a new Next user and have been using Redux with React for a long time
I had a lot of trouble in using  Redux with Next

I'm done with this solution

store.js

```<code>import { configureStore } from '@reduxjs/toolkit';
import reducers from './rootReducer';

export function makeStore() {
  return configureStore({
    reducer: reducers,
  });
}

const store = makeStore();

export default store;
</code>```

rootReducer.js

```<code>import { combineReducers } from '@reduxjs/toolkit';
import tes from './test/tes';

const reducers = combineReducers({
  test: tes,
});

export default reducers;
</code>```

_app.js

```<code>import React from 'react';
import { Provider } from 'react-redux';
import store from '../redux/store';
import { createWrapper } from 'next-redux-wrapper';

const MyApp = ({ Component, ...rest }) => {
  return (
    <Provider store={store}>
      <Component {...rest} />
    </Provider>
  );
};
const makestore = () => store;
const wrapper = createWrapper(makestore);

export default wrapper.withRedux(MyApp);
</code>```

But I discovered that any use of the useDispatch
Inside any page, the search engine does not recognize the content of the page after fetching the data

```<code>import React, { useEffect } from 'react';
import { Test } from '../../redux/test/tes';
import { useDispatch, useSelector } from 'react-redux';
import Link from 'next/link';

function TestPage() {
  const dispatch = useDispatch();
  const { data } = useSelector((state) => state.test);
  useEffect(() => {
    dispatch(Test('hi'));
  }, []);
  return (
    <div>
      <Link href="/">
        <a>home</a>
      </Link>{' '}
      {data.map((name) => (
        <h1>{name.title}</h1>
      ))}
    </div>
  );
}

export default TestPage;
</code>```

One of the next pre-render methods must be used

I wonder if this is normal with next

or there Is a better way for doing that?

#1 Update

Now after moving data fetching to getStaticProps

TestPage.js

```<code>import React from 'react';
import { Test } from '../../redux/test/tes';
import {  useSelector } from 'react-redux';
import Link from 'next/link';
import { wrapper } from '../../redux/store';

function TestPage({ pageProps }) {
  const { data } = useSelector((state) => state.test);
  console.log(data);

  return (
    <div>
      <Link href="/">
        <a>home</a>
      </Link>{' '}
      {data && data.map((name) => (
        <h1>{name.name}</h1>
      ))}
    </div>
  );
}
export const getStaticProps = wrapper.getStaticProps(
  (store) => async (context) => {
    const loading = store.getState().test.loading;
    if (loading === 'idle') {
      await store.dispatch(Test('hi'));

    }

    return {
      props: {  },
    };
  }
);

export default TestPage;
</code>```

The problem now is that the store is not updating
useSelector return []

Although console.log (data) from getStaticProps the data is present
__NEXT_REDUX_WRAPPER_HYDRATE__
i'm stuck

#2 Update

It was really hard to get here and after that, there are still problems getting Redux with Next js

Now everything works until navigating to any page have  getStaticProps or getServerProps

state getting reset automatically

store.js

```<code>import reducers from './rootReducer';
import { configureStore } from '@reduxjs/toolkit';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';

const reducer = (state, action) => {
  if (action.type === HYDRATE) {
    let nextState = {
      ...state,
      ...action.payload,
    };
    return nextState;
  } else {
    return reducers(state, action);
  }
};

const isDev = process.env.NODE_ENV === 'development';

const makeStore = (context) => {
  let middleware = [];

  const store = configureStore({
    reducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(middleware),
    devTools: isDev,
    preloadedState: undefined,
  });

  return store;
};

export const wrapper = createWrapper(makeStore, { debug: isDev });
</code>```

答:
In the end, this way only worked. Even the server and Client state separation did not work.

I used this jsondiffpatch.

rootReducer.js

```<code>const rootReducer = createReducer(
  combinedReducers(undefined, { type: '' }),
  (builder) => {
    builder
      .addCase(HYDRATE, (state, action) => {
        const stateDiff = diff(state, action.payload);
        const isdiff = stateDiff?.test?.data?.[0];
        const isdiff1 =
          stateDiff?.test1?.data?.[0]
        return {
          ...state,
          ...action.payload,

          test: isdiff ? action.payload.test : state.test,
          test1: isdiff1 ? action.payload.test1 : state.test1,
        };
      })
      .addDefaultCase(combinedReducers);
  }
);
</code>```

The only problem here is that you have to test every change in every piece inside the state

Update

Because a global hydrate reducer can be overkill, here is an example to handle hydration in each slice:

```<code>import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { diff } from 'jsondiffpatch';
import { HYDRATE } from 'next-redux-wrapper';

const initialState = {
  data: [],
};
export const TestFetch = createAsyncThunk(
  'TestFetch',
  async (data, { rejectWithValue, dispatch }) => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/users'
      );
      const d = await response.json();
      return d;
    } catch (error) {
      return rejectWithValue(error.response.data.error);
    }
  }
);

const test = createSlice({
  name: 'test',
  initialState,
  reducers: {
    update: {
      reducer: (state, { payload }) => {
        return { ...state, data: payload };
      },
    },
  },
  extraReducers: {
    [HYDRATE]: (state, action) => {
      const stateDiff = diff(state, action.payload);
      const isdiff1 = stateDiff?.server?.[0]?.test?.data?.[0];
      // return {
      //   ...state,
      //   data: isdiff1 ? action.payload.server.test.data : state.data,
      // };
      state.data = isdiff1 ? action.payload.server.test.data : state.data;
    },
    [TestFetch.fulfilled]: (state, action) => {
      state.data = action.payload;
    },
  },
});

export const { update } = test.actions;
export default test.reducer;
</code>```

Body:
I'm a new Next user and have been using Redux with React for a long time
I had a lot of trouble in using  Redux with Next

I'm done with this solution

store.js

import { configureStore } from '@reduxjs/toolkit';
import reducers from './rootReducer';

export function makeStore() {
  return configureStore({
    reducer: reducers,
  });
}

const store = makeStore();

export default store;

rootReducer.js

import { combineReducers } from '@reduxjs/toolkit';
import tes from './test/tes';

const reducers = combineReducers({
  test: tes,
});

export default reducers;

_app.js

import React from 'react';
import { Provider } from 'react-redux';
import store from '../redux/store';
import { createWrapper } from 'next-redux-wrapper';

const MyApp = ({ Component, ...rest }) => {
  return (
    <Provider store={store}>
      <Component {...rest} />
    </Provider>
  );
};
const makestore = () => store;
const wrapper = createWrapper(makestore);

export default wrapper.withRedux(MyApp);

But I discovered that any use of the useDispatch
Inside any page, the search engine does not recognize the content of the page after fetching the data

import React, { useEffect } from 'react';
import { Test } from '../../redux/test/tes';
import { useDispatch, useSelector } from 'react-redux';
import Link from 'next/link';

function TestPage() {
  const dispatch = useDispatch();
  const { data } = useSelector((state) => state.test);
  useEffect(() => {
    dispatch(Test('hi'));
  }, []);
  return (

      <Link href="/">
        home
      </Link>{' '}
      {data.map((name) => (

{name.title}

      ))}

  );
}

export default TestPage;

One of the next pre-render methods must be used

I wonder if this is normal with next

or there Is a better way for doing that?

#1 Update

Now after moving data fetching to getStaticProps

TestPage.js

import React from 'react';
import { Test } from '../../redux/test/tes';
import {  useSelector } from 'react-redux';
import Link from 'next/link';
import { wrapper } from '../../redux/store';

function TestPage({ pageProps }) {
  const { data } = useSelector((state) => state.test);
  console.log(data);

  return (

      <Link href="/">
        home
      </Link>{' '}
      {data && data.map((name) => (

{name.name}

      ))}

  );
}
export const getStaticProps = wrapper.getStaticProps(
  (store) => async (context) => {
    const loading = store.getState().test.loading;
    if (loading === 'idle') {
      await store.dispatch(Test('hi'));

    }

    return {
      props: {  },
    };
  }
);

export default TestPage;

The problem now is that the store is not updating
useSelector return []

Although console.log (data) from getStaticProps the data is present
__NEXT_REDUX_WRAPPER_HYDRATE__
i'm stuck

#2 Update

It was really hard to get here and after that, there are still problems getting Redux with Next js

Now everything works until navigating to any page have  getStaticProps or getServerProps

state getting reset automatically

store.js

import reducers from './rootReducer';
import { configureStore } from '@reduxjs/toolkit';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';

const reducer = (state, action) => {
  if (action.type === HYDRATE) {
    let nextState = {
      ...state,
      ...action.payload,
    };
    return nextState;
  } else {
    return reducers(state, action);
  }
};

const isDev = process.env.NODE_ENV === 'development';

const makeStore = (context) => {
  let middleware = [];

  const store = configureStore({
    reducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(middleware),
    devTools: isDev,
    preloadedState: undefined,
  });

  return store;
};

export const wrapper = createWrapper(makeStore, { debug: isDev });

Body:
In the end, this way only worked. Even the server and Client state separation did not work.

I used this jsondiffpatch.

rootReducer.js

const rootReducer = createReducer(
  combinedReducers(undefined, { type: '' }),
  (builder) => {
    builder
      .addCase(HYDRATE, (state, action) => {
        const stateDiff = diff(state, action.payload);
        const isdiff = stateDiff?.test?.data?.[0];
        const isdiff1 =
          stateDiff?.test1?.data?.[0]
        return {
          ...state,
          ...action.payload,

          test: isdiff ? action.payload.test : state.test,
          test1: isdiff1 ? action.payload.test1 : state.test1,
        };
      })
      .addDefaultCase(combinedReducers);
  }
);

The only problem here is that you have to test every change in every piece inside the state

Update

Because a global hydrate reducer can be overkill, here is an example to handle hydration in each slice:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { diff } from 'jsondiffpatch';
import { HYDRATE } from 'next-redux-wrapper';

const initialState = {
  data: [],
};
export const TestFetch = createAsyncThunk(
  'TestFetch',
  async (data, { rejectWithValue, dispatch }) => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/users'
      );
      const d = await response.json();
      return d;
    } catch (error) {
      return rejectWithValue(error.response.data.error);
    }
  }
);

const test = createSlice({
  name: 'test',
  initialState,
  reducers: {
    update: {
      reducer: (state, { payload }) => {
        return { ...state, data: payload };
      },
    },
  },
  extraReducers: {
    [HYDRATE]: (state, action) => {
      const stateDiff = diff(state, action.payload);
      const isdiff1 = stateDiff?.server?.[0]?.test?.data?.[0];
      // return {
      //   ...state,
      //   data: isdiff1 ? action.payload.server.test.data : state.data,
      // };
      state.data = isdiff1 ? action.payload.server.test.data : state.data;
    },
    [TestFetch.fulfilled]: (state, action) => {
      state.data = action.payload;
    },
  },
});

export const { update } = test.actions;
export default test.reducer;


问:
Scala _* to select a list of dataframe columns
I have a dataframe and a list of columns like this:

```<code>import spark.implicits._
import org.apache.spark.sql.functions._

val df = spark.createDataFrame(Seq(("Java", "20000"), ("Python", "100000"))).toDF("language","users_count")
val data_columns = List("language","users_count").map(x=>col(s"$x"))
</code>```

Why does this work:

```<code> df.select(data_columns:_ *).show()
</code>```

But not this?

```<code> df.select($"language", data_columns:_*).show()
</code>```

Gives the error:

```<code> error: no `: _*' annotation allowed here
    (such annotations are only allowed in arguments to *-parameters)
</code>```

And how do I get it to work so I can use _* to select all columns in a list, but I also want to specify some other columns in the select?

Thanks!

Update:

based on @chinayangyangyong answer below, this is how I solved it:

```<code>df.select( $"language" +: data_columns :_*)
</code>```

答:
It is because there is no method on Dataframe with the signature select(col: Column, cols: Column*): DataFrame, but there is one with the signature select(col: Column*): DataFrame, which is why your first example works.

Interestingly, your second example would work if you were using String to select the columns since there is a method select(col: String, cols: String*): DataFrame.

Body:
I have a dataframe and a list of columns like this:

import spark.implicits._
import org.apache.spark.sql.functions._

val df = spark.createDataFrame(Seq(("Java", "20000"), ("Python", "100000"))).toDF("language","users_count")
val data_columns = List("language","users_count").map(x=>col(s"$x"))

Why does this work:

 df.select(data_columns:_ *).show()

But not this?

 df.select($"language", data_columns:_*).show()

Gives the error:

 error: no `: _*' annotation allowed here
    (such annotations are only allowed in arguments to *-parameters)

And how do I get it to work so I can use _* to select all columns in a list, but I also want to specify some other columns in the select?

Thanks!

Update:

based on @chinayangyangyong answer below, this is how I solved it:

df.select( $"language" +: data_columns :_*)


问:
Angular way of doing javascript getById code
I'm working on a migration project from AngularJS to Angular8

where I came across this code

```<code>// get the pattern from SVG document and set the stroke color
 var patternElt = $scope.svgDocument.find("#striped");
 patternElt.css("fill", color);
 // apply the striped class to the element
 element.css("fill", "url(#striped)");
 $(zoneClassSelector, element).css("fill", "url(#striped)");
</code>```

what the above code does is when an element is clicked, it gets a pattern element from an svg file (below) and adds a fill color to it, and then applies it on the clicked DOM element :

```<code><defs>
    <pattern id="striped"
        width="8" height="8"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)">
        <rect width="4" height="8" transform="translate(0,0)"></rect>
    </pattern>
</defs>
</code>```

In my case in Typescript code I have the following

```<code>click($event: MouseEvent) {

let clickedEl = $event.target;
// check if clicked element is not an svg element
if (clickedEl instanceof SVGPolygonElement || clickedEl instanceof SVGPathElement || clickedEl instanceof SVGGElement) {
  this.renderer.setAttribute(clickedEl, "style", "fill:url(#striped);");
}
</code>```

}

Note: the SVG file is loaded with its path (no SVG xml in the component view to reference)

How could I get the striped  pattern element using Typscript to add a fill color to it before pass it to the renderer setAttribute

答:
Any DOM element reference can be obtained through the ViewChild attribute

so in your case, you would have the following:

```<code><pattern #MyReference
    id="striped"
    width="8" height="8"
    patternUnits="userSpaceOnUse"
    patternTransform="rotate(45)">
    <rect width="4" height="8" transform="translate(0,0)"></rect>
</pattern>
</code>```

Then in your class you would reference the DOM object

```<code>@ViewChild('MyReference', { static: false })
MyElem: ElementRef;
</code>```

You can now do any DOM manipulation utilising this reference, along with the Core Renderer2 library (import into your constructor private renderer: Renderer2).

If however you have a dynamic list of SVG elements loaded, and are looking for a way to get "within" the clicked elements DOM - I would go the route of creating a custom Component that "each" of these then initalises, and have the on click, and element references within here.
This way each component has a singular build pattern, and you don't have to do any parent/sibling DOM traversing.

e.g. (very basic, you'll know what inputs you require)

```<code><ng-container *ngFor="let svg of list">
    <my-custom-component [inputs]="svg"></my-custom-component>
</ng-container>
</code>```

Then using the above method, each component on click only has the single pattern element reference to manipulate without direct DOM traversing.
It will also keep your on click method quite precise and you don't need to check what was clicked, since only this component will trigger it (no need for global mouse events)

EDIT 1
In seeing the comments, I believe what you could be after is utilising global css variables.
For example, you can do the following in the XML:

Then set your root class to show its selected (on click), for example:

```<code><svg class="selected" >
    <use xlink:href="#" href="#" />
</svg>
</code>```

Then all you do is change your fill color via CSS to what you are wanting it to show i.e.

```<code>.selected pattern
{
   --fill-color:"#123456"
}
</code>```

If none of these are suitable, might have to update the question a little for understanding sorry

Body:
I'm working on a migration project from AngularJS to Angular8

where I came across this code

// get the pattern from SVG document and set the stroke color
 var patternElt = $scope.svgDocument.find("#striped");
 patternElt.css("fill", color);
 // apply the striped class to the element
 element.css("fill", "url(#striped)");
 $(zoneClassSelector, element).css("fill", "url(#striped)");

what the above code does is when an element is clicked, it gets a pattern element from an svg file (below) and adds a fill color to it, and then applies it on the clicked DOM element :

<defs>
    <pattern id="striped"
        width="8" height="8"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)">
        <rect width="4" height="8" transform="translate(0,0)"></rect>
    </pattern>
</defs>

In my case in Typescript code I have the following

click($event: MouseEvent) {

let clickedEl = $event.target;
// check if clicked element is not an svg element
if (clickedEl instanceof SVGPolygonElement || clickedEl instanceof SVGPathElement || clickedEl instanceof SVGGElement) {
  this.renderer.setAttribute(clickedEl, "style", "fill:url(#striped);");
}

}

Note: the SVG file is loaded with its path (no SVG xml in the component view to reference)

How could I get the striped  pattern element using Typscript to add a fill color to it before pass it to the renderer setAttribute

Body:
Any DOM element reference can be obtained through the ViewChild attribute

so in your case, you would have the following:

<pattern #MyReference
    id="striped"
    width="8" height="8"
    patternUnits="userSpaceOnUse"
    patternTransform="rotate(45)">
    <rect width="4" height="8" transform="translate(0,0)"></rect>
</pattern>

Then in your class you would reference the DOM object

@ViewChild('MyReference', { static: false })
MyElem: ElementRef;

You can now do any DOM manipulation utilising this reference, along with the Core Renderer2 library (import into your constructor private renderer: Renderer2).

If however you have a dynamic list of SVG elements loaded, and are looking for a way to get "within" the clicked elements DOM - I would go the route of creating a custom Component that "each" of these then initalises, and have the on click, and element references within here.
This way each component has a singular build pattern, and you don't have to do any parent/sibling DOM traversing.

e.g. (very basic, you'll know what inputs you require)

<ng-container *ngFor="let svg of list">
    <my-custom-component [inputs]="svg"></my-custom-component>
</ng-container>

Then using the above method, each component on click only has the single pattern element reference to manipulate without direct DOM traversing.
It will also keep your on click method quite precise and you don't need to check what was clicked, since only this component will trigger it (no need for global mouse events)

EDIT 1
In seeing the comments, I believe what you could be after is utilising global css variables.
For example, you can do the following in the XML:

Then set your root class to show its selected (on click), for example:

<svg class="selected" >
    <use xlink:href="#" href="#" />
</svg>

Then all you do is change your fill color via CSS to what you are wanting it to show i.e.

.selected pattern
{
   --fill-color:"#123456"
}

If none of these are suitable, might have to update the question a little for understanding sorry


问:
Bash: play all audio in the current directory
Here's a bash script, it

gets all files in the current dir, then

gets all audio files among them (allowing file-names to have whitespace)

sends the list to the audacious -p - which should play the list.

The thirt step is where the script fails. Here is the script:

```<code>#!/bin/bash

find $1 -name '* *' | while read filename; do

Type=`file -i "$filename" -F "::" | sed 's/.*:: //' | sed 's/\/.*$//'`

if [ $Type=audio ]; then
    List="$List '$filename'"
fi
done

audacious2 -p $List &
</code>```

So the question is: how do i convert

```<code>file name 1
file name 2
file name 3
</code>```

to

```<code>'file name 1' 'file name 2' 'file name 3'
</code>```

in bash?

答: BASH FAQ entry #50: "I'm trying to put a command in a variable, but the complex cases always fail!"</p>

ContentLicense: CC BY-SA 3.0

Body:
Here's a bash script, it

gets all files in the current dir, then

gets all audio files among them (allowing file-names to have whitespace)

sends the list to the audacious -p - which should play the list.

The thirt step is where the script fails. Here is the script:

#!/bin/bash

find $1 -name '* *' | while read filename; do

Type=`file -i "$filename" -F "::" | sed 's/.*:: //' | sed 's/\/.*$//'`

if [ $Type=audio ]; then
    List="$List '$filename'"
fi
done

audacious2 -p $List &

So the question is: how do i convert

file name 1
file name 2
file name 3

to

'file name 1' 'file name 2' 'file name 3'

in bash?


问:
How to run "docker login azure" from Azure DevOps pipeline
I have a shell script that deploys containers to Azure Container Instances that runs fine locally using the Azure CLI (on Linux) but I'm having trouble performing the login to Azure from a pipeline task.

Locally the following command will open a browser to login:

docker login azure

The docs suggest that to do the same in a pipeline task I can pass in a client id and client secret. I think that it should look like this:

docker login azure --client-id $servicePrincipalId --client-secret $servicePrincipalKey --tenant-id $tenantId

However, when I run this in my pipeline I get this error:

unknown flag: --client-id

docker login azure --help run locally tells me that --client-id is a valid flag, so I'm wondering is there another way to do this in an Azure DevOps pipeline?

答:
The Azure pipeline task for Docker allows you to use a service connection for the 'docker login' style task.  To use a username / password combination, you'll start by creating a Service Connection of type 'Docker Registry'.  Then specify 'other' for type.  Here you can enter your credentials.  The password is obfuscated for security as you would expect.

Now you can use this service connection in your azure devops pipeline docker tasks.

Sources cited:

https://learn.microsoft.com/en-us/azure/devops/pipelines/library/service-endpoints?view=azure-devops&tabs=yaml#docker-registry-service-connection

https://learn.microsoft.com/en-us/azure/devops/pipelines/library/service-endpoints?view=azure-devops&tabs=yaml#docker-hub-or-others


问:
Pandas: Divide values in one dataframe by corresponding values from another dataframe
Suppose I have two pandas dataframes:

```<code>d1 = {'year': [1, 2, 1, 2], 'val1': [3, 6, 9, 12]}
df1 = pd.DataFrame(data=d1)

   year val1
0   1    3
1   2    6
2   1    9
3   2    12

</code>```

and

```<code>d2 = {'year': [1, 2], 'val2': [3, 6]}
df2 = pd.DataFrame(data=d2)

   year val2
0   1    3
1   2    6
</code>```

I would like to divide the two values of val1 for a given year by the value of val2 for the same year. So the output should look like this:

```<code>   year val1
0   1    1
1   2    1
2   1    3
3   2    2
</code>```

An easy way to do this is with a for loop but I would prefer to have a non-loop solution. I tried different combinations of groupby, apply, and map without much success.

Here is the for loop solution:

```<code>df2 = df2.set_index('year')
df3 = df1.copy()
for t in [1, 2]:
    idx = df1['year'] == t
    df3.loc[idx, 'val1'] = df1.loc[idx, 'val1'].divide(df2.loc[t].item())
</code>```

答:
Here's a simple solution using map:

```<code>df1['val1'] /= df1['year'].map(df2.set_index('year')['val2'])
</code>```

Output:

```<code>>>> df1
   year  val1
0     1   1.0
1     2   1.0
2     1   3.0
3     2   2.0
</code>```

Body:
Suppose I have two pandas dataframes:

d1 = {'year': [1, 2, 1, 2], 'val1': [3, 6, 9, 12]}
df1 = pd.DataFrame(data=d1)

   year val1
0   1    3
1   2    6
2   1    9
3   2    12

and

d2 = {'year': [1, 2], 'val2': [3, 6]}
df2 = pd.DataFrame(data=d2)

   year val2
0   1    3
1   2    6

I would like to divide the two values of val1 for a given year by the value of val2 for the same year. So the output should look like this:

   year val1
0   1    1
1   2    1
2   1    3
3   2    2

An easy way to do this is with a for loop but I would prefer to have a non-loop solution. I tried different combinations of groupby, apply, and map without much success.

Here is the for loop solution:

df2 = df2.set_index('year')
df3 = df1.copy()
for t in [1, 2]:
    idx = df1['year'] == t
    df3.loc[idx, 'val1'] = df1.loc[idx, 'val1'].divide(df2.loc[t].item())

Body:
Here's a simple solution using map:

df1['val1'] /= df1['year'].map(df2.set_index('year')['val2'])

Output:

>>> df1
   year  val1
0     1   1.0
1     2   1.0
2     1   3.0
3     2   2.0


问:
Extract from an email header the Authentication-Results part using an Outlook Add-in with OfficeJS
I've been trying to the section of Authentication-Results
First I tried with:

```<code>Office.context.mailbox.item.internetHeaders.getAsync
</code>```

But for some reason interneHeader keeps returning undefined so I move to:

```<code>Office.context.mailbox.item.getAllInternetHeadersAsync
</code>```

In my tests with Regex on it I got results from the first line of it.

But when I use it on copying email headers on regex101 or Node I got the information I need. Meaning the entire section with spf, dkim and dmarc.

I use this regex:

```<code>header.match(/^Authentication-Results:[0-9a-zA-Z =\(\)\.\n;-]*$/gm)[0]
</code>```

Exemple:
This is a sample of header from a Steam email:

```<code>Received: from SN1NAM02FT0054.eop-nam02.prod.protection.outlook.com
 (2603:10b6:806:127:cafe::f5) by SN7PR04CA0211.outlook.office365.com
 (2603:10b6:806:127::6) with Microsoft SMTP Server (version=TLS1_2,
 cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.4930.15 via Frontend
 Transport; Tue, 1 Feb 2022 20:13:03 +0000
Authentication-Results: spf=pass (sender IP is xxx.xxx.xxx.xxx)
 smtp.mailfrom=steampowered.com; dkim=pass (signature was verified)
 header.d=steampowered.com;dmarc=pass action=none
 header.from=steampowered.com;compauth=pass reason=100
Received-SPF: Pass (protection.outlook.com: domain of steampowered.com
 designates xxx.xxx.xxx.xxx as permitted sender)
 receiver=protection.outlook.com; client-ip=xxx.xxx.xxx.xxx;
 helo=smtp-03-tuk1.steampowered.com;
</code>```

Using the my regex, on it it returns this:

```<code>Authentication-Results: spf=pass (sender IP is xxx.xxx.xxx.xxx)
 smtp.mailfrom=steampowered.com; dkim=pass (signature was verified)
 header.d=steampowered.com;dmarc=pass action=none
 header.from=steampowered.com;compauth=pass reason=100
</code>```

But when I use with Office.context.mailbox.item.getAllInternetHeadersAsync
It only returns this:

```<code>Authentication-Results: spf=pass (sender IP is xxx.xxx.xxx.xxx)
</code>```

So I wanna what approach I can do to this issue?

答:
Basically, your operating system defines the character / character sequence for the end of the line. Your particular application might or might not follow that.

If you want to limit the change to your initial regex, adding \r is (to me) the most straightforward approach. If you want to limit the number of characters in your regex, you could go for \s -- which would encompass blank, \n and \r - but \t as well, which is not allowed at this time.

Talking of potential simplification: Within the character class (between the square brackets), escaping round brackets/parentheses and the dot / full stop is usually not required - leaving you with

^Authentication-Results:[0-9a-zA-Z =().\n\r;-]*

But you need to verify in your particular environment.

Please comment, if and as this requires adjustment / further detail.

Body:
I've been trying to the section of Authentication-Results
First I tried with:

Office.context.mailbox.item.internetHeaders.getAsync

But for some reason interneHeader keeps returning undefined so I move to:

Office.context.mailbox.item.getAllInternetHeadersAsync

In my tests with Regex on it I got results from the first line of it.

But when I use it on copying email headers on regex101 or Node I got the information I need. Meaning the entire section with spf, dkim and dmarc.

I use this regex:

header.match(/^Authentication-Results:[0-9a-zA-Z =\(\)\.\n;-]*$/gm)[0]

Exemple:
This is a sample of header from a Steam email:

Received: from SN1NAM02FT0054.eop-nam02.prod.protection.outlook.com
 (2603:10b6:806:127:cafe::f5) by SN7PR04CA0211.outlook.office365.com
 (2603:10b6:806:127::6) with Microsoft SMTP Server (version=TLS1_2,
 cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.4930.15 via Frontend
 Transport; Tue, 1 Feb 2022 20:13:03 +0000
Authentication-Results: spf=pass (sender IP is xxx.xxx.xxx.xxx)
 smtp.mailfrom=steampowered.com; dkim=pass (signature was verified)
 header.d=steampowered.com;dmarc=pass action=none
 header.from=steampowered.com;compauth=pass reason=100
Received-SPF: Pass (protection.outlook.com: domain of steampowered.com
 designates xxx.xxx.xxx.xxx as permitted sender)
 receiver=protection.outlook.com; client-ip=xxx.xxx.xxx.xxx;
 helo=smtp-03-tuk1.steampowered.com;

Using the my regex, on it it returns this:

Authentication-Results: spf=pass (sender IP is xxx.xxx.xxx.xxx)
 smtp.mailfrom=steampowered.com; dkim=pass (signature was verified)
 header.d=steampowered.com;dmarc=pass action=none
 header.from=steampowered.com;compauth=pass reason=100

But when I use with Office.context.mailbox.item.getAllInternetHeadersAsync
It only returns this:

Authentication-Results: spf=pass (sender IP is xxx.xxx.xxx.xxx)

So I wanna what approach I can do to this issue?


问:
PyTorch convert function for op 'fft_rfftn' not implemented
I am trying to convert a pretrained pytorch model to coreml. I am using coremltools to do this. This is my code.

```<code>import torch
import coremltools as ct
traced_model = torch.jit.load("a.jit")
model = ct.convert(traced_model,
          inputs=[ct.TensorType(shape=image.shape), ct.TensorType(shape=mask.shape)])
</code>```

I am getting this error "PyTorch convert function for op 'fft_rfftn' not implemented."
How can I solve this?

答: Try use my project: RosaKit, there is implemented STFT, it's might help.</p>

Body:
I am trying to convert a pretrained pytorch model to coreml. I am using coremltools to do this. This is my code.

import torch
import coremltools as ct
traced_model = torch.jit.load("a.jit")
model = ct.convert(traced_model,
          inputs=[ct.TensorType(shape=image.shape), ct.TensorType(shape=mask.shape)])

I am getting this error "PyTorch convert function for op 'fft_rfftn' not implemented."
How can I solve this?


问:
Profiling the C++ compilation process
I tend to write rather large templated header-only C++ libraries and my users commonly complain about compilation times. After thinking about the matter, it occurred to me that I have no idea where the time is going. Is there some simple way to profile the C++ compilation process with common compilers, such as GCC (g++), Intel C++ Compiler (icc), and XL C/C++ (xlC)? For instance, is it possible to get an idea of how much time is spent within each of the phases of C++ compilation?

答:
Externis is a GCC plugin that will generate trace files very similar to Clang's -ftime-trace:

Disclaimer: I'm the author of this plugin.

Title: Profiling the C++ compilation process


答:
Using merge and eval:

```<code>(df1.merge(df2, on='year', how='left', sort=False)
    .eval('val1=val1/val2')
 )
</code>```

Output:

```<code>   year  val1  val2
0     1   1.0     3
1     2   1.0     6
2     1   3.0     3
3     2   2.0     6
</code>```

Or performing an in place modification of df1:

NB. how='left', sort=False is critical for this solution!

```<code>df1['val1'] /= df1.merge(df2, on='year', how='left', sort=False)['val2']
</code>```

Output:

```<code>   year  val1
0     1   1.0
1     2   1.0
2     1   3.0
3     2   2.0
</code>```

Title: Pandas: Divide values in one dataframe by corresponding values from another dataframe

Body:
Using merge and eval:

(df1.merge(df2, on='year', how='left', sort=False)
    .eval('val1=val1/val2')
 )

Output:

   year  val1  val2
0     1   1.0     3
1     2   1.0     6
2     1   3.0     3
3     2   2.0     6

Or performing an in place modification of df1:

NB. how='left', sort=False is critical for this solution!

df1['val1'] /= df1.merge(df2, on='year', how='left', sort=False)['val2']

Output:

   year  val1
0     1   1.0
1     2   1.0
2     1   3.0
3     2   2.0


问:
Sorting multiple arrays in the struct based on the ascending order of one array in C
I am trying to sort the multiple arrays based on the ascending order of one array.
Here is the example:

```<code>int a[10] = {55140, 32294, 33321, 64321, 55312}
float b[10] = {11.11, 202.22, 3213.21, 144.32, 1.32}
const char* c[10] = {+, -, -, -, +}
unsigned char* d[10] = {22DS3K, 1FGJ29, 21FD43, 98DS03, 56DK23}
</code>```

Now, after arranging the array 'a' in ascending order I want to sort the other arrays. The output should look like as follows:

```<code>a[10] = {32294, 33321, 55140, 55312, 64321}
b[10] = {202.22, 3213.21, 11.11, 1.32, 144.32}
c[10] = {-, -, +, +, -}
d[10] = {1FGJ29, 21FD43, 22DS3K, 56DK23, 98DS03}
</code>```

Arranging the ascending order works fine. But, I am unable to sort the other arrays. I woould like to create a function to use it in my main function. Pleased to hear some suggestions.

I have seen the below post, but did not help me.

Sorting an array based on another in C

Here is the code that I have tried:

```<code>struct Data{
    int a[10];
    float b[10];
    const char* c[10];
    unsigned char* d[10];
} data;

int data_a[10];
float data_b[10];
const char* data_c[10];
unsigned char* d[10];

void ascending(int *t; int N){
int i,j,tmp;
for(i=0;j<N;j++){
  for(j=i+1;j<N;j++){
     if(t[i] > t[j]){
       tmp=t[i];
       t[i]=t[j];
       t[j]=tmp;
}}}}

int main(){
   int i;
   for(i=0;i<5;i++){
   data.a[i] = data_a[i];
   data.b[i] = data_b[i];
   data.c[i] = data_c[i];
   data.d[i] = data_d[i];
   }
   ascending(data.a, 5);
   for(i=0;i<5;i++){
      printf("Data is %d,%.2f,%s,%hhn\n", data.a[i],data.b[i],data.c[i],data.d[i]};
   }}
</code>```

May I know if I am missing something or doing something completely wrong?

答:
Keeping such a set of arrays in synch is a nightmare.
What you seem to want is an array of structs instead of 5 separate arrays.

If I get you right, this is what would fit your needs better:
(Also your initializers don't really match the data type of your arrays c and d.)

typedef struct data_s {
  int a;
  float b;
  const char *c;
  const char *d;
} data_t;

data_t data[10] =
{
  [0] = {.a=55140, .b=11.11,   .c="+", .d="22DS3K"},
  [1] = {.a=32294, .b=202.22,  .c="-", .d="1FGJ29"},
  [2] = {.a=33321, .b=3213.21, .c="-", .d="21FD43"},
  [3] = {.a=64321, .b=144.32,  .c="-", .d="98DS03"},
  [4] = {.a=55312, .b=1.32,    .c="+", .d="56DK23"}
};
```
<p>Then you can sort (just use <code>qsort</code>) for member <code>a</code> of your struct and as you will swap whole structs at once, the corresponding other members will be sorted accordingly:</p>
<pre class="lang-c prettyprint-override"><code>
int compare_a(const void *data1, const void*data2)
{
  return ((data_t*)data2)->a - ((data_t*)data1)->a;
}

int compare_d(const void *data1, const void*data2)
{
  return strcmp(((data_t*)data1)->d, ((data_t*)data2)->d);
}

int main(void)
{
...
  // optional:
  // Populate the missing fields with some default data
  size_t num_elem = sizeof(data)/sizeof(data[0]);
  for (size_t i = 5; i < num_elem; i++)
  {
    data[i].a = (int)i * 111;
    data[i].b = i * 1.11;
    data[i].c = "none";
    data[i].d = "";
  }

  // Sort for field a
  qsort(data, num_elem, sizeof (data[0]), compare_a);

  // Variant: Size unknown, use dynamic memory allocation
  size_t num_elem2 = 123;
  data_t *data2 = malloc(num_elem2 * sizeof (*data2));
  for (size_t i = 0; i < num_elem; i++)
  {
    data2[i].a = (int)i * 111;
    data2[i].b = i*1.11;
    data2[i].c = "none";
    data2[i].d = "";
  }
  // Sort for field d
  qsort(data, num_elem, sizeof (data[0]), compare_d);
}
</code>```

Body:
I am trying to sort the multiple arrays based on the ascending order of one array.
Here is the example:

int a[10] = {55140, 32294, 33321, 64321, 55312}
float b[10] = {11.11, 202.22, 3213.21, 144.32, 1.32}
const char* c[10] = {+, -, -, -, +}
unsigned char* d[10] = {22DS3K, 1FGJ29, 21FD43, 98DS03, 56DK23}

Now, after arranging the array 'a' in ascending order I want to sort the other arrays. The output should look like as follows:

a[10] = {32294, 33321, 55140, 55312, 64321}
b[10] = {202.22, 3213.21, 11.11, 1.32, 144.32}
c[10] = {-, -, +, +, -}
d[10] = {1FGJ29, 21FD43, 22DS3K, 56DK23, 98DS03}

Arranging the ascending order works fine. But, I am unable to sort the other arrays. I woould like to create a function to use it in my main function. Pleased to hear some suggestions.

I have seen the below post, but did not help me.

Sorting an array based on another in C

Here is the code that I have tried:

struct Data{
    int a[10];
    float b[10];
    const char* c[10];
    unsigned char* d[10];
} data;

int data_a[10];
float data_b[10];
const char* data_c[10];
unsigned char* d[10];

void ascending(int *t; int N){
int i,j,tmp;
for(i=0;j<N;j++){
  for(j=i+1;j<N;j++){
     if(t[i] > t[j]){
       tmp=t[i];
       t[i]=t[j];
       t[j]=tmp;
}}}}

int main(){
   int i;
   for(i=0;i<5;i++){
   data.a[i] = data_a[i];
   data.b[i] = data_b[i];
   data.c[i] = data_c[i];
   data.d[i] = data_d[i];
   }
   ascending(data.a, 5);
   for(i=0;i<5;i++){
      printf("Data is %d,%.2f,%s,%hhn\n", data.a[i],data.b[i],data.c[i],data.d[i]};
   }}

May I know if I am missing something or doing something completely wrong?

Body:
Keeping such a set of arrays in synch is a nightmare.
What you seem to want is an array of structs instead of 5 separate arrays.

If I get you right, this is what would fit your needs better:
(Also your initializers don't really match the data type of your arrays c and d.)

typedef struct data_s {
  int a;
  float b;
  const char *c;
  const char *d;
} data_t;

data_t data[10] =
{
  [0] = {.a=55140, .b=11.11,   .c="+", .d="22DS3K"},
  [1] = {.a=32294, .b=202.22,  .c="-", .d="1FGJ29"},
  [2] = {.a=33321, .b=3213.21, .c="-", .d="21FD43"},
  [3] = {.a=64321, .b=144.32,  .c="-", .d="98DS03"},
  [4] = {.a=55312, .b=1.32,    .c="+", .d="56DK23"}
};

Then you can sort (just use qsort) for member a of your struct and as you will swap whole structs at once, the corresponding other members will be sorted accordingly:

int compare_a(const void *data1, const void*data2)
{
  return ((data_t*)data2)->a - ((data_t*)data1)->a;
}

int compare_d(const void *data1, const void*data2)
{
  return strcmp(((data_t*)data1)->d, ((data_t*)data2)->d);
}

int main(void)
{
...
  // optional:
  // Populate the missing fields with some default data
  size_t num_elem = sizeof(data)/sizeof(data[0]);
  for (size_t i = 5; i < num_elem; i++)
  {
    data[i].a = (int)i * 111;
    data[i].b = i * 1.11;
    data[i].c = "none";
    data[i].d = "";
  }

  // Sort for field a
  qsort(data, num_elem, sizeof (data[0]), compare_a);

  // Variant: Size unknown, use dynamic memory allocation
  size_t num_elem2 = 123;
  data_t *data2 = malloc(num_elem2 * sizeof (*data2));
  for (size_t i = 0; i < num_elem; i++)
  {
    data2[i].a = (int)i * 111;
    data2[i].b = i*1.11;
    data2[i].c = "none";
    data2[i].d = "";
  }
  // Sort for field d
  qsort(data, num_elem, sizeof (data[0]), compare_d);
}


问:
How to add in a missing day to gridded dataset?
So I have this dataset that runs on a strict 365-day calendar year, apparently meaning that data for December 31st isn't recorded on leap years. This leaves my "day" variable in netCDF files stuck at 365 instead of 366. For the type of analysis I'm doing in R, I need to add in December 31st on those leap years. Is there a way, either with netCDF or raster tools in R, to add in a "null" 366th day with the same attributes as the other days, but all points having no data/only the established fill value (e.g., "NA", "-9999")?

If so, as kind of a bonus, I have another dataset that's a little trickier. It's missing days at random points in the year, but originally came in GRIB/GRIB2 format. If the dates run from January 1st to June 1st, and then June 2nd is completely missing, but June 3rd through December 31st is intact, how should I move forward converting them all into one netCDF file with a "blank" data day for June 2nd? What I was initially thinking was concatenating those GRIB/GRIB2 files from January 1st to June 1st and writing a netCDF file for it, create a blank netCDF file with some fill value for June 2nd, and then concatenating those GRIB/GRIB2 files from June 3rd to December 31st and writing a netCDF file for it, and then combining all of those netCDF files somehow in R. If anyone has any ideas how I might create that blank file that matches all the attributes of the other dates, or how I might combine them all in R, please let me know!

Body:
The terra package has a method fillTime for that:

r <- rast(system.file("ex/logo.tif", package="terra"))
s <- c(r, r)
time(s) <- as.Date("2001-01-01") + c(0:2, 5:7)
time(s)
#[1] "2001-01-01" "2001-01-02" "2001-01-03" "2001-01-06" "2001-01-07"
#[6] "2001-01-08"

ss <- fillTime(s)
time(ss)
#[1] "2001-01-01" "2001-01-02" "2001-01-03" "2001-01-04" "2001-01-05"
#[6] "2001-01-06" "2001-01-07" "2001-01-08"

I would argue that the missing date is Feb 29, not Dec 31.


问:
Populate columns of an internal table with 1 or 0
I have a custom z_table containing document id (key), username and two status fields - in progress and completed. My goal is to count how many documents are in progress and completed by the distinct users.
I would like to populate the status fields of the internal table of type Z_table with 1s and 0s as follows and then I could use the aggregate functions to count. For displaying the data I am using class cl_salv_table. Below is an example how my table should look like:

```<code>- Doc ID-----User-----In progress-----Completed --
¦   201   ¦  user1 ¦      1        ¦      1      ¦
--------------------------------------------------
¦   202   ¦  user2 ¦      1        ¦      0      ¦
--------------------------------------------------
</code>```

How could I fill the fields "In progress" and "Completed" with 1s and 0s based by a condition? The condition I know.
Could anybody help me with this please?

Thank you very much!

答:
If I understand the problem well then a simple LOOP and IF condition will solve your problem.
If the username in your internal table is already filled in you will simply go through the table and if the username is the same you will fill in the status with the appropriate value.

```<code>SELECT *
FROM Z_TABLE
INTO @DATA(itab)
ORDER BY user.      "Sort by user

LOOP AT itab INTO DATA(itab_line).

  "If the user is new, append it to the table
  IF itab_line-user <> last_user.
    APPEND VALUE #( user = itab_line-user
                    in_progress = itab_line-in_progress
                    completed = itab_line-completed ) TO result_tab

  "If the user is already exists in the table, change the status
  ELSE.
    ASSIGN result_tab[ user = itab_line-user ] TO FIELD-SYMBOL(<itab_line_by_user>).
    <itab_line_by_user>-in_progress = <itab_line_by_user>-in_progress + itab_line-in_progress.
    <itab_line_by_user>-completed = <itab_line_by_user>-completed + itab_line-completed.
  ENDIF.

  "Set the last_user variable
  last_user = itab_line-user.
ENDLOOP.
</code>```

This is just one possible solution out of many.
For example: It is also possible to solve this with the LOOP AT GROUP or REDUCE command.

Body:
I have a custom z_table containing document id (key), username and two status fields - in progress and completed. My goal is to count how many documents are in progress and completed by the distinct users.
I would like to populate the status fields of the internal table of type Z_table with 1s and 0s as follows and then I could use the aggregate functions to count. For displaying the data I am using class cl_salv_table. Below is an example how my table should look like:

- Doc ID-----User-----In progress-----Completed --
¦   201   ¦  user1 ¦      1        ¦      1      ¦
--------------------------------------------------
¦   202   ¦  user2 ¦      1        ¦      0      ¦
--------------------------------------------------

How could I fill the fields "In progress" and "Completed" with 1s and 0s based by a condition? The condition I know.
Could anybody help me with this please?

Thank you very much!

Body:
If I understand the problem well then a simple LOOP and IF condition will solve your problem.
If the username in your internal table is already filled in you will simply go through the table and if the username is the same you will fill in the status with the appropriate value.

SELECT *
FROM Z_TABLE
INTO @DATA(itab)
ORDER BY user.      "Sort by user

LOOP AT itab INTO DATA(itab_line).

  "If the user is new, append it to the table
  IF itab_line-user <> last_user.
    APPEND VALUE #( user = itab_line-user
                    in_progress = itab_line-in_progress
                    completed = itab_line-completed ) TO result_tab

  "If the user is already exists in the table, change the status
  ELSE.
    ASSIGN result_tab[ user = itab_line-user ] TO FIELD-SYMBOL(<itab_line_by_user>).
    <itab_line_by_user>-in_progress = <itab_line_by_user>-in_progress + itab_line-in_progress.
    <itab_line_by_user>-completed = <itab_line_by_user>-completed + itab_line-completed.
  ENDIF.

  "Set the last_user variable
  last_user = itab_line-user.
ENDLOOP.

This is just one possible solution out of many.
For example: It is also possible to solve this with the LOOP AT GROUP or REDUCE command.