问:
SQL Query to get 2nd most recent results with multiple columns
I am trying to obtain the 2nd most recent results for all distinct part_id's(based off of order_date) to go into a report I am working on making to compare it to the most recent results.

The commented sections are from another approach I was trying but unsuccessful with.

Any help is greatly appreciated!

(Side note: I am new to posting on SO, and I apologize in advance if this is answered elsewhere, but I was unable to find anything that pertained to this issue)

I am using the following query:

```<code>SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            --, ROW_NUMBER() over (ORDER BY PURCHASE_ORDER.ORDER_DATE DESC)AS ROW
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID

                    WHERE PURCHASE_ORDER.ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER) AND PURC_ORDER_LINE.PART_ID = 'XXXX'
                    ORDER BY ORDER_dATE DESC

                    --WHERE PURC_ORDER_LINE.PART_ID = 'XXXX' and PURCHASE_ORDER.ORDER_DATE = (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER WHERE ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER))
</code>```

EDIT 5/28 LATE NIGHT:

Lets say below is the data set I need the 2nd result from each part_id (2nd based off of ORDER_DATE DESC)

```<code>+-------------+---------+-----------+
| ORDER_DATE  | PART_ID | VENDOR_ID |
+-------------+---------+-----------+
| 2020-05-29  | XXXX    | CVVB      |
| 2020-05-27  | XXXX    | CVVB      |
| 2020-05-28  | XXXX    | CVVA      |
| 2020-05-28  | YYYY    | GGNB      |
| 2020-04-12  | YYYY    | GGNB      |
| 2020-02-08  | YYYY    | GGNB      |
| 2020-05-28  | ZZZZ    | LLNB      |
| 2019-10-28  | ZZZZ    | LLNB      |
| 2019-05-27  | ZZZZ    | OKIJ      |
+-------------+---------+-----------+
</code>```

I am looking to receive the following output (for more than 3 different part id's):

```<code>+------------+---------+-----------+
| ORDER_DATE | PART_ID | VENDOR_ID |
+------------+---------+-----------+
| 2020-05-28 | XXXX    | CVVA      |
| 2020-04-12 | YYYY    | GGNB      |
| 2019-10-28 | ZZZZ    | LLNB      |
+------------+---------+-----------+

</code>```

There are also additional columns in the query but formatting them as a table would have taken much longer. I have left off a few of the columns on the examples.

ANOTHER EDIT

I am not sure if this information helps, but I am trying to compare the most recent results to the previous results to show pricing and vendor differences. We are compiling the data into Report Builder; My approach here was to create 2 separate datasets one with the most recent and the other with the 2nd most recent and combine the data from the datasets in Report Builder. If there is an easier approach and I am heading in the wrong direction please let me know!

Example:

```<code>+------------+---------+-----------+-------------+----------+------------+
| ORDER_DATE | PART_ID | VENDOR_ID | Porder_Date | Ppart_ID | pVendor_id |
+------------+---------+-----------+-------------+----------+------------+
| 2020-05-29 | XXXX    | CVVB      | 2020-05-28  | XXXX     | CVVA       |
| 2020-05-28 | YYYY    | GGNB      | 2020-04-12  | YYYY     | GGNB       |
| 2020-05-28 | ZZZZ    | LLNB      | 2019-10-28  | ZZZZ     | LLNB       |
+------------+---------+-----------+-------------+----------+------------+
</code>```

EDIT THE NEXT MORNING

Thanks everyone for all the help! After Harry posted his solution I went ahead and made some tiny edits to get the columns I needed added on. I swapped his union portion with the original select statement. Everything here seems to be exactly what I am looking for!

Code:

```<code>;
WITH mycte AS
          (
                    SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID
          )
        , mycte2 AS
          (
                    SELECT
                              CONVERT(DATE,order_date) AS order_date
                            , part_id
                            , vendor_id
                            , order_qty
                            , unit_price
                            , total_cost
                            , ROW_NUMBER() over(
                                      PARTITION BY part_id
                                      ORDER BY
                                                CONVERT(DATE,order_date) DESC) AS row_num
                    FROM
                              mycte
          )
SELECT
          mycte2.order_date
        , mycte2.part_id
        , mycte2.vendor_id
        , mycte2.order_qty
        , mycte2.unit_price
        , mycte2.total_cost
        , previous.order_date porder_date
        , previous.part_id    ppart_id
        , previous.vendor_id  pvendor_id
        , previous.order_qty  poqrder_qty
        , previous.unit_price punit_price
        , previous.total_cost ptotal_cost
FROM
          mycte2
          LEFT JOIN
                    mycte2 previous
          ON
                    previous.row_num   = mycte2.row_num +1
                    AND mycte2.part_id = previous.part_id
WHERE
          mycte2.row_num = 1
</code>```

答:
I think something like this would work to get the second most recent order :</p>

```<code>;WITH cteOrders AS (
 SELECT ROW_NUMBER() OVER (ORDER BY Order_Date DESC) AS row_num,
    PURCHASE_ORDER.ORDER_DATE
    , PURC_ORDER_LINE.PART_ID
    , PURCHASE_ORDER.VENDOR_ID
    , PURC_ORDER_LINE.LINE_STATUS
    , PURC_ORDER_LINE.ORDER_QTY
    , PURC_ORDER_LINE.UNIT_PRICE
 FROM PURCHASE_ORDER
 INNER JOIN PURC_ORDER_LINE ON PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID
 WHERE PURCHASE_ORDER.ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER) AND PURC_ORDER_LINE.PART_ID = 'XXXX'
 )
 SELECT * FROM cteOrders WHERE row_num = 2
</code>```

Body:
I am trying to obtain the 2nd most recent results for all distinct part_id's(based off of order_date) to go into a report I am working on making to compare it to the most recent results.

The commented sections are from another approach I was trying but unsuccessful with.

Any help is greatly appreciated!

(Side note: I am new to posting on SO, and I apologize in advance if this is answered elsewhere, but I was unable to find anything that pertained to this issue)

I am using the following query:

SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            --, ROW_NUMBER() over (ORDER BY PURCHASE_ORDER.ORDER_DATE DESC)AS ROW
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID

                    WHERE PURCHASE_ORDER.ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER) AND PURC_ORDER_LINE.PART_ID = 'XXXX'
                    ORDER BY ORDER_dATE DESC

                    --WHERE PURC_ORDER_LINE.PART_ID = 'XXXX' and PURCHASE_ORDER.ORDER_DATE = (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER WHERE ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER))

EDIT 5/28 LATE NIGHT:

Lets say below is the data set I need the 2nd result from each part_id (2nd based off of ORDER_DATE DESC)

+-------------+---------+-----------+
| ORDER_DATE  | PART_ID | VENDOR_ID |
+-------------+---------+-----------+
| 2020-05-29  | XXXX    | CVVB      |
| 2020-05-27  | XXXX    | CVVB      |
| 2020-05-28  | XXXX    | CVVA      |
| 2020-05-28  | YYYY    | GGNB      |
| 2020-04-12  | YYYY    | GGNB      |
| 2020-02-08  | YYYY    | GGNB      |
| 2020-05-28  | ZZZZ    | LLNB      |
| 2019-10-28  | ZZZZ    | LLNB      |
| 2019-05-27  | ZZZZ    | OKIJ      |
+-------------+---------+-----------+

I am looking to receive the following output (for more than 3 different part id's):

+------------+---------+-----------+
| ORDER_DATE | PART_ID | VENDOR_ID |
+------------+---------+-----------+
| 2020-05-28 | XXXX    | CVVA      |
| 2020-04-12 | YYYY    | GGNB      |
| 2019-10-28 | ZZZZ    | LLNB      |
+------------+---------+-----------+

There are also additional columns in the query but formatting them as a table would have taken much longer. I have left off a few of the columns on the examples.

ANOTHER EDIT

I am not sure if this information helps, but I am trying to compare the most recent results to the previous results to show pricing and vendor differences. We are compiling the data into Report Builder; My approach here was to create 2 separate datasets one with the most recent and the other with the 2nd most recent and combine the data from the datasets in Report Builder. If there is an easier approach and I am heading in the wrong direction please let me know!

Example:

+------------+---------+-----------+-------------+----------+------------+
| ORDER_DATE | PART_ID | VENDOR_ID | Porder_Date | Ppart_ID | pVendor_id |
+------------+---------+-----------+-------------+----------+------------+
| 2020-05-29 | XXXX    | CVVB      | 2020-05-28  | XXXX     | CVVA       |
| 2020-05-28 | YYYY    | GGNB      | 2020-04-12  | YYYY     | GGNB       |
| 2020-05-28 | ZZZZ    | LLNB      | 2019-10-28  | ZZZZ     | LLNB       |
+------------+---------+-----------+-------------+----------+------------+

EDIT THE NEXT MORNING

Thanks everyone for all the help! After Harry posted his solution I went ahead and made some tiny edits to get the columns I needed added on. I swapped his union portion with the original select statement. Everything here seems to be exactly what I am looking for!

Code:

;
WITH mycte AS
          (
                    SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID
          )
        , mycte2 AS
          (
                    SELECT
                              CONVERT(DATE,order_date) AS order_date
                            , part_id
                            , vendor_id
                            , order_qty
                            , unit_price
                            , total_cost
                            , ROW_NUMBER() over(
                                      PARTITION BY part_id
                                      ORDER BY
                                                CONVERT(DATE,order_date) DESC) AS row_num
                    FROM
                              mycte
          )
SELECT
          mycte2.order_date
        , mycte2.part_id
        , mycte2.vendor_id
        , mycte2.order_qty
        , mycte2.unit_price
        , mycte2.total_cost
        , previous.order_date porder_date
        , previous.part_id    ppart_id
        , previous.vendor_id  pvendor_id
        , previous.order_qty  poqrder_qty
        , previous.unit_price punit_price
        , previous.total_cost ptotal_cost
FROM
          mycte2
          LEFT JOIN
                    mycte2 previous
          ON
                    previous.row_num   = mycte2.row_num +1
                    AND mycte2.part_id = previous.part_id
WHERE
          mycte2.row_num = 1

Body:
I think something like this would work to get the second most recent order :

;WITH cteOrders AS (
 SELECT ROW_NUMBER() OVER (ORDER BY Order_Date DESC) AS row_num,
    PURCHASE_ORDER.ORDER_DATE
    , PURC_ORDER_LINE.PART_ID
    , PURCHASE_ORDER.VENDOR_ID
    , PURC_ORDER_LINE.LINE_STATUS
    , PURC_ORDER_LINE.ORDER_QTY
    , PURC_ORDER_LINE.UNIT_PRICE
 FROM PURCHASE_ORDER
 INNER JOIN PURC_ORDER_LINE ON PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID
 WHERE PURCHASE_ORDER.ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER) AND PURC_ORDER_LINE.PART_ID = 'XXXX'
 )
 SELECT * FROM cteOrders WHERE row_num = 2


来源: stackexchange

问:
'NoneType' object is not subscriptable - Data generator
I created a list out of two other lists which looks like this:

```<code>samples = list(map(lambda x, y: [x,y], image_path, labels8))
[['s01_l01/1_1.png', '7C2 4698'],
 ['s01_l01/2_1.png', '7C2 4698'],
 ['s01_l01/2_2.png', '7C2 4698'],
 ['s01_l01/2_3.png', '7C2 4698'],
 ['s01_l01/2_4.png', '7C2 4698']]
</code>```

The first entry is the image_path, the second a label.

I also created this function:

```<code>def shuffle_data(data):
  data=random.shuffle(data)
  return data
</code>```

To get a data_generator, I modified the code I found in a video on YouTube (https://www.youtube.com/watch?v=EkzB6PJIcCA&t=530s):

```<code>def data_generator(samples, batch_size=32, shuffle_data = True, resize=224):
  num_samples = len(samples)
  while True:
    samples = random.shuffle(samples)

    for offset in range(0, num_samples, batch_size):
      batch_samples = samples[offset: offset + batch_size]

      X_train = []
      y_train = []

      for batch_sample in batch_samples:
        img_name = batch_sample[0]
        label = batch_sample[1]
        img = cv2.imread(os.path.join(root_dir, img_name))

        #img, label = preprocessing(img, label, new_height=224, new_width=224, num_classes=37)
        img = preprocessing(img, new_height=224, new_width=224)
        label = my_onehot_encoded(label)

        X_train.append(img)
        y_train.append(label)

      X_train = np.array(X_train)
      y_train = np.array(y_train)

      yield X_train, y_train
</code>```

When I now try to execute this code:

```<code>train_datagen = data_generator(samples, batch_size=32)

x, y = next(train_datagen)
print('x_shape: ', x.shape)
print('labels shape: ', y.shape)
print('labels: ', y)
</code>```

I got the following error code:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-6adc7f4509cd> in <module>()
      1 train_datagen = data_generator(samples, batch_size=32)
      2
----> 3 x, y = next(train_datagen)
      4 print('x_shape: ', x.shape)
      5 print('labels shape: ', y.shape)

<ipython-input-88-0f34e3e5c990> in data_generator(samples, batch_size, shuffle_data, resize)
      5
      6     for offset in range(0, num_samples, batch_size):
----> 7       batch_samples = samples[offset: offset + batch_size]
      8
      9       X_train = []

TypeError: 'NoneType' object is not subscriptable
</code>```

I don't get where the error is...

答:
random.shuffle is an in-place operation, so you shouldn't be assigning its result (which is None) to the shufflee. Instead, leave it as is:

```<code>while True:
    random.shuffle(samples) # <--here

    for offset in range(0, num_samples, batch_size):
        batch_samples = samples[offset: offset + batch_size]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a list out of two other lists which looks like this:

samples = list(map(lambda x, y: [x,y], image_path, labels8))
[['s01_l01/1_1.png', '7C2 4698'],
 ['s01_l01/2_1.png', '7C2 4698'],
 ['s01_l01/2_2.png', '7C2 4698'],
 ['s01_l01/2_3.png', '7C2 4698'],
 ['s01_l01/2_4.png', '7C2 4698']]

The first entry is the image_path, the second a label.

I also created this function:

def shuffle_data(data):
  data=random.shuffle(data)
  return data

To get a data_generator, I modified the code I found in a video on YouTube (https://www.youtube.com/watch?v=EkzB6PJIcCA&t=530s):

def data_generator(samples, batch_size=32, shuffle_data = True, resize=224):
  num_samples = len(samples)
  while True:
    samples = random.shuffle(samples)

    for offset in range(0, num_samples, batch_size):
      batch_samples = samples[offset: offset + batch_size]

      X_train = []
      y_train = []

      for batch_sample in batch_samples:
        img_name = batch_sample[0]
        label = batch_sample[1]
        img = cv2.imread(os.path.join(root_dir, img_name))

        #img, label = preprocessing(img, label, new_height=224, new_width=224, num_classes=37)
        img = preprocessing(img, new_height=224, new_width=224)
        label = my_onehot_encoded(label)

        X_train.append(img)
        y_train.append(label)

      X_train = np.array(X_train)
      y_train = np.array(y_train)

      yield X_train, y_train

When I now try to execute this code:

train_datagen = data_generator(samples, batch_size=32)

x, y = next(train_datagen)
print('x_shape: ', x.shape)
print('labels shape: ', y.shape)
print('labels: ', y)

I got the following error code:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-6adc7f4509cd> in <module>()
      1 train_datagen = data_generator(samples, batch_size=32)
      2
----> 3 x, y = next(train_datagen)
      4 print('x_shape: ', x.shape)
      5 print('labels shape: ', y.shape)

<ipython-input-88-0f34e3e5c990> in data_generator(samples, batch_size, shuffle_data, resize)
      5
      6     for offset in range(0, num_samples, batch_size):
----> 7       batch_samples = samples[offset: offset + batch_size]
      8
      9       X_train = []

TypeError: 'NoneType' object is not subscriptable

I don't get where the error is...

Body:
random.shuffle is an in-place operation, so you shouldn't be assigning its result (which is None) to the shufflee. Instead, leave it as is:

while True:
    random.shuffle(samples) # <--here

    for offset in range(0, num_samples, batch_size):
        batch_samples = samples[offset: offset + batch_size]


问:
Discord bot ctx is being displayed as argument
Thats a test code where im trying to work in classes. Even tho in commands it displayes ctx as required arg instead and it works only if i put it before self.

class Quiz:
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    @bot.command(pass_context=True)
    async def quiz(self, ctx):
        fido = Quiz("Starter mass?", "yeah")
        nope = Quiz("WHAT?", "lel")
        await ctx.send(fido.question)

        def check(m):
            return m.content == 'heh'

        msg = await bot.wait_for('message', check=check)
        await ctx.send('Right {.author}!'.format(msg))
```
<p>Error:</p>
```discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
```

How can I fix this?

答:
As crazy as it sounds, remove the self argument from your method. The commands decorator will take care of this. (You can also use a command cog)

class Quiz:
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    @bot.command(pass_context=True)
    async def quiz(ctx):
        fido = Quiz("Starter mass?", "yeah")
        nope = Quiz("WHAT?", "lel")
        await ctx.send(fido.question)

        def check(m):
            return m.content == 'heh'

        msg = await bot.wait_for('message', check=check)
        await ctx.send('Right {.author}!'.format(msg))
```

<p>Also your check function doesn't work correctly. It always uses the <code>fido</code> question and says you are correct only after responding with <code>'heh'</code>.</p>

<pre class="lang-py prettyprint-override"><code>    @bot.command(pass_context=True)
    async def quiz(ctx):
        fido = Quiz("Starter mass?", "yeah")
        nope = Quiz("WHAT?", "lel")
        question = random.choice((fido, nope))
        await ctx.send(question.question)

        check = lambda m: m.content.lower() == question.answer
        msg = await bot.wait_for('message', check=check)
        await ctx.send(f'Right **{msg.author.name}**!')
</code>```

Body:
Thats a test code where im trying to work in classes. Even tho in commands it displayes ctx as required arg instead and it works only if i put it before self.

class Quiz:
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    @bot.command(pass_context=True)
    async def quiz(self, ctx):
        fido = Quiz("Starter mass?", "yeah")
        nope = Quiz("WHAT?", "lel")
        await ctx.send(fido.question)

        def check(m):
            return m.content == 'heh'

        msg = await bot.wait_for('message', check=check)
        await ctx.send('Right {.author}!'.format(msg))

Error:

discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

How can I fix this?

Body:
As crazy as it sounds, remove the self argument from your method. The commands decorator will take care of this. (You can also use a command cog)

class Quiz:
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    @bot.command(pass_context=True)
    async def quiz(ctx):
        fido = Quiz("Starter mass?", "yeah")
        nope = Quiz("WHAT?", "lel")
        await ctx.send(fido.question)

        def check(m):
            return m.content == 'heh'

        msg = await bot.wait_for('message', check=check)
        await ctx.send('Right {.author}!'.format(msg))

Also your check function doesn't work correctly. It always uses the fido question and says you are correct only after responding with 'heh'.

    @bot.command(pass_context=True)
    async def quiz(ctx):
        fido = Quiz("Starter mass?", "yeah")
        nope = Quiz("WHAT?", "lel")
        question = random.choice((fido, nope))
        await ctx.send(question.question)

        check = lambda m: m.content.lower() == question.answer
        msg = await bot.wait_for('message', check=check)
        await ctx.send(f'Right **{msg.author.name}**!')


问:
How should I interpret or intuitively explain the following results for my CNN model?
I am training a CNN model that has to classify 4 objects. 3 mugs (white, black, blue) and 1 glass. When I train my model for only 10 epochs, I get a validation accuracy of 25%, where everything is being labeled as the white mug. However when I would train the same model for longer, it eventually diverts from this 25% accuracy and climbs up to 80%, the only problem it has, is classifying the white mug.

In other words, if I am able to find why my classifier classifies the white mug wrongly, then I could potentially reach validation_accuracy of 90%. My question thus is, what are some things I could try to find out why it mispredicts, or things to improve. I have already used LIME to check why my model classifies something, but I could not get any wiser from it.

Some specs of the model:

No data augmentation

5 convolutional layers (32, 64, 128, 256, 512) -> into GlobalMaxPooling, Flatten, and 2 dense layers (128, 4)

Activation layers (relu)

2000 training images, 1000 validation images (classes are balanced)

Extra: The model gets 100% accuracy on the training data after 2 epochs, and slowly climbs up to 80% on the validation data (after about 40-50 epochs).

Extra 2: Sometimes the model gets 80%, sometimes only 74%

答:
There could be multiple issues here. It looks like your network is overfitting, so first off you may want to add regularization or dropout to your training process. Secondly, you'll also want to make sure your images come from the same source, i.e. if your training/test examples all come from Google images or have vastly different qualities, angles, colors, etc, this might harm the network's ability to classify the mug correctly.

Finally, you might want to add a softmax layer at the end of your network since you're doing a multiclass classification. By doing this, you'll be able to see what the probability is for the white mug compared to the other objects, which can help you with debugging.


问:
Dartz Right containing List throws Error when comparing with expect() function
Simple code like this

```<code>expect(Right(['Two', 'Three']), equals(Right(['Two', 'Three'])));
</code>```

throws error:

```<code>ERROR: Expected: Right<dynamic, List>:<Right([Two, Three])>
Actual: Right<dynamic, List>:<Right([Two, Three])>
</code>```

What am I doing wrong? Both lists are identical and both has equatable elements.

答:
Dart is checking for referential equality as default, and here you are compoaring two arrays which have equal values but not equal reference. Constant lists will behave as you expected, while runtime defined lists will not.

```<code>final a = ['Two', 'Three'] == ['Two', 'Three']; // false
final b = const ['Two', 'Three'] == const ['Two', 'Three']; // true
</code>```

It can be confusing since this will pass:

```<code>expect(['Two', 'Three'], equals(['Two', 'Three']));
</code>```

The testing libary has default matchers of iterators and will do a deep check to match all the strings in the list, therefore the above passes. That is not the case for the Right data type, which will fallback to the ==-operator and therefore fails, since it will return false as shown above.

Dartz has a list implementation (immutable) that checks for deep equality which will succeed, or with const as described above:

```<code>final a2 = ilist('Two', 'Three') == ilist('Two', 'Three') // true

expect(Right(ilist(['Two', 'Three'])), equals(Right(ilist(['Two', 'Three']))));

expect(Right(const ['Two', 'Three']), equals(Right(const ['Two', 'Three'])));
</code>```

Body:
Simple code like this

expect(Right(['Two', 'Three']), equals(Right(['Two', 'Three'])));

throws error:

ERROR: Expected: Right<dynamic, List>:<Right([Two, Three])>
Actual: Right<dynamic, List>:<Right([Two, Three])>

What am I doing wrong? Both lists are identical and both has equatable elements.

Body:
Dart is checking for referential equality as default, and here you are compoaring two arrays which have equal values but not equal reference. Constant lists will behave as you expected, while runtime defined lists will not.

final a = ['Two', 'Three'] == ['Two', 'Three']; // false
final b = const ['Two', 'Three'] == const ['Two', 'Three']; // true

It can be confusing since this will pass:

expect(['Two', 'Three'], equals(['Two', 'Three']));

The testing libary has default matchers of iterators and will do a deep check to match all the strings in the list, therefore the above passes. That is not the case for the Right data type, which will fallback to the ==-operator and therefore fails, since it will return false as shown above.

Dartz has a list implementation (immutable) that checks for deep equality which will succeed, or with const as described above:

final a2 = ilist('Two', 'Three') == ilist('Two', 'Three') // true

expect(Right(ilist(['Two', 'Three'])), equals(Right(ilist(['Two', 'Three']))));

expect(Right(const ['Two', 'Three']), equals(Right(const ['Two', 'Three'])));


问:
How to pause process run using Java's ProcessBuilder.start()?
Alright, so I'm writing this program that essentially batch runs other java programs for me (multiple times, varying parameters, parallel executions, etc).

So far the running part works great. Using ProcessBuilder's .start() method (equivalent to the Runtime.exec() I believe), it creates a separate java process and off it goes.

Problem is I would like to be able to pause/stop these processes once they've been started. With simple threads this is generally easy to do, however the external process doesn't seem to have any inbuilt functionality for waiting/sleeping, at least not from an external point of view.

My question(s) is this: Is there a way to pause a java.lang.Process object? If not, does anyone know of any related exec libraries that do contain this ability? Barring all of that, is extending Process a more viable alternative?

答:
My question(s) is this: Is there a way to pause a java.lang.Process object?

As you've probably discovered, there's no support for this in the standard API. Process for instance provides no suspend() / resume() methods.

If not, does anyone know of any related exec libraries that do contain this ability?

On POSIX compliant operating systems such as GNU/Linux or Mac OS you could use another system call (using Runtime.exec, ProcessBuilder or some natively implemented library) to issue a kill command.

Using the kill command you can send signals such as SIGSTOP (to suspend a process) and SIGCONT (to resume it).

(You will need to get hold of the process id of the external program. There are plenty of questions and answers around that answers this.)

ContentLicense: CC BY-SA 3.0


问:
How to write a CASE statement in the WHERE clause in Snowflake
I am trying to rewrite a piece of SQL code that was initially written for Vertica. Vertica has the AGE_IN_YEARS() built-in function which was great to get someone's age. But, now, I need to find a way to have it to work in Snowflake and I did.

An equivalent statement that replaces AGE_IN_YEARS(DateOfBirth) in Snowflake can be:

```<code>case when dateadd(year, datediff(years, DateOfBirth, CURRENT_DATE), DateOfBirth) > CURRENT_DATE
then datediff(years, DateOfBirth, CURRENT_DATE) -1
else datediff(years, DateOfBirth, CURRENT_DATE)
end as AGE
</code>```

The issue is when I have to use this in a WHERE clause. The original Vertica code is:

```<code>SELECT name, dob,
(SELECT AgeRangeCode
   FROM AgeRangeTable
   WHERE AGE_IN_YEARS(DateOfBirth) BETWEEN MinAge AND MaxAge) AS AgeRangeCode,
CURRENT_DATE as TODAY
from MemberInfoTable
</code>```

and if i add the AGE_IN_YEARS() replacement to the above query, I get

SQL compilation error: Unsupported subquery type cannot be evaluated

How do I go about writing this case in the WHERE clause

答:
not using a function to calculate age, just joining to the data you have like so works:

```<code>with age_range_table as (
    select * from values (0,16, 'A'),(16,18, 'B'),(18,1000, 'C') v(min_age, max_age, age_range_code)
), member_info_table as (
    select name, dob::date as dob from values ('user_80s', '1980-01-01'),('user_90s', '1990-01-01'),('user_10s', '2010-01-01') v(name, dob)
)
select m.name,
    m.dob,
    a.age_range_code
from member_info_table AS m
join age_range_table AS a
    ON m.dob < dateadd('years',-a.min_age, current_date)
    AND m.dob >= dateadd('years',-a.max_age, current_date);
</code>```

giving:

```<code>NAME    DOB AGE_RANGE_CODE
user_80s    1980-01-01  C
user_90s    1990-01-01  C
user_10s    2010-01-01  A
</code>```

but that is slightly gross to be doing function calls in a WHERE clause..

```<code>with age_range_table as (
    select *
    from values
        (0,16, 'A'),
        (16,18, 'B'),
        (18,1000, 'C')
        v(min_age, max_age, age_range_code)
), member_info_table as (
    select name, dob::date as dob
    from values
       ('user_80s', '1980-01-01'),
       ('user_90s', '1990-01-01'),
       ('user_10s', '2010-01-01')
       v(name, dob)
), today_age_range_table as (
    select age_range_code
        ,dateadd('years',-min_age, current_date) as range_end_date
        ,dateadd('years',-max_age, current_date) as range_start_date
    from age_range_table
)
select m.name,
    m.dob,
    a.age_range_code
from member_info_table AS m
join today_age_range_table AS a
    ON m.dob < a.range_end_date
    AND m.dob >= a.range_start_date;
</code>```

credit note: this is the same solution as Gordon's but with it explicitly shown. And the range logic changed to alter the range times once in a CTE verse altering user.dob for all rows. Based on the assumption you have more users than ranges, and if both are sub 1000 you have no problems ether.

Body:
I am trying to rewrite a piece of SQL code that was initially written for Vertica. Vertica has the AGE_IN_YEARS() built-in function which was great to get someone's age. But, now, I need to find a way to have it to work in Snowflake and I did.

An equivalent statement that replaces AGE_IN_YEARS(DateOfBirth) in Snowflake can be:

case when dateadd(year, datediff(years, DateOfBirth, CURRENT_DATE), DateOfBirth) > CURRENT_DATE
then datediff(years, DateOfBirth, CURRENT_DATE) -1
else datediff(years, DateOfBirth, CURRENT_DATE)
end as AGE

The issue is when I have to use this in a WHERE clause. The original Vertica code is:

SELECT name, dob,
(SELECT AgeRangeCode
   FROM AgeRangeTable
   WHERE AGE_IN_YEARS(DateOfBirth) BETWEEN MinAge AND MaxAge) AS AgeRangeCode,
CURRENT_DATE as TODAY
from MemberInfoTable

and if i add the AGE_IN_YEARS() replacement to the above query, I get

SQL compilation error: Unsupported subquery type cannot be evaluated

How do I go about writing this case in the WHERE clause

Body:
not using a function to calculate age, just joining to the data you have like so works:

with age_range_table as (
    select * from values (0,16, 'A'),(16,18, 'B'),(18,1000, 'C') v(min_age, max_age, age_range_code)
), member_info_table as (
    select name, dob::date as dob from values ('user_80s', '1980-01-01'),('user_90s', '1990-01-01'),('user_10s', '2010-01-01') v(name, dob)
)
select m.name,
    m.dob,
    a.age_range_code
from member_info_table AS m
join age_range_table AS a
    ON m.dob < dateadd('years',-a.min_age, current_date)
    AND m.dob >= dateadd('years',-a.max_age, current_date);

giving:

NAME    DOB AGE_RANGE_CODE
user_80s    1980-01-01  C
user_90s    1990-01-01  C
user_10s    2010-01-01  A

but that is slightly gross to be doing function calls in a WHERE clause..

with age_range_table as (
    select *
    from values
        (0,16, 'A'),
        (16,18, 'B'),
        (18,1000, 'C')
        v(min_age, max_age, age_range_code)
), member_info_table as (
    select name, dob::date as dob
    from values
       ('user_80s', '1980-01-01'),
       ('user_90s', '1990-01-01'),
       ('user_10s', '2010-01-01')
       v(name, dob)
), today_age_range_table as (
    select age_range_code
        ,dateadd('years',-min_age, current_date) as range_end_date
        ,dateadd('years',-max_age, current_date) as range_start_date
    from age_range_table
)
select m.name,
    m.dob,
    a.age_range_code
from member_info_table AS m
join today_age_range_table AS a
    ON m.dob < a.range_end_date
    AND m.dob >= a.range_start_date;

credit note: this is the same solution as Gordon's but with it explicitly shown. And the range logic changed to alter the range times once in a CTE verse altering user.dob for all rows. Based on the assumption you have more users than ranges, and if both are sub 1000 you have no problems ether.


问:
Batch Replace and add 1 to a number between specific text in an xml file
Ok i'm trying to write a batch to "grab" a serial number for the user. The serial number comes from another system and we have to periodically manually input a serial number.  I would like the user to run the batch file which would add 1 and replace the old number and then echo "Your serial number is ##" where ## is the new number. I'm pretty sure i can work out the Echo part and the writing to a temp file and overwriting the old file but its the middle part that im struggling with.
The xml file is that is being edited is:

```<code><?xml version="1.0"?>
<BatchSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SerialFormat>{0:yyMMdd}{1:00}</SerialFormat>
  <LastSerialDate>2020-05-27T00:00:00-05:00</LastSerialDate>
  <LastSerialNumber>10</LastSerialNumber>
</BatchSettings>
</code>```

the number i need to change is the ## between "lastserialnumber" <LastSerialNumber>10</LastSerialNumber>.
I've tried a few different approaches and this first one is close but definitely no cigar.

```<code>@echo off
set /a "replace=10"
set /a "replaced=replace+1"

set "source=Test.txt"
set "target=Test2.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
      set "line=%%b"
      if defined line set "line=!line:%replace%=%replaced%!"
      echo(!line!
   )
) > %target%
endlocal
</code>```

The problem with that one is the number won't always be "10" and I also don't want to replace all the other instances of "10" in the file.

I've also tried

```<code>@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

@echo off
    setlocal enableextensions disabledelayedexpansion

    (for /f "delims=" %%a in (%SrcFile%
    ) do for /f "tokens=2 delims=1234567890 " %%b in ("%%~a"
    ) do if not "%%b"==":"  (
        echo(%%~a
    ) else for /f "tokens=1 delims=  <LastSerialNumber>:" %%c in ("%%~a"
    ) do (
        set /a "n=%%c+1"
        setlocal enabledelayedexpansion
        echo(<LastSerialNumber>!n!:
        endlocal
    )) > %OutFile%
</code>```

but that doesn't increment the number and cuts off the remaining text.
and this one is just a hot mess that doesn't work at all.

```<code>@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

setlocal EnableDelayedExpansion

(for /F "delims=" %%a in ('findstr /I /L "<LastSerialNumber>" %SrcFile%') do (
   set "line=%%a
   set "line=!line:*<LastSerialNumber>=!"
   for /F "delims=<" %%b in ("!line!") do echo %%b+1
)) > %oldnumber%

set "newnumber=%oldnumber%+1"

(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %SrcFile%') do (
      set "line=%%b"
      if defined line set "line=!line:%oldnumber%=%newnumber%!"
        echo(!line!
   )
) > %OutFile%
endlocal
</code>```

答:
At first let us take a quick look at your attempts:

fails as it searches just for 10 and does not regard the <LastSerialNumber> tags at all.

fails because you try to define a string for the delims= option of for /F although it actually defines a set of characters.

fails because you try to redirect (>) into a variable, which cannot work, you can only redirect to files. Furthermore, you attempt to do arithmetics (+1) but this only works when using set /A. And the last section has got the same problem as approach 1.

Here is a way you could do it:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=%~1" & rem // (input file; `%~1` is the first argument)
set "_TAG=<LastSerialNumber>" & rem // (opening tag)

rem // Loop over all (non-empty) lines of the input file:
for /F "usebackq delims=" %%L in ("%_FILE%") do (
    rem // Store current line string:
    set "LINE=%%L"
    rem // Toggle delayed expansion to avoid troubles with `!`:
    setlocal EnableDelayedExpansion
    rem // Split off opening tag from line string:
    set "TEST=!LINE:*%_TAG%=!"
    rem // Check whether opening tag has been found:
    if not "!TEST!"=="!LINE!" (
        rem // Opening tag found, hence split off closing tag:
        for /F "tokens=1* eol=< delims=< " %%S in ("!TEST!") do (
            rem // Get extracted number and increment it:
            set /A "NUM=%%S+1"
            rem // Return rebuild line with incremented number:
            echo(  !_TAG!!NUM!^<%%T
        )
    ) else (
        rem // Opening tag not found, hence return original line:
        echo(!LINE!
    )
    endlocal
)

endlocal
exit /B
```

<p>Given the batch file is called <code>inc-serial.bat</code>, call it with the input XML file as a command line argument (say <code>test.xml</code> in the current directory):</p>

<pre class="lang-cmd prettyprint-override"><code>inc-serial.bat "test.xml"
</code>```

To write the output to another file use redirection (>):

inc-serial.bat "test.xml" > "test_NEW.xml"
```

Body:
Ok i'm trying to write a batch to "grab" a serial number for the user. The serial number comes from another system and we have to periodically manually input a serial number.  I would like the user to run the batch file which would add 1 and replace the old number and then echo "Your serial number is ##" where ## is the new number. I'm pretty sure i can work out the Echo part and the writing to a temp file and overwriting the old file but its the middle part that im struggling with.
The xml file is that is being edited is:

<?xml version="1.0"?>
<BatchSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SerialFormat>{0:yyMMdd}{1:00}</SerialFormat>
  <LastSerialDate>2020-05-27T00:00:00-05:00</LastSerialDate>
  <LastSerialNumber>10</LastSerialNumber>
</BatchSettings>

the number i need to change is the ## between "lastserialnumber" <LastSerialNumber>10</LastSerialNumber>.
I've tried a few different approaches and this first one is close but definitely no cigar.

@echo off
set /a "replace=10"
set /a "replaced=replace+1"

set "source=Test.txt"
set "target=Test2.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
      set "line=%%b"
      if defined line set "line=!line:%replace%=%replaced%!"
      echo(!line!
   )
) > %target%
endlocal

The problem with that one is the number won't always be "10" and I also don't want to replace all the other instances of "10" in the file.

I've also tried

@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

@echo off
    setlocal enableextensions disabledelayedexpansion

    (for /f "delims=" %%a in (%SrcFile%
    ) do for /f "tokens=2 delims=1234567890 " %%b in ("%%~a"
    ) do if not "%%b"==":"  (
        echo(%%~a
    ) else for /f "tokens=1 delims=  <LastSerialNumber>:" %%c in ("%%~a"
    ) do (
        set /a "n=%%c+1"
        setlocal enabledelayedexpansion
        echo(<LastSerialNumber>!n!:
        endlocal
    )) > %OutFile%

but that doesn't increment the number and cuts off the remaining text.
and this one is just a hot mess that doesn't work at all.

@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

setlocal EnableDelayedExpansion

(for /F "delims=" %%a in ('findstr /I /L "<LastSerialNumber>" %SrcFile%') do (
   set "line=%%a
   set "line=!line:*<LastSerialNumber>=!"
   for /F "delims=<" %%b in ("!line!") do echo %%b+1
)) > %oldnumber%

set "newnumber=%oldnumber%+1"

(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %SrcFile%') do (
      set "line=%%b"
      if defined line set "line=!line:%oldnumber%=%newnumber%!"
        echo(!line!
   )
) > %OutFile%
endlocal

Body:
At first let us take a quick look at your attempts:

fails as it searches just for 10 and does not regard the <LastSerialNumber> tags at all.

fails because you try to define a string for the delims= option of for /F although it actually defines a set of characters.

fails because you try to redirect (>) into a variable, which cannot work, you can only redirect to files. Furthermore, you attempt to do arithmetics (+1) but this only works when using set /A. And the last section has got the same problem as approach 1.

Here is a way you could do it:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=%~1" & rem // (input file; `%~1` is the first argument)
set "_TAG=<LastSerialNumber>" & rem // (opening tag)

rem // Loop over all (non-empty) lines of the input file:
for /F "usebackq delims=" %%L in ("%_FILE%") do (
    rem // Store current line string:
    set "LINE=%%L"
    rem // Toggle delayed expansion to avoid troubles with `!`:
    setlocal EnableDelayedExpansion
    rem // Split off opening tag from line string:
    set "TEST=!LINE:*%_TAG%=!"
    rem // Check whether opening tag has been found:
    if not "!TEST!"=="!LINE!" (
        rem // Opening tag found, hence split off closing tag:
        for /F "tokens=1* eol=< delims=< " %%S in ("!TEST!") do (
            rem // Get extracted number and increment it:
            set /A "NUM=%%S+1"
            rem // Return rebuild line with incremented number:
            echo(  !_TAG!!NUM!^<%%T
        )
    ) else (
        rem // Opening tag not found, hence return original line:
        echo(!LINE!
    )
    endlocal
)

endlocal
exit /B

Given the batch file is called inc-serial.bat, call it with the input XML file as a command line argument (say test.xml in the current directory):

inc-serial.bat "test.xml"

To write the output to another file use redirection (>):

inc-serial.bat "test.xml" > "test_NEW.xml"


问:
More efficient block resampling of R dataframe
I'm trying to resample an R dataframe in a clustered/blocked way. I'm doing so with the code snippet below, but its quite slow:

```<code>    index_sample <- sample(unique(data[[cluster_var]]),
                           size=length(unique(data[[cluster_var]])), replace=T)

    indices <- unlist(sapply(index_sample, FUN=function(x) {which(data[[cluster_var]] == x)}))
</code>```

Is there a more efficient way to do this? The unlist/sapply step in particular seems very slow.

Example of desired behavior:

```<code>set.seed(1919)
data <- data.frame(x=sample(seq(1,5,1), 20, replace=TRUE),
                   y = runif(20))
index_sample <- sample(unique(data[['x']]),
                       size=length(unique(data[['x']])), replace=T)
indices <- unlist(sapply(index_sample, FUN=function(x) {which(data[['x']] == x)}))
print(indices)
[1]  7  8  9 10 14 17 20  7  8  9 10 14 17 20  1 12  2 18 19  6 11 13 16
</code>```

答:
We can use outer

```<code>indices2 <- which(outer(data$x, index_sample, FUN = `==`), arr.ind = TRUE)[,1]
</code>```

-testing with OP's solution

```<code>identical(indices, indices2)
#[1] TRUE
</code>```

Body:
I'm trying to resample an R dataframe in a clustered/blocked way. I'm doing so with the code snippet below, but its quite slow:

    index_sample <- sample(unique(data[[cluster_var]]),
                           size=length(unique(data[[cluster_var]])), replace=T)

    indices <- unlist(sapply(index_sample, FUN=function(x) {which(data[[cluster_var]] == x)}))

Is there a more efficient way to do this? The unlist/sapply step in particular seems very slow.

Example of desired behavior:

set.seed(1919)
data <- data.frame(x=sample(seq(1,5,1), 20, replace=TRUE),
                   y = runif(20))
index_sample <- sample(unique(data[['x']]),
                       size=length(unique(data[['x']])), replace=T)
indices <- unlist(sapply(index_sample, FUN=function(x) {which(data[['x']] == x)}))
print(indices)
[1]  7  8  9 10 14 17 20  7  8  9 10 14 17 20  1 12  2 18 19  6 11 13 16

Body:
We can use outer

indices2 <- which(outer(data$x, index_sample, FUN = `==`), arr.ind = TRUE)[,1]

-testing with OP's solution

identical(indices, indices2)
#[1] TRUE


问:
Is the flamingo project still alive?
I want to use a ribbon menu in java and found the flamingo project. Unfortunately the most links to the flamingo project page are dead and it seams as there isn't a lot movement going on.
Does anyone know if the project is still alive and developing?

Best regards

答:
Doesn't look like the project's being updated, but the source is available:
https://github.com/kirillcool/flamingo</p>

Title: Is the flamingo project still alive?


问:
Change color of plot in R
I'm trying to find out why I'm not able to change the color of my bars. Hope you can help, I'm kinda new to this.

```<code>ggplot2(data, aes(x = data$Crop, y = data$"2018"))+
    geom_bar(color="black", fill="red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    main="Production value per crop in 2018" +
    ylab("Production value in 2018")+
    xlab("Crop")+
</code>```

Hope to hear from you.

答:
This is the code, which worked, though xlab gave an error referring to unexpected symbol

```<code>setwd("C:/Users/####/OneDrive/Documenten") # include the path to your data
data<-read_xlsx("datasetR.xlsx")
str(data) # get an overview of the data

library(ggplot2)
library(tidyverse)
dCrop <- data$Crop
d2018 <- data$"2018"

ggplot(data, aes(x = dCrop, y = d2018)) +
    geom_col(width=1, fill = "red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    ggtitle("Production value per crop in 2018")+
    ylab("Production value in 2018") +
    xlab("Crop")
</code>```

enter image description here

Title: Change color of plot in R

Body:
I'm trying to find out why I'm not able to change the color of my bars. Hope you can help, I'm kinda new to this.

ggplot2(data, aes(x = data$Crop, y = data$"2018"))+
    geom_bar(color="black", fill="red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    main="Production value per crop in 2018" +
    ylab("Production value in 2018")+
    xlab("Crop")+

Hope to hear from you.

Body:
This is the code, which worked, though xlab gave an error referring to unexpected symbol

setwd("C:/Users/####/OneDrive/Documenten") # include the path to your data
data<-read_xlsx("datasetR.xlsx")
str(data) # get an overview of the data

library(ggplot2)
library(tidyverse)
dCrop <- data$Crop
d2018 <- data$"2018"

ggplot(data, aes(x = dCrop, y = d2018)) +
    geom_col(width=1, fill = "red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    ggtitle("Production value per crop in 2018")+
    ylab("Production value in 2018") +
    xlab("Crop")

enter image description here


问:
Private-setter properties in C# 3.0 object initialization
If I have the following code:

```<code>public class MyClass
{
  public string myName { get; private set; }
  public string myId { get; set; }
}
</code>```

A private compiler-generated variable is created for the setter. I want the setter not to be accessible for object initialization only.  But, how do I get to initially set the myName variable?

Reading about object initialization I found the following:

... it’s read-only  and the
  private field representing the
  underlying storage has a
  compiler-generated name that we
  cannot use in a constructor to assign
  to it. The solution is to use [...] object
  initializers

The solution would be, then, to use:

```<code>MyClass mc = new MyClass {
myName = "What ever",
myId = "1234"
};
</code>```

But this ends up in a compiler error sayin that:

The property or indexer
  'MyClass.MyClass.myName'
  cannot be used in this context because
  the set accessor is inaccessible

So, is there a way to achieve setting this value using object initialization? If there is, what is the correct way to do it?

答:
Since C# 9.0 you can use init accessor which allows you to set property value only during initialization.

Declaration:

```<code>public class MyClass
{
  public string myName { get; init; }
  public string myId { get; set; }
}
</code>```

The object initialization will work with this configuration:

```<code>MyClass mc = new MyClass
{
  myName = "What ever",
  myId = "1234"
};
</code>```

See more details here.

Body:
If I have the following code:

public class MyClass
{
  public string myName { get; private set; }
  public string myId { get; set; }
}

A private compiler-generated variable is created for the setter. I want the setter not to be accessible for object initialization only.  But, how do I get to initially set the myName variable?

Reading about object initialization I found the following:

... it’s read-only  and the
  private field representing the
  underlying storage has a
  compiler-generated name that we
  cannot use in a constructor to assign
  to it. The solution is to use [...] object
  initializers

The solution would be, then, to use:

MyClass mc = new MyClass {
myName = "What ever",
myId = "1234"
};

But this ends up in a compiler error sayin that:

The property or indexer
  'MyClass.MyClass.myName'
  cannot be used in this context because
  the set accessor is inaccessible

So, is there a way to achieve setting this value using object initialization? If there is, what is the correct way to do it?

Body:
Since C# 9.0 you can use init accessor which allows you to set property value only during initialization.

Declaration:

public class MyClass
{
  public string myName { get; init; }
  public string myId { get; set; }
}

The object initialization will work with this configuration:

MyClass mc = new MyClass
{
  myName = "What ever",
  myId = "1234"
};

See more details here.


问:
Broadcast receiver in Android does not work
I have a simple service which runs package installer session and I want to get status from it. Package manager has different statuses and depending what status I receive, I want my activity to create a dialog but I encountered a problem.
InstallerService.kt:

```<code>class InstallerService: Service() {

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999)) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                Toast.makeText(this, "Installing...", Toast.LENGTH_SHORT).show()
                Log.d(TAG, "Requesting user confirmation for installation")
                val confirmationIntent =
                    intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
                confirmationIntent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                try {
                    startActivity(confirmationIntent)
                } catch (e: Exception) {
                }
            }
            PackageInstaller.STATUS_SUCCESS -> {
                Log.d(TAG, "Installation succeed")
                getSharedPreferences("installPrefs", Context.MODE_PRIVATE).edit().putBoolean("isInstalling", false).apply()
                val mIntent = Intent(MainActivity.INSTALL_COMPLETED)
                mIntent.action = MainActivity.INSTALL_COMPLETED
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_ABORTED -> {
                val mIntent = Intent(MainActivity.INSTALL_ABORTED)
                mIntent.action = MainActivity.INSTALL_ABORTED
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_INVALID -> {
                val mIntent = Intent(MainActivity.INSTALL_INVALID)
                mIntent.action = MainActivity.INSTALL_INVALID
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_CONFLICT -> {
                val mIntent = Intent(MainActivity.INSTALL_CONFLICT)
                mIntent.action = MainActivity.INSTALL_CONFLICT
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_STORAGE -> {
                val mIntent = Intent(MainActivity.INSTALL_STORAGE)
                mIntent.action = MainActivity.INSTALL_STORAGE
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_BLOCKED -> {
                val mIntent = Intent(MainActivity.INSTALL_BLOCKED)
                mIntent.action = MainActivity.INSTALL_BLOCKED
                sendBroadcast(mIntent)
            }
            else -> {
                Log.d(TAG, "Installation failed")
                val mIntent = Intent(MainActivity.INSTALL_FAILED)
                mIntent.action = MainActivity.INSTALL_ABORTED
                sendBroadcast(mIntent)
            }
        }
        stopSelf()
        return START_NOT_STICKY
    }

    @Nullable
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    companion object{
        const val TAG = "VMInstall"
    }

}
</code>```

Now when k try to receive intent action, it does not do anything at all
MainActivity.kt:

```<code>class MainActivity : Main() {

    private var isParent = true

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.home_toolbar)
        setSupportActionBar(toolbar)

        val navHost = findNavController(R.id.bottom_nav_host)
        val appBarConfiguration = AppBarConfiguration(navHost.graph)
        toolbar.setupWithNavController(navHost, appBarConfiguration)

        navHost.addOnDestinationChangedListener{_, currFrag: NavDestination, _ ->
            isParent = when (currFrag.id) {
                R.id.home_fragment -> true
                else -> false
            }

            setDisplayHomeAsUpEnabled(!isParent)

        }

        registerReceivers()

    }

    private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                INSTALL_COMPLETED -> launchVanced()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    }

    override fun onPause() {
        super.onPause()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    }

    override fun onResume() {
        super.onResume()
        registerReceivers()
    }

    private fun registerReceivers() {
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_COMPLETED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_ABORTED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_BLOCKED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_STORAGE
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_CONFLICT
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_FAILED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_INVALID
        ))

    }

    companion object {
        const val INSTALL_COMPLETED = "Installation completed"
        const val INSTALL_ABORTED = "user aborted installation"
        const val INSTALL_BLOCKED = "user blocked installation"
        const val INSTALL_STORAGE = "there was an error with storage.\n Hold up how is that even possible?"
        const val INSTALL_CONFLICT = "app conflicts with already installed app"
        const val INSTALL_FAILED = "it just failed idk"
        const val INSTALL_INVALID = "apk files are invalid"

    }
}
</code>```

Any recommendations? Thanks in advance

答:
Fixed by using

```<code>private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when {
            inten.action.equals(INSTALL_COMPLETED) -> launchVanced()
        }
    }
}
</code>```

Instead of

```<code>private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            INSTALL_COMPLETED -> launchVanced()
        }
    }
}
</code>```

Body:
I have a simple service which runs package installer session and I want to get status from it. Package manager has different statuses and depending what status I receive, I want my activity to create a dialog but I encountered a problem.
InstallerService.kt:

class InstallerService: Service() {

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999)) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                Toast.makeText(this, "Installing...", Toast.LENGTH_SHORT).show()
                Log.d(TAG, "Requesting user confirmation for installation")
                val confirmationIntent =
                    intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
                confirmationIntent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                try {
                    startActivity(confirmationIntent)
                } catch (e: Exception) {
                }
            }
            PackageInstaller.STATUS_SUCCESS -> {
                Log.d(TAG, "Installation succeed")
                getSharedPreferences("installPrefs", Context.MODE_PRIVATE).edit().putBoolean("isInstalling", false).apply()
                val mIntent = Intent(MainActivity.INSTALL_COMPLETED)
                mIntent.action = MainActivity.INSTALL_COMPLETED
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_ABORTED -> {
                val mIntent = Intent(MainActivity.INSTALL_ABORTED)
                mIntent.action = MainActivity.INSTALL_ABORTED
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_INVALID -> {
                val mIntent = Intent(MainActivity.INSTALL_INVALID)
                mIntent.action = MainActivity.INSTALL_INVALID
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_CONFLICT -> {
                val mIntent = Intent(MainActivity.INSTALL_CONFLICT)
                mIntent.action = MainActivity.INSTALL_CONFLICT
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_STORAGE -> {
                val mIntent = Intent(MainActivity.INSTALL_STORAGE)
                mIntent.action = MainActivity.INSTALL_STORAGE
                LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent)
            }
            PackageInstaller.STATUS_FAILURE_BLOCKED -> {
                val mIntent = Intent(MainActivity.INSTALL_BLOCKED)
                mIntent.action = MainActivity.INSTALL_BLOCKED
                sendBroadcast(mIntent)
            }
            else -> {
                Log.d(TAG, "Installation failed")
                val mIntent = Intent(MainActivity.INSTALL_FAILED)
                mIntent.action = MainActivity.INSTALL_ABORTED
                sendBroadcast(mIntent)
            }
        }
        stopSelf()
        return START_NOT_STICKY
    }

    @Nullable
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    companion object{
        const val TAG = "VMInstall"
    }

}

Now when k try to receive intent action, it does not do anything at all
MainActivity.kt:

class MainActivity : Main() {

    private var isParent = true

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.home_toolbar)
        setSupportActionBar(toolbar)

        val navHost = findNavController(R.id.bottom_nav_host)
        val appBarConfiguration = AppBarConfiguration(navHost.graph)
        toolbar.setupWithNavController(navHost, appBarConfiguration)

        navHost.addOnDestinationChangedListener{_, currFrag: NavDestination, _ ->
            isParent = when (currFrag.id) {
                R.id.home_fragment -> true
                else -> false
            }

            setDisplayHomeAsUpEnabled(!isParent)

        }

        registerReceivers()

    }

    private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                INSTALL_COMPLETED -> launchVanced()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    }

    override fun onPause() {
        super.onPause()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    }

    override fun onResume() {
        super.onResume()
        registerReceivers()
    }

    private fun registerReceivers() {
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_COMPLETED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_ABORTED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_BLOCKED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_STORAGE
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_CONFLICT
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_FAILED
        ))
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(
            INSTALL_INVALID
        ))

    }

    companion object {
        const val INSTALL_COMPLETED = "Installation completed"
        const val INSTALL_ABORTED = "user aborted installation"
        const val INSTALL_BLOCKED = "user blocked installation"
        const val INSTALL_STORAGE = "there was an error with storage.\n Hold up how is that even possible?"
        const val INSTALL_CONFLICT = "app conflicts with already installed app"
        const val INSTALL_FAILED = "it just failed idk"
        const val INSTALL_INVALID = "apk files are invalid"

    }
}

Any recommendations? Thanks in advance

Body:
Fixed by using

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when {
            inten.action.equals(INSTALL_COMPLETED) -> launchVanced()
        }
    }
}

Instead of

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            INSTALL_COMPLETED -> launchVanced()
        }
    }
}


问:
Accessing outer loop variable from inside loop in Java
My list consist of list character definition like List<Character> listCharacter = new ArrayList<Character>();

Character class:

```<code>private List<Result> results;
</code>```

Result Class :

```<code> private int id;

 private String name;
</code>```

I am trying to iterate over listCharacter like

```<code>listCharacter.forEach((characters) -> {

            characters.getResults().forEach((result) -> {

                if (result.getId() == id) {
                    return result;
                }

            });
        });
</code>```

But when am trying this i got foreach not applicable the type Iterable is not applicable for the arguments (( result) -> {}) error . I know chain loop not possible with foreach loop.

Also i know we can use consumers like duplicate question solutions.But then  i can't reach outer loop variable inside inner loop.The Consumer classes just using it and disposing it.Therefore I don't wanna use that.

How can i do this i mean reaching outer loop variable inside inner loop without dealing with this such errors?

TLDR: I have 2 list objects. I am iterating over outer one(listCharacter) that who has inner one list object(result) which has id and name.If the id matched the method would return.That's all.

答:
"results" is not a list or any other iterator, it's just a single object of type "Result". Thus, you can not iterate over it at all. Make sure getResults() actually returns a list, rather than a single object, and then you can iterate over it.

(Also note that forEach() is not actually a loop. It's a function call with a lambda function as a parameter. And as mentioned before, you can not use forEach() to collect some kind of result from the lambda function, you'll have to use map() for that.)

Body:
My list consist of list character definition like List<Character> listCharacter = new ArrayList<Character>();

Character class:

private List<Result> results;

Result Class :

 private int id;

 private String name;

I am trying to iterate over listCharacter like

listCharacter.forEach((characters) -> {

            characters.getResults().forEach((result) -> {

                if (result.getId() == id) {
                    return result;
                }

            });
        });

But when am trying this i got foreach not applicable the type Iterable is not applicable for the arguments (( result) -> {}) error . I know chain loop not possible with foreach loop.

Also i know we can use consumers like duplicate question solutions.But then  i can't reach outer loop variable inside inner loop.The Consumer classes just using it and disposing it.Therefore I don't wanna use that.

How can i do this i mean reaching outer loop variable inside inner loop without dealing with this such errors?

TLDR: I have 2 list objects. I am iterating over outer one(listCharacter) that who has inner one list object(result) which has id and name.If the id matched the method would return.That's all.


问:
Best option for modal screens in ASP.NET
I'm looking for the best way to implement a modal popup in ASP.NET of another ASP.NET page. I'm coding for Firefox 2.x+ and can use JQuery, but I'm not very familiar with it.

I see a lot of solutions that use "AJAX", but I'm not sure in what context, so I haven't gone down that route.

答:
For simple modal displays, I've found BlockUI to be a great solution.

For example, here's a post about using BlockUI as a modal progress indicator, and here's one about using BlockUI to display a modal confirmation dialog.

If you need something more complex, I'd second the jQueryUI Dialog.

OwnerDisplayName: Caveatrob

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mausch

OwnerDisplayName: Dave Ward


问:
Exporting charts as Image sometimes generates empty files
I'm doing a macro that exports all the charts in the sheet and then opens Outlook and attaches them. However, I've noticed, several times the charts do export but as 0KB (the file is created, but the image can't be seen)

But it doesn't happen to all the charts. Just most of them and sometimes, it generates them all without a problem. (When I execute the code step by step, all charts generate without a problem, also after executing the step by step, then I execute it normally and all charts generate, BUT if I close and reopen the workbook, it gives the same issue, generates only two and the rest are empty files)

Here's the code:

```<code>Dim sheetNumber, Size, i As Integer
    Dim chartNames(), FNames() As String
    Dim objChrt As ChartObject
    Dim myChart As Chart

    'Activate Charts Sheet
    Sheets("GRAFICAS").Activate
    'Calculate Number of Charts in Sheet
    Dim chartNumber
    chartNumber = ActiveSheet.ChartObjects.Count
    'Redimension Arrays to fit all Chart Export Names
    ReDim chartNames(chartNumber)
    ReDim FNames(chartNumber)
    'Loops through all the charts in the GRAFICAS sheet
    For i = 1 To chartNumber
        'Select chart with index i
        Set objChrt = ActiveSheet.ChartObjects(i)
        Set myChart = objChrt.Chart
        'Generate a name for the chart
        chartNames(i) = "myChart" & i & ".png"

        On Error Resume Next
        Kill ThisWorkbook.Path & "\" & chartNames(i)
        On Error GoTo 0
        'Export Chart
        myChart.Export FileName:=Environ$("TEMP") & "\" & chartNames(i), Filtername:="PNG"
        'Save path to exported chart
        FNames(i) = Environ$("TEMP") & "\" & chartNames(i)
    Next i
</code>```

What am I missing?

答: After a bit of head scratching, it appears that a Chart to be exported needs to be within the visible area of the sheet on which it is embedded. The sheet does not need to be visible, but the chart needs to be within the area that would be visible if the sheet on which the chart is embedded were the ActiveSheet.  Otherwise empty files are written.</p>

Body:
I'm doing a macro that exports all the charts in the sheet and then opens Outlook and attaches them. However, I've noticed, several times the charts do export but as 0KB (the file is created, but the image can't be seen)

But it doesn't happen to all the charts. Just most of them and sometimes, it generates them all without a problem. (When I execute the code step by step, all charts generate without a problem, also after executing the step by step, then I execute it normally and all charts generate, BUT if I close and reopen the workbook, it gives the same issue, generates only two and the rest are empty files)

Here's the code:

Dim sheetNumber, Size, i As Integer
    Dim chartNames(), FNames() As String
    Dim objChrt As ChartObject
    Dim myChart As Chart

    'Activate Charts Sheet
    Sheets("GRAFICAS").Activate
    'Calculate Number of Charts in Sheet
    Dim chartNumber
    chartNumber = ActiveSheet.ChartObjects.Count
    'Redimension Arrays to fit all Chart Export Names
    ReDim chartNames(chartNumber)
    ReDim FNames(chartNumber)
    'Loops through all the charts in the GRAFICAS sheet
    For i = 1 To chartNumber
        'Select chart with index i
        Set objChrt = ActiveSheet.ChartObjects(i)
        Set myChart = objChrt.Chart
        'Generate a name for the chart
        chartNames(i) = "myChart" & i & ".png"

        On Error Resume Next
        Kill ThisWorkbook.Path & "\" & chartNames(i)
        On Error GoTo 0
        'Export Chart
        myChart.Export FileName:=Environ$("TEMP") & "\" & chartNames(i), Filtername:="PNG"
        'Save path to exported chart
        FNames(i) = Environ$("TEMP") & "\" & chartNames(i)
    Next i

What am I missing?


问:
Converting a string date to useful date
I'm pretty new to programming and I'm working with a database that has a date field. All the data in the field are saved as strings on the yyyymmdd format. I want to convert those to something friendlier to display to the user. I created the following struct and function to do it. It works, but I was wondering if there are any simpler ideas.

```<code>struct MyDate {
   var day: String
   var month: String
   var year: String
}

func ConvertToUsefullDate (_ date: String) -> MyDate {
    var myDate: MyDate = .init(day: "", month: "", year: "")

    myDate.year =
    String(date[date.index(date.startIndex, offsetBy: 0)]) +
    String(date[date.index(date.startIndex, offsetBy: 1)]) +
    String(date[date.index(date.startIndex, offsetBy: 2)]) +
    String(date[date.index(date.startIndex, offsetBy: 3)])

myDate.month =
    String(date[date.index(date.startIndex, offsetBy: 4)]) +
    String(date[date.index(date.startIndex, offsetBy: 5)])

myDate.day =
    String(date[date.index(date.startIndex, offsetBy: 6)]) +
    String(date[date.index(date.startIndex, offsetBy: 7)])

switch myDate.month {
    case "01": myDate.month = "Jan"
    case "02": myDate.month = "Feb"
    case "03": myDate.month = "Mar"
    case "04": myDate.month = "Apr"
    case "05": myDate.month = "May"
    case "06": myDate.month = "Jun"
    case "07": myDate.month = "Jul"
    case "08": myDate.month = "Aug"
    case "09": myDate.month = "Sep"
    case "10": myDate.month = "Oct"
    case "11": myDate.month = "Nov"
    case "12": myDate.month = "Dec"
    default: myDate.month = "Invalid"
}

return myDate
</code>```

}

Thank you  --  all feedback is welcome.

Daniel

答:
There's an existing type Date that you should probably use instead of your own type.

To create a Date object from a formatted string, use the DateFormatter:

```<code>let inputDateString = "20200428"

let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyyMMdd"
inputFormatter.locale = Locale(identifier: "en_US_POSIX")

// date is optional
let date = inputFormatter.date(from: inputDateString)
</code>```

Once you have a Date object, you could output it in whatever format you'd like:

```<code>let outputFormatter = DateFormatter()

// 28 April, 2020
outputFormatter.dateFormat = "dd MMMM, yyyy"
</code>```

Or, better, use the locale-aware way:

```<code>let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .long
outputFormatter.timeStyle = .none
</code>```

Then you can convert it to a String:

```<code>let outputDateString = outputFormatter.string(from: date!) // ! for simplicity

print(outputDateString)
</code>```

Title: Converting a string date to useful date

Body:
I'm pretty new to programming and I'm working with a database that has a date field. All the data in the field are saved as strings on the yyyymmdd format. I want to convert those to something friendlier to display to the user. I created the following struct and function to do it. It works, but I was wondering if there are any simpler ideas.

struct MyDate {
   var day: String
   var month: String
   var year: String
}

func ConvertToUsefullDate (_ date: String) -> MyDate {
    var myDate: MyDate = .init(day: "", month: "", year: "")

    myDate.year =
    String(date[date.index(date.startIndex, offsetBy: 0)]) +
    String(date[date.index(date.startIndex, offsetBy: 1)]) +
    String(date[date.index(date.startIndex, offsetBy: 2)]) +
    String(date[date.index(date.startIndex, offsetBy: 3)])

myDate.month =
    String(date[date.index(date.startIndex, offsetBy: 4)]) +
    String(date[date.index(date.startIndex, offsetBy: 5)])

myDate.day =
    String(date[date.index(date.startIndex, offsetBy: 6)]) +
    String(date[date.index(date.startIndex, offsetBy: 7)])

switch myDate.month {
    case "01": myDate.month = "Jan"
    case "02": myDate.month = "Feb"
    case "03": myDate.month = "Mar"
    case "04": myDate.month = "Apr"
    case "05": myDate.month = "May"
    case "06": myDate.month = "Jun"
    case "07": myDate.month = "Jul"
    case "08": myDate.month = "Aug"
    case "09": myDate.month = "Sep"
    case "10": myDate.month = "Oct"
    case "11": myDate.month = "Nov"
    case "12": myDate.month = "Dec"
    default: myDate.month = "Invalid"
}

return myDate

}

Thank you  --  all feedback is welcome.

Daniel

Body:
There's an existing type Date that you should probably use instead of your own type.

To create a Date object from a formatted string, use the DateFormatter:

let inputDateString = "20200428"

let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyyMMdd"
inputFormatter.locale = Locale(identifier: "en_US_POSIX")

// date is optional
let date = inputFormatter.date(from: inputDateString)

Once you have a Date object, you could output it in whatever format you'd like:

let outputFormatter = DateFormatter()

// 28 April, 2020
outputFormatter.dateFormat = "dd MMMM, yyyy"

Or, better, use the locale-aware way:

let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .long
outputFormatter.timeStyle = .none

Then you can convert it to a String:

let outputDateString = outputFormatter.string(from: date!) // ! for simplicity

print(outputDateString)


问:
Submitted a pull request, which was merged, now I need to update my fork
Here is what I did:

Forked a repo

Created new feature branch on my fork

Submitted PR to original repo master (accepted, merged)

Next How Do I:

Update "master" in my own fork?

答:
Below two commands will update your local master branch.

git checkout master

git pull


问:
Django database cache queryset methods
I have a database cache for my django application.

I can do the following to get multiple cache rows from the table:

```<code>cache.get_many(cache_keys_list)
</code>```

This is a sequential query retrieving one record at a time:

Is it possible to have a queryset method for a database cache like would for any other model object to retrieve multiple values?

答:
It seems you are using Django version prior to release of following optimization

You could update Django , use following function as snippet or create custom MyDatabaseCache from new code

current source is here

Title: Django database cache queryset methods

Body:
I have a database cache for my django application.

I can do the following to get multiple cache rows from the table:

cache.get_many(cache_keys_list)

This is a sequential query retrieving one record at a time:

Is it possible to have a queryset method for a database cache like would for any other model object to retrieve multiple values?


问:
Should Class Implement Both IAsyncDisposable and IDisposable?
For example I have this class:

```<code>public class UnitOfWork : IUnitOfWork
{
    private readonly ApplicationDbContext _context;

    public IProductRepository Products { get; private set; }
    public ICategoryRepository Categories { get; private set; }
    public IPhotoRepository Photos { get; private set; }

    public UnitOfWork(ApplicationDbContext context, IProductRepository productRepository,
        ICategoryRepository categoryRepository, IPhotoRepository photoRepository)
    {
        _context = context;
        Products = productRepository;
        Categories = categoryRepository;
        Photos = photoRepository;
    }

    public int Complete()
    {
        return _context.SaveChanges();
    }

    public Task<int> CompleteAsync()
    {
        return _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }

    public async ValueTask DisposeAsync()
    {
        await _context.DisposeAsync();
    }
}
</code>```

With a such Interface:

```<code>public interface IUnitOfWork : IDisposable, IAsyncDisposable
{
    IProductRepository Products { get; }
    ICategoryRepository Categories { get; }
    IPhotoRepository Photos { get; }
    int Complete();
    Task<int> CompleteAsync();
}
</code>```

Is it right to have both Async and Sync methods? Also what method will be called during disposal if I'm using DI in asp net core for example.

答:
Regardless of your AspNetCore concern;
yes, it is perfectly ok to have both Sync and Async methods implemented in one class.

But, having interface chains (one interface mandates to implement another one) is considered as not clean-code.

see this

Body:
For example I have this class:

public class UnitOfWork : IUnitOfWork
{
    private readonly ApplicationDbContext _context;

    public IProductRepository Products { get; private set; }
    public ICategoryRepository Categories { get; private set; }
    public IPhotoRepository Photos { get; private set; }

    public UnitOfWork(ApplicationDbContext context, IProductRepository productRepository,
        ICategoryRepository categoryRepository, IPhotoRepository photoRepository)
    {
        _context = context;
        Products = productRepository;
        Categories = categoryRepository;
        Photos = photoRepository;
    }

    public int Complete()
    {
        return _context.SaveChanges();
    }

    public Task<int> CompleteAsync()
    {
        return _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }

    public async ValueTask DisposeAsync()
    {
        await _context.DisposeAsync();
    }
}

With a such Interface:

public interface IUnitOfWork : IDisposable, IAsyncDisposable
{
    IProductRepository Products { get; }
    ICategoryRepository Categories { get; }
    IPhotoRepository Photos { get; }
    int Complete();
    Task<int> CompleteAsync();
}

Is it right to have both Async and Sync methods? Also what method will be called during disposal if I'm using DI in asp net core for example.


问:
Remove list from inside another list
I would like to remove a list from inside another list. I have a list which looks like this:
[[1, 2, 3, 4, 5, 6]]

I would like the list to look like this, so it is only a singular list rather than nested:
[1, 2, 3, 4, 5, 6]

答:
To achieve the desired result, you can just access the zero index from original list.</p>

```<code>a = [[1, 2, 3, 4, 5, 6]]
>>> b = a[0]
>>> b
// [1, 2, 3, 4, 5, 6]
</code>```

Title: Remove list from inside another list

Body:
To achieve the desired result, you can just access the zero index from original list.

a = [[1, 2, 3, 4, 5, 6]]
>>> b = a[0]
>>> b
// [1, 2, 3, 4, 5, 6]


问:
Laravel + Vue + Axios issue with POST method
I am working on a Laravel 5.6 project which is stored on a VPS (we call it "production", despite there is no such created environment).

We also combined Plesk & Github to deploy the web app from our local environments to the server manually.

The issue is when I load some data from the APIs they return error 405 Method not allowed (GET)... but they actually are registered as POST in the app.js and in routes/api.php.

And the best thing is that in my local environment they work perfectly.

Here some information:

The server:

Ubuntu Server 14.04

Apache / MySQL

PHP 7.2.5

My computer:

Windows 10 with XAMPP

Apache / MySQL

PHP 7.2.2

The Developer tool in every browser:

Request Method: GET

Status Code: 405 Method Not Allowed

And here is the code within the app.js:

```<code>loadCountries: function loadCountries(total) {
    axios.post('/api/properties/countries/').then(function (response) {
        app.countries = response.data;
    });

    total = total <= this.countries.length ? total : this.countries.length;

    if (total) {
        var newArr = [];
        for (i = 0; i < total; i++) {
            newArr.push(this.countries[i]);
        }
        this.countries = newArr;
    }
},
</code>```

Note: If I edit the same request in the developer tool and send it again but as a POST request it returns me everything ok, so the API seems to work fine on POST request.

答:
i faced this issue and i solve it by make computed attribute with full url like that

```<code>computed: {
    sendAnswersUrl: function () {
        return window.location.protocol + "//" + window.location.hostname, +  "/api/properties/countries";
     }
  }
</code>```

then when post using axios

```<code>axios.post(this.sendAnswersUrl, {
          group: this.id,
        })
        .then(data => {})
        .catch(() => {});
</code>```

Body:
I am working on a Laravel 5.6 project which is stored on a VPS (we call it "production", despite there is no such created environment).

We also combined Plesk & Github to deploy the web app from our local environments to the server manually.

The issue is when I load some data from the APIs they return error 405 Method not allowed (GET)... but they actually are registered as POST in the app.js and in routes/api.php.

And the best thing is that in my local environment they work perfectly.

Here some information:

The server:

Ubuntu Server 14.04

Apache / MySQL

PHP 7.2.5

My computer:

Windows 10 with XAMPP

Apache / MySQL

PHP 7.2.2

The Developer tool in every browser:

Request Method: GET

Status Code: 405 Method Not Allowed

And here is the code within the app.js:

loadCountries: function loadCountries(total) {
    axios.post('/api/properties/countries/').then(function (response) {
        app.countries = response.data;
    });

    total = total <= this.countries.length ? total : this.countries.length;

    if (total) {
        var newArr = [];
        for (i = 0; i < total; i++) {
            newArr.push(this.countries[i]);
        }
        this.countries = newArr;
    }
},

Note: If I edit the same request in the developer tool and send it again but as a POST request it returns me everything ok, so the API seems to work fine on POST request.

Body:
i faced this issue and i solve it by make computed attribute with full url like that

computed: {
    sendAnswersUrl: function () {
        return window.location.protocol + "//" + window.location.hostname, +  "/api/properties/countries";
     }
  }

then when post using axios

axios.post(this.sendAnswersUrl, {
          group: this.id,
        })
        .then(data => {})
        .catch(() => {});


答:
If your list is :

```<code>lst = [[1,2,3,4,5,6]]
</code>```

then you can do like this

```<code>new_lst = lst[0]
</code>```

You new_lst would be :

[1,2,3,4,5,6]

If your original lst has many lists inside it like :

```<code>lst = [[1,2,3,4,5,6],[7,8,9,10],...]
</code>```

Then you can do the following :

```<code>new_lst = []
for i in lst :
    for j in i :
        new_lst.append(j)
</code>```

So your new_lst would be :

```<code>[1,2,3,4,5,6,7,8,9,10...]
</code>```

You could also do it in a shorthand notation as :

```<code>new_list = [element for sublist in lst for element in sublist]
</code>```

The above snippet is exactly similar as previous one, just a shorthand notation

Title: Remove list from inside another list

Body:
I would like to remove a list from inside another list. I have a list which looks like this:
[[1, 2, 3, 4, 5, 6]]

I would like the list to look like this, so it is only a singular list rather than nested:
[1, 2, 3, 4, 5, 6]

Body:
If your list is :

lst = [[1,2,3,4,5,6]]

then you can do like this

new_lst = lst[0]

You new_lst would be :

[1,2,3,4,5,6]

If your original lst has many lists inside it like :

lst = [[1,2,3,4,5,6],[7,8,9,10],...]

Then you can do the following :

new_lst = []
for i in lst :
    for j in i :
        new_lst.append(j)

So your new_lst would be :

[1,2,3,4,5,6,7,8,9,10...]

You could also do it in a shorthand notation as :

new_list = [element for sublist in lst for element in sublist]

The above snippet is exactly similar as previous one, just a shorthand notation


问:
How to stop console from repeating loop over and over?
I'm trying to make the incorrect password start the loop over until the right password is inputted (which it does) but System.out.println statements repeat infinitely in the console. A break statement just terminates the code, but I want it to keep going except only printing the statements once. Any solutions?</p>

```<code>    public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String pass = passwordScan.nextLine();
    String password = "JohnnyRoberts123";

    while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");

        continue;
</code>```

答:
I don't see any code that would get any input from the user. The while loop gets immediately reiterated when it hits continue.

You rather want something like:

```<code>java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");
        password = in.readLine();
        continue;
}

</code>```

Body:
I'm trying to make the incorrect password start the loop over until the right password is inputted (which it does) but System.out.println statements repeat infinitely in the console. A break statement just terminates the code, but I want it to keep going except only printing the statements once. Any solutions?

    public static void main(String[] args){

    System.out.println("What is the password?");

    Scanner passwordScan = new Scanner(System.in);
    String pass = passwordScan.nextLine();
    String password = "JohnnyRoberts123";

    while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");

        continue;

Body:
I don't see any code that would get any input from the user. The while loop gets immediately reiterated when it hits continue.

You rather want something like:

java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(password != pass) {
        System.out.println("Wrong password!");
        System.out.println("Try again, what is the password?");
        password = in.readLine();
        continue;
}


问:
Delete white space between divs
I'm getting some strange whitespace between two divs I have.

Each div has the css property display: inline-block and each have a set height and width.

I cannot find where the whitespace is.

Here is a Fiddle

答: best way is settings parent element's font-size to 0 then normal font-size to child elements inside that parent (otherwise inherits zero from parent)</p>

Title: Delete white space between divs


问:
Cannot Receive JSON Response from Postman using Laravel API
I receive this error when I try to login with wrong credentials :

```<code><!doctype html>
<html class="theme-light">
<!--
TypeError: Argument 2 passed to Symfony\Component\HttpFoundation\JsonResponse::__construct() must be of the type integer, array given, called in /home/stylmyvz/cars.styleshopeg.com/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php on line 31 in file /home/stylmyvz/cars.styleshopeg.com/vendor/symfony/http-foundation/JsonResponse.php on line 42

#0 /home/stylmyvz/cars.styleshopeg.com/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php(31): Symfony\Component\HttpFoundation\JsonResponse->__construct(Array, Array, Array)
#1 /home/stylmyvz/cars.styleshopeg.com/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php(99): Illuminate\Http\JsonResponse->__construct(Array, Array, Array, 0)
#2 /home/stylmyvz/cars.styleshopeg.com/app/Http/Controllers/APILoginController.php(31): Illuminate\Routing\ResponseFactory->json(Array, Array)
#3 [internal function]: App\Http\Controllers\APILoginController->login(Object(Illuminate\Http\Request)
I want to receive JSON response like this in Postman :
{
  "error":"invalid username or password"
}
</code>```

Here is Login Controller and I instruct it to give me "invalid username or password"

Can anyone tell me what is wrong with it

```<code>class APILoginController extends Controller
{
    //
    public function login(Request $request){
        $validator = Validator::make($request -> all(),[
            'email' => 'required|string|email|max:255',
            'password' =>'required'
        ]);

        if($validator->fails()){
            return response()->json($validator->errors());
        }

        $credentials = $request->only('email', 'password');
        try {
            if(! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error'=>'invalid username or password'], [401]);
            }
        } catch (JWTException $e) {
            //throw $th;
            return response()->json(['error'=>'could not create token'], [500]);
        }

        return response()->json(compact('token'));

    }
}
</code>```

Contents of api.php file:

```<code>Route::post('user/register','APIRegisterController@register');

Route::post('user/login','APILoginController@login');

Route::middleware('jwt.auth')->get('/users', function (Request $request) {
    return auth()->user();
});

Route::middleware('jwt.auth')->group( function(){
   Route::resource('/cars', 'API\CarController');
} );
</code>```

答:
Please Change this try & catch both..

```<code>try {
            if(! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error'=>'invalid username or password'], 401);
            }
        } catch (JWTException $e) {
            //throw $th;
            return response()->json(['error'=>'could not create token'], 500);
        }
</code>```

This is how I do it in Laravel....

```<code>return Response::json(['message' => $value,'other_info'=>$vlue2],201);
</code>```

Or using a helper function:

```<code>return response()->json(['message' => $value,'other_info'=>$vlue2], 201);
</code>```

Body:
I receive this error when I try to login with wrong credentials :

<!doctype html>

Body:
Please Change this try & catch both..

try {
            if(! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error'=>'invalid username or password'], 401);
            }
        } catch (JWTException $e) {
            //throw $th;
            return response()->json(['error'=>'could not create token'], 500);
        }

This is how I do it in Laravel....

return Response::json(['message' => $value,'other_info'=>$vlue2],201);

Or using a helper function:

return response()->json(['message' => $value,'other_info'=>$vlue2], 201);


问:
Call Rest API and handle response in existing Azure Logic App Flow
I have an existing Azure Logic App Flow, on a condition I want to call an API and want to return the response.
Note- not just have to call API, but handle the response and send it as a response from Logic App
Any help is appreciated.

答: Found solution, added Parse Json to parse response from request action


问:
Parse an XML object from a column into multiple rows and allow the next XML object after last row
This is a little hard to explain in words so I create an example spreadsheet to show you the issue:
https://docs.google.com/spreadsheets/d/1zqqVOWkp8dw87lhr05NSuiE9ezb84CFtQphwrpZxpes/

I have an export from a system with a list of XML files.
I need to parse each XML into rows and each row needs to have the ID of the project.

The issue is that when parsing the XML, it can have up to 12 rows in it. Sometimes it will only have 1, sometime it will have 12 or anything in between.

I need this to work based on a formula that will account for the dynamic number of rows per XML file.
It sounds like I need to count the rows needed for each xml and then adjust where the second XML file starts in a secondary list.

The XML and the Project ID is the information that's known from the start.

答:
If what you are looking for is the number of activities in each project then

```<code>=importxml($j$3,"count(//ActivityDetails)")
</code>```

would output 3 for the url in that cell in your sheet, and that's the number of rows you need for that entry.

Body:
If what you are looking for is the number of activities in each project then

=importxml($j$3,"count(//ActivityDetails)")

would output 3 for the url in that cell in your sheet, and that's the number of rows you need for that entry.