问:
Semantic Segmentation Model's loss and binary IOU are not improving
I am new to machine learning and I am trying to make a semantic segmentation model for detecting couches in images. However, my validation loss and training loss are stuck at around 0.25, and my validation binary IoU and training binary IoU are stuck at around 0.7. Here is the code for my model and my training parameters.

```<code>def upsample(filters, size, norm_type='batchnorm', apply_dropout=False, kernel_regularizer=None):
    """Upsamples an input.
    Conv2DTranspose => Batchnorm => Dropout => Relu
    Args:
    filters: number of filters
    size: filter size
    norm_type: Normalization type; either 'batchnorm' or 'instancenorm'.
    apply_dropout: If True, adds the dropout layer
    Returns:
    Upsample Sequential Model
    """

    initializer = tf.random_normal_initializer(0., 0.02)

    result = tf.keras.Sequential()
    result.add(
      tf.keras.layers.Conv2DTranspose(filters, size, strides=2,
                                      padding='same',
                                      kernel_initializer=initializer,
                                      kernel_regularizer=kernel_regularizer,
                                      use_bias=False))

    if norm_type.lower() == 'batchnorm':
        result.add(tf.keras.layers.BatchNormalization())
    elif norm_type.lower() == 'instancenorm':
        result.add(InstanceNormalization())

    if apply_dropout:
        result.add(tf.keras.layers.Dropout(0.3))
    result.add(tf.keras.layers.ReLU())

    return result

class Unet:
    output_channels = 1

    def __init__(self):
        base_model = tf.keras.applications.MobileNetV2(input_shape=[224, 224, 3], include_top=False)

        # Use the activations of these layers
        layer_names = [
            'block_1_expand_relu',
            'block_3_expand_relu',
            'block_6_expand_relu',
            'block_13_expand_relu',
            'block_16_project',
        ]
        base_model_outputs = [base_model.get_layer(name).output for name in layer_names]

        # Create the feature extraction model
        down_stack = tf.keras.Model(inputs=base_model.input, outputs=base_model_outputs)

        down_stack.trainable = False

        up_stack = [
            upsample(1024, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
            upsample(512, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
            upsample(256, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
            upsample(128, 3, norm_type='batchnorm', apply_dropout=False, kernel_regularizer="l2"),
            upsample(64, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
        ]
        inputs = tf.keras.layers.Input(shape=[224, 224, 3])

        # Downsampling through the model
        skips = down_stack(inputs)
        x = skips[-1]
        skips = reversed(skips[:-1])

        # Upsampling and establishing the skip connections
        for up, skip in zip(up_stack, skips):
          x = up(x)
          concat = tf.keras.layers.Concatenate()
          x = concat([x, skip])

        last = tf.keras.layers.Conv2DTranspose(
            self.output_channels,
            kernel_size=3, strides=2,
            padding='same', activation='sigmoid')

        x = last(x)

        optimizer = tf.keras.optimizers.Nadam(1e-4)
        metrics = [tf.keras.metrics.BinaryIoU(target_class_ids=[0, 1], threshold=0.5)]

        self.model = tf.keras.Model(inputs=inputs, outputs=x)

        self.model.compile(
                  optimizer=optimizer,
                  loss=tf.keras.losses.BinaryCrossentropy(),
                  metrics=metrics)

def train():
    batch_size = 4
    EPOCHS = 250
    VAL_SUBSPLITS = 2
    VALIDATION_STEPS = dataset_size // batch_size // VAL_SUBSPLITS
    STEPS_PER_EPOCH = train_dataset_size // batch_size
    unet.load_weights('./checkpoints/my_checkpoint')

    history = unet.fit(train_gen, epochs=EPOCHS,
                       steps_per_epoch=STEPS_PER_EPOCH,
                       validation_steps=VALIDATION_STEPS,
                       validation_data=val_gen,
                       callbacks=[
                                  ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=4),
                                  EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=False)
                                  ],
                       )

</code>```

Are there any tips to improve my model?

Current output: https://imgur.com/a/5Jqn1oX

What I've tried:

Augmented my data generator which is based from the COCO dataset

Used an Adam optimizer with an exponential decaying learning rate schedule

Increased batch size from 4 to 32

Used learning rates from 0.01 to 0.0000001

Body:
I am new to machine learning and I am trying to make a semantic segmentation model for detecting couches in images. However, my validation loss and training loss are stuck at around 0.25, and my validation binary IoU and training binary IoU are stuck at around 0.7. Here is the code for my model and my training parameters.

def upsample(filters, size, norm_type='batchnorm', apply_dropout=False, kernel_regularizer=None):
    """Upsamples an input.
    Conv2DTranspose => Batchnorm => Dropout => Relu
    Args:
    filters: number of filters
    size: filter size
    norm_type: Normalization type; either 'batchnorm' or 'instancenorm'.
    apply_dropout: If True, adds the dropout layer
    Returns:
    Upsample Sequential Model
    """

    initializer = tf.random_normal_initializer(0., 0.02)

    result = tf.keras.Sequential()
    result.add(
      tf.keras.layers.Conv2DTranspose(filters, size, strides=2,
                                      padding='same',
                                      kernel_initializer=initializer,
                                      kernel_regularizer=kernel_regularizer,
                                      use_bias=False))

    if norm_type.lower() == 'batchnorm':
        result.add(tf.keras.layers.BatchNormalization())
    elif norm_type.lower() == 'instancenorm':
        result.add(InstanceNormalization())

    if apply_dropout:
        result.add(tf.keras.layers.Dropout(0.3))
    result.add(tf.keras.layers.ReLU())

    return result

class Unet:
    output_channels = 1

    def __init__(self):
        base_model = tf.keras.applications.MobileNetV2(input_shape=[224, 224, 3], include_top=False)

        # Use the activations of these layers
        layer_names = [
            'block_1_expand_relu',
            'block_3_expand_relu',
            'block_6_expand_relu',
            'block_13_expand_relu',
            'block_16_project',
        ]
        base_model_outputs = [base_model.get_layer(name).output for name in layer_names]

        # Create the feature extraction model
        down_stack = tf.keras.Model(inputs=base_model.input, outputs=base_model_outputs)

        down_stack.trainable = False

        up_stack = [
            upsample(1024, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
            upsample(512, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
            upsample(256, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
            upsample(128, 3, norm_type='batchnorm', apply_dropout=False, kernel_regularizer="l2"),
            upsample(64, 3, norm_type='batchnorm', apply_dropout=True, kernel_regularizer="l2"),
        ]
        inputs = tf.keras.layers.Input(shape=[224, 224, 3])

        # Downsampling through the model
        skips = down_stack(inputs)
        x = skips[-1]
        skips = reversed(skips[:-1])

        # Upsampling and establishing the skip connections
        for up, skip in zip(up_stack, skips):
          x = up(x)
          concat = tf.keras.layers.Concatenate()
          x = concat([x, skip])

        last = tf.keras.layers.Conv2DTranspose(
            self.output_channels,
            kernel_size=3, strides=2,
            padding='same', activation='sigmoid')

        x = last(x)

        optimizer = tf.keras.optimizers.Nadam(1e-4)
        metrics = [tf.keras.metrics.BinaryIoU(target_class_ids=[0, 1], threshold=0.5)]

        self.model = tf.keras.Model(inputs=inputs, outputs=x)

        self.model.compile(
                  optimizer=optimizer,
                  loss=tf.keras.losses.BinaryCrossentropy(),
                  metrics=metrics)

def train():
    batch_size = 4
    EPOCHS = 250
    VAL_SUBSPLITS = 2
    VALIDATION_STEPS = dataset_size // batch_size // VAL_SUBSPLITS
    STEPS_PER_EPOCH = train_dataset_size // batch_size
    unet.load_weights('./checkpoints/my_checkpoint')

    history = unet.fit(train_gen, epochs=EPOCHS,
                       steps_per_epoch=STEPS_PER_EPOCH,
                       validation_steps=VALIDATION_STEPS,
                       validation_data=val_gen,
                       callbacks=[
                                  ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=4),
                                  EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=False)
                                  ],
                       )

Are there any tips to improve my model?

Current output: https://imgur.com/a/5Jqn1oX

What I've tried:

Augmented my data generator which is based from the COCO dataset

Used an Adam optimizer with an exponential decaying learning rate schedule

Increased batch size from 4 to 32

Used learning rates from 0.01 to 0.0000001


来源: stackexchange

问:
How to handle 0E-8 in Hive query
I am running an Sql query and extracting the result in Excel.In Excel, particular column was showing as Exponential format(0E-8).Column datatype has Decimal(31,8).

I have tried below:

```<code>cast(column as double)
</code>```

Result was showing as 0[If column has 0.00000000].
If my Excel need to be show like 0.00000000[Exact same has DB has],how we can handle in query.

ContentLicense: CC BY-SA 4.0

Title: How to handle 0E-8 in Hive query

Body:
I am running an Sql query and extracting the result in Excel.In Excel, particular column was showing as Exponential format(0E-8).Column datatype has Decimal(31,8).

I have tried below:

cast(column as double)

Result was showing as 0[If column has 0.00000000].
If my Excel need to be show like 0.00000000[Exact same has DB has],how we can handle in query.


问:
Channel behavior in subtest differs from production (unbuffered but receiving many times)
I have this functionality that works well in production, and worked well in some basic tests. I have tried converting into a table-based test but I am getting issues. The code involved is fairly large for SO but I will try to sketch out the details:

The function "sendReadyUpPrompt":

func (w *webServer) sendReadyUpPrompt(m *Match) {
    for _, player := range w.getPlayerConns(m) {
        if player == nil {
            log.Println("Couldn't send rup signal to player (no connection object)", player)
        } else {
            player.sendJSON <- NewRupSignalMsg(true, false, w.rupTime)
        }
    }
    m.timer = time.NewTimer(time.Second * time.Duration(w.rupTime))
    m.Status = matchRupSignal

    p1 := m.players[0].Connection
    p2 := m.players[1].Connection
    p1ready := false
    p2ready := false
    for !(p1ready && p2ready) { //while not both players readied
        select {
            case <- m.timer.C: //Block until timer reaches maturity
                log.Println("Timer expired in rup. ready states:", p1ready, p2ready)
                w.expireRup(m, p1ready, p2ready)
                return
            case <- p1.playerReady:
                p1ready = true
                log.Println("player 1 has readied") //In production this only prints once, but in the table driven tests it prints multiple times per any given test.
            case <- p2.playerReady:
                p2ready = true
                log.Println("player 2 has readied")
        }
    }
    log.Println("both players have readied")
    w.expireRup(m, false, false)
    w.initializeMatch(m)
}
```
<p>This waits for messages to come across two channels or a timer to expire to determine whether two players are ready for a game. It is run as a goroutine.
In a production environment, where I am sending on the playerReady channels like this:</p>
<pre class="lang-golang prettyprint-override"><code>if i receive a json message from a client called "ready" {
    conn.playerReady <- true
}
</code>```

I get a normal output where one message of "player 2 has readied" is logged.
In a test environment I get something like this for test B but not for the other tests:

```<code>2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
</code>```

Interspersed with this I get messages from the objects in the previous tests that are closing

```<code>2023/01/01 21:20:51 Removed connection 1 from game hub //this should be logged after calling gameConn.Close() at the end of the previous subtest
2023/01/01 21:20:51 player 2 has readied
2023/01/01 21:20:51 player 2 has readied
2023/01/01 21:20:51 Removed connection Mario from user hub //same for this
</code>```

How can that be? Shouldn't one test finish and its objects complete their Closing duties before the next test?

And now here is my embarrassing test

func TestTableRUP(t *testing.T) {
    type rupper map[string]int //key: id, int: seconds after signal to rup
    type exq map[string]bool

    var tests = []struct{
        name string
        responders rupper
        matchOrQueue string
        expectedQueue exq
    }{
        {name: "A", responders: make(rupper), matchOrQueue: "q", expectedQueue: make(exq)},
        {name: "B", responders: rupper{"Mario": 1}, matchOrQueue: "q", expectedQueue: exq{"Mario": true}},
        {name: "C", responders: rupper{"Mario": 1, "Luigi": 1}, matchOrQueue: "m", expectedQueue: make(exq)}, //after put in a match, q should be empty
        {name: "D", responders: rupper{"Mario": 1, "Luigi": 6}, matchOrQueue: "q", expectedQueue: exq{"Mario": true}},
    }
    for _, test := range tests {
        test := test
        t.Run(test.name, func(t *testing.T) {
            t.Log("~~~~~~~~~~~~~Running test", test.name)
            mgeme := newWebServer()
            //these lines create a gin engine I can connect to with createOneUser
            sv := createServerHandler(mgeme, defaultErrHandler, t)
            //launch the engine and create a user's game server (necessary for the test)
            gameConn, server := createServerAndGameConns(sv, t)
            //create two users using websocket.DefaultDialer.Dial()
            wsConnA := createOneUser(t, server, "Luigi")
            wsConnB := createOneUser(t, server, "Mario")

            //Add two players to queue
            players := make(map[string]*connection)
            var mario *connection
            var luigi *connection

            player_cond := func() bool {
                mario, _ = mgeme.playerHub.findConnection("Mario")
                luigi, _ = mgeme.playerHub.findConnection("Luigi")
                return mario != nil && luigi != nil
            }

            require.Eventuallyf(t, player_cond, 1 * time.Second, 1 * time.Millisecond, "Player conns shouldn't be nil in test %s", test.name)
            //put my two players in a gamequeue so when i send a ready up signal they can receive it
            mgeme.queueUpdate(true, mario)
            mgeme.queueUpdate(true, luigi)
            players["Mario"] = mario
            players["Luigi"] = luigi
            //create a match using the two players in the queue
            match, err := mgeme.dummyMatch()
            require.NoErrorf(t, err, "Error forming dummy match: %v", err)
            //send ready up prompt to the two players in the queue
            go mgeme.sendReadyUpPrompt(match)
            //one of the players will wait for a json message here so they know to respond to the rup signal
            msg := readWaitFor(wsConnA, "RupSignal", t, false)
            var rs RupSignal
            json.Unmarshal(msg, &rs)
            t.Logf("Rup signal: %v", rs)
            expected_rs := NewRupSignalMsg(true, false, mgeme.rupTime)
            require.EqualValues(t, expected_rs, rs, "Rup signal value not what was expected")

            //each player will now respond (on time or late) or ignore the signal.
            var wg sync.WaitGroup
            for id, conn := range players {
                wg.Add(1)
                go func(id string, conn *connection) { //<------------- potentially of interest
                    defer wg.Done()
                    seconds, exists := test.responders[id] //see how many seconds each player should wait before responding for this test
                    if exists {
                        <-time.After(time.Duration(seconds) * time.Second) //wait either 1 or 6 seconds (at 5, the ready up signal expires and the player's ready signal is ignored (that blocks due to being unbuffered but thats unrelated to this question at this point. in the tests where the players respond on time or dont respond at all i am getting odd behavior)
                        t.Log("Sending rup signal....")
                        conn.playerReady <- true //<------------- potentially of interest
                    }
                }(id, conn)
            }
            wg.Wait()
            //here i am testing how the server has handled a cancelled ready up signal
            //players that ready upped should be placed back in the queue but the
            //ones who didnt should be left out
            queue_cond := func() bool {
                mgeme.queueMutex.RLock()
                _, mq := mgeme.gameQueue["Mario"]
                _, lq := mgeme.gameQueue["Luigi"]
                mgeme.queueMutex.RUnlock()
                return (test.expectedQueue["Mario"] == mq && test.expectedQueue["Luigi"] == lq)
            }
            require.Eventuallyf(t, queue_cond, 5500 * time.Millisecond, 10*time.Millisecond, "Queues should be equal in test %s", test.name)
            //in one of the tests we don't just want to know the queue, we want to know if the match creation processes completed when both players readied in time
            if test.matchOrQueue == "m" {
                _, obj := mgeme.gameServerHub.findConnection("1")
                <-time.After(500 * time.Millisecond)
                require.True(t, obj.(*gameServer).findMatchByPlayer("Mario") != -1)
            }

            gameConn.Close()
            wsConnA.Close()
            wsConnB.Close()
            server.Close()
        })
    }
}
```

To some my question up, look again at the part of my test where i have a goroutine send, at most, one message on .playerReady per player. But my test logs out a lot of messages that it received this. What is causing this discrepancy between my production execution and my test?

Body:
I have this functionality that works well in production, and worked well in some basic tests. I have tried converting into a table-based test but I am getting issues. The code involved is fairly large for SO but I will try to sketch out the details:

The function "sendReadyUpPrompt":

func (w *webServer) sendReadyUpPrompt(m *Match) {
    for _, player := range w.getPlayerConns(m) {
        if player == nil {
            log.Println("Couldn't send rup signal to player (no connection object)", player)
        } else {
            player.sendJSON <- NewRupSignalMsg(true, false, w.rupTime)
        }
    }
    m.timer = time.NewTimer(time.Second * time.Duration(w.rupTime))
    m.Status = matchRupSignal

    p1 := m.players[0].Connection
    p2 := m.players[1].Connection
    p1ready := false
    p2ready := false
    for !(p1ready && p2ready) { //while not both players readied
        select {
            case <- m.timer.C: //Block until timer reaches maturity
                log.Println("Timer expired in rup. ready states:", p1ready, p2ready)
                w.expireRup(m, p1ready, p2ready)
                return
            case <- p1.playerReady:
                p1ready = true
                log.Println("player 1 has readied") //In production this only prints once, but in the table driven tests it prints multiple times per any given test.
            case <- p2.playerReady:
                p2ready = true
                log.Println("player 2 has readied")
        }
    }
    log.Println("both players have readied")
    w.expireRup(m, false, false)
    w.initializeMatch(m)
}

This waits for messages to come across two channels or a timer to expire to determine whether two players are ready for a game. It is run as a goroutine.
In a production environment, where I am sending on the playerReady channels like this:

if i receive a json message from a client called "ready" {
    conn.playerReady <- true
}

I get a normal output where one message of "player 2 has readied" is logged.
In a test environment I get something like this for test B but not for the other tests:

2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied
2023/01/01 21:07:31 player 2 has readied

Interspersed with this I get messages from the objects in the previous tests that are closing

2023/01/01 21:20:51 Removed connection 1 from game hub //this should be logged after calling gameConn.Close() at the end of the previous subtest
2023/01/01 21:20:51 player 2 has readied
2023/01/01 21:20:51 player 2 has readied
2023/01/01 21:20:51 Removed connection Mario from user hub //same for this

How can that be? Shouldn't one test finish and its objects complete their Closing duties before the next test?

And now here is my embarrassing test

func TestTableRUP(t *testing.T) {
    type rupper map[string]int //key: id, int: seconds after signal to rup
    type exq map[string]bool

    var tests = []struct{
        name string
        responders rupper
        matchOrQueue string
        expectedQueue exq
    }{
        {name: "A", responders: make(rupper), matchOrQueue: "q", expectedQueue: make(exq)},
        {name: "B", responders: rupper{"Mario": 1}, matchOrQueue: "q", expectedQueue: exq{"Mario": true}},
        {name: "C", responders: rupper{"Mario": 1, "Luigi": 1}, matchOrQueue: "m", expectedQueue: make(exq)}, //after put in a match, q should be empty
        {name: "D", responders: rupper{"Mario": 1, "Luigi": 6}, matchOrQueue: "q", expectedQueue: exq{"Mario": true}},
    }
    for _, test := range tests {
        test := test
        t.Run(test.name, func(t *testing.T) {
            t.Log("~~~~~~~~~~~~~Running test", test.name)
            mgeme := newWebServer()
            //these lines create a gin engine I can connect to with createOneUser
            sv := createServerHandler(mgeme, defaultErrHandler, t)
            //launch the engine and create a user's game server (necessary for the test)
            gameConn, server := createServerAndGameConns(sv, t)
            //create two users using websocket.DefaultDialer.Dial()
            wsConnA := createOneUser(t, server, "Luigi")
            wsConnB := createOneUser(t, server, "Mario")

            //Add two players to queue
            players := make(map[string]*connection)
            var mario *connection
            var luigi *connection

            player_cond := func() bool {
                mario, _ = mgeme.playerHub.findConnection("Mario")
                luigi, _ = mgeme.playerHub.findConnection("Luigi")
                return mario != nil && luigi != nil
            }

            require.Eventuallyf(t, player_cond, 1 * time.Second, 1 * time.Millisecond, "Player conns shouldn't be nil in test %s", test.name)
            //put my two players in a gamequeue so when i send a ready up signal they can receive it
            mgeme.queueUpdate(true, mario)
            mgeme.queueUpdate(true, luigi)
            players["Mario"] = mario
            players["Luigi"] = luigi
            //create a match using the two players in the queue
            match, err := mgeme.dummyMatch()
            require.NoErrorf(t, err, "Error forming dummy match: %v", err)
            //send ready up prompt to the two players in the queue
            go mgeme.sendReadyUpPrompt(match)
            //one of the players will wait for a json message here so they know to respond to the rup signal
            msg := readWaitFor(wsConnA, "RupSignal", t, false)
            var rs RupSignal
            json.Unmarshal(msg, &rs)
            t.Logf("Rup signal: %v", rs)
            expected_rs := NewRupSignalMsg(true, false, mgeme.rupTime)
            require.EqualValues(t, expected_rs, rs, "Rup signal value not what was expected")

            //each player will now respond (on time or late) or ignore the signal.
            var wg sync.WaitGroup
            for id, conn := range players {
                wg.Add(1)
                go func(id string, conn *connection) { //<------------- potentially of interest
                    defer wg.Done()
                    seconds, exists := test.responders[id] //see how many seconds each player should wait before responding for this test
                    if exists {
                        <-time.After(time.Duration(seconds) * time.Second) //wait either 1 or 6 seconds (at 5, the ready up signal expires and the player's ready signal is ignored (that blocks due to being unbuffered but thats unrelated to this question at this point. in the tests where the players respond on time or dont respond at all i am getting odd behavior)
                        t.Log("Sending rup signal....")
                        conn.playerReady <- true //<------------- potentially of interest
                    }
                }(id, conn)
            }
            wg.Wait()
            //here i am testing how the server has handled a cancelled ready up signal
            //players that ready upped should be placed back in the queue but the
            //ones who didnt should be left out
            queue_cond := func() bool {
                mgeme.queueMutex.RLock()
                _, mq := mgeme.gameQueue["Mario"]
                _, lq := mgeme.gameQueue["Luigi"]
                mgeme.queueMutex.RUnlock()
                return (test.expectedQueue["Mario"] == mq && test.expectedQueue["Luigi"] == lq)
            }
            require.Eventuallyf(t, queue_cond, 5500 * time.Millisecond, 10*time.Millisecond, "Queues should be equal in test %s", test.name)
            //in one of the tests we don't just want to know the queue, we want to know if the match creation processes completed when both players readied in time
            if test.matchOrQueue == "m" {
                _, obj := mgeme.gameServerHub.findConnection("1")
                <-time.After(500 * time.Millisecond)
                require.True(t, obj.(*gameServer).findMatchByPlayer("Mario") != -1)
            }

            gameConn.Close()
            wsConnA.Close()
            wsConnB.Close()
            server.Close()
        })
    }
}

To some my question up, look again at the part of my test where i have a goroutine send, at most, one message on .playerReady per player. But my test logs out a lot of messages that it received this. What is causing this discrepancy between my production execution and my test?


问:
Decimal values being rounded when using Float and Decimal data types while importing with SQL Server Management Studio
I'm new to SQL programming, and am using SQL Server 16.0.1000.6 with SSMS 19 preview 4. I am trying to import a csv flat file into my personal desktop instance of SQL server. Two columns in the flat file - (Total_Charges, and Total_Costs) contain  monetary values and I want to keep those in decimal or numeric format up to two decimal places. I've tried uploading the flat file as a bulk insert, and using the import wizard with the data type set to numeric, decimal and even float and have run with mixed success.

I am experiencing the following problems:

While uploading using bulk insert, the decimal values are rounded to the nearest whole integer, irrespective of how the precision and scale values I use for decimal and numeric data types. When I first uploaded using bulk insert and used float data type, the values transferred over as floats, but lately, running the same script yields whole integer values.

When I used import wizard and set the values to decimal/numeric, the values transferred over as intended however when i repeated this process, they stopped coming in as decimals and began returning in as integers as described previously

Can anyone explain why I'm experiencing these inconsistencies in results and do you have recommendations for how I can avoid these problems going forward when I need to import data with decimal values?

My representative sample, original source files and scripts/processes I'm using are as follows:

Direct Link to source File:
Hospital Inpatient Discharges (SPARCS De-Identified) File: 2019

Original Source Page:
https://health.data.ny.gov/Health/Hospital-Inpatient-Discharges-SPARCS-De-Identified/4ny4-j5zv

Representative Sample CSV (Note: the source file was created from unix/linux and has LR carriage return lines):

```<code>Hospital Service Area,Hospital County,Operating Certificate Number,Permanent Facility Id,Facility Name,Age Group,Zip Code - 3 digits,Gender,Race,Ethnicity,Length of Stay,Type of Admission,Patient Disposition,Discharge Year,CCSR Diagnosis Code,CCSR Diagnosis Description,CCSR Procedure Code,CCSR Procedure Description,APR DRG Code,APR DRG Description,APR MDC Code,APR MDC Description,APR Severity of Illness Code,APR Severity of Illness Description,APR Risk of Mortality,APR Medical Surgical Description,Payment Typology 1,Payment Typology 2,Payment Typology 3,Birth Weight,Emergency Department Indicator,Total Charges,Total Costs
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,30 to 49,106,M,Other Race,Not Span/Hispanic,2,Emergency,Home or Self Care,2019,INF008,VIRAL INFECTION,,,723,VIRAL ILLNESS,18,INFECTIOUS AND PARASITIC DISEASES (SYSTEMIC OR UNSPECIFIED SITES),2,Moderate,Minor,Medical,Private Health Insurance,,,,true,26507,4773.11
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,105,F,Black/African American,Not Span/Hispanic,3,Emergency,Home or Self Care,2019,GEN002,ACUTE AND UNSPECIFIED RENAL FAILURE,,,469,ACUTE KIDNEY INJURY,11,DISEASES AND DISORDERS OF THE KIDNEY AND URINARY TRACT,2,Moderate,Moderate,Medical,Medicare,,,,true,20693,5631.3
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,105,F,Other Race,Not Span/Hispanic,7,Elective,Home or Self Care,2019,GEN006,OTHER SPECIFIED AND UNSPECIFIED DISEASES OF KIDNEY AND URETERS,GIS005,EXPLORATION OF PERITONEAL CAVITY,443,KIDNEY & URINARY TRACT PROCEDURES FOR NONMALIGNANCY,11,DISEASES AND DISORDERS OF THE KIDNEY AND URINARY TRACT,4,Extreme,Extreme,Surgical,Medicare,Blue Cross/Blue Shield,,,false,138252,29848.69
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,106,F,Black/African American,Not Span/Hispanic,1,Emergency,Left Against Medical Advice,2019,RSP009,ASTHMA,,,141,ASTHMA,04,DISEASES AND DISORDERS OF THE RESPIRATORY SYSTEM,2,Moderate,Minor,Medical,Medicare,Medicaid,,,true,11799,2595.72
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,105,F,Other Race,Not Span/Hispanic,3,Emergency,Psychiatric Hospital or Unit of Hosp,2019,MBD012,SUICIDAL IDEATION/ATTEMPT/INTENTIONAL SELF-HARM,MST007,HIP ARTHROPLASTY,817,OVERDOSE,21,"INJURIES, POISONINGS AND TOXIC EFFECTS OF DRUGS",2,Moderate,Moderate,Medical,Medicare,Private Health Insurance,,,true,52711,11355.62
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,105,M,Other Race,Not Span/Hispanic,5,Emergency,Home or Self Care,2019,END003,DIABETES MELLITUS WITH COMPLICATION,MST020,SUBCUTANEOUS TISSUE AND FASCIA EXCISION,344,"OSTEOMYELITIS, SEPTIC ARTHRITIS & OTHER MUSCULOSKELETAL INFECTIONS",08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Moderate,Medical,Private Health Insurance,,,,true,51161,12017.19
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,OOS,F,Other Race,Not Span/Hispanic,9,Emergency,Home or Self Care,2019,DIG012,INTESTINAL OBSTRUCTION AND ILEUS,GIS022,GI SYSTEM LYSIS OF ADHESIONS,223,OTHER SMALL & LARGE BOWEL PROCEDURES,06,DISEASES AND DISORDERS OF THE DIGESTIVE SYSTEM,3,Major,Major,Surgical,Medicare,,,,true,96700,18905.83
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,105,F,Other Race,Not Span/Hispanic,3,Emergency,Home or Self Care,2019,RSP002,PNEUMONIA (EXCEPT THAT CAUSED BY TUBERCULOSIS),,,139,OTHER PNEUMONIA,04,DISEASES AND DISORDERS OF THE RESPIRATORY SYSTEM,3,Major,Major,Medical,Medicare,Medicaid,,,true,28909,6740.04
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,106,M,Black/African American,Not Span/Hispanic,1,Emergency,Home or Self Care,2019,CIR012,NONSPECIFIC CHEST PAIN,,,203,CHEST PAIN,05,DISEASES AND DISORDERS OF THE CIRCULATORY SYSTEM,2,Moderate,Minor,Medical,Medicare,,,,true,26740,5209.08
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,105,F,Other Race,Not Span/Hispanic,4,Emergency,Home w/ Home Health Services,2019,SKN001,SKIN AND SUBCUTANEOUS TISSUE INFECTIONS,,,383,CELLULITIS & OTHER SKIN INFECTIONS,09,"DISEASES AND DISORDERS OF THE SKIN, SUBCUTANEOUS TISSUE AND BREAST",2,Moderate,Moderate,Medical,Medicare,Private Health Insurance,,,true,32346,6999.27
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,106,M,Other Race,Not Span/Hispanic,2,Emergency,Home or Self Care,2019,SYM002,FEVER,,,722,FEVER,18,INFECTIOUS AND PARASITIC DISEASES (SYSTEMIC OR UNSPECIFIED SITES),2,Moderate,Minor,Medical,Medicare,Blue Cross/Blue Shield,,,true,16346,4300.71
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,106,F,Other Race,Not Span/Hispanic,1,Emergency,Home or Self Care,2019,DIG012,INTESTINAL OBSTRUCTION AND ILEUS,,,247,INTESTINAL OBSTRUCTION,06,DISEASES AND DISORDERS OF THE DIGESTIVE SYSTEM,3,Major,Major,Medical,Medicare,,,,true,11282,2284.73
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,106,M,Other Race,Not Span/Hispanic,4,Emergency,Home or Self Care,2019,RSP002,PNEUMONIA (EXCEPT THAT CAUSED BY TUBERCULOSIS),,,139,OTHER PNEUMONIA,04,DISEASES AND DISORDERS OF THE RESPIRATORY SYSTEM,3,Major,Moderate,Medical,Medicare,Private Health Insurance,,,true,38689,9001.06
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,OOS,M,White,Not Span/Hispanic,1,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Private Health Insurance,,,,false,171695.19,27119.19
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,50 to 69,OOS,M,White,Not Span/Hispanic,4,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Private Health Insurance,,,,false,215167.53,40692.52
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,103,M,White,Not Span/Hispanic,7,Elective,Home w/ Home Health Services,2019,INJ037,"COMPLICATION OF OTHER SURGICAL OR MEDICAL CARE, INJURY, INITIAL ENCOUNTER",MST004,INCISION AND DRAINAGE OF MUSCULOSKELETAL TISSUE AND JOINTS,711,"POST-OP, POST-TRAUMA, OTHER DEVICE INFECTIONS W O.R. PROCEDURE",18,INFECTIOUS AND PARASITIC DISEASES (SYSTEMIC OR UNSPECIFIED SITES),3,Major,Major,Surgical,Miscellaneous/Other,Blue Cross/Blue Shield,,,false,104796.21,37762.06
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,112,M,Other Race,Not Span/Hispanic,1,Elective,Home or Self Care,2019,MUS011,SPONDYLOPATHIES/SPONDYLOARTHROPATHY (INCLUDING INFECTIVE),MST013,SPINE FUSION,321,CERVICAL SPINAL FUSION & OTHER BACK/NECK PROC EXC DISC EXCIS/DECOMP,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Private Health Insurance,,,,false,194117.25,31406.84
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,50 to 69,104,F,Black/African American,Not Span/Hispanic,3,Elective,Skilled Nursing Home,2019,INJ035,"COMPLICATION OF INTERNAL ORTHOPEDIC DEVICE OR IMPLANT, INITIAL ENCOUNTER",MST006,KNEE ARTHROPLASTY,302,KNEE JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Blue Cross/Blue Shield,,,,false,257171.1,44434.58
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,70 or Older,112,F,Other Race,Not Span/Hispanic,3,Elective,Skilled Nursing Home,2019,MUS006,OSTEOARTHRITIS,MST006,KNEE ARTHROPLASTY,302,KNEE JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,1,Minor,Minor,Surgical,Medicare,,,,false,104628.37,21668.1
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,50 to 69,113,F,White,Not Span/Hispanic,3,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,3,Major,Minor,Surgical,Medicaid,,,,false,206263.82,36636.28
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,104,F,White,Not Span/Hispanic,2,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Blue Cross/Blue Shield,Blue Cross/Blue Shield,,,false,190443.58,31916.43
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,0 to 17,104,F,Other Race,Spanish/Hispanic,37,Emergency,Home or Self Care,2019,MBD001,SCHIZOPHRENIA SPECTRUM AND OTHER PSYCHOTIC DISORDERS,MHT001,PHARMACOTHERAPY FOR MENTAL HEALTH (EXCLUDING SUBSTANCE USE),751,MAJOR DEPRESSIVE DISORDERS & OTHER/UNSPECIFIED PSYCHOSES,19,MENTAL DISEASES AND DISORDERS,1,Minor,Minor,Medical,Self-Pay,,,,false,56670.83,37663.43
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,104,M,Black/African American,Not Span/Hispanic,48,Emergency,Home or Self Care,2019,MBD001,SCHIZOPHRENIA SPECTRUM AND OTHER PSYCHOTIC DISORDERS,MHT001,PHARMACOTHERAPY FOR MENTAL HEALTH (EXCLUDING SUBSTANCE USE),750,SCHIZOPHRENIA,19,MENTAL DISEASES AND DISORDERS,2,Moderate,Minor,Medical,Medicaid,,,,true,68635.76,45615.33
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,100,M,Other Race,Spanish/Hispanic,5,Emergency,Home or Self Care,2019,MBD017,ALCOHOL-RELATED DISORDERS,SUD001,SUBSTANCE USE DETOXIFICATION,772,ALCOHOL & DRUG DEPENDENCE W REHAB OR REHAB/DETOX THERAPY,20,ALCOHOL/DRUG USE AND ALCOHOL/DRUG INDUCED ORGANIC MENTAL DISORDERS,2,Moderate,Moderate,Medical,Medicaid,,,,true,8008.06,5322.16
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,100,M,Other Race,Not Span/Hispanic,6,Emergency,Home or Self Care,2019,BLD006,COAGULATION AND HEMORRHAGIC DISORDERS,SUD001,SUBSTANCE USE DETOXIFICATION,661,COAGULATION & PLATELET DISORDERS,16,DISEASES AND DISORDERS OF THE BLOOD AND BLOOD FORMING ORGANS AND IMMUNOLOGICAL DISORDERS,1,Minor,Moderate,Medical,Medicaid,,,,true,38721.94,25734.6
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,30 to 49,112,M,Other Race,Spanish/Hispanic,2,Emergency,Home or Self Care,2019,MBD017,ALCOHOL-RELATED DISORDERS,SUD001,SUBSTANCE USE DETOXIFICATION,772,ALCOHOL & DRUG DEPENDENCE W REHAB OR REHAB/DETOX THERAPY,20,ALCOHOL/DRUG USE AND ALCOHOL/DRUG INDUCED ORGANIC MENTAL DISORDERS,2,Moderate,Minor,Medical,Medicaid,,,,true,4022.74,2673.51
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,112,F,Black/African American,Not Span/Hispanic,1,Emergency,Home or Self Care,2019,CIR008,HYPERTENSION WITH COMPLICATIONS AND SECONDARY HYPERTENSION,,,199,HYPERTENSION,05,DISEASES AND DISORDERS OF THE CIRCULATORY SYSTEM,2,Moderate,Moderate,Medical,Medicaid,,,,true,11535.34,7666.39
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,30 to 49,100,M,Black/African American,Not Span/Hispanic,39,Emergency,Inpatient Rehabilitation Facility,2019,INJ021,"EFFECT OF OTHER EXTERNAL CAUSES, INITIAL ENCOUNTER",RES007,AIRWAY INTUBATION,792,EXTENSIVE OR PROCEDURES FOR OTHER COMPLICATIONS OF TREATMENT,21,"INJURIES, POISONINGS AND TOXIC EFFECTS OF DRUGS",4,Extreme,Extreme,Surgical,Medicaid,Medicaid,,,true,224350.76,149103.52
</code>```

Scenario 1

Create Table Script (floats):

```<code>DROP TABLE IF EXISTS NYHospitals.dbo.SPARC2019
GO
CREATE TABLE NYhospitals.dbo.SPARC2019
    (
        ID INT IDENTITY (1,1) NOT NULL CONSTRAINT PK_ID PRIMARY KEY,
        Hospital_Service_Area VARCHAR(15) null,
        Hospital_County VARCHAR(11) null,
        Operating_Certificate_Number VARCHAR(12) null,
        Permanent_Facility_Id INT null,
        Facility_Name VARCHAR(112) null,
        Age_Group VARCHAR(11) null,
        Zip_Code_3_digits VARCHAR(3) null,
        Gender VARCHAR(1) null,
        Race VARCHAR(32) null,
        Ethnicity VARCHAR(20) null,
        Length_of_Stay VARCHAR(5) null,
        Type_of_Admission VARCHAR(15) null,
        Patient_Disposition VARCHAR(37) null,
        Discharge_Year VARCHAR(4) null,
        CCSR_Diagnosis_Code VARCHAR(10) null,
        CCSR_Diagnosis_Description VARCHAR(250) null,
        CCSR_Procedure_Code VARCHAR(10) null,
        CCSR_Procedure_Description VARCHAR(250) null,
        APR_DRG_Code VARCHAR(3) null,
        APR_DRG_Description VARCHAR(500) null,
        APR_MDC_Code VARCHAR(2) null,
        APR_MDC_Description VARCHAR(500) null,
        APR_Severity_of_Illness_Code VARCHAR(1) null,
        APR_Severity_of_Illness_Description VARCHAR(8) null,
        APR_Risk_of_Mortality VARCHAR(8) null,
        APR_Medical_Surgical_Description VARCHAR(14) null,
        Payment_Typology_1 VARCHAR(25) null,
        Payment_Typology_2 VARCHAR(25) null,
        Payment_Typology_3 VARCHAR(25) null,
        Birth_Weight VARCHAR(5) null,
        Emergency_Department_Indicator VARCHAR(12) null,
        Total_Charges float null,
        Total_Costs float null

    )

</code>```

Create View Script (to allow bulk insert to import data through to the table)

```<code>--Allows data to be passed through it using bulkinsert from flatfile source whose column count does not match destination table SPARC2019.
DROP VIEW IF EXISTS dbo.rawdataview
GO
CREATE VIEW rawdataview
AS
    SELECT

        Hospital_Service_Area,
        Hospital_County,
        Operating_Certificate_Number,
        Permanent_Facility_Id,
        Facility_Name,
        Age_Group,
        Zip_Code_3_digits,
        Gender,
        Race,
        Ethnicity,
        Length_of_Stay,
        Type_of_Admission,
        Patient_Disposition,
        Discharge_Year,
        CCSR_Diagnosis_Code,
        CCSR_Diagnosis_Description,
        CCSR_Procedure_Code,
        CCSR_Procedure_Description,
        APR_DRG_Code,
        APR_DRG_Description,
        APR_MDC_Code,
        APR_MDC_Description,
        APR_Severity_of_Illness_Code,
        APR_Severity_of_Illness_Description,
        APR_Risk_of_Mortality,
        APR_Medical_Surgical_Description,
        Payment_Typology_1,
        Payment_Typology_2,
        Payment_Typology_3,
        Birth_Weight,
        Emergency_Department_Indicator,
        Total_Charges,
        Total_Costs

    FROM dbo.sparc2019

</code>```

Bulk Insert Script

```<code>USE NYHospitals

BULK INSERT NYHospitals.dbo.rawdataview
FROM 'C:\Users\Bob\Downloads\Hospital_Inpatient_Discharges__SPARCS_De-Identified___2019.csv'
    WITH
        (
        BATCHSIZE = 100000
        ,ERRORFILE = 'C:\Users\Bob\Downloads\Hospital_Inpatient_Discharges__SPARCS_De-Identified___2019_ERROR.log'
        ,MAXERRORS = 1
        ,FIRSTROW = 2
        ,KEEPNULLS
        ,FORMAT = 'CSV'
        ,FIELDTERMINATOR = ','
        ,ROWTERMINATOR = '0x0a'
        )

</code>```

Output after running Bulk Insert Script (float data type)

The expected outcome was ex. 190443.58

Scenario 2

Create Table Script (decimal)

```<code>DROP TABLE IF EXISTS NYHospitals.dbo.SPARC2019
GO
CREATE TABLE NYhospitals.dbo.SPARC2019
    (
        ID INT IDENTITY (1,1) NOT NULL CONSTRAINT PK_ID PRIMARY KEY,
        Hospital_Service_Area VARCHAR(15) null,
        Hospital_County VARCHAR(11) null,
        Operating_Certificate_Number VARCHAR(12) null,
        Permanent_Facility_Id INT null,
        Facility_Name VARCHAR(112) null,
        Age_Group VARCHAR(11) null,
        Zip_Code_3_digits VARCHAR(3) null,
        Gender VARCHAR(1) null,
        Race VARCHAR(32) null,
        Ethnicity VARCHAR(20) null,
        Length_of_Stay VARCHAR(5) null,
        Type_of_Admission VARCHAR(15) null,
        Patient_Disposition VARCHAR(37) null,
        Discharge_Year VARCHAR(4) null,
        CCSR_Diagnosis_Code VARCHAR(10) null,
        CCSR_Diagnosis_Description VARCHAR(250) null,
        CCSR_Procedure_Code VARCHAR(10) null,
        CCSR_Procedure_Description VARCHAR(250) null,
        APR_DRG_Code VARCHAR(3) null,
        APR_DRG_Description VARCHAR(500) null,
        APR_MDC_Code VARCHAR(2) null,
        APR_MDC_Description VARCHAR(500) null,
        APR_Severity_of_Illness_Code VARCHAR(1) null,
        APR_Severity_of_Illness_Description VARCHAR(8) null,
        APR_Risk_of_Mortality VARCHAR(8) null,
        APR_Medical_Surgical_Description VARCHAR(14) null,
        Payment_Typology_1 VARCHAR(25) null,
        Payment_Typology_2 VARCHAR(25) null,
        Payment_Typology_3 VARCHAR(25) null,
        Birth_Weight VARCHAR(5) null,
        Emergency_Department_Indicator VARCHAR(12) null,
        Total_Charges decimal(12,2) null,
        Total_Costs decimal(12,2) null

    )

</code>```

Output after running Bulk Insert Script (decimal data type)

The expected outcome was ex. 190443.58

Body:
I'm new to SQL programming, and am using SQL Server 16.0.1000.6 with SSMS 19 preview 4. I am trying to import a csv flat file into my personal desktop instance of SQL server. Two columns in the flat file - (Total_Charges, and Total_Costs) contain  monetary values and I want to keep those in decimal or numeric format up to two decimal places. I've tried uploading the flat file as a bulk insert, and using the import wizard with the data type set to numeric, decimal and even float and have run with mixed success.

I am experiencing the following problems:

While uploading using bulk insert, the decimal values are rounded to the nearest whole integer, irrespective of how the precision and scale values I use for decimal and numeric data types. When I first uploaded using bulk insert and used float data type, the values transferred over as floats, but lately, running the same script yields whole integer values.

When I used import wizard and set the values to decimal/numeric, the values transferred over as intended however when i repeated this process, they stopped coming in as decimals and began returning in as integers as described previously

Can anyone explain why I'm experiencing these inconsistencies in results and do you have recommendations for how I can avoid these problems going forward when I need to import data with decimal values?

My representative sample, original source files and scripts/processes I'm using are as follows:

Direct Link to source File:
Hospital Inpatient Discharges (SPARCS De-Identified) File: 2019

Original Source Page:
https://health.data.ny.gov/Health/Hospital-Inpatient-Discharges-SPARCS-De-Identified/4ny4-j5zv

Representative Sample CSV (Note: the source file was created from unix/linux and has LR carriage return lines):

Hospital Service Area,Hospital County,Operating Certificate Number,Permanent Facility Id,Facility Name,Age Group,Zip Code - 3 digits,Gender,Race,Ethnicity,Length of Stay,Type of Admission,Patient Disposition,Discharge Year,CCSR Diagnosis Code,CCSR Diagnosis Description,CCSR Procedure Code,CCSR Procedure Description,APR DRG Code,APR DRG Description,APR MDC Code,APR MDC Description,APR Severity of Illness Code,APR Severity of Illness Description,APR Risk of Mortality,APR Medical Surgical Description,Payment Typology 1,Payment Typology 2,Payment Typology 3,Birth Weight,Emergency Department Indicator,Total Charges,Total Costs
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,30 to 49,106,M,Other Race,Not Span/Hispanic,2,Emergency,Home or Self Care,2019,INF008,VIRAL INFECTION,,,723,VIRAL ILLNESS,18,INFECTIOUS AND PARASITIC DISEASES (SYSTEMIC OR UNSPECIFIED SITES),2,Moderate,Minor,Medical,Private Health Insurance,,,,true,26507,4773.11
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,105,F,Black/African American,Not Span/Hispanic,3,Emergency,Home or Self Care,2019,GEN002,ACUTE AND UNSPECIFIED RENAL FAILURE,,,469,ACUTE KIDNEY INJURY,11,DISEASES AND DISORDERS OF THE KIDNEY AND URINARY TRACT,2,Moderate,Moderate,Medical,Medicare,,,,true,20693,5631.3
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,105,F,Other Race,Not Span/Hispanic,7,Elective,Home or Self Care,2019,GEN006,OTHER SPECIFIED AND UNSPECIFIED DISEASES OF KIDNEY AND URETERS,GIS005,EXPLORATION OF PERITONEAL CAVITY,443,KIDNEY & URINARY TRACT PROCEDURES FOR NONMALIGNANCY,11,DISEASES AND DISORDERS OF THE KIDNEY AND URINARY TRACT,4,Extreme,Extreme,Surgical,Medicare,Blue Cross/Blue Shield,,,false,138252,29848.69
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,106,F,Black/African American,Not Span/Hispanic,1,Emergency,Left Against Medical Advice,2019,RSP009,ASTHMA,,,141,ASTHMA,04,DISEASES AND DISORDERS OF THE RESPIRATORY SYSTEM,2,Moderate,Minor,Medical,Medicare,Medicaid,,,true,11799,2595.72
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,105,F,Other Race,Not Span/Hispanic,3,Emergency,Psychiatric Hospital or Unit of Hosp,2019,MBD012,SUICIDAL IDEATION/ATTEMPT/INTENTIONAL SELF-HARM,MST007,HIP ARTHROPLASTY,817,OVERDOSE,21,"INJURIES, POISONINGS AND TOXIC EFFECTS OF DRUGS",2,Moderate,Moderate,Medical,Medicare,Private Health Insurance,,,true,52711,11355.62
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,105,M,Other Race,Not Span/Hispanic,5,Emergency,Home or Self Care,2019,END003,DIABETES MELLITUS WITH COMPLICATION,MST020,SUBCUTANEOUS TISSUE AND FASCIA EXCISION,344,"OSTEOMYELITIS, SEPTIC ARTHRITIS & OTHER MUSCULOSKELETAL INFECTIONS",08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Moderate,Medical,Private Health Insurance,,,,true,51161,12017.19
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,OOS,F,Other Race,Not Span/Hispanic,9,Emergency,Home or Self Care,2019,DIG012,INTESTINAL OBSTRUCTION AND ILEUS,GIS022,GI SYSTEM LYSIS OF ADHESIONS,223,OTHER SMALL & LARGE BOWEL PROCEDURES,06,DISEASES AND DISORDERS OF THE DIGESTIVE SYSTEM,3,Major,Major,Surgical,Medicare,,,,true,96700,18905.83
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,105,F,Other Race,Not Span/Hispanic,3,Emergency,Home or Self Care,2019,RSP002,PNEUMONIA (EXCEPT THAT CAUSED BY TUBERCULOSIS),,,139,OTHER PNEUMONIA,04,DISEASES AND DISORDERS OF THE RESPIRATORY SYSTEM,3,Major,Major,Medical,Medicare,Medicaid,,,true,28909,6740.04
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,50 to 69,106,M,Black/African American,Not Span/Hispanic,1,Emergency,Home or Self Care,2019,CIR012,NONSPECIFIC CHEST PAIN,,,203,CHEST PAIN,05,DISEASES AND DISORDERS OF THE CIRCULATORY SYSTEM,2,Moderate,Minor,Medical,Medicare,,,,true,26740,5209.08
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,105,F,Other Race,Not Span/Hispanic,4,Emergency,Home w/ Home Health Services,2019,SKN001,SKIN AND SUBCUTANEOUS TISSUE INFECTIONS,,,383,CELLULITIS & OTHER SKIN INFECTIONS,09,"DISEASES AND DISORDERS OF THE SKIN, SUBCUTANEOUS TISSUE AND BREAST",2,Moderate,Moderate,Medical,Medicare,Private Health Insurance,,,true,32346,6999.27
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,106,M,Other Race,Not Span/Hispanic,2,Emergency,Home or Self Care,2019,SYM002,FEVER,,,722,FEVER,18,INFECTIOUS AND PARASITIC DISEASES (SYSTEMIC OR UNSPECIFIED SITES),2,Moderate,Minor,Medical,Medicare,Blue Cross/Blue Shield,,,true,16346,4300.71
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,106,F,Other Race,Not Span/Hispanic,1,Emergency,Home or Self Care,2019,DIG012,INTESTINAL OBSTRUCTION AND ILEUS,,,247,INTESTINAL OBSTRUCTION,06,DISEASES AND DISORDERS OF THE DIGESTIVE SYSTEM,3,Major,Major,Medical,Medicare,,,,true,11282,2284.73
Hudson Valley,Westchester,5902001,001045,White Plains Hospital Center,70 or Older,106,M,Other Race,Not Span/Hispanic,4,Emergency,Home or Self Care,2019,RSP002,PNEUMONIA (EXCEPT THAT CAUSED BY TUBERCULOSIS),,,139,OTHER PNEUMONIA,04,DISEASES AND DISORDERS OF THE RESPIRATORY SYSTEM,3,Major,Moderate,Medical,Medicare,Private Health Insurance,,,true,38689,9001.06
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,OOS,M,White,Not Span/Hispanic,1,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Private Health Insurance,,,,false,171695.19,27119.19
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,50 to 69,OOS,M,White,Not Span/Hispanic,4,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Private Health Insurance,,,,false,215167.53,40692.52
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,103,M,White,Not Span/Hispanic,7,Elective,Home w/ Home Health Services,2019,INJ037,"COMPLICATION OF OTHER SURGICAL OR MEDICAL CARE, INJURY, INITIAL ENCOUNTER",MST004,INCISION AND DRAINAGE OF MUSCULOSKELETAL TISSUE AND JOINTS,711,"POST-OP, POST-TRAUMA, OTHER DEVICE INFECTIONS W O.R. PROCEDURE",18,INFECTIOUS AND PARASITIC DISEASES (SYSTEMIC OR UNSPECIFIED SITES),3,Major,Major,Surgical,Miscellaneous/Other,Blue Cross/Blue Shield,,,false,104796.21,37762.06
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,112,M,Other Race,Not Span/Hispanic,1,Elective,Home or Self Care,2019,MUS011,SPONDYLOPATHIES/SPONDYLOARTHROPATHY (INCLUDING INFECTIVE),MST013,SPINE FUSION,321,CERVICAL SPINAL FUSION & OTHER BACK/NECK PROC EXC DISC EXCIS/DECOMP,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Private Health Insurance,,,,false,194117.25,31406.84
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,50 to 69,104,F,Black/African American,Not Span/Hispanic,3,Elective,Skilled Nursing Home,2019,INJ035,"COMPLICATION OF INTERNAL ORTHOPEDIC DEVICE OR IMPLANT, INITIAL ENCOUNTER",MST006,KNEE ARTHROPLASTY,302,KNEE JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Blue Cross/Blue Shield,,,,false,257171.1,44434.58
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,70 or Older,112,F,Other Race,Not Span/Hispanic,3,Elective,Skilled Nursing Home,2019,MUS006,OSTEOARTHRITIS,MST006,KNEE ARTHROPLASTY,302,KNEE JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,1,Minor,Minor,Surgical,Medicare,,,,false,104628.37,21668.1
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,50 to 69,113,F,White,Not Span/Hispanic,3,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,3,Major,Minor,Surgical,Medicaid,,,,false,206263.82,36636.28
New York City,Manhattan,7002053,001446,NYU Langone Orthopedic Hospital,30 to 49,104,F,White,Not Span/Hispanic,2,Elective,Home w/ Home Health Services,2019,MUS006,OSTEOARTHRITIS,MST007,HIP ARTHROPLASTY,301,HIP JOINT REPLACEMENT,08,DISEASES AND DISORDERS OF THE MUSCULOSKELETAL SYSTEM AND CONNECTIVE TISSUE,2,Moderate,Minor,Surgical,Blue Cross/Blue Shield,Blue Cross/Blue Shield,,,false,190443.58,31916.43
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,0 to 17,104,F,Other Race,Spanish/Hispanic,37,Emergency,Home or Self Care,2019,MBD001,SCHIZOPHRENIA SPECTRUM AND OTHER PSYCHOTIC DISORDERS,MHT001,PHARMACOTHERAPY FOR MENTAL HEALTH (EXCLUDING SUBSTANCE USE),751,MAJOR DEPRESSIVE DISORDERS & OTHER/UNSPECIFIED PSYCHOSES,19,MENTAL DISEASES AND DISORDERS,1,Minor,Minor,Medical,Self-Pay,,,,false,56670.83,37663.43
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,104,M,Black/African American,Not Span/Hispanic,48,Emergency,Home or Self Care,2019,MBD001,SCHIZOPHRENIA SPECTRUM AND OTHER PSYCHOTIC DISORDERS,MHT001,PHARMACOTHERAPY FOR MENTAL HEALTH (EXCLUDING SUBSTANCE USE),750,SCHIZOPHRENIA,19,MENTAL DISEASES AND DISORDERS,2,Moderate,Minor,Medical,Medicaid,,,,true,68635.76,45615.33
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,100,M,Other Race,Spanish/Hispanic,5,Emergency,Home or Self Care,2019,MBD017,ALCOHOL-RELATED DISORDERS,SUD001,SUBSTANCE USE DETOXIFICATION,772,ALCOHOL & DRUG DEPENDENCE W REHAB OR REHAB/DETOX THERAPY,20,ALCOHOL/DRUG USE AND ALCOHOL/DRUG INDUCED ORGANIC MENTAL DISORDERS,2,Moderate,Moderate,Medical,Medicaid,,,,true,8008.06,5322.16
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,100,M,Other Race,Not Span/Hispanic,6,Emergency,Home or Self Care,2019,BLD006,COAGULATION AND HEMORRHAGIC DISORDERS,SUD001,SUBSTANCE USE DETOXIFICATION,661,COAGULATION & PLATELET DISORDERS,16,DISEASES AND DISORDERS OF THE BLOOD AND BLOOD FORMING ORGANS AND IMMUNOLOGICAL DISORDERS,1,Minor,Moderate,Medical,Medicaid,,,,true,38721.94,25734.6
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,30 to 49,112,M,Other Race,Spanish/Hispanic,2,Emergency,Home or Self Care,2019,MBD017,ALCOHOL-RELATED DISORDERS,SUD001,SUBSTANCE USE DETOXIFICATION,772,ALCOHOL & DRUG DEPENDENCE W REHAB OR REHAB/DETOX THERAPY,20,ALCOHOL/DRUG USE AND ALCOHOL/DRUG INDUCED ORGANIC MENTAL DISORDERS,2,Moderate,Minor,Medical,Medicaid,,,,true,4022.74,2673.51
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,50 to 69,112,F,Black/African American,Not Span/Hispanic,1,Emergency,Home or Self Care,2019,CIR008,HYPERTENSION WITH COMPLICATIONS AND SECONDARY HYPERTENSION,,,199,HYPERTENSION,05,DISEASES AND DISORDERS OF THE CIRCULATORY SYSTEM,2,Moderate,Moderate,Medical,Medicaid,,,,true,11535.34,7666.39
New York City,Manhattan,7002001,001438,Bellevue Hospital Center,30 to 49,100,M,Black/African American,Not Span/Hispanic,39,Emergency,Inpatient Rehabilitation Facility,2019,INJ021,"EFFECT OF OTHER EXTERNAL CAUSES, INITIAL ENCOUNTER",RES007,AIRWAY INTUBATION,792,EXTENSIVE OR PROCEDURES FOR OTHER COMPLICATIONS OF TREATMENT,21,"INJURIES, POISONINGS AND TOXIC EFFECTS OF DRUGS",4,Extreme,Extreme,Surgical,Medicaid,Medicaid,,,true,224350.76,149103.52

Scenario 1

Create Table Script (floats):

DROP TABLE IF EXISTS NYHospitals.dbo.SPARC2019
GO
CREATE TABLE NYhospitals.dbo.SPARC2019
    (
        ID INT IDENTITY (1,1) NOT NULL CONSTRAINT PK_ID PRIMARY KEY,
        Hospital_Service_Area VARCHAR(15) null,
        Hospital_County VARCHAR(11) null,
        Operating_Certificate_Number VARCHAR(12) null,
        Permanent_Facility_Id INT null,
        Facility_Name VARCHAR(112) null,
        Age_Group VARCHAR(11) null,
        Zip_Code_3_digits VARCHAR(3) null,
        Gender VARCHAR(1) null,
        Race VARCHAR(32) null,
        Ethnicity VARCHAR(20) null,
        Length_of_Stay VARCHAR(5) null,
        Type_of_Admission VARCHAR(15) null,
        Patient_Disposition VARCHAR(37) null,
        Discharge_Year VARCHAR(4) null,
        CCSR_Diagnosis_Code VARCHAR(10) null,
        CCSR_Diagnosis_Description VARCHAR(250) null,
        CCSR_Procedure_Code VARCHAR(10) null,
        CCSR_Procedure_Description VARCHAR(250) null,
        APR_DRG_Code VARCHAR(3) null,
        APR_DRG_Description VARCHAR(500) null,
        APR_MDC_Code VARCHAR(2) null,
        APR_MDC_Description VARCHAR(500) null,
        APR_Severity_of_Illness_Code VARCHAR(1) null,
        APR_Severity_of_Illness_Description VARCHAR(8) null,
        APR_Risk_of_Mortality VARCHAR(8) null,
        APR_Medical_Surgical_Description VARCHAR(14) null,
        Payment_Typology_1 VARCHAR(25) null,
        Payment_Typology_2 VARCHAR(25) null,
        Payment_Typology_3 VARCHAR(25) null,
        Birth_Weight VARCHAR(5) null,
        Emergency_Department_Indicator VARCHAR(12) null,
        Total_Charges float null,
        Total_Costs float null

    )

Create View Script (to allow bulk insert to import data through to the table)

--Allows data to be passed through it using bulkinsert from flatfile source whose column count does not match destination table SPARC2019.
DROP VIEW IF EXISTS dbo.rawdataview
GO
CREATE VIEW rawdataview
AS
    SELECT

        Hospital_Service_Area,
        Hospital_County,
        Operating_Certificate_Number,
        Permanent_Facility_Id,
        Facility_Name,
        Age_Group,
        Zip_Code_3_digits,
        Gender,
        Race,
        Ethnicity,
        Length_of_Stay,
        Type_of_Admission,
        Patient_Disposition,
        Discharge_Year,
        CCSR_Diagnosis_Code,
        CCSR_Diagnosis_Description,
        CCSR_Procedure_Code,
        CCSR_Procedure_Description,
        APR_DRG_Code,
        APR_DRG_Description,
        APR_MDC_Code,
        APR_MDC_Description,
        APR_Severity_of_Illness_Code,
        APR_Severity_of_Illness_Description,
        APR_Risk_of_Mortality,
        APR_Medical_Surgical_Description,
        Payment_Typology_1,
        Payment_Typology_2,
        Payment_Typology_3,
        Birth_Weight,
        Emergency_Department_Indicator,
        Total_Charges,
        Total_Costs

    FROM dbo.sparc2019

Bulk Insert Script

USE NYHospitals

BULK INSERT NYHospitals.dbo.rawdataview
FROM 'C:\Users\Bob\Downloads\Hospital_Inpatient_Discharges__SPARCS_De-Identified___2019.csv'
    WITH
        (
        BATCHSIZE = 100000
        ,ERRORFILE = 'C:\Users\Bob\Downloads\Hospital_Inpatient_Discharges__SPARCS_De-Identified___2019_ERROR.log'
        ,MAXERRORS = 1
        ,FIRSTROW = 2
        ,KEEPNULLS
        ,FORMAT = 'CSV'
        ,FIELDTERMINATOR = ','
        ,ROWTERMINATOR = '0x0a'
        )

Output after running Bulk Insert Script (float data type)

The expected outcome was ex. 190443.58

Scenario 2

Create Table Script (decimal)

DROP TABLE IF EXISTS NYHospitals.dbo.SPARC2019
GO
CREATE TABLE NYhospitals.dbo.SPARC2019
    (
        ID INT IDENTITY (1,1) NOT NULL CONSTRAINT PK_ID PRIMARY KEY,
        Hospital_Service_Area VARCHAR(15) null,
        Hospital_County VARCHAR(11) null,
        Operating_Certificate_Number VARCHAR(12) null,
        Permanent_Facility_Id INT null,
        Facility_Name VARCHAR(112) null,
        Age_Group VARCHAR(11) null,
        Zip_Code_3_digits VARCHAR(3) null,
        Gender VARCHAR(1) null,
        Race VARCHAR(32) null,
        Ethnicity VARCHAR(20) null,
        Length_of_Stay VARCHAR(5) null,
        Type_of_Admission VARCHAR(15) null,
        Patient_Disposition VARCHAR(37) null,
        Discharge_Year VARCHAR(4) null,
        CCSR_Diagnosis_Code VARCHAR(10) null,
        CCSR_Diagnosis_Description VARCHAR(250) null,
        CCSR_Procedure_Code VARCHAR(10) null,
        CCSR_Procedure_Description VARCHAR(250) null,
        APR_DRG_Code VARCHAR(3) null,
        APR_DRG_Description VARCHAR(500) null,
        APR_MDC_Code VARCHAR(2) null,
        APR_MDC_Description VARCHAR(500) null,
        APR_Severity_of_Illness_Code VARCHAR(1) null,
        APR_Severity_of_Illness_Description VARCHAR(8) null,
        APR_Risk_of_Mortality VARCHAR(8) null,
        APR_Medical_Surgical_Description VARCHAR(14) null,
        Payment_Typology_1 VARCHAR(25) null,
        Payment_Typology_2 VARCHAR(25) null,
        Payment_Typology_3 VARCHAR(25) null,
        Birth_Weight VARCHAR(5) null,
        Emergency_Department_Indicator VARCHAR(12) null,
        Total_Charges decimal(12,2) null,
        Total_Costs decimal(12,2) null

    )

Output after running Bulk Insert Script (decimal data type)

The expected outcome was ex. 190443.58


问:
Laravel - Sever is not reading the files from the path
I'm facing a problem with my Laravel application. It is deployed on the server and uses nginx as the main web server.

I am unable to read two files from the path I set in the deployment server, but on the local environment, it is working fine. These two files are confidential, one is .crt file and second is .pem file. I placed both of these files in laravel-app/app/Certificates directory.

laravel-app/app/Certificates/test2-2023_cert.pem

laravel-app/app/Certificates/curl-bundle.crt

The file path in .env is set like this:

```<code>PEM=/Certificates/test2-2023_cert.pem
CRT=/Certificates/curl-bundle.crt
</code>```

My config/services file:

```<code><?php

return [

    'pay' => [
        'pem' => app_path() . env('PEM', ''),
        'crt' => app_path() . env('CRT', '')
    ]

];
</code>```

My Controller construct function:

```<code>public function __construct()
    {

        $this->pem = config('services.pay.pem');
        $this->crt = config('services.pay.crt');
    }
</code>```

It is returning the following path on server:

```<code>/var/www/laravel-app/app/Certificates/test2-2023_cert.pem
/var/www/laravel-app/app/Certificates/curl-bundle.crt
</code>```

but the server is not loading the file and gives me an error response in the API call. What I'm doing wrong?

Body:
I'm facing a problem with my Laravel application. It is deployed on the server and uses nginx as the main web server.

I am unable to read two files from the path I set in the deployment server, but on the local environment, it is working fine. These two files are confidential, one is .crt file and second is .pem file. I placed both of these files in laravel-app/app/Certificates directory.

laravel-app/app/Certificates/test2-2023_cert.pem

laravel-app/app/Certificates/curl-bundle.crt

The file path in .env is set like this:

PEM=/Certificates/test2-2023_cert.pem
CRT=/Certificates/curl-bundle.crt

My config/services file:

<?php

return [

    'pay' => [
        'pem' => app_path() . env('PEM', ''),
        'crt' => app_path() . env('CRT', '')
    ]

];

My Controller construct function:

public function __construct()
    {

        $this->pem = config('services.pay.pem');
        $this->crt = config('services.pay.crt');
    }

It is returning the following path on server:

/var/www/laravel-app/app/Certificates/test2-2023_cert.pem
/var/www/laravel-app/app/Certificates/curl-bundle.crt

but the server is not loading the file and gives me an error response in the API call. What I'm doing wrong?


问:
extends block for HTML is showing up as text rather than actually parsing
```<code>{% extends 'base.html' %}
{% block content %}
</code>```

my index file starts like this but it's not extending base.html it's just showing me my index.html with what I pasted up there as text in my index.html. Im so confused..

I just tried searching solutions but i dont see what else i could change. I'm new to this stuff so only thing it could be is something with the routing but I'm just launching these without app.yaml or main.py files

Body:
{% extends 'base.html' %}
{% block content %}

my index file starts like this but it's not extending base.html it's just showing me my index.html with what I pasted up there as text in my index.html. Im so confused..

I just tried searching solutions but i dont see what else i could change. I'm new to this stuff so only thing it could be is something with the routing but I'm just launching these without app.yaml or main.py files


问:
Does GTK4 compiled using mingw-w64 give a memory leak when using drag and drop?
I'm using GTK-4 (version 4.8.2-1) with g++ on mingw-w64. I'm running Windows 11. I'm creating an app with a moveable widget and noticed that on task manager, the app rapidly eats up memory whenever a drag action is performed. Below is a minimal working example that produces this issue on my machine. Obviously this code doesn't actually do anything, but dragging the label repeatedly (on my machine, about 20 times) will cause the app to crash. Am I misunderstanding the API in some fundamental way and inadvertently causing this? Or is this an issue with GTK? mingw?

```<code>#include <gtk/gtk.h>

static GdkContentProvider* on_drag_prepare(GtkDragSource *source, double x, double y, GtkWidget* label) {

    GValue* a = new GValue;
    (*a) = G_VALUE_INIT;
    g_value_init(a, G_TYPE_INT);
    g_value_set_int(a, 1);

    // The content is basically a single integer.
    return gdk_content_provider_new_for_value(a);
}

static void activate( GtkApplication *app, gpointer user_data) {

    // window
    GtkWidget* window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Drag Memory Leak");
    gtk_window_set_default_size (GTK_WINDOW (window), 400, 400);

    // label to drag
    GtkWidget* label = gtk_label_new("Drag Me");
    gtk_window_set_child(GTK_WINDOW (window), label);

    // setting up drag callback
    GtkDragSource *drag_source = gtk_drag_source_new();
    gtk_drag_source_set_actions(drag_source, GDK_ACTION_MOVE);
    g_signal_connect (drag_source, "prepare", G_CALLBACK (on_drag_prepare), label);
    gtk_widget_add_controller (GTK_WIDGET (label), GTK_EVENT_CONTROLLER (drag_source));

    gtk_window_present (GTK_WINDOW (window));
}

int main( int argc, char **argv) {

    GtkApplication *app;
    int status;

    app = gtk_application_new("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}
</code>```

I expected that when I compiled and ran this program, I'd not have a memory leak when dragging a widget repeatedly.

Body:
I'm using GTK-4 (version 4.8.2-1) with g++ on mingw-w64. I'm running Windows 11. I'm creating an app with a moveable widget and noticed that on task manager, the app rapidly eats up memory whenever a drag action is performed. Below is a minimal working example that produces this issue on my machine. Obviously this code doesn't actually do anything, but dragging the label repeatedly (on my machine, about 20 times) will cause the app to crash. Am I misunderstanding the API in some fundamental way and inadvertently causing this? Or is this an issue with GTK? mingw?

#include <gtk/gtk.h>

static GdkContentProvider* on_drag_prepare(GtkDragSource *source, double x, double y, GtkWidget* label) {

    GValue* a = new GValue;
    (*a) = G_VALUE_INIT;
    g_value_init(a, G_TYPE_INT);
    g_value_set_int(a, 1);

    // The content is basically a single integer.
    return gdk_content_provider_new_for_value(a);
}

static void activate( GtkApplication *app, gpointer user_data) {

    // window
    GtkWidget* window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Drag Memory Leak");
    gtk_window_set_default_size (GTK_WINDOW (window), 400, 400);

    // label to drag
    GtkWidget* label = gtk_label_new("Drag Me");
    gtk_window_set_child(GTK_WINDOW (window), label);

    // setting up drag callback
    GtkDragSource *drag_source = gtk_drag_source_new();
    gtk_drag_source_set_actions(drag_source, GDK_ACTION_MOVE);
    g_signal_connect (drag_source, "prepare", G_CALLBACK (on_drag_prepare), label);
    gtk_widget_add_controller (GTK_WIDGET (label), GTK_EVENT_CONTROLLER (drag_source));

    gtk_window_present (GTK_WINDOW (window));
}

int main( int argc, char **argv) {

    GtkApplication *app;
    int status;

    app = gtk_application_new("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

I expected that when I compiled and ran this program, I'd not have a memory leak when dragging a widget repeatedly.


问:
React Query useQuery Fetcher function returns undefined even though data prints
This is my second stackoverflow post regarding useQuery hooks. In this issue, i have a fetcher function that does not want to return the data. I also have an onSuccess function, however, it still returns undefined regardless of onSuccess. I was hoping to get some assistance on how useQuery should work so that the onSuccess allows me to work with the data from the fetcher function. The link to the original post from where this code derivated from is How to wait for useQuery data to finish loading to start working with it NextJS.

```<code> async function fetchDocs() {
        const queryCollection = query(collection(db, loc))
        const snapshot = await getDocs(queryCollection);
        let arr = []
        snapshot.forEach(doc => {
            console.log(doc.data())
            arr.push(doc.data())
        })
        return Promise.all(arr)
    }

    const {data, status} = useQuery({queryKey: ['firestoreData', db]}, {queryFn: () => fetchDocs()}, {
        onSuccess: (dataCollection) => {
          // do something here, not in useEffect

            console.log(data)
            return dataCollection

        }
      });
</code>```

Body:
This is my second stackoverflow post regarding useQuery hooks. In this issue, i have a fetcher function that does not want to return the data. I also have an onSuccess function, however, it still returns undefined regardless of onSuccess. I was hoping to get some assistance on how useQuery should work so that the onSuccess allows me to work with the data from the fetcher function. The link to the original post from where this code derivated from is How to wait for useQuery data to finish loading to start working with it NextJS.

 async function fetchDocs() {
        const queryCollection = query(collection(db, loc))
        const snapshot = await getDocs(queryCollection);
        let arr = []
        snapshot.forEach(doc => {
            console.log(doc.data())
            arr.push(doc.data())
        })
        return Promise.all(arr)
    }

    const {data, status} = useQuery({queryKey: ['firestoreData', db]}, {queryFn: () => fetchDocs()}, {
        onSuccess: (dataCollection) => {
          // do something here, not in useEffect

            console.log(data)
            return dataCollection

        }
      });


问:
"Expected spy on mockLogin.getToken to equal true." is the error showing up
What I am trying to do is get access to my return value of the mockLoginService.getToken and check if it is equal to true. How can I achieve that?

```<code>import { async, ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import { AppMetadataHandler } from 'app/BaseFramework/configs';
import { AuthenticationService, LoginService } from 'app/BaseFramework/core';
import { ThreadsService } from 'app/BaseFramework/core/utilities/threads.service';
import { NgZorroAntdModule } from 'app/ng-zorro.module';
import { AsyncSubject, of } from 'rxjs';
import { LoginComponent } from './login.component';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  const mockDb={username:'admin',password:'admin'}
  let mockAuthenticationService;
  let mockAppMetadataHandler;
  // const mockThreadsService= jasmine.createSpyObj<ThreadsService>(['PRELOGINTHREAD'])
  let mockLoginService;

  beforeEach(waitForAsync(() => {
    mockLoginService=jasmine.createSpyObj<LoginService>('mockLogin',['getToken']);
    mockAppMetadataHandler = jasmine.createSpyObj\<AppMetadataHandler>(['getEntryPoint','featureFlags']);
    mockAuthenticationService = jasmine.createSpyObj<AuthenticationService>(['logout','fetchToken'])

    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers:[
        {provide:AuthenticationService,useValue:mockAuthenticationService },
        {provide:AppMetadataHandler,useValue: mockAppMetadataHandler},
        {provide:ThreadsService,useValue: {
          PRELOGINTHREAD: () => of([1,2,3]),
          _errorThreadLog:()=>of('')
       }}
      ],
      imports:[NgZorroAntdModule, RouterTestingModule,TranslateModule.forRoot(),FormsModule,]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {

    expect(component).toBeTruthy();
  });
  it('Should be Login Successful if success is true ', () => {
    component.loginContext={username:'admin',password:'admin'}
    expect(component.loginContext).toEqual(mockDb)
    let returnval = mockLoginService.getToken.and.returnValue(of(true));
    expect(returnval).toEqual(true)
  });

});
</code>```

Angular CLI: 12.2.18

Node: 14.17.3

Package Manager: npm 6.14.13

OS: win32 x64

Angular: 12.2.17

Body:
What I am trying to do is get access to my return value of the mockLoginService.getToken and check if it is equal to true. How can I achieve that?

import { async, ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import { AppMetadataHandler } from 'app/BaseFramework/configs';
import { AuthenticationService, LoginService } from 'app/BaseFramework/core';
import { ThreadsService } from 'app/BaseFramework/core/utilities/threads.service';
import { NgZorroAntdModule } from 'app/ng-zorro.module';
import { AsyncSubject, of } from 'rxjs';
import { LoginComponent } from './login.component';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  const mockDb={username:'admin',password:'admin'}
  let mockAuthenticationService;
  let mockAppMetadataHandler;
  // const mockThreadsService= jasmine.createSpyObj<ThreadsService>(['PRELOGINTHREAD'])
  let mockLoginService;

  beforeEach(waitForAsync(() => {
    mockLoginService=jasmine.createSpyObj<LoginService>('mockLogin',['getToken']);
    mockAppMetadataHandler = jasmine.createSpyObj\<AppMetadataHandler>(['getEntryPoint','featureFlags']);
    mockAuthenticationService = jasmine.createSpyObj<AuthenticationService>(['logout','fetchToken'])

    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      providers:[
        {provide:AuthenticationService,useValue:mockAuthenticationService },
        {provide:AppMetadataHandler,useValue: mockAppMetadataHandler},
        {provide:ThreadsService,useValue: {
          PRELOGINTHREAD: () => of([1,2,3]),
          _errorThreadLog:()=>of('')
       }}
      ],
      imports:[NgZorroAntdModule, RouterTestingModule,TranslateModule.forRoot(),FormsModule,]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {

    expect(component).toBeTruthy();
  });
  it('Should be Login Successful if success is true ', () => {
    component.loginContext={username:'admin',password:'admin'}
    expect(component.loginContext).toEqual(mockDb)
    let returnval = mockLoginService.getToken.and.returnValue(of(true));
    expect(returnval).toEqual(true)
  });

});

Angular CLI: 12.2.18

Node: 14.17.3

Package Manager: npm 6.14.13

OS: win32 x64

Angular: 12.2.17


问:
is there any JDK which will help to resolve my issue
enter image description here

I am not able to run my Test Runner file in my BDD framework

I had change jdk also but still facing same issue


问:
How to clip path in React Native?

In css, to clip the image like abvoe, we can write:

```<code>clip-path: polygon(0 0, 100% 0, 100% 64%, 0% 100%);
</code>```

But how to do the same thing in React Native?

I tried to use clipPath in <Image>, but the property does not exist.

Title: How to clip path in React Native?

Body:
In css, to clip the image like abvoe, we can write:

clip-path: polygon(0 0, 100% 0, 100% 64%, 0% 100%);

But how to do the same thing in React Native?

I tried to use clipPath in <Image>, but the property does not exist.


问:
I tested on the iPhone. The layout viewport is always equal to the visual viewport. Under what circumstances, they will not be equal?
The website tested is https://www.quirksmode.org/mobile/metaviewport/initialscale/1-none.html , I copy the source code to the local, and then modify the meta tag to run.Layout viewport is always equal to visual viewport. Is this a special treatment made by Apple? Under what circumstances can they be unequal?

initial-scale=0.5

<meta name="viewport" content="initial-scale=0.5" />
```
<p><img src="https://i.stack.imgur.com/z7Hv0.png" alt="enter image description here" /></p>
<h3>initial-scale=1</h3>
<pre class="lang-html prettyprint-override"><code><meta name="viewport" content="initial-scale=1" />
</code>```

initial-scale=2

<meta name="viewport" content="initial-scale=2" />
```
<p><img src="https://i.stack.imgur.com/y2aiM.png" alt="enter image description here" /></p>
<h3>width=1000</h3>
<pre class="lang-html prettyprint-override"><code><meta name="viewport" content="width=1000" />
</code>```

width=device-width

<meta name="viewport" content="width=device-width" />
```
<p><img src="https://i.stack.imgur.com/iNBKS.png" alt="enter image description here" /></p>
<h3>width=device-width,initial-scale=2.0</h3>
<pre class="lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width,initial-scale=2.0" />
</code>```

width=device-width,initial-scale=0.5

<meta name="viewport" content="width=device-width,initial-scale=0.5" />
```

Body:
The website tested is https://www.quirksmode.org/mobile/metaviewport/initialscale/1-none.html , I copy the source code to the local, and then modify the meta tag to run.Layout viewport is always equal to visual viewport. Is this a special treatment made by Apple? Under what circumstances can they be unequal?

initial-scale=0.5

<meta name="viewport" content="initial-scale=0.5" />

initial-scale=1

<meta name="viewport" content="initial-scale=1" />

initial-scale=2

<meta name="viewport" content="initial-scale=2" />

width=1000

<meta name="viewport" content="width=1000" />

width=device-width

<meta name="viewport" content="width=device-width" />

width=device-width,initial-scale=2.0

<meta name="viewport" content="width=device-width,initial-scale=2.0" />

width=device-width,initial-scale=0.5

<meta name="viewport" content="width=device-width,initial-scale=0.5" />


问:
Python: Can We SSL wrap any http server to https server?
This is a simple HTTPS python server (not for production use)

```<code># libraries needed:
from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl , socket

# address set
server_ip = '0.0.0.0'
server_port = 3389

# configuring HTTP -> HTTPS
httpd = HTTPServer((server_ip, server_port), SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./public_cert.pem',keyfile='./private_key.pem', server_side=True)
httpd.serve_forever()
</code>```

as you see in the above script i wrap a simple python HTTP server with ssl certificate and make it a simple HTTPS server

Detailed example of python simple HTTPS server

Is there a way to ssl wrap any, already running HTTP server to HTTPS server ?

Suppose I have a HTTP server running at port 8080. Can I just ssl wrap it to port 443?

Body:
This is a simple HTTPS python server (not for production use)

# libraries needed:
from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl , socket

# address set
server_ip = '0.0.0.0'
server_port = 3389

# configuring HTTP -> HTTPS
httpd = HTTPServer((server_ip, server_port), SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./public_cert.pem',keyfile='./private_key.pem', server_side=True)
httpd.serve_forever()

as you see in the above script i wrap a simple python HTTP server with ssl certificate and make it a simple HTTPS server

Detailed example of python simple HTTPS server

Is there a way to ssl wrap any, already running HTTP server to HTTPS server ?

Suppose I have a HTTP server running at port 8080. Can I just ssl wrap it to port 443?


问:
Redirect extracted texts with different directions and circle shapes from image with python
I'm working on extracting text from image with pytesseract OCR and I encountered with image that have texts with different direction(not only just one direction) or folded  or circled and pytesseract cant identification them for example for follow image, pytesseract give me incorrect text .
How can I improve accuracy?
enter image description here</p>


问:
Cant able to play High Quality video in node js local video streaming
Creating a Local media player using node js to stream video in the browser.

I am using below node js code to stream local videos.

```<code>const express = require('express')
const fs = require('fs')
const path = require('path')
const os = require('os')
var walk    = require('walk');
const app = express()
const port = 3000;
const ipaddr = "localhost";

app.use(express.static(path.join(__dirname, 'public')))

app.set('view engine', 'ejs');
const videoHomeDir = os.homedir() + `/Videos`;
var files   = [];

var walker  = walk.walk(videoHomeDir, { followLinks: false });

walker.on('file', function(root, stat, next) {
    files.push(root + '/' + stat.name);
    next();
});

walker.on('end', function() {
    console.log("GOT ALL VIDEOS")
});

app.get('/', function(req, res) {
    res.render('pages/index', {files: files, ipaddress:ipaddr,port:port});
})

app.get('/video/:id', function(req, res) {
  var video = files[req.params.id];
  const path = `${video}`;
  const stat = fs.statSync(path)
  const fileSize = stat.size
  const range = req.headers.range

  if (range) {
    const parts = range.replace(/bytes=/, "").split("-")
    const start = parseInt(parts[0], 10)
    const end = parts[1]
      ? parseInt(parts[1], 10)
      : fileSize-1

    if(start >= fileSize) {
      res.status(416).send('Requested range not satisfiable\n'+start+' >= '+fileSize);
      return
    }

    const chunksize = (end-start)+1
    const file = fs.createReadStream(path, {start, end})
    const head = {
      'Content-Range': 'bytes chunkStart****chunkEnd/chunkSize' ,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    }

    res.writeHead(206, head)
    file.pipe(res)
  } else {
    const head = {
      'Content-Range': `bytes`,
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    }
    res.writeHead(200, head)
    fs.createReadStream(path).pipe(res)
  }

})

app.listen(port, function () {
  console.log(`Listening on port ${port}!`)
})
</code>```

Some video are playing properly but some video with High data rate video are not playing in browser, why? & How to resolve this issue with node js.

Here is the video details shown :

How to resolve this issue with node js

Body:
Creating a Local media player using node js to stream video in the browser.

I am using below node js code to stream local videos.

const express = require('express')
const fs = require('fs')
const path = require('path')
const os = require('os')
var walk    = require('walk');
const app = express()
const port = 3000;
const ipaddr = "localhost";

app.use(express.static(path.join(__dirname, 'public')))

app.set('view engine', 'ejs');
const videoHomeDir = os.homedir() + `/Videos`;
var files   = [];

var walker  = walk.walk(videoHomeDir, { followLinks: false });

walker.on('file', function(root, stat, next) {
    files.push(root + '/' + stat.name);
    next();
});

walker.on('end', function() {
    console.log("GOT ALL VIDEOS")
});

app.get('/', function(req, res) {
    res.render('pages/index', {files: files, ipaddress:ipaddr,port:port});
})

app.get('/video/:id', function(req, res) {
  var video = files[req.params.id];
  const path = `${video}`;
  const stat = fs.statSync(path)
  const fileSize = stat.size
  const range = req.headers.range

  if (range) {
    const parts = range.replace(/bytes=/, "").split("-")
    const start = parseInt(parts[0], 10)
    const end = parts[1]
      ? parseInt(parts[1], 10)
      : fileSize-1

    if(start >= fileSize) {
      res.status(416).send('Requested range not satisfiable\n'+start+' >= '+fileSize);
      return
    }

    const chunksize = (end-start)+1
    const file = fs.createReadStream(path, {start, end})
    const head = {
      'Content-Range': 'bytes chunkStart****chunkEnd/chunkSize' ,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    }

    res.writeHead(206, head)
    file.pipe(res)
  } else {
    const head = {
      'Content-Range': `bytes`,
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    }
    res.writeHead(200, head)
    fs.createReadStream(path).pipe(res)
  }

})

app.listen(port, function () {
  console.log(`Listening on port ${port}!`)
})

Some video are playing properly but some video with High data rate video are not playing in browser, why? & How to resolve this issue with node js.

Here is the video details shown :

How to resolve this issue with node js


问:
How do you place a meeple in a disabled JButton in java swing, awt?

I have a disabled JButton with an icon.

I want to place a meeple on it.

I want a transparent meeple to appear, and if I click(clickable) on this meeple, it becomes opaque

Is it possible to do this on Java Swing?


问:
How to get the angle value using xcubememsmic1 expansion pack?
I am working on a project with 4 mems microphones and I want to get the angle of sound(sound source localization) using xcubememsicmic1 sound expansion pack but I don't know how can I get it?

Anyone who has experience in mems technology and sound source localization, please help me.

I have some of the functions here, please tell me how to use it in my main()?

```<code>uint32_t AcousticSL_Process(int32_t * Estimated_Angle, AcousticSL_Handler_t * pHandler); //taken from AcousticSL.c

static float32_t GCC_GetAngle(libSoundSourceLoc_Handler_Internal * SLocInternal, int32_t * out_angles); //taken from libSoundSourceLoc.c
</code>```

Body:
I am working on a project with 4 mems microphones and I want to get the angle of sound(sound source localization) using xcubememsicmic1 sound expansion pack but I don't know how can I get it?

Anyone who has experience in mems technology and sound source localization, please help me.

I have some of the functions here, please tell me how to use it in my main()?

uint32_t AcousticSL_Process(int32_t * Estimated_Angle, AcousticSL_Handler_t * pHandler); //taken from AcousticSL.c

static float32_t GCC_GetAngle(libSoundSourceLoc_Handler_Internal * SLocInternal, int32_t * out_angles); //taken from libSoundSourceLoc.c


问:
403 Forbidden when post request with unEscape html content in laravel
403 error when this type data save.
this problem is only Namecheap server

when save then result in this

**but without unEscape HTML content  data save successfully **

data seve with unEscape HTML content.

.................. /admin/page/update route point code below

```<code>public function update(Request $request)
{

    $input = $request->all();

    $content = $request->except(['page_code', 'status', '_token']);

    $pageCode = $input['page_code'];
    $page = Page::where('code', $pageCode)->first();

    if ($page->type == 'dynamic') {
        $content = [
            'section_id' => $input['section_id'] ?? null,
            'meta_keywords' => $input['meta_keywords'],
            'meta_description' => $input['meta_description'],
            'content' => Purifier::clean(htmlspecialchars_decode($input['content'])),
        ];

        $data = [
            'title' => $input['title'],
            'data' => json_encode($content),
            'status' => $input['status'],
        ];

    } else {

        $oldData = json_decode($page->data, true);
        foreach ($content as $key => $value) {

            if (is_file($value)) {
                $oldValue = Arr::get($oldData, $key);
                $content[$key] = self::imageUploadTrait($value, $oldValue);

            } elseif ($key == 'content') {
                $content[$key] = Purifier::clean(htmlspecialchars_decode($value));
            }
        }

        $content = array_merge($oldData, $content);

        $data = [
            'status' => $input['status'] ?? true,
            'data' => json_encode($content)
        ];

    }

    $page->update($data);

    if ($page->type == 'dynamic') Cache::pull('pages');

    notify()->success($page->title . ' ' . __(' Updated
       Successfully'));
    return redirect()->back();
}
</code>```

Body:
403 error when this type data save.
this problem is only Namecheap server

when save then result in this

**but without unEscape HTML content  data save successfully **

data seve with unEscape HTML content.

.................. /admin/page/update route point code below

public function update(Request $request)
{

    $input = $request->all();

    $content = $request->except(['page_code', 'status', '_token']);

    $pageCode = $input['page_code'];
    $page = Page::where('code', $pageCode)->first();

    if ($page->type == 'dynamic') {
        $content = [
            'section_id' => $input['section_id'] ?? null,
            'meta_keywords' => $input['meta_keywords'],
            'meta_description' => $input['meta_description'],
            'content' => Purifier::clean(htmlspecialchars_decode($input['content'])),
        ];

        $data = [
            'title' => $input['title'],
            'data' => json_encode($content),
            'status' => $input['status'],
        ];

    } else {

        $oldData = json_decode($page->data, true);
        foreach ($content as $key => $value) {

            if (is_file($value)) {
                $oldValue = Arr::get($oldData, $key);
                $content[$key] = self::imageUploadTrait($value, $oldValue);

            } elseif ($key == 'content') {
                $content[$key] = Purifier::clean(htmlspecialchars_decode($value));
            }
        }

        $content = array_merge($oldData, $content);

        $data = [
            'status' => $input['status'] ?? true,
            'data' => json_encode($content)
        ];

    }

    $page->update($data);

    if ($page->type == 'dynamic') Cache::pull('pages');

    notify()->success($page->title . ' ' . __(' Updated
       Successfully'));
    return redirect()->back();
}


问:
Bootstrap carousel does not start slide automatically on mobile web
My bootstrap carousel slides automatically when I am viewing it on my computer, but it does not on mobile I have to swipe it to get it started on using the carousel inside a react component.

https://codesandbox.io/p/github/Adugnatad/stefan_project/draft/inspiring-albattani?file=%2FREADME.md

```<code><div id="carouselExampleControls" className="relative carousel slide h-full" data-interval="500" data-ride="carousel">
    <div className="carousel-inner">
        <div className="carousel-item active">
            <PageHero background='/assets/homepageHeroSvg.svg' mobileBackground='/assets/mobileBackgroundSvg.svg'>
                <Slide3 />
            </PageHero>
        </div>
        <div className="carousel-item">
            <PageHero background='/assets/homepageHeroSvg.svg' mobileBackground='/assets/mobileBackgroundSvg.svg'>
                <Slide1 />
            </PageHero>
        </div>
        <div className="carousel-item">
            <PageHero background='/assets/homepageHeroSvg.svg' mobileBackground='/assets/mobileBackgroundSvg.svg'>
                <Slide2 />
            </PageHero>
        </div>
    </div>
</div>
</code>```

I have tried to get it started by clicking the button that contains the data-slide on useEffect but it just slides it that one time.

Body:
My bootstrap carousel slides automatically when I am viewing it on my computer, but it does not on mobile I have to swipe it to get it started on using the carousel inside a react component.

https://codesandbox.io/p/github/Adugnatad/stefan_project/draft/inspiring-albattani?file=%2FREADME.md

            <PageHero background='/assets/homepageHeroSvg.svg' mobileBackground='/assets/mobileBackgroundSvg.svg'>
                <Slide3 />
            </PageHero>

            <PageHero background='/assets/homepageHeroSvg.svg' mobileBackground='/assets/mobileBackgroundSvg.svg'>
                <Slide1 />
            </PageHero>

            <PageHero background='/assets/homepageHeroSvg.svg' mobileBackground='/assets/mobileBackgroundSvg.svg'>
                <Slide2 />
            </PageHero>

I have tried to get it started by clicking the button that contains the data-slide on useEffect but it just slides it that one time.