问:
init function TypeError: Cannot read property 'style' of null
No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.

I get the message that all these lines are wrong

I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.

document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';

```<code>var scores, roundScore, activePlayer, gamePlaying;

var lastDice;

function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}

document.querySelector('.btn-new').addEventListener('click', init);

init();

</code>```

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
        <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="style.css">
        <title>Pig Game</title>
    </head>

    <body>
        <div class="wrapper clearfix">
            <div class="player-0-panel active">
                <div class="player-name" id="name-0">Player 1</div>
                <div class="player-score" id="score-0">43</div>
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="current-0">11</div>
                </div>
            </div>

            <div class="player-1-panel">
                <div class="player-name" id="name-1">Player 2</div>
                <div class="player-score" id="score-1">72</div>
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="current-1">0</div>
                </div>
            </div>

            <button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
            <button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
            <button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>

            <input type="text" placeholder="Final Score" class="final-score">

            <img src="dice-5.png" alt="Dice" class="dice">
        </div>

        <script type='text/javascript' src="challenges.js"></script>
    </body>
</html>
</code>```

```<code>/**********************************************
*** GENERAL
**********************************************/

.final-score {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 520px;
    color: #555;
    font-size: 18px;
    font-family: 'Lato';
    text-align: center;
    padding: 10px;
    width: 160px;
    text-transform: uppercase;
}

.final-score:focus { outline: none; }

dice-1 { top: 120px; }
#dice-2 { top: 250px; }

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

body {
    background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
    background-size: cover;
    background-position: center;
    font-family: Lato;
    font-weight: 300;
    position: relative;
    height: 100vh;
    color: #555;
}

.wrapper {
    width: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.player-0-panel,
.player-1-panel {
    width: 50%;
    float: left;
    height: 600px;
    padding: 100px;
}

/**********************************************
*** PLAYERS
**********************************************/

.player-name {
    font-size: 40px;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: 100;
    margin-top: 20px;
    margin-bottom: 10px;
    position: relative;
}

.player-score {
    text-align: center;
    font-size: 80px;
    font-weight: 100;
    color: #EB4D4D;
    margin-bottom: 130px;
}

.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }

.active .player-name::after {
    content: "\2022";
    font-size: 47px;
    position: absolute;
    color: #EB4D4D;
    top: -7px;
    right: 10px;

}

.player-current-box {
    background-color: #EB4D4D;
    color: #fff;
    width: 40%;
    margin: 0 auto;
    padding: 12px;
    text-align: center;
}

.player-current-label {
    text-transform: uppercase;
    margin-bottom: 10px;
    font-size: 12px;
    color: #222;
}

.player-current-score {
    font-size: 30px;
}

button {
    position: absolute;
    width: 200px;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    background: none;
    border: none;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }

button:focus {
    outline: none;
}

i {
    color: #EB4D4D;
    display: inline-block;
    margin-right: 15px;
    font-size: 32px;
    line-height: 1;
    vertical-align: text-top;
    margin-top: -4px;
    transition: margin 0.3s;
}

.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}

.dice {
    position: absolute;
    left: 50%;
    top: 178px;
    transform: translateX(-50%);
    height: 100px;
    box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}

.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }
</code>```

Please help me.

答: I don't see any HTML elements with id="dice-1" nor id="dice-2", which would explain the error you're receiving.

Body:
No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.

I get the message that all these lines are wrong

I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.

document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';

var scores, roundScore, activePlayer, gamePlaying;

var lastDice;

function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}

document.querySelector('.btn-new').addEventListener('click', init);

init();

<!DOCTYPE html>

        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
        <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="style.css">
        <title>Pig Game</title>

Player 1

43

Current

11

Player 2

72

Current

0

            <button class="btn-new">New game</button>
            <button class="btn-roll">Roll dice</button>
            <button class="btn-hold">Hold</button>

            <input type="text" placeholder="Final Score" class="final-score">

/**********************************************
*** GENERAL
**********************************************/

.final-score {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 520px;
    color: #555;
    font-size: 18px;
    font-family: 'Lato';
    text-align: center;
    padding: 10px;
    width: 160px;
    text-transform: uppercase;
}

.final-score:focus { outline: none; }

dice-1 { top: 120px; }
#dice-2 { top: 250px; }

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

body {
    background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
    background-size: cover;
    background-position: center;
    font-family: Lato;
    font-weight: 300;
    position: relative;
    height: 100vh;
    color: #555;
}

.wrapper {
    width: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.player-0-panel,
.player-1-panel {
    width: 50%;
    float: left;
    height: 600px;
    padding: 100px;
}

/**********************************************
*** PLAYERS
**********************************************/

.player-name {
    font-size: 40px;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: 100;
    margin-top: 20px;
    margin-bottom: 10px;
    position: relative;
}

.player-score {
    text-align: center;
    font-size: 80px;
    font-weight: 100;
    color: #EB4D4D;
    margin-bottom: 130px;
}

.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }

.active .player-name::after {
    content: "\2022";
    font-size: 47px;
    position: absolute;
    color: #EB4D4D;
    top: -7px;
    right: 10px;

}

.player-current-box {
    background-color: #EB4D4D;
    color: #fff;
    width: 40%;
    margin: 0 auto;
    padding: 12px;
    text-align: center;
}

.player-current-label {
    text-transform: uppercase;
    margin-bottom: 10px;
    font-size: 12px;
    color: #222;
}

.player-current-score {
    font-size: 30px;
}

button {
    position: absolute;
    width: 200px;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    background: none;
    border: none;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }

button:focus {
    outline: none;
}

i {
    color: #EB4D4D;
    display: inline-block;
    margin-right: 15px;
    font-size: 32px;
    line-height: 1;
    vertical-align: text-top;
    margin-top: -4px;
    transition: margin 0.3s;
}

.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}

.dice {
    position: absolute;
    left: 50%;
    top: 178px;
    transform: translateX(-50%);
    height: 100px;
    box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}

.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }

Please help me.


来源: stackexchange

问:
django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile
My models.py file looks like:

```<code>from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'
</code>```

When I'm trying to look it into the shell:

```<code>>> from django.contrib.auth.models import User
>>> user = User.objects.filter(username='TestUser').first()
>>> user
<User: TestUser>
>>> user.profile
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "D:\Visual Studio Code Projects\cs50\Learning Django(other source)\Corey\djangoenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 423, in __get__
    self.related.get_accessor_name()
django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile.
</code>```

I looked various different tutorials and solutions it works fine for everyone.
Please help me with this regards, really stuck at this point.

答:
You have to create a userprofile for the user first:

```<code>profile = UserProfile.objects.create(user=request.user)
</code>```

In your views.py you can use get_or_create so that a userprofile is created for a user if the user doesn't have one.

```<code>user, created = UserProfile.objects.get_or_create(user=request.user)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My models.py file looks like:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

When I'm trying to look it into the shell:

>> from django.contrib.auth.models import User
>>> user = User.objects.filter(username='TestUser').first()
>>> user
<User: TestUser>
>>> user.profile
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "D:\Visual Studio Code Projects\cs50\Learning Django(other source)\Corey\djangoenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 423, in __get__
    self.related.get_accessor_name()
django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile.

I looked various different tutorials and solutions it works fine for everyone.
Please help me with this regards, really stuck at this point.

Body:
You have to create a userprofile for the user first:

profile = UserProfile.objects.create(user=request.user)

In your views.py you can use get_or_create so that a userprofile is created for a user if the user doesn't have one.

user, created = UserProfile.objects.get_or_create(user=request.user)


问:
duplicate same following elements in array
I should build a function that gets an array and it's size and return a pointer
to new array (i need do create new array by using malloc and realloc) that find the identical numbers and duplicates them in the row
for example the array:{1,8,8,70,2,2,2,5,5,2} and size 10 suppose to return a pointer to this array
{1,8,8,8,8,70,2,2,2,2,2,2,5,5,5,5,2}. Any clue what's wrong with my code??</p>

```<code>int * duplicateArray(int* arr, int n)

{
    int g = 1;
    int i,j=0;
    int *p = (int*)(calloc)(n, sizeof(int));
    assert(p);
    for (i = 0; i < n-1; i++)
    {
        if (arr[i] == arr[i + 1])
        {
             p= (int*)(realloc)(p, n+g * sizeof(int));
             n=n+g;
             assert(p);
             p[j] = arr[i];
             j++;
             p[j] = arr[i+1];
        }
        else
            p[j] = arr[i];
        j++;
    }
   return p;
}
</code>```

答:
The approach used by you when the memory is constantly reallocated is inefficient.

Also the function should return not only the pointer to the dynamically allocated array but also the number of elements in the allocated array. Otherwise the user of the function will not know how many elements are in the allocated array. To use a sentinel value for an integer dynamically allocated array is not a good idea.

I suggest to split the task into two separate tasks that will correspond to two separate functions..

The first function will count the number of repeated elements in a given array.

The second function will create dynamically an array with the specified size based on the returned value of the first function and copy elements of the source array to the newly created array.

Here is a demonstrative program

```<code>#include <stdio.h>
#include <stdlib.h>

size_t countRepeated( const int a[], size_t n )
{
    size_t repeated = 0;

    for ( size_t i = 0; i != n;  )
    {
        size_t m = 1;

        while ( ++i != n && a[i] == a[i-1] ) ++m;

        if ( m != 1 ) repeated += m;
    }

    return repeated;
}

int * copyWithDuplication( const int a[], size_t n, size_t m )
{
    int *result = m == 0 ? NULL : calloc( m, sizeof( int ) );

    if ( result )
    {
        for ( size_t i = 0, j = 0; j != m && i != n;  )
        {
            result[j++] = a[i++];

            size_t k = 1;

            while ( j != m && i != n && a[i] == a[i-1] )
            {
                result[j++] = a[i++];
                ++k;
            }

            if ( k != 1 )
            {
                while ( j != m && k-- ) result[j++] = a[i-1];
            }
        }
    }

    return result;
}

int main(void)
{
    int a[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    size_t m = N + countRepeated( a, N );

    int *b = copyWithDuplication( a, N, m );

    if ( b )
    {
        for ( size_t i = 0; i < m; i++ )
        {
            printf( "%d ", b[i] );
        }
        putchar( '\n' );
    }

    free( b );

    return 0;
}
</code>```

The program output is

```<code>1 8 8 70 2 2 2 5 5 2
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5 2
</code>```

And here is another more interesting demonstrative program.

```<code>#include <stdio.h>
#include <stdlib.h>

size_t countRepeated( const int a[], size_t n )
{
    size_t repeated = 0;

    for ( size_t i = 0; i != n;  )
    {
        size_t m = 1;

        while ( ++i != n && a[i] == a[i-1] ) ++m;

        if ( m != 1 ) repeated += m;
    }

    return repeated;
}

int * copyWithDuplication( const int a[], size_t n, size_t m )
{
    int *result = m == 0 ? NULL : calloc( m, sizeof( int ) );

    if ( result )
    {
        for ( size_t i = 0, j = 0; j != m && i != n;  )
        {
            result[j++] = a[i++];

            size_t k = 1;

            while ( j != m && i != n && a[i] == a[i-1] )
            {
                result[j++] = a[i++];
                ++k;
            }

            if ( k != 1 )
            {
                while ( j != m && k-- ) result[j++] = a[i-1];
            }
        }
    }

    return result;
}

int main(void)
{
    int a[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    size_t m = N + countRepeated( a, N );

    for ( size_t i = 0; i < m; i++ )
    {
        int *b = copyWithDuplication( a, N, i + 1 );

        if ( b )
        {
            for ( size_t j = 0; j < i + 1; j++ )
            {
                printf( "%d ", b[j] );
            }
            putchar( '\n' );
        }

        free( b );
    }

    return 0;
}
</code>```

Its output is

```<code>1 8 8 70 2 2 2 5 5 2
1
1 8
1 8 8
1 8 8 8
1 8 8 8 8
1 8 8 8 8 70
1 8 8 8 8 70 2
1 8 8 8 8 70 2 2
1 8 8 8 8 70 2 2 2
1 8 8 8 8 70 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2 2 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5 2
</code>```

Body:
I should build a function that gets an array and it's size and return a pointer
to new array (i need do create new array by using malloc and realloc) that find the identical numbers and duplicates them in the row
for example the array:{1,8,8,70,2,2,2,5,5,2} and size 10 suppose to return a pointer to this array
{1,8,8,8,8,70,2,2,2,2,2,2,5,5,5,5,2}. Any clue what's wrong with my code??

int * duplicateArray(int* arr, int n)

{
    int g = 1;
    int i,j=0;
    int *p = (int*)(calloc)(n, sizeof(int));
    assert(p);
    for (i = 0; i < n-1; i++)
    {
        if (arr[i] == arr[i + 1])
        {
             p= (int*)(realloc)(p, n+g * sizeof(int));
             n=n+g;
             assert(p);
             p[j] = arr[i];
             j++;
             p[j] = arr[i+1];
        }
        else
            p[j] = arr[i];
        j++;
    }
   return p;
}

Body:
The approach used by you when the memory is constantly reallocated is inefficient.

Also the function should return not only the pointer to the dynamically allocated array but also the number of elements in the allocated array. Otherwise the user of the function will not know how many elements are in the allocated array. To use a sentinel value for an integer dynamically allocated array is not a good idea.

I suggest to split the task into two separate tasks that will correspond to two separate functions..

The first function will count the number of repeated elements in a given array.

The second function will create dynamically an array with the specified size based on the returned value of the first function and copy elements of the source array to the newly created array.

Here is a demonstrative program

#include <stdio.h>
#include <stdlib.h>

size_t countRepeated( const int a[], size_t n )
{
    size_t repeated = 0;

    for ( size_t i = 0; i != n;  )
    {
        size_t m = 1;

        while ( ++i != n && a[i] == a[i-1] ) ++m;

        if ( m != 1 ) repeated += m;
    }

    return repeated;
}

int * copyWithDuplication( const int a[], size_t n, size_t m )
{
    int *result = m == 0 ? NULL : calloc( m, sizeof( int ) );

    if ( result )
    {
        for ( size_t i = 0, j = 0; j != m && i != n;  )
        {
            result[j++] = a[i++];

            size_t k = 1;

            while ( j != m && i != n && a[i] == a[i-1] )
            {
                result[j++] = a[i++];
                ++k;
            }

            if ( k != 1 )
            {
                while ( j != m && k-- ) result[j++] = a[i-1];
            }
        }
    }

    return result;
}

int main(void)
{
    int a[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    size_t m = N + countRepeated( a, N );

    int *b = copyWithDuplication( a, N, m );

    if ( b )
    {
        for ( size_t i = 0; i < m; i++ )
        {
            printf( "%d ", b[i] );
        }
        putchar( '\n' );
    }

    free( b );

    return 0;
}

The program output is

1 8 8 70 2 2 2 5 5 2
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5 2

And here is another more interesting demonstrative program.

#include <stdio.h>
#include <stdlib.h>

size_t countRepeated( const int a[], size_t n )
{
    size_t repeated = 0;

    for ( size_t i = 0; i != n;  )
    {
        size_t m = 1;

        while ( ++i != n && a[i] == a[i-1] ) ++m;

        if ( m != 1 ) repeated += m;
    }

    return repeated;
}

int * copyWithDuplication( const int a[], size_t n, size_t m )
{
    int *result = m == 0 ? NULL : calloc( m, sizeof( int ) );

    if ( result )
    {
        for ( size_t i = 0, j = 0; j != m && i != n;  )
        {
            result[j++] = a[i++];

            size_t k = 1;

            while ( j != m && i != n && a[i] == a[i-1] )
            {
                result[j++] = a[i++];
                ++k;
            }

            if ( k != 1 )
            {
                while ( j != m && k-- ) result[j++] = a[i-1];
            }
        }
    }

    return result;
}

int main(void)
{
    int a[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    size_t m = N + countRepeated( a, N );

    for ( size_t i = 0; i < m; i++ )
    {
        int *b = copyWithDuplication( a, N, i + 1 );

        if ( b )
        {
            for ( size_t j = 0; j < i + 1; j++ )
            {
                printf( "%d ", b[j] );
            }
            putchar( '\n' );
        }

        free( b );
    }

    return 0;
}

Its output is

1 8 8 70 2 2 2 5 5 2
1
1 8
1 8 8
1 8 8 8
1 8 8 8 8
1 8 8 8 8 70
1 8 8 8 8 70 2
1 8 8 8 8 70 2 2
1 8 8 8 8 70 2 2 2
1 8 8 8 8 70 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2 2
1 8 8 8 8 70 2 2 2 2 2 2 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5
1 8 8 8 8 70 2 2 2 2 2 2 5 5 5 5 2


问:
Difference between dynamically allocated arrays and static arrays
I am getting an introduction to dynamic memory allocation, and I learned that a dynamic array ( the one like int *p = new int[n] \\ where n is the user input describing the number of elements is used when you do not know how many elements the user requires/ declaring an array of a size that the user wants. However, instead of doing that, why can't we declare a static array like this:

```<code>int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
</code>```

What is the advantage of dynamic arrays in this case then? I am not understanding this concept.

Edit : Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

```<code>int main(){
    int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
    cout << "Enter your numbers : " <<endl;
    for (int i=0;i<=n;i++){
        cin>>a[i];
    }
    for (int i=0;i<=n;i++){
        cout<<a[i]<<endl;
    }
}
</code>```

答:
```<code>int a[n];
</code>```

This line declares a variable-length array, but that's not part of C++.  Some compilers implement it as an extension, but it's not actually C++ at that point.  It would be a specific compiler's dialect of C++.

So, this isn't even an option (if you want your code to be portable).

The standard advice is to use std::vector<int> instead of managing your own memory, so I would suggest doing that.  (Of course, there is nothing wrong with exercises to help you understand how to do proper memory management.)

Body:
I am getting an introduction to dynamic memory allocation, and I learned that a dynamic array ( the one like int *p = new int[n] \\ where n is the user input describing the number of elements is used when you do not know how many elements the user requires/ declaring an array of a size that the user wants. However, instead of doing that, why can't we declare a static array like this:

int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];

What is the advantage of dynamic arrays in this case then? I am not understanding this concept.

Edit : Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

int main(){
    int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
    cout << "Enter your numbers : " <<endl;
    for (int i=0;i<=n;i++){
        cin>>a[i];
    }
    for (int i=0;i<=n;i++){
        cout<<a[i]<<endl;
    }
}

Body:
int a[n];

This line declares a variable-length array, but that's not part of C++.  Some compilers implement it as an extension, but it's not actually C++ at that point.  It would be a specific compiler's dialect of C++.

So, this isn't even an option (if you want your code to be portable).

The standard advice is to use std::vector<int> instead of managing your own memory, so I would suggest doing that.  (Of course, there is nothing wrong with exercises to help you understand how to do proper memory management.)


问:
Read non alphabetic character using pandas from excel
I am trying to read this file using pandas in UTF-8 encoding.

English alphabetic characters are read properly but those characters which are not English alphabet are not read properly. I tried reading by changing encoding from utf8 to cp1252, ASCII but nothing worked for me.

For more detail see the image.

答:
```<code>>>> import pandas as pd
>>> file = "D:\\Python\\SO3\\data\\62015078.xlsx"
>>> data = pd.read_excel(file,encoding='utf8')
>>> data.en
0     Release note
1    Sales package
2        Schematic
3         Software
4        Statistic
5            Video
Name: en, dtype: object
>>> data.ja
0    リリースノート
1    販売パッケージ
2        回路図
3     ソフトウェア
4         統計
5         動画
Name: ja, dtype: object
>>> data.zh
0    版本说明
1     销售包
2     示意图
3      软件
4      统计
5      视频
Name: zh, dtype: object
</code>```

The code snippet works. The � character is Replacement Character (U+FFFD). You need to set proper console / terminal font:

The same window with a common console font:

Body:
>>> import pandas as pd
>>> file = "D:\\Python\\SO3\\data\\62015078.xlsx"
>>> data = pd.read_excel(file,encoding='utf8')
>>> data.en
0     Release note
1    Sales package
2        Schematic
3         Software
4        Statistic
5            Video
Name: en, dtype: object
>>> data.ja
0    リリースノート
1    販売パッケージ
2        回路図
3     ソフトウェア
4         統計
5         動画
Name: ja, dtype: object
>>> data.zh
0    版本说明
1     销售包
2     示意图
3      软件
4      统计
5      视频
Name: zh, dtype: object

The code snippet works. The � character is Replacement Character (U+FFFD). You need to set proper console / terminal font:

The same window with a common console font:


问:
Using let instead of var breaks User:*/vector.js in MediaWiki
I try to understand what's going on with my adaption of the basic example of a MediaWiki user script.

It works in the original form, but when I replace var by let in the format_words function, it stops working. I'm quite new to JavaScript and jQuery. Here is the working version:

function format_words(title, numWords){
  var text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});
```

<p>And here the version that doesn't work</p>

<pre class="lang-js prettyprint-override"><code>function format_words(title, numWords){
  let text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});
</code>```

The first gives leads to this h1 heading:

User:Wolf/vector.js (74 words)

the second gives

User:Wolf/vector.js

I tested this in MediaWiki 1.31.6 and in MediaWiki 1.35.0-wmf.34 (6ff15fd), same effect.

After slowly getting familiar with jQuery, I expect a lot of asynchrony, but at this point I cannot figure out its influence.

Counter example

When I tested similar code in local HTML+JavaScript (with hot jQuery), switching from var to let doesn't break the code.

Console log

Thanks to charlietfl I changed my script to

function format_words(title, numWords){
  console.log("format_words [enter]");
  let text = title+" ("+numWords+" words)";
  console.log("format_words: text:"+text);
  return text;
}

$(document).ready(function(){
  console.log("on ready [enter]");
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
  console.log("on ready [leave]");
});
```

<p>... and opened the console. For the <code>let</code> version it shows the following error:</p>

<pre class="lang-none prettyprint-override"><code>JavaScript parse error: Parse error: Missing ; before statement in file↵
 'User:Wolf/vector.js' on line 3 vector.js line 1 > scriptElement:1:8
    <anonym> https://some.wiki/w/User:Wolf/vector.js line 1 > scriptElement:1
    jQuery 9
        DOMEval
        globalEval
        runScript
        fire
        add
        always
        checkCssHandles
        execute
        implement
    <anonym> https://some.wiki/load.php?debug=false&lang=en&modules=user&↵
skin=vector&user=Wolf&version=0hjxbj8:1
</code>```

I read this as let not being supported by JavaScript. Very strange: I was sure that JavaScript comes from the browser? And it worked with my Counter example.

What is going on here?

答:
The JS minifier used by MediaWiki does not support ES6 language features like let.

The console error you see is an error generated by the (server-side) minifier, transferred as a script.

Body:
I try to understand what's going on with my adaption of the basic example of a MediaWiki user script.

It works in the original form, but when I replace var by let in the format_words function, it stops working. I'm quite new to JavaScript and jQuery. Here is the working version:

function format_words(title, numWords){
  var text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});

And here the version that doesn't work

function format_words(title, numWords){
  let text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});

The first gives leads to this h1 heading:

User:Wolf/vector.js (74 words)

the second gives

User:Wolf/vector.js

I tested this in MediaWiki 1.31.6 and in MediaWiki 1.35.0-wmf.34 (6ff15fd), same effect.

After slowly getting familiar with jQuery, I expect a lot of asynchrony, but at this point I cannot figure out its influence.

Counter example

When I tested similar code in local HTML+JavaScript (with hot jQuery), switching from var to let doesn't break the code.

Console log

Thanks to charlietfl I changed my script to

function format_words(title, numWords){
  console.log("format_words [enter]");
  let text = title+" ("+numWords+" words)";
  console.log("format_words: text:"+text);
  return text;
}

$(document).ready(function(){
  console.log("on ready [enter]");
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
  console.log("on ready [leave]");
});

... and opened the console. For the let version it shows the following error:

JavaScript parse error: Parse error: Missing ; before statement in file↵
 'User:Wolf/vector.js' on line 3 vector.js line 1 > scriptElement:1:8
    <anonym> https://some.wiki/w/User:Wolf/vector.js line 1 > scriptElement:1
    jQuery 9
        DOMEval
        globalEval
        runScript
        fire
        add
        always
        checkCssHandles
        execute
        implement
    <anonym> https://some.wiki/load.php?debug=false&lang=en&modules=user&↵
skin=vector&user=Wolf&version=0hjxbj8:1

I read this as let not being supported by JavaScript. Very strange: I was sure that JavaScript comes from the browser? And it worked with my Counter example.

What is going on here?


问:
How is memory properly allocated?
so I am learning and trying to figure out memory allocation in c, in this piece of code, is the memory allocated correctly or no? Do I need to allocate the array too or is the array already allocated because everything that user inputs goes to the array(will be stored in the array)?</p>

```<code>#include <stdio.h>
#include <stdlib.h>
int main() {
    int i;
    int arr[20];
    int b;
    int *ptr;
    ptr = &b;

    ptr = (int*) malloc(20 *sizeof(int));

    //find largest element in array
    printf("Enter the number of elements: ");
    scanf("%d", &b);
    if(ptr == NULL)
    {
        printf(" No memory allocated.");
        exit(0);
    }

    for (i = 0; i < b; ++i) {
        printf("Enter number%d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    for (i = 1; i < b; ++i) {
        if (arr[0] < arr[i])
            arr[0] = arr[i];
    }
    free(ptr);
    printf("Largest element = %d", arr[0]);

    return 0;
}
</code>```

答:
You can clean up the malloc call:

```<code>ptr = malloc( 20 * sizeof *ptr );
</code>```

You don’t need to cast the result of malloc unless you using an ancient pre-C89 implementation or C++ (in which case you should use new/delete instead of malloc/free, or more preferably a container type like vector).

sizeof *ptr is equivalent to sizeof (int) in this case.

However, you aren’t actually using that memory - you allocate it and free it, but you never write anything to it.

You initially assign &b to ptr, but then you overwrite it with the result of the malloc call, so if you’re expecting that memory to be attached to b somehow, be aware that it isn’t.

Title: How is memory properly allocated?

Body:
so I am learning and trying to figure out memory allocation in c, in this piece of code, is the memory allocated correctly or no? Do I need to allocate the array too or is the array already allocated because everything that user inputs goes to the array(will be stored in the array)?

#include <stdio.h>
#include <stdlib.h>
int main() {
    int i;
    int arr[20];
    int b;
    int *ptr;
    ptr = &b;

    ptr = (int*) malloc(20 *sizeof(int));

    //find largest element in array
    printf("Enter the number of elements: ");
    scanf("%d", &b);
    if(ptr == NULL)
    {
        printf(" No memory allocated.");
        exit(0);
    }

    for (i = 0; i < b; ++i) {
        printf("Enter number%d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    for (i = 1; i < b; ++i) {
        if (arr[0] < arr[i])
            arr[0] = arr[i];
    }
    free(ptr);
    printf("Largest element = %d", arr[0]);

    return 0;
}

Body:
You can clean up the malloc call:

ptr = malloc( 20 * sizeof *ptr );

You don’t need to cast the result of malloc unless you using an ancient pre-C89 implementation or C++ (in which case you should use new/delete instead of malloc/free, or more preferably a container type like vector).

sizeof *ptr is equivalent to sizeof (int) in this case.

However, you aren’t actually using that memory - you allocate it and free it, but you never write anything to it.

You initially assign &b to ptr, but then you overwrite it with the result of the malloc call, so if you’re expecting that memory to be attached to b somehow, be aware that it isn’t.


问:
flash vs flex for android development
I've seen some videos using Flash and others using catalyst/Builder. I'm not sure which to start learning, I'm very interested though. I'm comfortable with flash (and have new 5.5 creative) but feel like builder/catalyst will eventually be more powerful.

what are the advantages and disadvantages of them (is there somewhere I can read up on this if it's too long of an answer?)

are there any good websites or books that really dig into the actual code from beginner to advanced? I don't even know where to look, the documentation is just very overwhelming. how would you advise even beginning? I don't want to get into bad habbits. i.e. learn in Flash then find out that I am limited by the program, or learn bad coding practices.

答:
Answer is very simple.

Flash CS 5
mostly used for developing application or website that involved some high animations and off course timeline.
Flash Builder 4.5.

develop application with more supported on code hinting/profiling, code unit testing, micro architecture support like caringorm, pureMVC.

based on your application requirements.
If your application need more comprehensive modules, back-end communication then use Flash builder otherwise use Flash CS.

But i prefer to use Flash builder 4.5(because i am in flex from  last three years) due to its debugging and easy to mange the action script code features.

ContentLicense: CC BY-SA 3.0

Title: flash vs flex for android development


问:
How to fix content background sharing within Linkedin
When my client wants to share this page on his Linkedin:
https://www.mysimilasan.com/distributeur-worden/

The background of the page is shown on Linkedin. I set all the right variables they have on there support page:
"Improve content sharing with Open Graph"
https://developer.linkedin.com/docs/share-on-linkedin

I waited 1,5 month because I thought it was a linkedin cache problem. But now the background image is still showing when trying to share this page.

it should share this image right:?

Anybody have ideas what I have done wrong here?
Or is this a Linkedin bug?

答:
og: tags are the right way to go, but they are not the only way to go.  After all, looking at your page, I see, in fact, that you are also using oEmbed.  Just look at this URL on your site:

https://www.mysimilasan.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.mysimilasan.com%2Fdistributeur-worden%2F

The above link is used on your page, because your HTML indicates it, as so...

```<code><link rel="alternate" type="application/json+oembed" href="https://www.mysimilasan.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.mysimilasan.com%2Fdistributeur-worden%2F" />
<link rel="alternate" type="text/xml+oembed" href="https://www.mysimilasan.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.mysimilasan.com%2Fdistributeur-worden%2F&format=xml" />
</code>```

And then looking at your oEmbed file itself, I see...

```<code>{
    ...
    thumbnail_url: "https://www.mysimilasan.com/wp-content/uploads/2018/01/swiss-bg-2.jpg",
    thumbnail_width: 600,
    thumbnail_height: 362
}
</code>```

Hey, that's the image that's showing up incorrectly!  That's where it's coming from!  I bet, if you change your oEmbed file, you'll make this work instantly!  (or, disable oEmbed, but let's go with the elegant solution)

To verify, I put your URL into the LinkedIn Post Inspector, and it gave a list of all possible files available for an icon, and why it chose that image.  Take a look!

Body:
og: tags are the right way to go, but they are not the only way to go.  After all, looking at your page, I see, in fact, that you are also using oEmbed.  Just look at this URL on your site:

https://www.mysimilasan.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.mysimilasan.com%2Fdistributeur-worden%2F

The above link is used on your page, because your HTML indicates it, as so...

<link rel="alternate" type="application/json+oembed" href="https://www.mysimilasan.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.mysimilasan.com%2Fdistributeur-worden%2F" />
<link rel="alternate" type="text/xml+oembed" href="https://www.mysimilasan.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.mysimilasan.com%2Fdistributeur-worden%2F&#038;format=xml" />

And then looking at your oEmbed file itself, I see...

{
    ...
    thumbnail_url: "https://www.mysimilasan.com/wp-content/uploads/2018/01/swiss-bg-2.jpg",
    thumbnail_width: 600,
    thumbnail_height: 362
}

Hey, that's the image that's showing up incorrectly!  That's where it's coming from!  I bet, if you change your oEmbed file, you'll make this work instantly!  (or, disable oEmbed, but let's go with the elegant solution)

To verify, I put your URL into the LinkedIn Post Inspector, and it gave a list of all possible files available for an icon, and why it chose that image.  Take a look!


问:
Time() By 5 Minutes Select
PHP Function to convert time() seconds to time format Hour:Minutes

```<code>function secondsToTime($seconds) {
 $dtF = new \DateTime('@0');
 $dtT = new \DateTime("@$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
 return $dtF->diff($dtT)->format('%h:%i');
}

echo secondsToTime(time());
</code>```

I need a function for something like:

```<code>If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50
</code>```

But the output to be show by time() format seconds so this way i can check via mysql how many rows updated from time() format show 23:45 if time now is 23:49 so in past 4 minutes ...

答:
You need to round the minutes and then reformat your output date.

There's some gotchas hidden in here. As you can end up with 60 minutes (should be 00) and 24 hours (also should be 00). So special checks are put in place to catch that.

Also, you way of getting the current time is very convoluted. Getting "now" gets the same value which is what DateTime() gets by default.

```<code>function secondsToTime() {
    $now      = new \DateTime();
    $cminutes = $now->format('i');
    $hour     = $now->format('H');
    $nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
    if ($nminutes > $cminutes) {
        $nminutes -= 5;
    }
    if ($nminutes === 60) {
        $nminutes = 0;
        $hour++;
    }
    if ($hour === 24) {
        $hour = 0;
    }
    return sprintf('%02d:%02d', $hour, $nminutes);
}

echo secondsToTime();
</code>```

Demo

Title: Time() By 5 Minutes Select

Body:
PHP Function to convert time() seconds to time format Hour:Minutes

function secondsToTime($seconds) {
 $dtF = new \DateTime('@0');
 $dtT = new \DateTime("@$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
 return $dtF->diff($dtT)->format('%h:%i');
}

echo secondsToTime(time());

I need a function for something like:

If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50

But the output to be show by time() format seconds so this way i can check via mysql how many rows updated from time() format show 23:45 if time now is 23:49 so in past 4 minutes ...

Body:
You need to round the minutes and then reformat your output date.

There's some gotchas hidden in here. As you can end up with 60 minutes (should be 00) and 24 hours (also should be 00). So special checks are put in place to catch that.

Also, you way of getting the current time is very convoluted. Getting "now" gets the same value which is what DateTime() gets by default.

function secondsToTime() {
    $now      = new \DateTime();
    $cminutes = $now->format('i');
    $hour     = $now->format('H');
    $nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
    if ($nminutes > $cminutes) {
        $nminutes -= 5;
    }
    if ($nminutes === 60) {
        $nminutes = 0;
        $hour++;
    }
    if ($hour === 24) {
        $hour = 0;
    }
    return sprintf('%02d:%02d', $hour, $nminutes);
}

echo secondsToTime();

Demo


答:
İn javascript  , remove  init();   or define init function.

try this:

```<code>function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);

function init(){
}
</code>```

Title: init function TypeError: Cannot read property 'style' of null

Body:
İn javascript  , remove  init();   or define init function.

try this:

function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);

function init(){
}


问:
Readability cs50 problem with float and round
I've tried everything but I can't figure out the bug in my code.

Getting the user inupt and counting the letters

```<code>int main(void)
{
int letters = 0;

//Getting user input
string text = get_string("Text: ");

//Counting the letters
for (int i = 0; i < strlen(text); i++)
{
    if (isalpha(text[i]))
    {
        letters++;
    }

}
</code>```

counting the words and the sentences

```<code>int words = 1;

//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
    if ((isspace(text[i])) && (isalpha(text[i+1])) )
    {
        words++;
    }
}

int sentences = 0;

//Checking the symbols and counting the sentences
for (int i = 0; i < strlen(text); i++)
{
    if (text[i] == '.' || text[i] == '!' || text[i] == '?')
    {
        sentences++;
    }
}
</code>```

And then applying the formula

```<code>double L = 100.0 * letters / words;
double S = 100.0 * sentences / words;

double index = 0.0588 * L - 0.296 * S - 15.8;

int trueIndex = round(index);

if (trueIndex >= 1 && trueIndex <= 16)
{
    printf("Grade %i\n", trueIndex);
}
else
{
    if (trueIndex < 1)
    {
        printf("Before Grade 1\n");
    }
    if (trueIndex > 16)
    {
        printf("Grade 16+\n");
    }
}
</code>```

}

It gives me this error: expected "Grade 8\n", not "Grade 9\n". I know it has something to do with how I handled floats but I don't understand what's wrong

答:
Try to delete (isalpha(text[i+1]) part from counting words. isalpha() will return true for alphabetical characters only, i.e. a - z , A - Z. For quotation mark will return false and won't count such word.

Alice was beginning to get very tired of sitting by her sister on the
  bank, and of having nothing to do: once or twice she had peeped into
  the book her sister was reading, but it had no pictures or
  conversations in it, "and what is the use of a book," thought Alice
  "without pictures or conversation?"

```<code>//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
    if (isspace(text[i]))
    {
        words++;
    }
}
</code>```

Body:
I've tried everything but I can't figure out the bug in my code.

Getting the user inupt and counting the letters

int main(void)
{
int letters = 0;

//Getting user input
string text = get_string("Text: ");

//Counting the letters
for (int i = 0; i < strlen(text); i++)
{
    if (isalpha(text[i]))
    {
        letters++;
    }

}

counting the words and the sentences

int words = 1;

//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
    if ((isspace(text[i])) && (isalpha(text[i+1])) )
    {
        words++;
    }
}

int sentences = 0;

//Checking the symbols and counting the sentences
for (int i = 0; i < strlen(text); i++)
{
    if (text[i] == '.' || text[i] == '!' || text[i] == '?')
    {
        sentences++;
    }
}

And then applying the formula

double L = 100.0 * letters / words;
double S = 100.0 * sentences / words;

double index = 0.0588 * L - 0.296 * S - 15.8;

int trueIndex = round(index);

if (trueIndex >= 1 && trueIndex <= 16)
{
    printf("Grade %i\n", trueIndex);
}
else
{
    if (trueIndex < 1)
    {
        printf("Before Grade 1\n");
    }
    if (trueIndex > 16)
    {
        printf("Grade 16+\n");
    }
}

}

It gives me this error: expected "Grade 8\n", not "Grade 9\n". I know it has something to do with how I handled floats but I don't understand what's wrong

Body:
Try to delete (isalpha(text[i+1]) part from counting words. isalpha() will return true for alphabetical characters only, i.e. a - z , A - Z. For quotation mark will return false and won't count such word.

Alice was beginning to get very tired of sitting by her sister on the
  bank, and of having nothing to do: once or twice she had peeped into
  the book her sister was reading, but it had no pictures or
  conversations in it, "and what is the use of a book," thought Alice
  "without pictures or conversation?"

//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
    if (isspace(text[i]))
    {
        words++;
    }
}


问:
AutoMapper - Map Many-to-Many Relationships
In my DAL, I have the following models establishing a many-to-many relationship.

```<code>public class FamilyMember
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}
public class FamilyMemberPhone
{
    public int FamilyMemberId { get; set; }
    public int PhoneId { get; set; }
    public FamilyMember FamilyMember { get; set; }
    public Phone Phone { get; set; }
}
public class Phone : AuditableEntity
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}
</code>```

In my DTO, I have the following classes

```<code>public class FamilyMemberDto
{
    public int Id { get; set; }
    public int FamilyId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public bool IsPrimary { get; set; }
    [Required]
    public List<Phone> FamilyMemberPhones { get; set; }
    public string FullName => $" {FirstName} {LastName}";
}
public class PhoneDto
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public PhoneType PhoneType { get; set; }
}
</code>```

My Mapping configuration looks like this:

```<code>CreateMap<Dal.Models.Phone, Dto.PhoneDto>().ReverseMap().IgnoreAuditableFields();

CreateMap<Dal.Models.FamilyMember, Dto.FamilyMemberDto>();

CreateMap<Dal.Models.FamilyMemberPhone, Dto.PhoneDto>()
            .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
            .ForMember(d => d.PhoneNumber, opt => opt.MapFrom(s => s.Phone.PhoneNumber))
            .ForMember(d => d.PhoneType, opt => opt.MapFrom(s => s.Phone.PhoneType));

CreateMap<Dto.FamilyMemberDto, Dal.Models.FamilyMember>()
            .AfterMap((s, d) =>
            {
                if (d.FamilyMemberPhones != null)
                    foreach (var fmp in d.FamilyMemberPhones)
                        fmp.Id = s.Id;
            });

CreateMap<Dto.PhoneDto, Dal.Models.FamilyMemberPhone>()
            .ForMember(d => d.PhoneId, opt => opt.MapFrom(s => s.Id));
</code>```

My Unit Test looks like this:

```<code>var member = new Bll.Dto.FamilyMemberDto
        {
            FamilyId = 12,
            FirstName = "Jane",
            LastName = "Doe",
            BirthDate = DateTime.Parse("11-01-1990"),
            Email = "test@test.com",
            FamilyMemberPhones = new List<Bll.Dto.PhoneDto>
            {
                new Bll.Dto.PhoneDto
                {
                    PhoneNumber = "test",
                    IsPreferred = true,
                },
                new Bll.Dto.Phone
                {
                    PhoneNumber = "hello",
                    IsPreferred = false,
                }
            }
        };
        await Manager.Save(member);
</code>```

When I'm trying to map the DTO to Model using Mapper.Map<Dal.Models.FamilyMember>(dto), in the entity.FamilyMemberPhones object, I see two items in the collection. However, digging deeper into the collection, all Dal.Models.Phone properties are null.

What am I doing wrong?

答:
From this area of your code

```<code>
CreateMap<Dto.FamilyMemberDto, Dal.Models.FamilyMember>()
            .AfterMap((s, d) =>
            {
                if (d.FamilyMemberPhones != null)
                    foreach (var fmp in d.FamilyMemberPhones)
                        fmp.Id = s.Id;
            });
</code>```

You are assigning a value to a variable created in a loop. That is fmp.Id = s.Id; maybe instead of s.Id = fmp.Id; or even something else. Because that doesn't look like you're doing anything there.

Body:
In my DAL, I have the following models establishing a many-to-many relationship.

public class FamilyMember
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}
public class FamilyMemberPhone
{
    public int FamilyMemberId { get; set; }
    public int PhoneId { get; set; }
    public FamilyMember FamilyMember { get; set; }
    public Phone Phone { get; set; }
}
public class Phone : AuditableEntity
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}

In my DTO, I have the following classes

public class FamilyMemberDto
{
    public int Id { get; set; }
    public int FamilyId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public bool IsPrimary { get; set; }
    [Required]
    public List<Phone> FamilyMemberPhones { get; set; }
    public string FullName => $" {FirstName} {LastName}";
}
public class PhoneDto
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public PhoneType PhoneType { get; set; }
}

My Mapping configuration looks like this:

CreateMap<Dal.Models.Phone, Dto.PhoneDto>().ReverseMap().IgnoreAuditableFields();

CreateMap<Dal.Models.FamilyMember, Dto.FamilyMemberDto>();

CreateMap<Dal.Models.FamilyMemberPhone, Dto.PhoneDto>()
            .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
            .ForMember(d => d.PhoneNumber, opt => opt.MapFrom(s => s.Phone.PhoneNumber))
            .ForMember(d => d.PhoneType, opt => opt.MapFrom(s => s.Phone.PhoneType));

CreateMap<Dto.FamilyMemberDto, Dal.Models.FamilyMember>()
            .AfterMap((s, d) =>
            {
                if (d.FamilyMemberPhones != null)
                    foreach (var fmp in d.FamilyMemberPhones)
                        fmp.Id = s.Id;
            });

CreateMap<Dto.PhoneDto, Dal.Models.FamilyMemberPhone>()
            .ForMember(d => d.PhoneId, opt => opt.MapFrom(s => s.Id));

My Unit Test looks like this:

var member = new Bll.Dto.FamilyMemberDto
        {
            FamilyId = 12,
            FirstName = "Jane",
            LastName = "Doe",
            BirthDate = DateTime.Parse("11-01-1990"),
            Email = "test@test.com",
            FamilyMemberPhones = new List<Bll.Dto.PhoneDto>
            {
                new Bll.Dto.PhoneDto
                {
                    PhoneNumber = "test",
                    IsPreferred = true,
                },
                new Bll.Dto.Phone
                {
                    PhoneNumber = "hello",
                    IsPreferred = false,
                }
            }
        };
        await Manager.Save(member);

When I'm trying to map the DTO to Model using Mapper.Map<Dal.Models.FamilyMember>(dto), in the entity.FamilyMemberPhones object, I see two items in the collection. However, digging deeper into the collection, all Dal.Models.Phone properties are null.

What am I doing wrong?

Body:
From this area of your code

CreateMap<Dto.FamilyMemberDto, Dal.Models.FamilyMember>()
            .AfterMap((s, d) =>
            {
                if (d.FamilyMemberPhones != null)
                    foreach (var fmp in d.FamilyMemberPhones)
                        fmp.Id = s.Id;
            });

You are assigning a value to a variable created in a loop. That is fmp.Id = s.Id; maybe instead of s.Id = fmp.Id; or even something else. Because that doesn't look like you're doing anything there.


问:
Rails translate rich text with Mobility and ActionText as backend?
Mobility has a syntax to translate Rails ActiveRecord strings and text:

class Word < ApplicationRecord
  extend Mobility
  translates :content
end
```

<p>On the other hand, here is the syntax to declare rich text with ActionText:</p>

<pre class="lang-rb prettyprint-override"><code>class Word < ApplicationRecord
  has_rich_text :content
end
</code>```

How can these be combined to efficiently translate rich text with Mobility? Ideally I want to avoid doing a double-join as suggested here in the context of Globalize, i.e. avoiding needing to join a translation table then joining a rich-text table.

There seems to be an opportunity to combine both steps using the ActionText table, which is already a polymorphic relationship similar to the key-value backend, so that the translation would be available "for free" with no performance impact compared to untranslated rich text.

答: I guess this is why action-text-attachment tag are not rendered in the views yet.

Body:
Mobility has a syntax to translate Rails ActiveRecord strings and text:

class Word < ApplicationRecord
  extend Mobility
  translates :content
end

On the other hand, here is the syntax to declare rich text with ActionText:

class Word < ApplicationRecord
  has_rich_text :content
end

How can these be combined to efficiently translate rich text with Mobility? Ideally I want to avoid doing a double-join as suggested here in the context of Globalize, i.e. avoiding needing to join a translation table then joining a rich-text table.

There seems to be an opportunity to combine both steps using the ActionText table, which is already a polymorphic relationship similar to the key-value backend, so that the translation would be available "for free" with no performance impact compared to untranslated rich text.


问:
Why does getch() output 10 characters on first run (line) but 9 characters for all following lines?
I have this program that create a new line after every 10 characters. However, once it hits the second iteration and there after it only outputs 9 characters. The program works if I set the second i to -1 but I do not understand why it will not work with i set to 0. The logic is the exact same as the first run as the first i is only run once, so when I want a new line I reset i. Can someone explain what I am missing? I drew out the steps on paper but it still doesn't make sense. Thank you.

```<code>#include <stdio.h>
#include <ncurses.h>

#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = 0;          // Counter is reset. To break out of the loop use CTRL + D.
         }
    }

    // to close curses terminal
    endwin();
}
</code>```

答: The first time through the loop i is zero. When you set i to zero inside the loop, when control reaches the end of the for, the statement executed is i++ (making i 1), then (c = getch()) != EOF

Body:
I have this program that create a new line after every 10 characters. However, once it hits the second iteration and there after it only outputs 9 characters. The program works if I set the second i to -1 but I do not understand why it will not work with i set to 0. The logic is the exact same as the first run as the first i is only run once, so when I want a new line I reset i. Can someone explain what I am missing? I drew out the steps on paper but it still doesn't make sense. Thank you.

#include <stdio.h>
#include <ncurses.h>

#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = 0;          // Counter is reset. To break out of the loop use CTRL + D.
         }
    }

    // to close curses terminal
    endwin();
}


答: The first iteration starts with i set to zero. When the test in the loop resets i to zero, the usual execution of i++ in the for loop still occurs, so the next iteration has i set to one, not zero.

Title: Why does getch() output 10 characters on first run (line) but 9 characters for all following lines?


问:
How to join three regexp
I have a code:

```<code>this.valor = String(this.valor).replace(/R\$/, '');
this.valor = String(this.valor).replace(/,/g, '');
this.valor = String(this.valor).replace(/\./g, '');
</code>```

Example: putR$1.000,00 and return 100000

How to convert in a one line?

答:
Simply use " | " between regular expressions to combine them. As for solution Hitmands answer is recommended

console.log("R$1.000,00".replace(/\.|R\$|\,/g,''))```

Title: How to join three regexp

Body:
I have a code:

this.valor = String(this.valor).replace(/R\$/, '');
this.valor = String(this.valor).replace(/,/g, '');
this.valor = String(this.valor).replace(/\./g, '');

Example: putR$1.000,00 and return 100000

How to convert in a one line?


问:
how to restart spring batch failed job with old job paramters
I am passing time in my job parameters .After running my job , i can see in console my job started with time parameters :-

Job: [FlowJob: [name=DB2-SQL-LOAD56]] launched with the following parameters: [{Time=1590853755581}]

I am wondering how can i restart the job if my job fails because everytime when my job fails , it runs a new instance since it picks up the current time (passed as job parameter)

How do i restart my failed job with old time parameter(mentioned above) ?

Do i need to add logic to accept time parameter in my code ? if yes , how do I handle that ?

I have attached my code. I would really appreciate if someone can help me what am i missing here in order to restart my failed job.

```<code>@SpringBootApplication
public class Db2MySqlLoadApplication implements CommandLineRunner {

@Autowired
private JobLauncher jobLauncher;

@Autowired
private Job job;

public static void main(String args[]) {
    SpringApplication.run(Db2MySqlLoadApplication.class, args);
}

@Override
public void run(String... args) throws Exception {

    JobParameters params = new JobParametersBuilder()
                    .addLong("Time" ,System.currentTimeMillis())
            .toJobParameters();
    jobLauncher.run(job, params);
}
}
</code>```

答:
Since you use Spring Boot, you don't really need to implement CommandLineRunner. Spring Boot already provides the JobLauncherCommandLineRunner that does that for you. What you can do is remove this run method (note that the args parameter is not used in your case) and launch your job from the command line with something like:

```<code>java -jar myjob.jar Time=$(date +%s)
</code>```

This example uses the date +%s command on unix/linux which gives the current date as a timestamp since the Unix epoch, you would need to look for an equivalent if you are on MS windows.

With that, if you want to restart a specific job instance with a previous Time parameter, you can pass the previous value as follows:

```<code>java -jar myjob.jar Time=1590853755581
</code>```

Body:
I am passing time in my job parameters .After running my job , i can see in console my job started with time parameters :-

Job: [FlowJob: [name=DB2-SQL-LOAD56]] launched with the following parameters: [{Time=1590853755581}]

I am wondering how can i restart the job if my job fails because everytime when my job fails , it runs a new instance since it picks up the current time (passed as job parameter)

How do i restart my failed job with old time parameter(mentioned above) ?

Do i need to add logic to accept time parameter in my code ? if yes , how do I handle that ?

I have attached my code. I would really appreciate if someone can help me what am i missing here in order to restart my failed job.

@SpringBootApplication
public class Db2MySqlLoadApplication implements CommandLineRunner {

@Autowired
private JobLauncher jobLauncher;

@Autowired
private Job job;

public static void main(String args[]) {
    SpringApplication.run(Db2MySqlLoadApplication.class, args);
}

@Override
public void run(String... args) throws Exception {

    JobParameters params = new JobParametersBuilder()
                    .addLong("Time" ,System.currentTimeMillis())
            .toJobParameters();
    jobLauncher.run(job, params);
}
}

Body:
Since you use Spring Boot, you don't really need to implement CommandLineRunner. Spring Boot already provides the JobLauncherCommandLineRunner that does that for you. What you can do is remove this run method (note that the args parameter is not used in your case) and launch your job from the command line with something like:

java -jar myjob.jar Time=$(date +%s)

This example uses the date +%s command on unix/linux which gives the current date as a timestamp since the Unix epoch, you would need to look for an equivalent if you are on MS windows.

With that, if you want to restart a specific job instance with a previous Time parameter, you can pass the previous value as follows:

java -jar myjob.jar Time=1590853755581


问:
gitlab-runner cannot clone due to expired root certificate
I have this error while cloning on gitlab ci:

unable to access 'https://gitlab-ci-token:[secure]@git.mydomain.com/mydomain/api.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none.

```

My Root CA has expired today the 30th  and thus must have been removed from my keychain.

I have upgraded my certificates (debian) and all seems fines except this error does not go away in my dockerized gitlab-runner.

How can I fix it?

答:
This is a problem on the server side, and it needs to be fixed by replacing the chain of CA certificates.

Because Sectigo knew that this root certificate would expire soon, several years ago, they created a new root certificate and registered it with all the major browser vendors and OS manufacturers.  However, because many older systems don't upgrade their certificates, this new root CA was signed by an older CA, a process called cross-signing.  This allows people to use the new root for issuing certificates yet remain compatible with older systems.

Any systems on the Internet today can no longer handle the legacy root because it's now expired, so there's no benefit to using it anymore.

Some TLS libraries can figure out that a certificate chains to a trusted root and ignore the extra, expired root certificates, but some cannot.  As a result, the fact that you have the old AddTrust External Root CA certificate in your certificate chain can break some of those TLS libraries, which is what's happening here.

Sectigo has documentation on this issue.  You want to remove the AddTrust CA certificate and make sure that the UserTrust or COMODO root that you're using is self-signed.  If you're using a Debian or Ubuntu system, you may be able to find the appropriate root certificate in /etc/ssl/certs.

Even better, you can just remove the root certificate altogether and only include intermediates, since the root certificate isn't actually needed when creating the TLS connection, since the client must already have it.

Body:
I have this error while cloning on gitlab ci:

unable to access 'https://gitlab-ci-token:[secure]@git.mydomain.com/mydomain/api.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none.

My Root CA has expired today the 30th  and thus must have been removed from my keychain.

I have upgraded my certificates (debian) and all seems fines except this error does not go away in my dockerized gitlab-runner.

How can I fix it?


问:
Splitting a string_view using ranges
I have a string containing a sequence of numbers separated with the , character. To read values from the sequence into an array I created the following code the GCC 10 refuses to compile:

```<code>#include <ranges>
#include <string_view>
#include <charconv>
#include <array>

template<std::size_t Sz>
bool to_bytes(std::array<std::uint8_t, Sz> &data, std::string_view string) {
    auto target = data.rbegin();
    for (const auto octet : string | std::views::split('.')) {
        if (target == data.rend()) {
            return false;
        }

        const auto octet_begin = octet.data();
        const auto octet_end = octet_begin + octet.size();
        const auto error = std::error_code(std::from_chars(octet_begin, octet_end, *target).ec);
        if (error) {
            return false;
        }

        ++target;
    }

    return target == data.rend();
}
</code>```

Briefly speaking the compiler complains that there are no data() and size() methods available for the type of the octet variable. Do I misunderstand that type of octet should meet the contiguous_range criteria as the string_view does? It seems to be argumentative from my POV.

答:
After the adoption of P2210 as a defect report against C++20, views::split can now preserve contiguity, so the above code is now valid and compiles on gcc trunk.

Do I misunderstand that type of octet should meet the contiguous_range criteria as the string_view does?

Yes. octet is not a contiguous_range. The inner range of a split_view is never stronger than a forward_range - it is only ever a forward_range or an input_range.

This makes views::split exceedingly awkward to use for any kind of non-trivial parsing - precisely because, as you demonstrate in the question, you can't use things like from_chars (or scanf or ... ) unless you then manually produce a contiguous range out of it.

Title: Splitting a string_view using ranges

Body:
I have a string containing a sequence of numbers separated with the , character. To read values from the sequence into an array I created the following code the GCC 10 refuses to compile:

#include <ranges>
#include <string_view>
#include <charconv>
#include <array>

template<std::size_t Sz>
bool to_bytes(std::array<std::uint8_t, Sz> &data, std::string_view string) {
    auto target = data.rbegin();
    for (const auto octet : string | std::views::split('.')) {
        if (target == data.rend()) {
            return false;
        }

        const auto octet_begin = octet.data();
        const auto octet_end = octet_begin + octet.size();
        const auto error = std::error_code(std::from_chars(octet_begin, octet_end, *target).ec);
        if (error) {
            return false;
        }

        ++target;
    }

    return target == data.rend();
}

Briefly speaking the compiler complains that there are no data() and size() methods available for the type of the octet variable. Do I misunderstand that type of octet should meet the contiguous_range criteria as the string_view does? It seems to be argumentative from my POV.


问:
Searching NTFS directory .NET
I would like to write a web page where users can search a directory on NTFS for certain criteria and display the results.

Does the directory have to be indexed?

Is there a .NET accessible windows search API that I can use to query the directory?

答:
If you are using .NET 2.0 or greater (and VB.Net) then you can use the
My.Computer.FileSystem.GetFiles Method. This method has three parameters:

Directory

SearchType (enumeration)

Wildcards

The SearchType enumeration has two values one of which is SearchAllSubDirectories.  So 1 method which returns a ReadOnly String Collection of all the file (names) that match.

If you are using C# then you could use the DirectoryInfo.GetFiles Method .  There are only 2 parameters with DirectoryInfo.GetFiles:

SearchPattern

SearchOption

If you specify AllDirectories for the SearchOption you'd get a similar result.

The key difference being that the FileSystem.GetFiles returns as Collection of Strings while the DirectoryInfo.GetFiles returns an array of FileInfo Objects.

ContentLicense: CC BY-SA 2.5

Title: Searching NTFS directory .NET

OwnerDisplayName: CertifiedCrazy

LastEditorDisplayName: CertifiedCrazy


答:
However, instead of doing that, why can't we declare a static array like this:

Because the language rules say so. In C++, the size of all variables must be known at compile time.

Note that if you declare an array like that (if the size was known at compile time), the array would have automatic storage, not static storage.

What is the advantage of dynamic arrays in this case then?

The advantage is that the size of a dynamic array doesn't need to be known at compile time.

Furthermore, the amount of automatic storage is very limited typically, while dynamic storage is not. Creating large arrays with automatic storage has high chance of causing a stack overflow.

Title: Difference between dynamically allocated arrays and static arrays

Body:
I am getting an introduction to dynamic memory allocation, and I learned that a dynamic array ( the one like int *p = new int[n] \\ where n is the user input describing the number of elements is used when you do not know how many elements the user requires/ declaring an array of a size that the user wants. However, instead of doing that, why can't we declare a static array like this:

int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];

What is the advantage of dynamic arrays in this case then? I am not understanding this concept.

Edit : Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

int main(){
    int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
    cout << "Enter your numbers : " <<endl;
    for (int i=0;i<=n;i++){
        cin>>a[i];
    }
    for (int i=0;i<=n;i++){
        cout<<a[i]<<endl;
    }
}


问:
Distinguish 1 from True in python 3.8
I have some code where I want to do different things if a particular input variable is 1 vs True.  (In short numbers refer to which of several objects to do something on, and True means do it to all the objects, but that's not particularly relevant to this question.)

Currently, I used more or less the equivalent of:

```<code>if x is True:
   # Do something
elif x is 1:
   # Do something else
else:
   # More possibilities follow...
</code>```

But in Python 3.8, I'm now getting

```<code>SyntaxWarning: "is" with a literal. Did you mean "=="?
</code>```

Well, no I didn't.  Using == doesn't distinguish True and 1, since True == 1 in python.

But it sounds like the python devs think using is with a literal is always a bug. It's just a warning, not an error, so I'm still fine for now, but what is the non-buggy way to do this that I should switch to?

答:
Perhaps cleaner than your mixed approach would be to explicitly test the type:

```<code>>>> type(1) == bool
False
>>> type(1) == int
True
>>>
>>> type(True) == bool
True
>>> type(True) == int
False
</code>```

Title: Distinguish 1 from True in python 3.8

Body:
I have some code where I want to do different things if a particular input variable is 1 vs True.  (In short numbers refer to which of several objects to do something on, and True means do it to all the objects, but that's not particularly relevant to this question.)

Currently, I used more or less the equivalent of:

if x is True:
   # Do something
elif x is 1:
   # Do something else
else:
   # More possibilities follow...

But in Python 3.8, I'm now getting

SyntaxWarning: "is" with a literal. Did you mean "=="?

Well, no I didn't.  Using == doesn't distinguish True and 1, since True == 1 in python.

But it sounds like the python devs think using is with a literal is always a bug. It's just a warning, not an error, so I'm still fine for now, but what is the non-buggy way to do this that I should switch to?

Body:
Perhaps cleaner than your mixed approach would be to explicitly test the type:

>>> type(1) == bool
False
>>> type(1) == int
True
>>>
>>> type(True) == bool
True
>>> type(True) == int
False


答:
You could try something like this,
however, I don't feel like I should suggest you to go down this path.

Blindly stripping , and . out might lead to wrong data,
it seems like you are parsing a currency here and $1.000,00 doeesn't necessarily equal to 100000

const sanitize = (string) => string.replace(/[R$.,]/g, '');

console.log(sanitize('R$1.000,00'));```

Title: How to join three regexp


问:
I have a question about C ++ boost :: asio and std :: async
I know that both are designed asynchronously.

What I'm curious about is the function callback when creating a thread using the above two.

Is it possible for a single thread to write and read asynchronously?

答:
Yes. In fact I have many examples of that on this site.

I wrote one yesterday that starts out with true single-threading:

How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server

Note that you can easily also do multi-client servers on a single thread:

Boost.Asio: Is it a good thing to use a `io_service` per connection/socket?

With a twist (because it wants to synchronize writing to all clients) Thread-safety when accessing data from N-theads in context of an async TCP-server

There must be many more, but these are the first hits I see.


问:
What is efficient way to check if current word is close to a word in string?
consider examples below :

Example 1 :

```<code>str1 = "wow...it  looks amazing"
str2 = "looks amazi"
</code>```

You see that amazi is close to amazing, str2 is mistyped, i wanted to write a program that will tell me that amazi is close to amazing then in str2 i will replace amazi with amazing

Example 2 :

```<code>str1 = "is looking good"
str2 = "looks goo"
</code>```

In this case updated str2 will be "looking good"

Example 3 :

```<code>str1 = "you are really looking good"
str2 = "lok goo"
</code>```

In this case str2 will be "good" as lok is not close to looking (or even if program can convert in this case lok to looking then it's just fine for my  problem's solution)

Example 4 :

```<code>str1 = "Stu is actually SEVERLY sunburnt....it hurts!!!"
str2 = "hurts!!"
</code>```

Updated str2 will be "hurts!!!"

Example 5 :

```<code>str1 = "you guys were absolutely amazing tonight, a..."
str2 = "ly amazin"
</code>```

Updated str2 will be "amazing", "ly" shall be removed or replace by absolutely.

What will be the  algo and  code for this?

Maybe we can do it by looking at character lexicographically and set a
threshold like 0.8 or 80% so if word2 gets 80% sequential characters of word1 from str1 then we replace word2 in str2 with word of str1?
Any other efficient solution with python code please?

答:
I made through it with regular expressions

```<code>def check_regex(str1,str2):
    #New list to store the updated value
    str_new = []
    for i in str2:
        # regular expression for comparing the strings
        x = ['['+i+']','^'+i,i+'$','('+i+')']
        for k in x:
            h=0
            for j in str1:
                #Conditions to make sure the word is close enough to the particular word
                if "".join(re.findall(k,j)) == i or ("".join(re.findall(k,j)) in i and abs(len("".join(re.findall(k,j)))-len(i)) == 1 and len(i)!=2):
                    str_new.append(j)
                    h=1
                    break
            if h==1:
                break
    return str_new
import re
str1 = input().split()
str2 = input().split()
print(" ".join(check_regex(str1,str2)))
</code>```

Body:
consider examples below :

Example 1 :

str1 = "wow...it  looks amazing"
str2 = "looks amazi"

You see that amazi is close to amazing, str2 is mistyped, i wanted to write a program that will tell me that amazi is close to amazing then in str2 i will replace amazi with amazing

Example 2 :

str1 = "is looking good"
str2 = "looks goo"

In this case updated str2 will be "looking good"

Example 3 :

str1 = "you are really looking good"
str2 = "lok goo"

In this case str2 will be "good" as lok is not close to looking (or even if program can convert in this case lok to looking then it's just fine for my  problem's solution)

Example 4 :

str1 = "Stu is actually SEVERLY sunburnt....it hurts!!!"
str2 = "hurts!!"

Updated str2 will be "hurts!!!"

Example 5 :

str1 = "you guys were absolutely amazing tonight, a..."
str2 = "ly amazin"

Updated str2 will be "amazing", "ly" shall be removed or replace by absolutely.

What will be the  algo and  code for this?

Maybe we can do it by looking at character lexicographically and set a
threshold like 0.8 or 80% so if word2 gets 80% sequential characters of word1 from str1 then we replace word2 in str2 with word of str1?
Any other efficient solution with python code please?

Body:
I made through it with regular expressions

def check_regex(str1,str2):
    #New list to store the updated value
    str_new = []
    for i in str2:
        # regular expression for comparing the strings
        x = ['['+i+']','^'+i,i+'$','('+i+')']
        for k in x:
            h=0
            for j in str1:
                #Conditions to make sure the word is close enough to the particular word
                if "".join(re.findall(k,j)) == i or ("".join(re.findall(k,j)) in i and abs(len("".join(re.findall(k,j)))-len(i)) == 1 and len(i)!=2):
                    str_new.append(j)
                    h=1
                    break
            if h==1:
                break
    return str_new
import re
str1 = input().split()
str2 = input().split()
print(" ".join(check_regex(str1,str2)))