问:
HAL_UART_Transmit sends wrong data
When ch = 0x80, on PC I receive 0x00,

When ch = 0x40, on PC I receive 0x80,

When ch = 0x20, on PC I receive 0x60,

When ch = 0x10, on PC I receive 0x10,

When ch = 0x08, on PC I receive 0x08,

When ch = 0x04, on PC I receive 0x04,

When ch = 0x02, on PC I receive 0x02,

When ch = 0x01, on PC I receive 0x01,

Can't figure what is going on here... I am attaching USART Initialization, Transmit Function and Main. I should be software issue, already tested the hardware and it's ok. MCU = STM32L011

```<code>void InitUSART(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    USARTx_CLK_ENABLE();

    UartHandle.Instance = USARTx;
    UartHandle.Init.BaudRate = 9600;
    UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits = UART_STOPBITS_1;
    UartHandle.Init.Parity = UART_PARITY_NONE;
    UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode = UART_MODE_TX_RX;
    //UartHandle.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_ENABLE;
    HAL_UART_Init(&UartHandle);

    /* Transmit Configuration */
    USARTx_TX_GPIO_CLK_ENABLE();
    GPIO_InitStruct.Pin = USARTx_TX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = USARTx_TX_AF;
    HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct);

    /* Receive Configuration */
    USARTx_RX_GPIO_CLK_ENABLE();
    GPIO_InitStruct.Pin = USARTx_RX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = USARTx_TX_AF;
    HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct);

    HAL_NVIC_SetPriority(USARTx_IRQn, 0, 1);
    HAL_NVIC_EnableIRQ(USARTx_IRQn);
}

HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
  uint16_t* tmp;
  uint32_t tickstart = 0;

  /* Check that a Tx process is not already ongoing */
  if(huart->gState == HAL_UART_STATE_READY)
  {
    if((pData == NULL ) || (Size == 0U))
    {
      return  HAL_ERROR;
    }

    /* In case of 9bits/No Parity transfer, pData buffer provided as input paramter
       should be aligned on a u16 frontier, as data to be filled into TDR will be
       handled through a u16 cast. */
    if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE))
    {
      if((((uint32_t)pData)&1) != 0)
      {
        return  HAL_ERROR;
      }
    }

    /* Process Locked */
    __HAL_LOCK(huart);

    huart->ErrorCode = HAL_UART_ERROR_NONE;
    huart->gState = HAL_UART_STATE_BUSY_TX;

    /* Init tickstart for timeout managment*/
    tickstart = HAL_GetTick();

    huart->TxXferSize = Size;
    huart->TxXferCount = Size;
    while(huart->TxXferCount > 0U)
    {
      huart->TxXferCount--;
      if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
      {
        return HAL_TIMEOUT;
      }
      if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE))
      {
        tmp = (uint16_t*) pData;
        huart->Instance->TDR = (*tmp & (uint16_t)0x01FFU);
        pData += 2U;
      }
      else
      {
        huart->Instance->TDR = (*pData++ & (uint8_t)0xFFU);
      }
    }
    if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK)
    {
      return HAL_TIMEOUT;
    }

    /* At end of Tx process, restore huart->gState to Ready */
    huart->gState = HAL_UART_STATE_READY;

    /* Process Unlocked */
    __HAL_UNLOCK(huart);

    return HAL_OK;
  }
  else
  {
    return HAL_BUSY;
  }
}

int main(void)
{
  /* STM32L0xx HAL library initialization:
       - Configure the Flash prefetch, Flash preread and Buffer caches
       - Systick timer is configured by default as source of time base, but user
             can eventually implement his proper time base source (a general purpose
             timer for example or other time source), keeping in mind that Time base
             duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
             handled in milliseconds basis.
       - Low Level Initialization
     */
    HAL_Init();

    /* Configure the system clock to 32 MHz */
    SystemClock_Config();

    InitUSART();
    //Transmit(txBuffer, 2);

    extern UART_HandleTypeDef UartHandle;
    uint16_t ch = 0x80;
    TransmitEnable();
    while(1){
        HAL_UART_Transmit(&UartHandle, &ch, 1, 0xFF);
        HAL_Delay(5);
    }
}
</code>```

答: Acording your sent source file, you programmed the usart as "8 bits", but this STM HAL routine compute data_bits+parity_bit=8bits(your selection). For standard text transmission, for this STM HAL should be: 9 bits (8_data_bits+one_parity_bit). </p>

Title: HAL_UART_Transmit sends wrong data

Body:
When ch = 0x80, on PC I receive 0x00,

When ch = 0x40, on PC I receive 0x80,

When ch = 0x20, on PC I receive 0x60,

When ch = 0x10, on PC I receive 0x10,

When ch = 0x08, on PC I receive 0x08,

When ch = 0x04, on PC I receive 0x04,

When ch = 0x02, on PC I receive 0x02,

When ch = 0x01, on PC I receive 0x01,

Can't figure what is going on here... I am attaching USART Initialization, Transmit Function and Main. I should be software issue, already tested the hardware and it's ok. MCU = STM32L011

void InitUSART(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    USARTx_CLK_ENABLE();

    UartHandle.Instance = USARTx;
    UartHandle.Init.BaudRate = 9600;
    UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits = UART_STOPBITS_1;
    UartHandle.Init.Parity = UART_PARITY_NONE;
    UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode = UART_MODE_TX_RX;
    //UartHandle.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_ENABLE;
    HAL_UART_Init(&UartHandle);

    /* Transmit Configuration */
    USARTx_TX_GPIO_CLK_ENABLE();
    GPIO_InitStruct.Pin = USARTx_TX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = USARTx_TX_AF;
    HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct);

    /* Receive Configuration */
    USARTx_RX_GPIO_CLK_ENABLE();
    GPIO_InitStruct.Pin = USARTx_RX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = USARTx_TX_AF;
    HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct);

    HAL_NVIC_SetPriority(USARTx_IRQn, 0, 1);
    HAL_NVIC_EnableIRQ(USARTx_IRQn);
}

HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
  uint16_t* tmp;
  uint32_t tickstart = 0;

  /* Check that a Tx process is not already ongoing */
  if(huart->gState == HAL_UART_STATE_READY)
  {
    if((pData == NULL ) || (Size == 0U))
    {
      return  HAL_ERROR;
    }

    /* In case of 9bits/No Parity transfer, pData buffer provided as input paramter
       should be aligned on a u16 frontier, as data to be filled into TDR will be
       handled through a u16 cast. */
    if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE))
    {
      if((((uint32_t)pData)&1) != 0)
      {
        return  HAL_ERROR;
      }
    }

    /* Process Locked */
    __HAL_LOCK(huart);

    huart->ErrorCode = HAL_UART_ERROR_NONE;
    huart->gState = HAL_UART_STATE_BUSY_TX;

    /* Init tickstart for timeout managment*/
    tickstart = HAL_GetTick();

    huart->TxXferSize = Size;
    huart->TxXferCount = Size;
    while(huart->TxXferCount > 0U)
    {
      huart->TxXferCount--;
      if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
      {
        return HAL_TIMEOUT;
      }
      if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE))
      {
        tmp = (uint16_t*) pData;
        huart->Instance->TDR = (*tmp & (uint16_t)0x01FFU);
        pData += 2U;
      }
      else
      {
        huart->Instance->TDR = (*pData++ & (uint8_t)0xFFU);
      }
    }
    if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK)
    {
      return HAL_TIMEOUT;
    }

    /* At end of Tx process, restore huart->gState to Ready */
    huart->gState = HAL_UART_STATE_READY;

    /* Process Unlocked */
    __HAL_UNLOCK(huart);

    return HAL_OK;
  }
  else
  {
    return HAL_BUSY;
  }
}

int main(void)
{
  /* STM32L0xx HAL library initialization:
       - Configure the Flash prefetch, Flash preread and Buffer caches
       - Systick timer is configured by default as source of time base, but user
             can eventually implement his proper time base source (a general purpose
             timer for example or other time source), keeping in mind that Time base
             duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
             handled in milliseconds basis.
       - Low Level Initialization
     */
    HAL_Init();

    /* Configure the system clock to 32 MHz */
    SystemClock_Config();

    InitUSART();
    //Transmit(txBuffer, 2);

    extern UART_HandleTypeDef UartHandle;
    uint16_t ch = 0x80;
    TransmitEnable();
    while(1){
        HAL_UART_Transmit(&UartHandle, &ch, 1, 0xFF);
        HAL_Delay(5);
    }
}


来源: stackexchange

问:
Javascript modified array before group by
i am trying to modified array before groupBy

i have this array

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

答:
It looks like you want to build a new array based on the contents of an existing one. For this, I would turn to Array.reduce(). For example:</p>

```<code>const input = [
  {
    name: 'BoxOne',
    count: 3
  },
  {
    name: 'BoxTwo',
    count: 2
  },
];

const output = input.reduce((boxes, box) => {
  const { count = 0 } = box;

  for (let i = 0; i < count; i++) {
    boxes.push(box);
  }

  return boxes;
}, []);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i am trying to modified array before groupBy

i have this array

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

Body:
It looks like you want to build a new array based on the contents of an existing one. For this, I would turn to Array.reduce(). For example:

const input = [
  {
    name: 'BoxOne',
    count: 3
  },
  {
    name: 'BoxTwo',
    count: 2
  },
];

const output = input.reduce((boxes, box) => {
  const { count = 0 } = box;

  for (let i = 0; i < count; i++) {
    boxes.push(box);
  }

  return boxes;
}, []);


问:
How do you use reduce(into:) in swift
I am reading iOS 13 Programming Fundamentals with Swift, got to the part about reduce() and I think I understand it more or less, but then there is reduce(into:) and this piece of code:

```<code>let nums = [1,2,3,4,5]
let result = nums.reduce(into: [[],[]]) { temp, i in
    temp[i%2].append(i)
}
// result is now [[2,4],[1,3,5]]
</code>```

So this code takes an array of Int and splits it into 2 arrays, even and odd. The problem is that I have no idea what's happening inside the brackets {}.

In the case of reduce, the first parameter is the first one of the iteration and then the closure is supposed to process all the items one after the other, similar to map() but more powerful (here one loop is enough to get the two arrays but with map() I would need 2 loops, according to the book).

I cannot understand the syntax here anyway, especially what does "temp" stand for and that use of "in". And how is "append()" appending the value to the proper array??

答:
Inside the closure, "temp" is the result format which is [[][]] and "i" is each number. As you said it processes all numbers in a loop. When % is used it returns the division remainder, so for the odd numbers like "1,3,5", it returns "1" and for the even numbers "0", which means that "temp" appends these values to the array in these respective indexes.

So if we debug and replace the variables for constants the results would be:

```<code>temp[1].append(1) //1%2 = 1/2 left 1 [[][1]]
temp[0].append(2) //2%2 = 2/2 left 0 [[2][1]]
temp[1].append(3) //3%2 = 3/2 = 1 left 1 [[2][1,3]]
temp[0].append(4) //4%2 = 4/2 left 0 [[2,4][1,3]]
temp[1].append(5) //5%2 = 5/2 = 2 left 1 [[2,4][1,3,5]]
</code>```

According to the documentation the closure is called sequentially with a mutable accumulating value initialized that when exhausted, is returned to the caller.

Title: How do you use reduce(into:) in swift

Body:
I am reading iOS 13 Programming Fundamentals with Swift, got to the part about reduce() and I think I understand it more or less, but then there is reduce(into:) and this piece of code:

let nums = [1,2,3,4,5]
let result = nums.reduce(into: [[],[]]) { temp, i in
    temp[i%2].append(i)
}
// result is now [[2,4],[1,3,5]]

So this code takes an array of Int and splits it into 2 arrays, even and odd. The problem is that I have no idea what's happening inside the brackets {}.

In the case of reduce, the first parameter is the first one of the iteration and then the closure is supposed to process all the items one after the other, similar to map() but more powerful (here one loop is enough to get the two arrays but with map() I would need 2 loops, according to the book).

I cannot understand the syntax here anyway, especially what does "temp" stand for and that use of "in". And how is "append()" appending the value to the proper array??

Body:
Inside the closure, "temp" is the result format which is [[][]] and "i" is each number. As you said it processes all numbers in a loop. When % is used it returns the division remainder, so for the odd numbers like "1,3,5", it returns "1" and for the even numbers "0", which means that "temp" appends these values to the array in these respective indexes.

So if we debug and replace the variables for constants the results would be:

temp[1].append(1) //1%2 = 1/2 left 1 [[][1]]
temp[0].append(2) //2%2 = 2/2 left 0 [[2][1]]
temp[1].append(3) //3%2 = 3/2 = 1 left 1 [[2][1,3]]
temp[0].append(4) //4%2 = 4/2 left 0 [[2,4][1,3]]
temp[1].append(5) //5%2 = 5/2 = 2 left 1 [[2,4][1,3,5]]

According to the documentation the closure is called sequentially with a mutable accumulating value initialized that when exhausted, is returned to the caller.


问:
List of increasing lists
Given integers n >= m, I want to build the list of all increasing lists of length m with elements the set {1,...,n}.

For instance, if n= 4 and m=2, I want
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].

Is there a nice way to do that with very few lines of Python code?

I would like to build an efficient function

```<code>def listOfLists(n, m):
    ????
    return ? # the list of all increasing lists of m elements in {1, 2, ..., n}
</code>```

Thanks!

Remark: I have basically done this, but my code is ridiculously long https://sagecell.sagemath.org/?z=eJxVkcFuwyAQRO98xR5Bdqo66ikq-YJIvfRm5eDIuF2ZbBB21H5-FpYWh4PFmHmzHjy6Ccj9rp_34J2eWyBzUMArvQQLc384Zx1YeEd6NlkiywA76LL6-Ubv2ItnsJbPGiA-C5Ik9p0t3hScjI19ghHeJbBC4mw6Dq1UgST0PyO69R4pu5QauZPHZf2YTvxcNLUQSiuceMgRqA4pZC8tZx7Vv8p-ukUegQRxoC-nu5qSnS9DCI5GjXIhl2HBJdEVjk_wBel2xcHL56Qim7RM_yWmOzd1UGm_-UPbyplUKkSkVW9bv7WwN-YBIpR8dQ==&lang=python&interacts=eJyLjgUAARUAuQ==

答:
Use combinations from itertools</p>

```<code>In [29]: from itertools import combinations

In [30]: def get_list(n, m):
    ...:     return [i for i in combinations(range(1, n+1), m)]

In [31]: get_list(4, 2)
Out[31]: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
</code>```

Title: List of increasing lists

Body:
Given integers n >= m, I want to build the list of all increasing lists of length m with elements the set {1,...,n}.

For instance, if n= 4 and m=2, I want
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].

Is there a nice way to do that with very few lines of Python code?

I would like to build an efficient function

def listOfLists(n, m):
    ????
    return ? # the list of all increasing lists of m elements in {1, 2, ..., n}

Thanks!

Remark: I have basically done this, but my code is ridiculously long https://sagecell.sagemath.org/?z=eJxVkcFuwyAQRO98xR5Bdqo66ikq-YJIvfRm5eDIuF2ZbBB21H5-FpYWh4PFmHmzHjy6Ccj9rp_34J2eWyBzUMArvQQLc384Zx1YeEd6NlkiywA76LL6-Ubv2ItnsJbPGiA-C5Ik9p0t3hScjI19ghHeJbBC4mw6Dq1UgST0PyO69R4pu5QauZPHZf2YTvxcNLUQSiuceMgRqA4pZC8tZx7Vv8p-ukUegQRxoC-nu5qSnS9DCI5GjXIhl2HBJdEVjk_wBel2xcHL56Qim7RM_yWmOzd1UGm_-UPbyplUKkSkVW9bv7WwN-YBIpR8dQ==&lang=python&interacts=eJyLjgUAARUAuQ==

Body:
Use combinations from itertools

In [29]: from itertools import combinations

In [30]: def get_list(n, m):
    ...:     return [i for i in combinations(range(1, n+1), m)]

In [31]: get_list(4, 2)
Out[31]: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


问:
Select multiple values in a dropdown in angular 9
I would like to select multiple values in a dropdown. But the dropdown options are asynchronously fetched through REST API. I tried with <select multiple> with ngFor Directive, but it didn't work.

答:
You can always use check boxes in the drop-down list and create a custom directive that check if check box is selected then it triggers some CSS highlight style and furthermore if you don't want to show check-box set its visibility to invisible so it works but only under the hood
(Just an idea)
There would be some extra work like if the drop down goes out of focus you would want the check-boxes to be deselected again so you would also have to check for that in the directive.</p>


问:
Why does the Mac ABI require 16-byte stack alignment for x86-32?
I can understand this requirement for the old PPC RISC systems and even for x86-64, but for the old tried-and-true x86? In this case, the stack needs to be aligned on 4 byte boundaries only. Yes, some of the MMX/SSE instructions require 16byte alignments, but if that is a requirement of the callee, then it should ensure the alignments are correct. Why burden every caller with this extra requirement? This can actually cause some drops in performance because every call-site must manage this requirement. Am I missing something?

Update: After some more investigation into this and some consultation with some internal colleagues, I have some theories about this:

Consistency between the PPC, x86, and x64 version of the OS

It seems that the GCC codegen now consistently does a sub esp,xxx and then "mov"s the data onto the stack rather than simply doing a "push" instruction. This could actually be faster on some hardware.

While this does complicate the call sites a little, there is very little extra overhead when using the default "cdecl" convention where the caller cleans up the stack.

The issue I have with the last item, is that for calling conventions that rely on the callee cleaning the stack, the above requirements really "uglifies" the codegen. For instance, what some compiler decided to implement a faster register-based calling style for its own internal use (ie any code that isn't intended to be called from other languages or sources)? This stack-alignment thing could negate some of the performance gains achieved by passing some parameters in registers.

Update: So far the only real answers have been consistency, but to me that's a bit too easy of an answer. I have well over 20 years experience with the x86 architecture and if consistency, not performance, or something else concrete, is really the reason then I respectfully suggest that is a bit naive for the developers to require it. They're ignoring nearly three decades of tools and support. Especially if they're expecting tools vendors to quickly and easily adapt their tools for their platform (maybe not... it is Apple...) without having to jump through several seemingly unnecessary hoops.

I'll give this topic another day or so then close it...

Related

It’s my stack frame, I don’t care about your stack frame!

答: I believe it's to keep it inline with the x86-64 ABI.</p>

OwnerDisplayName: Allen Bauer

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Allen Bauer

OwnerDisplayName: Andrew Grant

ContentLicense: CC BY-SA 2.5


问:
How to avoid iOS automatic font size adjustment?
I am NOT talking about zooming the page, but rather the way MobileSafari on iOS automatically bumps up some font sizes sometimes.

When, exactly, is this done? Can it be prevented or discouraged?

答:
```<code>body {
    -webkit-text-size-adjust: 100%;
}
</code>```

Just make sure all your text is at a legible size in the first place. The iPhone and iPod touch have a rather small screen, so keep that in mind too.

Body:
body {
    -webkit-text-size-adjust: 100%;
}

Just make sure all your text is at a legible size in the first place. The iPhone and iPod touch have a rather small screen, so keep that in mind too.


问:
How do I convert string to date, compare by date and remove the result in MongoDB?
I am currently trying to do these steps in MongoDB Query:
In the picture below there is commitDate or commitDate instant.

1-I want to convert this commitDate to date format

2-I want to compare this commitDate with a given date for example like:
{ $match: { date: { $lte: date, $gte: date }}}

3-I want to delete the results.

I know there is aggregation pipeline function $dateToString but I don't know how to compare and remove the documents in the range.

答:
If you are using version 3.6 or greater of MongoDB, I would recommend using the $dateFromString operator to convert the Strings in the database to to a date value before the comparison. It will make the comparison more accurate than trying to do so on Strings (in case there are bad values, e.g., "2020-13" is greater than "2020-01").

If you are using version 4.0 or greater, you can do something like the following. Note that the $dateFromString operation will make those dates that cannot be converted a null value and thus will not be matched by the $match operator.

```<code>db.myCollection.aggregate([
  {
    $project:
      {
        date2:{
          $dateFromString: {
              dateString: '$date',
              onError: null
          }
        }
      }
  },
  {
    $match: {
      date2:   {
        $gte: ISODate('2020-03-01T00:00:00.000'),
        $lte: ISODate('2020-05-01T00:00:00.000')
      }
    }
  }
]).forEach(doc=> {
  db.dated.deleteOne({_id: doc._id});
  print(doc._id);
});
</code>```

If you are using version later than 3.6 but earlier than 4.0, there is no onError parameter in the $dateFromString operator. So if you need to account for non-date values in the field, you'll have to filter those out before the conversion. Here is an aggregation pipeline matching dates by a regex. Regex may have to be changed depending on the date format of the field. (If you have no data issues, you don't need to worry about the first $match operation.)

```<code>db.myCollection.aggregate([
  {
    $match: {
     date: {$regex: /(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})\.\d{3}/}
    }
  },
  {
    $project:
      {
        date2:{
          $dateFromString: {
              dateString: '$date'
          }
        }
      }
  },
  {
    $match: {
      date2:   {
        $gte: ISODate('2020-03-01T00:00:00.000'),
        $lte: ISODate('2020-05-01T00:00:00.000')
      }
    }
  }
]).forEach(doc=> {
  db.dated.deleteOne({_id: doc._id});
  print(doc._id);
});
</code>```

Body:
If you are using version 3.6 or greater of MongoDB, I would recommend using the $dateFromString operator to convert the Strings in the database to to a date value before the comparison. It will make the comparison more accurate than trying to do so on Strings (in case there are bad values, e.g., "2020-13" is greater than "2020-01").

If you are using version 4.0 or greater, you can do something like the following. Note that the $dateFromString operation will make those dates that cannot be converted a null value and thus will not be matched by the $match operator.

db.myCollection.aggregate([
  {
    $project:
      {
        date2:{
          $dateFromString: {
              dateString: '$date',
              onError: null
          }
        }
      }
  },
  {
    $match: {
      date2:   {
        $gte: ISODate('2020-03-01T00:00:00.000'),
        $lte: ISODate('2020-05-01T00:00:00.000')
      }
    }
  }
]).forEach(doc=> {
  db.dated.deleteOne({_id: doc._id});
  print(doc._id);
});

If you are using version later than 3.6 but earlier than 4.0, there is no onError parameter in the $dateFromString operator. So if you need to account for non-date values in the field, you'll have to filter those out before the conversion. Here is an aggregation pipeline matching dates by a regex. Regex may have to be changed depending on the date format of the field. (If you have no data issues, you don't need to worry about the first $match operation.)

db.myCollection.aggregate([
  {
    $match: {
     date: {$regex: /(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})\.\d{3}/}
    }
  },
  {
    $project:
      {
        date2:{
          $dateFromString: {
              dateString: '$date'
          }
        }
      }
  },
  {
    $match: {
      date2:   {
        $gte: ISODate('2020-03-01T00:00:00.000'),
        $lte: ISODate('2020-05-01T00:00:00.000')
      }
    }
  }
]).forEach(doc=> {
  db.dated.deleteOne({_id: doc._id});
  print(doc._id);
});


问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
If you're having this issue with "curl" (or similar) on a Ubuntu 16 system, here's how we fixed it:

On the Ubuntu 16 system hosting the curl / app that fails:

nano /etc/ca-certificates.conf

Remove the line (or comment) specifying AddTrust_External_Root.crt

apt update && apt install ca-certificates

update-ca-certificates -f -v

Try curl again with the URL that was failing before - hopefully it works now :)

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);


问:
TypeError: this.state.userDtl.map is not a function
I am new to react coding, am trying to fetch values from a api response.

```<code>class AdminDashboard extends Component {
    constructor() {
        super()
        this.state = {
            mobile: "",
            userDtl: "",
        }
        this.getDetails = this.getDetails.bind(this)
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        });
    }

    getDetails() {
        console.log("Inside getDetails...")
        Service.getUserByMobileNumber(this.state.mobile)
            .then(
                response => {
                    console.log(response.data)
                    this.setState({
                        userDtl: response.data
                    })

                },
                document.getElementById("userDetails").style.visibility = "visible",
            )
    }

    componentDidMount() {
        document.getElementById("userDetails").style.visibility = "hidden";
    }

    render() {
        return (
            <>
                <br /><br />
                <div className="userdashboard">
                    <h3 className="container"><span><u>Admin Dashboard</u><br /></span></h3>
                    <br />
                    <div className="container">
                        <table>
                            <tr>
                                <td><b>Mobile Number</b>  </td>
                                <td><input type="text" name="mobile" value={this.state.mobile} onChange={this.handleChange} placeholder="Enter your mobile number" /> </td>
                                <td><button className="btn btn-success" onClick={this.getDetails}>Get Details</button></td>
                            </tr>
                        </table>
                        <br /><br />
                    </div>
                    <div className="container">
                        <div id="userDetails">
                            <>
                                {
                                    this.state.userDtl.map(
                                    userDtl =>
                                        <table>
                                            <tr>
                                                <td><b>Email</b>  </td>
                                                <td>{userDtl.email}</td>
                                            </tr>
                                            <tr>
                                                <td><b>Given Name</b>  </td>
                                                <td>{userDtl.fName}</td>
                                            </tr>
                                            <tr>
                                                <td><b>Family Name</b>  </td>
                                                <td>{userDtl.lName}</td>
                                            </tr>
                                        </table>
                                    )
                                }
                            </>
                        </div>
                </div>
            </>
        )
    }
}
export default AdminDashboard
</code>```

Below is the response from the api

```<code>{fName: "test", lName: "test1", email: "wer", role: null, mobileNumber: "12342"}
</code>```

Below is the error that I am getting

```<code>Uncaught (in promise) TypeError: this.state.userDtl.map is not a function
    at AdminDashboard.render (AdminDashboard.jsx:108)
    at finishClassComponent (react-dom.development.js:17160)
</code>```

答:
Your initial value for userDtl is not an array. and your response is not, too.

Your response is an object and you have to map through an object.

I create working codesandbox. https://codesandbox.io/s/green-sun-ym38o.

Body:
I am new to react coding, am trying to fetch values from a api response.

class AdminDashboard extends Component {
    constructor() {
        super()
        this.state = {
            mobile: "",
            userDtl: "",
        }
        this.getDetails = this.getDetails.bind(this)
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        });
    }

    getDetails() {
        console.log("Inside getDetails...")
        Service.getUserByMobileNumber(this.state.mobile)
            .then(
                response => {
                    console.log(response.data)
                    this.setState({
                        userDtl: response.data
                    })

                },
                document.getElementById("userDetails").style.visibility = "visible",
            )
    }

    componentDidMount() {
        document.getElementById("userDetails").style.visibility = "hidden";
    }

    render() {
        return (
            <>

Admin Dashboard

                                Mobile Number
                                <input type="text" name="mobile" value={this.state.mobile} onChange={this.handleChange} placeholder="Enter your mobile number" />
                                <button className="btn btn-success" onClick={this.getDetails}>Get Details</button>

                            <>
                                {
                                    this.state.userDtl.map(
                                    userDtl =>

                                                Email
                                                {userDtl.email}

                                                Given Name
                                                {userDtl.fName}

                                                Family Name
                                                {userDtl.lName}

                                    )
                                }
                            </>

            </>
        )
    }
}
export default AdminDashboard

Below is the response from the api

{fName: "test", lName: "test1", email: "wer", role: null, mobileNumber: "12342"}

Below is the error that I am getting

Uncaught (in promise) TypeError: this.state.userDtl.map is not a function
    at AdminDashboard.render (AdminDashboard.jsx:108)
    at finishClassComponent (react-dom.development.js:17160)


问:
How to ask the user for an integer at runtime, and recursively ask again if you didn't get one?
I'm trying to write some code that does all of the following:

At run time, asks, with an actual question (e.g. "How many PCs do you have? ") the user to type in an integer.

Check if the user has given either an object of integer type or something that can be coerced in to that without error. This step must not require any sort of grep (e.g. that makes this solution invalid).

Instead of giving any warning or errors if the input wasn't an integer, ask a new question that is repeated until they do give an integer (e.g. ask "Try again? " until an integer is given).

Outputs this integer.

The solutions to similar questions appear to be to use either scan or readlines. I've ruled out scan because it likes to throw its own error messages, needs help from print to ask questions, and will ask for another input if given an invalid one even if you've told it to only try for one (e.g. scan(n = 1,quiet = TRUE) will ask for another input if you give it a bunch of letters). I've found that readlines is almost satisfactory, but because readlines treats its input as a string, I've been unable to write atrycatch block that satisfies requirement #3.

What are my options? It's looking like I've missed a simple solution.

答:
We could either use a recursive function or a while or repeat loop to check if the answer is numeric

```<code>f1 <- function(question){

  flag <- TRUE
    while(flag) {
    out <- readline(paste0(question, "\n"))
    out1 <- type.convert(out, as.is = TRUE)
    if(is.numeric(out1)) flag <- FALSE
    }

    out1
}

v1 <- f1('how many PCs')
how many PCs
not sure
how many PCs
you asked the wrong person
how many PCs
#2432
how many PCs
20

v1
#[1] 20
</code>```

Or another option is to convert to integer with as.integer.  if there is any value that is not an integer/numeric, it would return NA.  Using is.na as a logical condition, we can change the if line in the above code

Body:
We could either use a recursive function or a while or repeat loop to check if the answer is numeric

f1 <- function(question){

  flag <- TRUE
    while(flag) {
    out <- readline(paste0(question, "\n"))
    out1 <- type.convert(out, as.is = TRUE)
    if(is.numeric(out1)) flag <- FALSE
    }

    out1
}

v1 <- f1('how many PCs')
how many PCs
not sure
how many PCs
you asked the wrong person
how many PCs
#2432
how many PCs
20

v1
#[1] 20

Or another option is to convert to integer with as.integer.  if there is any value that is not an integer/numeric, it would return NA.  Using is.na as a logical condition, we can change the if line in the above code


问:
Handle back press on react native depending on component state
I'm trying to customize the back navigation event on my react native app. Basically, in the body of the component I render different sections depending on the currentSection state variable. What I found out is that the value of currentSection inside the onBackPress function does not get updated, and apparently always has the value of when it was first called (during the useEffect invocation).

```<code>    const [currentSection, setCurrentSection] = useState<ProviderDetailSections>(ProviderDetailSections.MAIN);

    useEffect(() => {
        BackHandler.addEventListener(
            "hardwareBackPress",
            onBackPress
        );

        return () => BackHandler.removeEventListener(
            "hardwareBackPress",
            onBackPress
        );
    }, []);

    function onBackPress(): boolean {
        console.log(`onBackPress currentSection: ${currentSection}`);
        if (currentSection === ProviderDetailSections.MAIN) {
            return false;
        }
        else {
            setCurrentSection(ProviderDetailSections.MAIN);
            return true;
        }
    }
</code>```

The console.log() inside onBackPress always logs the same section (MAIN), no matter what is the actual current section.
Any help would be greatly appreciated!

答:
Check the answer</p>

```<code>const [currentSection, setCurrentSection] = useState<ProviderDetailSections>(ProviderDetailSections.MAIN);

useEffect(() => {
    BackHandler.addEventListener(
        "hardwareBackPress",
        onBackPress
    );

    return () => BackHandler.removeEventListener(
        "hardwareBackPress",
        onBackPress
    );
}, []);

function onBackPress(): boolean {
    console.log(`onBackPress currentSection: ${currentSection}`);
        setCurrentSection(ProviderDetailSections.MAIN);
        return true;
    }
}
</code>```

Body:
I'm trying to customize the back navigation event on my react native app. Basically, in the body of the component I render different sections depending on the currentSection state variable. What I found out is that the value of currentSection inside the onBackPress function does not get updated, and apparently always has the value of when it was first called (during the useEffect invocation).

    const [currentSection, setCurrentSection] = useState<ProviderDetailSections>(ProviderDetailSections.MAIN);

    useEffect(() => {
        BackHandler.addEventListener(
            "hardwareBackPress",
            onBackPress
        );

        return () => BackHandler.removeEventListener(
            "hardwareBackPress",
            onBackPress
        );
    }, []);

    function onBackPress(): boolean {
        console.log(`onBackPress currentSection: ${currentSection}`);
        if (currentSection === ProviderDetailSections.MAIN) {
            return false;
        }
        else {
            setCurrentSection(ProviderDetailSections.MAIN);
            return true;
        }
    }

The console.log() inside onBackPress always logs the same section (MAIN), no matter what is the actual current section.
Any help would be greatly appreciated!

Body:
Check the answer

const [currentSection, setCurrentSection] = useState<ProviderDetailSections>(ProviderDetailSections.MAIN);

useEffect(() => {
    BackHandler.addEventListener(
        "hardwareBackPress",
        onBackPress
    );

    return () => BackHandler.removeEventListener(
        "hardwareBackPress",
        onBackPress
    );
}, []);

function onBackPress(): boolean {
    console.log(`onBackPress currentSection: ${currentSection}`);
        setCurrentSection(ProviderDetailSections.MAIN);
        return true;
    }
}


问:
How to extend terraform module input variable schema without breaking existing clients?
I have a module with the following input variable:

```<code>variable "apsvc_map" {
  description = "The App Services sharing the same App Service Plan. Maps an App Service name to its properties."
  type        = map(object({
    identity_ids = list(string),
    disabled = bool
  }))
}
</code>```

Now I would like to add a new property to the schema - no_custom_hostname_binding. The new version would be:

```<code>variable "apsvc_map" {
  description = "The App Services sharing the same App Service Plan. Maps an App Service name to its properties."
  type        = map(object({
    identity_ids = list(string),
    disabled = bool
    no_custom_hostname_binding = bool
  }))
}
</code>```

And this change can be made backwards compatible in the module code with the help of the try function, because omitting the new property is equivalent to providing it with the false value.

However, terraform treats this schema strictly and would not allow passing an input without the new field:

```<code>2020-05-30T15:34:20.8061749Z Error: Invalid value for module argument
2020-05-30T15:34:20.8062005Z
2020-05-30T15:34:20.8062205Z   on ..\..\modules\web\main.tf line 47, in module "web":
2020-05-30T15:34:20.8062336Z   47:   apsvc_map = {
2020-05-30T15:34:20.8062484Z   48:     dfhub = {
2020-05-30T15:34:20.8062727Z   49:       disabled     = false
2020-05-30T15:34:20.8065156Z   50:       identity_ids = [local.identity_id]
2020-05-30T15:34:20.8065370Z   51:     }
2020-05-30T15:34:20.8065459Z   52:   }
2020-05-30T15:34:20.8065538Z
</code>```

I understand from the error that terraform complains because I did not specify the value for the new property in the input.

So, there are three solutions:

Update all the existing code to add the new property - out of the question.

Tag the new version of the module differently and let the new code reference the new tag, while the old code continues to reference the old tag - in the long run would lead to proliferation of tags, creating all kinds of bizarre Cartesian multiplications of features in the tag names. Ultimately - out of the question.

Relax the input variable schema by commenting out the optional properties and use try in the code.

The last option is not ideal, because the documentation for the module would not list the optional properties. But from the code management perspective - it is the best.

So the question is - can input object properties be defined as optional? Ideally, it should include the default value, but I am OK with the try approach for now.

EDIT 1

I actually thought I could pass unknown properties in the object, but no. Once the schema is given it is nothing less nothing more. So, the only backwards compatible solution is to use map(any) in my case.

答:
Optional arguments in object variable have been suggested for Terraform:

https://github.com/hashicorp/terraform/issues/19898

Unfortunately as of May 30 2020, there has not been any progress on this.

That is the most upvoted issue on their repo, all we can do is keep upvoting and hopefully, that will be implemented soon.

And you are right the alternatives are just out of the question or plain hackish

Body:
I have a module with the following input variable:

variable "apsvc_map" {
  description = "The App Services sharing the same App Service Plan. Maps an App Service name to its properties."
  type        = map(object({
    identity_ids = list(string),
    disabled = bool
  }))
}

Now I would like to add a new property to the schema - no_custom_hostname_binding. The new version would be:

variable "apsvc_map" {
  description = "The App Services sharing the same App Service Plan. Maps an App Service name to its properties."
  type        = map(object({
    identity_ids = list(string),
    disabled = bool
    no_custom_hostname_binding = bool
  }))
}

And this change can be made backwards compatible in the module code with the help of the try function, because omitting the new property is equivalent to providing it with the false value.

However, terraform treats this schema strictly and would not allow passing an input without the new field:

2020-05-30T15:34:20.8061749Z Error: Invalid value for module argument
2020-05-30T15:34:20.8062005Z
2020-05-30T15:34:20.8062205Z   on ..\..\modules\web\main.tf line 47, in module "web":
2020-05-30T15:34:20.8062336Z   47:   apsvc_map = {
2020-05-30T15:34:20.8062484Z   48:     dfhub = {
2020-05-30T15:34:20.8062727Z   49:       disabled     = false
2020-05-30T15:34:20.8065156Z   50:       identity_ids = [local.identity_id]
2020-05-30T15:34:20.8065370Z   51:     }
2020-05-30T15:34:20.8065459Z   52:   }
2020-05-30T15:34:20.8065538Z

I understand from the error that terraform complains because I did not specify the value for the new property in the input.

So, there are three solutions:

Update all the existing code to add the new property - out of the question.

Tag the new version of the module differently and let the new code reference the new tag, while the old code continues to reference the old tag - in the long run would lead to proliferation of tags, creating all kinds of bizarre Cartesian multiplications of features in the tag names. Ultimately - out of the question.

Relax the input variable schema by commenting out the optional properties and use try in the code.

The last option is not ideal, because the documentation for the module would not list the optional properties. But from the code management perspective - it is the best.

So the question is - can input object properties be defined as optional? Ideally, it should include the default value, but I am OK with the try approach for now.

EDIT 1

I actually thought I could pass unknown properties in the object, but no. Once the schema is given it is nothing less nothing more. So, the only backwards compatible solution is to use map(any) in my case.


问:
How to get carriage return without line feed effect in Eclipse console?
If I

```<code>System.out.print("something\r");
</code>```

at console, I have cursor back at the beginning of line, and finally after

```<code>System.out.print("something\r");
System.out.print(" any\r");
</code>```

I have

```<code> anything
</code>```

typed.

But at Eclipse console I get

```<code>something
 anything
</code>```

as if it treated \r as CR/LF.

How can I setup this?

答:
The bug is fixed by now (Eclipse 2020-03).
Just go to

```Window ➺ Preferences ➺ Run/Debug ➺ Console```

and make sure that both checkboxes

```Interpret ASCII control characters```

and

```Interpret Carriage Return (\r) as control character```

are enabled.

Body:
If I

System.out.print("something\r");

at console, I have cursor back at the beginning of line, and finally after

System.out.print("something\r");
System.out.print(" any\r");

I have

 anything

typed.

But at Eclipse console I get

something
 anything

as if it treated \r as CR/LF.

How can I setup this?

Body:
The bug is fixed by now (Eclipse 2020-03).
Just go to

Window ➺ Preferences ➺ Run/Debug ➺ Console

and make sure that both checkboxes

Interpret ASCII control characters

and

Interpret Carriage Return (\r) as control character

are enabled.


问:
Numpy flatten dimension function
I am new to Python and am trying to extract RGB-encoded pixel labels from a numpy array. For example:

```<code>image.shape
>> (256, 256, 3)
</code>```

to be converted to:

```<code>image.shape
>> (256, 256, 1)
</code>```

based on a custom function. In Javascript such a function would be (the exact RGB encoding is, of course, irrelevant - but being able to use a custom function is relevant):

```<code>RGBtoVal = ([r,g,b])=>{
   r = Math.floor(r*9/255);
   g = Math.floor(g*9/255);
   b = Math.floor(b*9/255);
   if (r>0) return r+18;
   if (g>0) return r+9;
   return b;
}
</code>```

I understand that reshape and squeeze are helpful in reducing the dimensionality but without a function. Also, is a numpy matrix of shape (256,256,1) the same as (256,256)?

答:
In numpy you can work with vectors and you don't have to work with every pixel separatelly.

In examples I use image 4x4 with values (1,1,1)

```<code>import numpy as np

image = np.ones([4,4,3])  # image 4x4 with RGB (3 values)

print(image.shape) # (4, 4, 3)

R = image[:,:,0]  # all R values
G = image[:,:,1]  # all G values
B = image[:,:,2]  # all B values

print(R.shape) # (4, 4)
print(G.shape) # (4, 4)
print(B.shape) # (4, 4)

R = R * 9/255
G = R * 9/255
B = B * 9/255

R[ R > 0 ] += 18
G[ G > 0 ] += 9

print(R)
print(G)
print(B)

print(image)
</code>```

or you can even use * 9/255 before you split to R,G,B

```<code>import numpy as np

image = np.ones([4,4,3])

print(image.shape)

image = image * 9/255

R = image[:,:,0]
G = image[:,:,1]
B = image[:,:,2]

R[ R > 0 ] += 18
G[ G > 0 ] += 9

print(R)
print(G)
print(B)

print(image)
</code>```

If you want to do this in more traditional way then use numpy.apply_along_axis(func, axis, arr) with axis 2

```<code>import numpy as np

# --- fuctions ---

def function(rgb):
    #rgb = rgb * 9/255
    r, g, b = rgb

    r = r * 9/255
    g = g * 9/255
    b = b * 9/255

    if r > 0:
        r += 18
    if g > 0 :
        g += 9

    return [r,g,b]

# --- main ---

image = np.ones([4,4,3])

print(image.shape)

image = np.apply_along_axis(function, 2, image)

print(image[:,:,0])  # R
print(image[:,:,1])  # G
print(image[:,:,2])  # B

print(image)
</code>```

Title: Numpy flatten dimension function

Body:
I am new to Python and am trying to extract RGB-encoded pixel labels from a numpy array. For example:

image.shape
>> (256, 256, 3)

to be converted to:

image.shape
>> (256, 256, 1)

based on a custom function. In Javascript such a function would be (the exact RGB encoding is, of course, irrelevant - but being able to use a custom function is relevant):

RGBtoVal = ([r,g,b])=>{
   r = Math.floor(r*9/255);
   g = Math.floor(g*9/255);
   b = Math.floor(b*9/255);
   if (r>0) return r+18;
   if (g>0) return r+9;
   return b;
}

I understand that reshape and squeeze are helpful in reducing the dimensionality but without a function. Also, is a numpy matrix of shape (256,256,1) the same as (256,256)?

Body:
In numpy you can work with vectors and you don't have to work with every pixel separatelly.

In examples I use image 4x4 with values (1,1,1)

import numpy as np

image = np.ones([4,4,3])  # image 4x4 with RGB (3 values)

print(image.shape) # (4, 4, 3)

R = image[:,:,0]  # all R values
G = image[:,:,1]  # all G values
B = image[:,:,2]  # all B values

print(R.shape) # (4, 4)
print(G.shape) # (4, 4)
print(B.shape) # (4, 4)

R = R * 9/255
G = R * 9/255
B = B * 9/255

R[ R > 0 ] += 18
G[ G > 0 ] += 9

print(R)
print(G)
print(B)

print(image)

or you can even use * 9/255 before you split to R,G,B

import numpy as np

image = np.ones([4,4,3])

print(image.shape)

image = image * 9/255

R = image[:,:,0]
G = image[:,:,1]
B = image[:,:,2]

R[ R > 0 ] += 18
G[ G > 0 ] += 9

print(R)
print(G)
print(B)

print(image)

If you want to do this in more traditional way then use numpy.apply_along_axis(func, axis, arr) with axis 2

import numpy as np

# --- fuctions ---

def function(rgb):
    #rgb = rgb * 9/255
    r, g, b = rgb

    r = r * 9/255
    g = g * 9/255
    b = b * 9/255

    if r > 0:
        r += 18
    if g > 0 :
        g += 9

    return [r,g,b]

# --- main ---

image = np.ones([4,4,3])

print(image.shape)

image = np.apply_along_axis(function, 2, image)

print(image[:,:,0])  # R
print(image[:,:,1])  # G
print(image[:,:,2])  # B

print(image)


问:
How can I generate random text file with random content and size?
```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tests
{
    class RandomTests
    {
        private static Random random = new Random();
        public static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        static List<string> listv;
        public static void GenerateRandomStrings()
        {
            for (int i = 0; i < random.Next(20, 1000); i++)
            {
                string rand = RandomString(20);
                ListViewCostumControl.lvnf.Items.Add(rand);
            }

            listv = ListViewCostumControl.lvnf.Items.Cast<ListViewItem>()
                                 .Select(item => item.Text)
                                 .ToList();
        }

        private void UsageExample()
        {
            GenerateRandom(5, 1, 6);
        }

        public static List<int> GenerateRandom(int count)
        {
            return GenerateRandom(count, 0, Int32.MaxValue);
        }

        // Note, max is exclusive here!
        public static List<int> GenerateRandom(int count, int min, int max)
        {

            //  initialize set S to empty
            //  for J := N-M + 1 to N do
            //    T := RandInt(1, J)
            //    if T is not in S then
            //      insert T in S
            //    else
            //      insert J in S
            //
            // adapted for C# which does not have an inclusive Next(..)
            // and to make it from configurable range not just 1.

            if (max <= min || count < 0 ||
                    // max - min > 0 required to avoid overflow
                    (count > max - min && max - min > 0))
            {
                // need to use 64-bit to support big ranges (negative min, positive max)
                throw new ArgumentOutOfRangeException("Range " + min + " to " + max +
                        " (" + ((Int64)max - (Int64)min) + " values), or count " + count + " is illegal");
            }

            // generate count random values.
            HashSet<int> candidates = new HashSet<int>();

            // start count values before max, and end at max
            for (int top = max - count; top < max; top++)
            {
                // May strike a duplicate.
                // Need to add +1 to make inclusive generator
                // +1 is safe even for MaxVal max value because top < max
                if (!candidates.Add(random.Next(min, top + 1)))
                {
                    // collision, add inclusive max.
                    // which could not possibly have been added before.
                    candidates.Add(top);
                }
            }

            // load them in to a list, to sort
            List<int> result = candidates.ToList();

            // shuffle the results because HashSet has messed
            // with the order, and the algorithm does not produce
            // random-ordered results (e.g. max-1 will never be the first value)
            for (int i = result.Count - 1; i > 0; i--)
            {
                int k = random.Next(i + 1);
                int tmp = result[k];
                result[k] = result[i];
                result[i] = tmp;
            }
            return result;
        }
    }
}
</code>```

For now I'm using only the GenerateRandomStrings() in Form1.
but now I ant to generate random text files with random content and size.
for example 100MB or 100GB files sizes with random content.

The files sizes should be from bytes to giga bytes. can be 1b file or 100GB file.

and then add the files to the listview as items like doing in the GenerateRandomStrings() function.

```<code>ListViewCostumControl.lvnf.Items.Add(rand);
</code>```

the same idea to add generated text files with random content and sizes.

答:
This code creates a file, with size defined by the user and filled with random text,

```<code>Console.WriteLine("Give file size in bytes");
var fileSize = int.Parse(Console.ReadLine());
var buffer = new byte[fileSize];
new Random().NextBytes(buffer);
var text = System.Text.Encoding.Default.GetString(buffer);
File.WriteAllText("/home/path/to/file/randomtext.txt", text);
</code>```

Note: I am using Linux so you wanna change that path.

Body:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tests
{
    class RandomTests
    {
        private static Random random = new Random();
        public static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        static List<string> listv;
        public static void GenerateRandomStrings()
        {
            for (int i = 0; i < random.Next(20, 1000); i++)
            {
                string rand = RandomString(20);
                ListViewCostumControl.lvnf.Items.Add(rand);
            }

            listv = ListViewCostumControl.lvnf.Items.Cast<ListViewItem>()
                                 .Select(item => item.Text)
                                 .ToList();
        }

        private void UsageExample()
        {
            GenerateRandom(5, 1, 6);
        }

        public static List<int> GenerateRandom(int count)
        {
            return GenerateRandom(count, 0, Int32.MaxValue);
        }

        // Note, max is exclusive here!
        public static List<int> GenerateRandom(int count, int min, int max)
        {

            //  initialize set S to empty
            //  for J := N-M + 1 to N do
            //    T := RandInt(1, J)
            //    if T is not in S then
            //      insert T in S
            //    else
            //      insert J in S
            //
            // adapted for C# which does not have an inclusive Next(..)
            // and to make it from configurable range not just 1.

            if (max <= min || count < 0 ||
                    // max - min > 0 required to avoid overflow
                    (count > max - min && max - min > 0))
            {
                // need to use 64-bit to support big ranges (negative min, positive max)
                throw new ArgumentOutOfRangeException("Range " + min + " to " + max +
                        " (" + ((Int64)max - (Int64)min) + " values), or count " + count + " is illegal");
            }

            // generate count random values.
            HashSet<int> candidates = new HashSet<int>();

            // start count values before max, and end at max
            for (int top = max - count; top < max; top++)
            {
                // May strike a duplicate.
                // Need to add +1 to make inclusive generator
                // +1 is safe even for MaxVal max value because top < max
                if (!candidates.Add(random.Next(min, top + 1)))
                {
                    // collision, add inclusive max.
                    // which could not possibly have been added before.
                    candidates.Add(top);
                }
            }

            // load them in to a list, to sort
            List<int> result = candidates.ToList();

            // shuffle the results because HashSet has messed
            // with the order, and the algorithm does not produce
            // random-ordered results (e.g. max-1 will never be the first value)
            for (int i = result.Count - 1; i > 0; i--)
            {
                int k = random.Next(i + 1);
                int tmp = result[k];
                result[k] = result[i];
                result[i] = tmp;
            }
            return result;
        }
    }
}

For now I'm using only the GenerateRandomStrings() in Form1.
but now I ant to generate random text files with random content and size.
for example 100MB or 100GB files sizes with random content.

The files sizes should be from bytes to giga bytes. can be 1b file or 100GB file.

and then add the files to the listview as items like doing in the GenerateRandomStrings() function.

ListViewCostumControl.lvnf.Items.Add(rand);

the same idea to add generated text files with random content and sizes.

Body:
This code creates a file, with size defined by the user and filled with random text,

Console.WriteLine("Give file size in bytes");
var fileSize = int.Parse(Console.ReadLine());
var buffer = new byte[fileSize];
new Random().NextBytes(buffer);
var text = System.Text.Encoding.Default.GetString(buffer);
File.WriteAllText("/home/path/to/file/randomtext.txt", text);

Note: I am using Linux so you wanna change that path.


问:
Toggle Button value when onClick() is invoked React
When the App starts, the button's text is initially 'c'. When the button is clicked, it goes to toggleDisplay() and checks if unit === 'c'. If it's true, then update the unit variable to 'f'. This part works as I tested it using console.log. But the unit variable that in inside <button> tag is not updating. It's only showing 'c' but it has to toggle between 'c' and 'f'

```<code>function App() {
...
...
let unit = "c";
const toggleDisplay = () =>{
if(unit === 'c'){
    unit = "f";
    console.log(unit)
}
else{
    unit = "c";
    console.log(unit)
 }
}

return(
    <button className="temp" onClick={toggleDisplay}>
        {unit}
    </button>
)
</code>```

Ps. This is actually a weather app and the toggle between 'c' and 'f' is the toggle between values of celsius and fahrenheit.

答:
Use a state hook to store the unit. In your code, unit is being set to "c" every time the component updates.

```<code>import {useState} from "react";

function App() {
    const [unit, setUnit] = useState("c");
    const toggleDisplay = () => {
        if (unit === "c") {
            setUnit("f");
            console.log(unit);
        } else {
            setUnit("c");
            console.log(unit);
        }
    };
    return (
        <button className="temp" onClick={toggleDisplay}>
            {unit}
        </button>
    );
}
</code>```

Body:
When the App starts, the button's text is initially 'c'. When the button is clicked, it goes to toggleDisplay() and checks if unit === 'c'. If it's true, then update the unit variable to 'f'. This part works as I tested it using console.log. But the unit variable that in inside <button> tag is not updating. It's only showing 'c' but it has to toggle between 'c' and 'f'

function App() {
...
...
let unit = "c";
const toggleDisplay = () =>{
if(unit === 'c'){
    unit = "f";
    console.log(unit)
}
else{
    unit = "c";
    console.log(unit)
 }
}

return(
    <button className="temp" onClick={toggleDisplay}>
        {unit}
    </button>
)

Ps. This is actually a weather app and the toggle between 'c' and 'f' is the toggle between values of celsius and fahrenheit.

Body:
Use a state hook to store the unit. In your code, unit is being set to "c" every time the component updates.

import {useState} from "react";

function App() {
    const [unit, setUnit] = useState("c");
    const toggleDisplay = () => {
        if (unit === "c") {
            setUnit("f");
            console.log(unit);
        } else {
            setUnit("c");
            console.log(unit);
        }
    };
    return (
        <button className="temp" onClick={toggleDisplay}>
            {unit}
        </button>
    );
}


问:
How do I handle phone numbers with NextJS Links?
I have a Link component that uses Next/Link and I'm passing in a telephone number formatted like this: tel:+15555555555

However I get an error:

Invalid href passed to router: tel:+15555555555
```

Are telephone numbers not supported?

答:
Next/Link is a component for page navigation. There is no good reason to use it with special links such as tel: / mailto:.
Use regular a element

tel
```

Body:
I have a Link component that uses Next/Link and I'm passing in a telephone number formatted like this: tel:+15555555555

However I get an error:

Invalid href passed to router: tel:+15555555555

Are telephone numbers not supported?

Body:
Next/Link is a component for page navigation. There is no good reason to use it with special links such as tel: / mailto:.
Use regular a element

<a href={`tel:${phone}`}>tel</a>


问:
Replace Homepage background image used in Journal Theme 3.x for Opencart 2.x?
I'm new here and also new to OpenCart. I just installed OpenCart 2.3.0.2 version on local hosting using Xampp. I then installed Journal Theme 3.0.2.46 (Demo 4) (https://www.journal-theme.com/4/) everything was going fine until i wanted to change the default theme background image used on the home page which appears behind the "Testimonial" block and scrolls up/down as i navigate on the page. i want to replace the default background image with my own but cant locate any link in the Journal theme editor in the admin panel. i have tried all possible links but failed to find the link to replace that file which is quite nerving. please help me!!! TIA.</p>

答:
Agree, Journal theme is a bit challenge. Lucky to you, i had the same issue.

Background setting of this block you will find at

Journal - Layouts - Home

It might be a Bottom, the may be Row 2 - you will see Testimonial module inside of this row. On the right side of this row panel you will see a pencil icon, calls "Edit row" while hover it. Press it and you will see Background tab. Tada! Your image is here (icon #3).


问:
How to redirect properly in Django URL , I am having issue in redirecting

Having issue with redirecting, I am at registration page("accounts/register") on my website where I want if someone register then a verification code will send on his email id and to verify we have a url "accounts/verify". but when I am trying to register it register a user but does not send them on "accounts/verify" instead it send that to "accounts/register/accounts/verify" ,

Also please let me know how to use user email address, while registering him into database. I just want his email id to send verification code.

Here is my URL.py of my app:

```<code>from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.auth.models import User

    urlpatterns = [
        path('login/', views.login, name='Login-Page'),
        path('register/', views.register, name='Registeration-page'),
        path('logout/', views.logout),
        path('verify/', views.verify, name='verification page')
</code>```

Here is my View.py for registration and profile:

```<code>from django.shortcuts import render, redirect
import requests
from django.contrib.auth.models import User, auth
from django.contrib import messages
from datetime import date
import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def register(request):

    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        password1 = request.POST['password1']
        password2 = request.POST['password2']

        if password1==password2:
            if User.objects.filter(username=username).exists():
                messages.info(request, "Username already taken")
                return redirect('accounts/register')
            elif User.objects.filter(email=email).exists():
                messages.info(request, "email already taken")
                return redirect('accounts/register')
            else:
                user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)
                user.save();
                return redirect('accounts/verify') # 'accounts/login'
        else:
            messages.info(request,"password not matched")
            return redirect('accounts/register')

    else:
        return render(request, 'register.html')

def verify(request):
    if request.method == 'POST':
        sender_address = 'xyz@gmail.com'
        sender_pass = 'password'
        user_email = register.user.objects.email
        receiver_address = user_email
        passd = random.randrange(111111,10000000,39)
        mail_content = "Hello This is your verficatiob code   " + str(passd)

        def check(code):
            if code==passd:
                return redirect('accounts/login')
            else:
                messages.info(request,"Code is incorrect")
                return redirect('accounts/verify')

        message = MIMEMultipart()
        message['From'] = sender_address
        message['To'] = receiver_address
        message['Subject'] = 'Verification Code'
        message.attach(MIMEText(mail_content, 'plain'))
        session = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        session.starttls()
        session.login(sender_address, sender_pass)
        text = message.as_string()
        session.sendmail(sender_address, receiver_address, text)
        session.quit()
        print('Mail Sent')
        code = request.POST['code']

        check(code)
    else:
        return render(request, 'email_verify.html')
</code>```

Here is my register template:

```<code><div class="limiter">
        <div class="container-login100" style="background-image: url ('/images/bg-01.jpg');">
            <div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">
                <form action="{{register}}" method="post">
                    {% csrf_token %}
                <!--<form class="login100-form validate-form">-->
                    <span class="login100-form-title p-b-49">
                        Registration
                    </span>
                    <div>
                    {% for message in messages %}
                    <input class="wrap-input validate-input m-b-23" data-validate="{{message}}">
                    {% endfor %}
                    </div>

                    <div class="wrap-input100 validate-input m-b-23" data-validate = "First name is reauired">
                        <span class="label-input100"><th>first name</th></span>
                        <input class="input100" type="text" name="first_name" placeholder="Type your First name">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input m-b-23" data-validate = "Last name is reauired">
                        <span class="label-input100"><th>last name</th></span>
                        <input class="input100" type="text" name="last_name" placeholder="Type your Last name">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input" data-validate="Username is required">
                        <span class="label-input100">Username</span>
                        <input class="input100" type="username" name="username" placeholder="Type your username">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input" data-validate="email is required">
                        <span class="label-input100">email</span>
                        <input class="input100" type="email" name="email" placeholder="Type your email">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="password is required">
                        <span class="label-input100">Password</span>
                        <input class="input100" type="password" name="password1" placeholder="Type your password">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <div class="wrap-input100 validate-input" data-validate="confirm password is required">
                        <span class="label-input100">Confirm Password</span>
                        <input class="input100" type="password" name="password2" placeholder="Type your password Again">
                        <span class="focus-input100" data-symbol=""></span>
                    </div>
                    <br>
                    <div class="container-login100-form-btn">
                        <div class="wrap-login100-form-btn">
                            <div class="login100-form-bgbtn"></div>
                            <button class="login100-form-btn">
                                Register
                            </button>
                        </div>
                    </div>
                </form>
             </div>
          </div>
       </div>
</code>```

This is the error:

```<code>Page not found (404)
Request Method: GET
Request URL:    localhost/accounts/register/accounts/verify
Using the URLconf defined in made.urls, Django tried these URL patterns, in this order:

admin/
[name='Homepage']
accounts/ login/ [name='Login-Page']
accounts/ register/ [name='Registeration-page']
accounts/ logout/
accounts/ verify/ [name='verification page']
</code>```

答:
If you don't add /(slash) to beginnig of URL like how you did in  return redirect('accounts/verify'), it will be added on current URL and you will unfortunately will be redirected to "accounts/register/accounts/verify" which is not defined. You need to change all like return redirect('/accounts/verify'). Or, my advice is representing them by their name. In this case, it would be return redirect('verification page').

And here is how I could send an email, a bit different from your way. But it worked fine on my project.

settings.py

```<code>EMAIL_BACKEND ="django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "youremailadress@gmail.com"
EMAIL_HOST_PASSWORD = "yourpassword"
</code>```

views.py

```<code>from django.core.mail import send_mail

send_mail("subject","message", EMAIL_HOST_USER, ["recipient@gmail.com"])
</code>```

Body:
Having issue with redirecting, I am at registration page("accounts/register") on my website where I want if someone register then a verification code will send on his email id and to verify we have a url "accounts/verify". but when I am trying to register it register a user but does not send them on "accounts/verify" instead it send that to "accounts/register/accounts/verify" ,

Also please let me know how to use user email address, while registering him into database. I just want his email id to send verification code.

Here is my URL.py of my app:

from django.contrib import admin
from django.urls import path,include
from . import views
from django.contrib.auth.models import User

    urlpatterns = [
        path('login/', views.login, name='Login-Page'),
        path('register/', views.register, name='Registeration-page'),
        path('logout/', views.logout),
        path('verify/', views.verify, name='verification page')

Here is my View.py for registration and profile:

from django.shortcuts import render, redirect
import requests
from django.contrib.auth.models import User, auth
from django.contrib import messages
from datetime import date
import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def register(request):

    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        password1 = request.POST['password1']
        password2 = request.POST['password2']

        if password1==password2:
            if User.objects.filter(username=username).exists():
                messages.info(request, "Username already taken")
                return redirect('accounts/register')
            elif User.objects.filter(email=email).exists():
                messages.info(request, "email already taken")
                return redirect('accounts/register')
            else:
                user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name)
                user.save();
                return redirect('accounts/verify') # 'accounts/login'
        else:
            messages.info(request,"password not matched")
            return redirect('accounts/register')

    else:
        return render(request, 'register.html')

def verify(request):
    if request.method == 'POST':
        sender_address = 'xyz@gmail.com'
        sender_pass = 'password'
        user_email = register.user.objects.email
        receiver_address = user_email
        passd = random.randrange(111111,10000000,39)
        mail_content = "Hello This is your verficatiob code   " + str(passd)

        def check(code):
            if code==passd:
                return redirect('accounts/login')
            else:
                messages.info(request,"Code is incorrect")
                return redirect('accounts/verify')

        message = MIMEMultipart()
        message['From'] = sender_address
        message['To'] = receiver_address
        message['Subject'] = 'Verification Code'
        message.attach(MIMEText(mail_content, 'plain'))
        session = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        session.starttls()
        session.login(sender_address, sender_pass)
        text = message.as_string()
        session.sendmail(sender_address, receiver_address, text)
        session.quit()
        print('Mail Sent')
        code = request.POST['code']

        check(code)
    else:
        return render(request, 'email_verify.html')

Here is my register template:

                <form action="{{register}}" method="post">
                    {% csrf_token %}

                        Registration

                    {% for message in messages %}
                    <input class="wrap-input validate-input m-b-23" data-validate="{{message}}">
                    {% endfor %}

                        first name
                        <input class="input100" type="text" name="first_name" placeholder="Type your First name">

                        last name
                        <input class="input100" type="text" name="last_name" placeholder="Type your Last name">

                        Username
                        <input class="input100" type="username" name="username" placeholder="Type your username">

                        email
                        <input class="input100" type="email" name="email" placeholder="Type your email">

                        Password
                        <input class="input100" type="password" name="password1" placeholder="Type your password">

                        Confirm Password
                        <input class="input100" type="password" name="password2" placeholder="Type your password Again">

                            <button class="login100-form-btn">
                                Register
                            </button>

                </form>

This is the error:

Page not found (404)
Request Method: GET
Request URL:    localhost/accounts/register/accounts/verify
Using the URLconf defined in made.urls, Django tried these URL patterns, in this order:

admin/
[name='Homepage']
accounts/ login/ [name='Login-Page']
accounts/ register/ [name='Registeration-page']
accounts/ logout/
accounts/ verify/ [name='verification page']

Body:
If you don't add /(slash) to beginnig of URL like how you did in  return redirect('accounts/verify'), it will be added on current URL and you will unfortunately will be redirected to "accounts/register/accounts/verify" which is not defined. You need to change all like return redirect('/accounts/verify'). Or, my advice is representing them by their name. In this case, it would be return redirect('verification page').

And here is how I could send an email, a bit different from your way. But it worked fine on my project.

settings.py

EMAIL_BACKEND ="django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "youremailadress@gmail.com"
EMAIL_HOST_PASSWORD = "yourpassword"

views.py

from django.core.mail import send_mail

send_mail("subject","message", EMAIL_HOST_USER, ["recipient@gmail.com"])


问:
How can I force a child to only inherit the position of its parent while ignoring its parents rotation?
I want to create a simple mechanic where I control the rotation of an object that is childed to a parent.

Imagine a pot of water on the shoulder of a person. When the person jumps, the pot also changes position since it is a child. But I dont want to inherit the parent rotation. As I want to control the rotation of this child via script/gyroscope.

I know that a common solution to this would be to freeze the rotation in script within LateUpdate():

```<code>Vector3 InitPos;

void Start ()
{
    InitRot = transform.rotation;
}

void LateUpdate ()
{
   transform.rotation = InitRot;
}
</code>```

This would work, if I did not intend on controlling the rotation separately. Like mentioned above, I want to control the rotation of the child via touch or gyroscope. How can I achieve this?

Thanks

答:
You can detach the child object from parent object, then make an empty gameobject under the parent object which will be target object, then with a basic follow script just follow the empty target object like </p>

```<code>void Update()
transform.position = Vector3.MoveTowards(transform.position, following.transform.position,followSpeed);
</code>```

<p>or directly </p>

```<code> void Update()
    transform.position = following.transform.position
</code>```

Body:
I want to create a simple mechanic where I control the rotation of an object that is childed to a parent.

Imagine a pot of water on the shoulder of a person. When the person jumps, the pot also changes position since it is a child. But I dont want to inherit the parent rotation. As I want to control the rotation of this child via script/gyroscope.

I know that a common solution to this would be to freeze the rotation in script within LateUpdate():

Vector3 InitPos;

void Start ()
{
    InitRot = transform.rotation;
}

void LateUpdate ()
{
   transform.rotation = InitRot;
}

This would work, if I did not intend on controlling the rotation separately. Like mentioned above, I want to control the rotation of the child via touch or gyroscope. How can I achieve this?

Thanks

Body:
You can detach the child object from parent object, then make an empty gameobject under the parent object which will be target object, then with a basic follow script just follow the empty target object like

void Update()
transform.position = Vector3.MoveTowards(transform.position, following.transform.position,followSpeed);

or directly

 void Update()
    transform.position = following.transform.position


问:
window.open('', '_blank') doesn't open new tab on iOS only
I have a call to window.open with _blank, and it works in all browsers except on iOS.  In my web app, when I click the button to Add to Cart on an iOS device, nothing happens at all, whereas in all other browsers, a new window opens.

```<code>const addProducts = (products) => {
    setProductsAdded(false);
    cService
      .add(products)
      .then(() => {
        setLoading(null);
        setProductsAdded(true);
        window.open(C_LINK, '_blank');
      })
      .catch(() => {
        setError('Error');
      });
  };
</code>```

I found this question and answer, which seems to be the same problem - but I am new to Javascript and not exactly sure how to implement it: window.open(url, '_blank'); not working on iMac/Safari

So my first question is, am I right in thinking the question and answer I just mentioned could be the same problem?  My second question is, if I were to try to implement the solution as mentioned in the previous question, would I modify the existing function or would it be separate?  Where would I set window.open()?  Could someone explain what "myService" is exactly?   Thank you for your help.

答:
I haven't tried this before, but implementing the solution from the SO answer would look like this:

```<code>// Open a new window and save a reference to it
var newWindow = window.open();

const addProducts = (products) => {
    setProductsAdded(false);
    cService
      .add(products)
      .then(() => {
        setLoading(null);
        setProductsAdded(true);

        // Set the URL of the new window
        newWindow.location = C_LINK;
      })
      .catch(() => {
        setError('Error');
      });
  };
</code>```

In the other post, myService is a non-existent, example service that returns a URL.

Body:
I have a call to window.open with _blank, and it works in all browsers except on iOS.  In my web app, when I click the button to Add to Cart on an iOS device, nothing happens at all, whereas in all other browsers, a new window opens.

const addProducts = (products) => {
    setProductsAdded(false);
    cService
      .add(products)
      .then(() => {
        setLoading(null);
        setProductsAdded(true);
        window.open(C_LINK, '_blank');
      })
      .catch(() => {
        setError('Error');
      });
  };

I found this question and answer, which seems to be the same problem - but I am new to Javascript and not exactly sure how to implement it: window.open(url, '_blank'); not working on iMac/Safari

So my first question is, am I right in thinking the question and answer I just mentioned could be the same problem?  My second question is, if I were to try to implement the solution as mentioned in the previous question, would I modify the existing function or would it be separate?  Where would I set window.open()?  Could someone explain what "myService" is exactly?   Thank you for your help.

Body:
I haven't tried this before, but implementing the solution from the SO answer would look like this:

// Open a new window and save a reference to it
var newWindow = window.open();

const addProducts = (products) => {
    setProductsAdded(false);
    cService
      .add(products)
      .then(() => {
        setLoading(null);
        setProductsAdded(true);

        // Set the URL of the new window
        newWindow.location = C_LINK;
      })
      .catch(() => {
        setError('Error');
      });
  };

In the other post, myService is a non-existent, example service that returns a URL.


答:
For this, you need to bind the  URL to elements onclick event .

Please follow the code. add this button in your HTML.

```<code><button class='btn' id="btnClick" onclick='window.open("https://www.google.com", "_blank");' style='position: absolute;top: 0;display: none'>Open Google search</button>
</code>```

Replace your link in onclick event. Now trigger the click event using javascript.

Change window.open(C_LINK, '_blank');

to

```<code>document.getElementById("btnClick").click()
</code>```

REFERENCE

Title: window.open('', '_blank') doesn't open new tab on iOS only

Body:
For this, you need to bind the  URL to elements onclick event .

Please follow the code. add this button in your HTML.

<button class='btn' id="btnClick" onclick='window.open("https://www.google.com", "_blank");' style='position: absolute;top: 0;display: none'>Open Google search</button>

Replace your link in onclick event. Now trigger the click event using javascript.

Change window.open(C_LINK, '_blank');

to

document.getElementById("btnClick").click()

REFERENCE