问:
Flutter how can I create a 3 layer stack
I need to show 3 containers but for a column but need to show like they are overlapping

Like this

As you see in the image I need to show 3 widgets Image then this creates a new account title than another container.

My code is just showing an image and the last container I need to know how can I add this middle container as in the image

```<code>Stack(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: statusBarHeight * 0.8),
              height: height * 0.4,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    'assets/images/place2.jpg',
                  ),
                  fit: BoxFit.fill,
                ),
              ),
            ),
            SingleChildScrollView(
              child: Padding(

                padding: EdgeInsets.only(top: height * 0.3),
                child: SingleChildScrollView(
                  child: ClipRRect(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(30), topLeft: Radius.circular(30)),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[

                          SizedBox(
                            height: height * 0.031,
                          ),
                          Container(
                            width: width,
                            margin: EdgeInsets.only(left: 10),
                            child: Text(
                              'PLACES',
                              textAlign: TextAlign.left,
                              style: TextStyle(fontSize: 30),
                            ),
                          ),
                          SizedBox(
                            height: height * 0.02,
                          ),

                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                print('back');
              },
              child: Align(
                alignment: Alignment.topLeft,
                child: Container(
                  margin: EdgeInsets.only(left: width * 0.03),
                  padding: EdgeInsets.only(top: statusBarHeight * 2),

                  child: Icon(
                    Icons.arrow_back_ios,
                    size: 25,
                    color: Colors.white,
                  ),
                ),
              ),
            ),

          ],
        )
</code>```

答:
Try Using 'Stack' widget.
Its Similar to a Column but its Stacks its children on top of each other.
its featured on Flutter Widget of the Week in Here
Read the Usage in Here</p>

Body:
I need to show 3 containers but for a column but need to show like they are overlapping

Like this

As you see in the image I need to show 3 widgets Image then this creates a new account title than another container.

My code is just showing an image and the last container I need to know how can I add this middle container as in the image

Stack(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: statusBarHeight * 0.8),
              height: height * 0.4,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    'assets/images/place2.jpg',
                  ),
                  fit: BoxFit.fill,
                ),
              ),
            ),
            SingleChildScrollView(
              child: Padding(

                padding: EdgeInsets.only(top: height * 0.3),
                child: SingleChildScrollView(
                  child: ClipRRect(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(30), topLeft: Radius.circular(30)),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[

                          SizedBox(
                            height: height * 0.031,
                          ),
                          Container(
                            width: width,
                            margin: EdgeInsets.only(left: 10),
                            child: Text(
                              'PLACES',
                              textAlign: TextAlign.left,
                              style: TextStyle(fontSize: 30),
                            ),
                          ),
                          SizedBox(
                            height: height * 0.02,
                          ),

                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                print('back');
              },
              child: Align(
                alignment: Alignment.topLeft,
                child: Container(
                  margin: EdgeInsets.only(left: width * 0.03),
                  padding: EdgeInsets.only(top: statusBarHeight * 2),

                  child: Icon(
                    Icons.arrow_back_ios,
                    size: 25,
                    color: Colors.white,
                  ),
                ),
              ),
            ),

          ],
        )


来源: stackexchange

问:
Why Django Rest API id not in order?
So, I have django rest api with model like

```<code>class Data(models.Model):
node_id = models.ForeignKey("Node", on_delete=models.CASCADE)
timestamp = models.DateTimeField()
vibration = models.IntegerField()
moisture = models.IntegerField()
gps_latitude = models.CharField(max_length=250)
gps_longitude = models.CharField(max_length=250)
gyro_x = models.FloatField()
gyro_y = models.FloatField()
gyro_z = models.FloatField()
accelero_x = models.FloatField()
accelero_y = models.FloatField()
accelero_z = models.FloatField()
displacement = models.IntegerField()
</code>```

The serializer is like this:

```<code>class DataSerializer(serializers.ModelSerializer):
class Meta:
    model = Data
    fields = '__all__'
</code>```

And the views is like this :

```<code>class DataViewSet(viewsets.ModelViewSet):
    queryset = Data.objects.all()
    serializer_class = DataSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['node_id']
</code>```

You can access my api on : https://gmlews.com/api/data/

The problem is my id on the web page won't come in order. I receive all the data from raspberry pi. Where the problem come from? the code from raspberry or my django rest code?

After id 253, it come id 255,257,259. It should be id 254 and so on in order. How can I handle this id to be in order?

答:
You have to add an ordering field in the Meta of your model :

```<code>class SomeModel(models.Model):
    class Meta:
        ordering = ["id"]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why Django Rest API id not in order?

Body:
So, I have django rest api with model like

class Data(models.Model):
node_id = models.ForeignKey("Node", on_delete=models.CASCADE)
timestamp = models.DateTimeField()
vibration = models.IntegerField()
moisture = models.IntegerField()
gps_latitude = models.CharField(max_length=250)
gps_longitude = models.CharField(max_length=250)
gyro_x = models.FloatField()
gyro_y = models.FloatField()
gyro_z = models.FloatField()
accelero_x = models.FloatField()
accelero_y = models.FloatField()
accelero_z = models.FloatField()
displacement = models.IntegerField()

The serializer is like this:

class DataSerializer(serializers.ModelSerializer):
class Meta:
    model = Data
    fields = '__all__'

And the views is like this :

class DataViewSet(viewsets.ModelViewSet):
    queryset = Data.objects.all()
    serializer_class = DataSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['node_id']

You can access my api on : https://gmlews.com/api/data/

The problem is my id on the web page won't come in order. I receive all the data from raspberry pi. Where the problem come from? the code from raspberry or my django rest code?

After id 253, it come id 255,257,259. It should be id 254 and so on in order. How can I handle this id to be in order?

Body:
You have to add an ordering field in the Meta of your model :

class SomeModel(models.Model):
    class Meta:
        ordering = ["id"]


问:
RuntimeError (never awaited) while using discord.py
I want add to my bot an poll command, which takes an opt1 and opt2 parameters, add two reactions to embed, and users have expir time to vote, then it send an message which option had more votes, but I have an error: RuntimeError: coroutine 'poll.<locals>.whowin' was never awaited. I don't know how to fix it! I tried some solutions, but they didn't work. Here's my code:

```<code>@commands.cooldown(1, 45, commands.BucketType.guild)
async def poll(ctx, title, opt1, opt2, expir):
    try:
        expir = float(expir)
        if expir > 120:
            await ctx.send('Expiration time cannot be greater than 120 seconds.')
            return False
    except:
        await ctx.send('Error while converting `expir` parameter.')
        return False
    pollEmbed=discord.Embed(
        title=title,
        description='React with role below:',
        colour=discord.Colour.blue()
    )
    pollEmbed.add_field(name='Option 1', value=opt1)
    pollEmbed.add_field(name='Option 2', value=opt2)
    thisEmbed = await ctx.send(embed=pollEmbed)
    await discord.Message.add_reaction(thisEmbed, emoji='1\U000020e3')
    await discord.Message.add_reaction(thisEmbed, emoji='2\U000020e3')

    async def whowin():
        if len(users1) > len(users2):
            await ctx.send('People most voted for: {0}'.format(opt1))
            return True
        elif len(users1) < len(users2):
            await ctx.send('People most voted for: {0}'.format(opt2))
            return True
        else:
            await ctx.send('There\'s a tie!')
            return True

    pollTimer = Timer(expir, whowin)
    pollTimer.start()

@bot.event
async def on_reaction_add(reaction, user):
    if discord.Reaction.message == thisEmbed:
        if discord.Reaction.emoji == '1\U000020e3':
            users1.append(user)
        else:
            users2.append(user)
</code>```

I though I knew the answer for second error (NameError): I tried to make thisEmbed global. This fixed it for now, but still having RuntimeError.

答:
From the code you've given, I'm not sure what Timer is doing with the second parameter, but because whowin is a coroutine (i.e. async def), you'll need to call and await it:

pollTimer = Timer(expir, await whowin())
```

However, if you're passing the function into your Timer class, then I'm guessing that you didn't await it in there.

Body:
I want add to my bot an poll command, which takes an opt1 and opt2 parameters, add two reactions to embed, and users have expir time to vote, then it send an message which option had more votes, but I have an error: RuntimeError: coroutine 'poll.<locals>.whowin' was never awaited. I don't know how to fix it! I tried some solutions, but they didn't work. Here's my code:

@commands.cooldown(1, 45, commands.BucketType.guild)
async def poll(ctx, title, opt1, opt2, expir):
    try:
        expir = float(expir)
        if expir > 120:
            await ctx.send('Expiration time cannot be greater than 120 seconds.')
            return False
    except:
        await ctx.send('Error while converting `expir` parameter.')
        return False
    pollEmbed=discord.Embed(
        title=title,
        description='React with role below:',
        colour=discord.Colour.blue()
    )
    pollEmbed.add_field(name='Option 1', value=opt1)
    pollEmbed.add_field(name='Option 2', value=opt2)
    thisEmbed = await ctx.send(embed=pollEmbed)
    await discord.Message.add_reaction(thisEmbed, emoji='1\U000020e3')
    await discord.Message.add_reaction(thisEmbed, emoji='2\U000020e3')

    async def whowin():
        if len(users1) > len(users2):
            await ctx.send('People most voted for: {0}'.format(opt1))
            return True
        elif len(users1) < len(users2):
            await ctx.send('People most voted for: {0}'.format(opt2))
            return True
        else:
            await ctx.send('There\'s a tie!')
            return True

    pollTimer = Timer(expir, whowin)
    pollTimer.start()

@bot.event
async def on_reaction_add(reaction, user):
    if discord.Reaction.message == thisEmbed:
        if discord.Reaction.emoji == '1\U000020e3':
            users1.append(user)
        else:
            users2.append(user)

I though I knew the answer for second error (NameError): I tried to make thisEmbed global. This fixed it for now, but still having RuntimeError.

Body:
From the code you've given, I'm not sure what Timer is doing with the second parameter, but because whowin is a coroutine (i.e. async def), you'll need to call and await it:

pollTimer = Timer(expir, await whowin())

However, if you're passing the function into your Timer class, then I'm guessing that you didn't await it in there.


问:
Access to filesystem in a Mac App JSContext
I am working on a Mac app that uses a JSContext for some functionality.

It uses a call like this (where ctx is a JSContext):

```<code>let result: JSValue? = ctx.evaluateScript("someFunction")?.call(withArguments: [someArg1!, someArg2])
</code>```

Inside the someFunction script, we need to parse a directory and determine whether it exists on the filesystem. Apple's JavaScriptCore API does not have filesystem access as far as I can tell.

Is there some way I can have a function like this in swift:

```<code>    public static func isAppDirectory(_ path: String) -> Bool {
        var isDirectory = ObjCBool(true)
        let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
        return exists && isDirectory.boolValue
    }
</code>```

and pass some custom function pointer into the JSContext to call that function?

答:
You could set up a message handler for a WKWebView. You can then pass data between web view and your app. Answer in Objective-C, but easily adaptable. (I think you should be able to set the message handlers in JavaScriptCore too, but I'm not familiar with it.)

// Set this while configuring WKWebView.
// For this example, we'll use self as the message handler,
// meaning the class that originally sets up the view
[webView.configuration.userContentController addScriptMessageHandler:self name:@"testPath"];
```

<p>You can now send a string to the app from JavaScript:</p>

<pre class="lang-js prettyprint-override"><code>function testPath(path) {
    window.webkit.messageHandlers.testPath.postMessage(path);
}
</code>```

The message handler in Objective-C:

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *) message{
    // .name is the handler's name,
    // .body is the message itself, in this case the path
    if ([message.name isEqualToString:@"testPath"]) {
        ...
        [webView evaluateJavaScript:@"doSomething()"];
    }
}
```

Note that the webkit messages are asynchronous, so you need to implement some sort of structure to continue running your JS code later.

Hope this helps.

Body:
I am working on a Mac app that uses a JSContext for some functionality.

It uses a call like this (where ctx is a JSContext):

let result: JSValue? = ctx.evaluateScript("someFunction")?.call(withArguments: [someArg1!, someArg2])

Inside the someFunction script, we need to parse a directory and determine whether it exists on the filesystem. Apple's JavaScriptCore API does not have filesystem access as far as I can tell.

Is there some way I can have a function like this in swift:

    public static func isAppDirectory(_ path: String) -> Bool {
        var isDirectory = ObjCBool(true)
        let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
        return exists && isDirectory.boolValue
    }

and pass some custom function pointer into the JSContext to call that function?

Body:
You could set up a message handler for a WKWebView. You can then pass data between web view and your app. Answer in Objective-C, but easily adaptable. (I think you should be able to set the message handlers in JavaScriptCore too, but I'm not familiar with it.)

// Set this while configuring WKWebView.
// For this example, we'll use self as the message handler,
// meaning the class that originally sets up the view
[webView.configuration.userContentController addScriptMessageHandler:self name:@"testPath"];

You can now send a string to the app from JavaScript:

function testPath(path) {
    window.webkit.messageHandlers.testPath.postMessage(path);
}

The message handler in Objective-C:

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *) message{
    // .name is the handler's name,
    // .body is the message itself, in this case the path
    if ([message.name isEqualToString:@"testPath"]) {
        ...
        [webView evaluateJavaScript:@"doSomething()"];
    }
}

Note that the webkit messages are asynchronous, so you need to implement some sort of structure to continue running your JS code later.

Hope this helps.


问:
federated learning implementing
I new in python and machine learning. I tried to implement the following code for federated learning with the MNIST dataset but it doesn't work !! it tried to train a model in a distributed way in local workers. the jpeg version of the MNIST data set is using here. It consists of 42000 digit images with each class kept in a separate folder. I will load the data into memory using this code snippet and keep 10% of the data for testing the trained global model later on.
The following error appears when i implement the following fl_implemetation.py

```<code>(base) C:\python1>fl_implemetation.py

  File "C:\python1\fl_implemetation.py", line 112
    global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)
                                                                                ^
SyntaxError: invalid syntax
 there are two python files, first **fl_implemetation.py**.
</code>```

The original code I am using can be found here:
https://github.com/datafrick/tutorial

```<code>import NumPy as np
import random
import cv2
import os
from imutils import paths
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score

import TensorFlow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import backend as K

from fl_mnist_implementation_tutorial_utils import *

#declear path to your mnist data folder
img_path = '/path/to/your/training/dataset'

#get the path list using the path object
image_paths = list(paths.list_images(img_path))

#apply our function
image_list, label_list = load(image_paths, verbose=10000)

#binarize the labels
lb = LabelBinarizer()
label_list = lb.fit_transform(label_list)

#split data into training and test set
X_train, X_test, y_train, y_test = train_test_split(image_list,
                                                    label_list,
                                                    test_size=0.1,
                                                    random_state=42)

#create clients
clients = create_clients(X_train, y_train, num_clients=10, initial='client')

#process and batch the training data for each client
clients_batched = dict()
for (client_name, data) in clients.items():
    clients_batched[client_name] = batch_data(data)

#process and batch the test set
test_batched = tf.data.Dataset.from_tensor_slices((X_test, y_test)).batch(len(y_test))

comms_round = 100

#create optimizer
lr = 0.01
loss='categorical_crossentropy'
metrics = ['accuracy']
optimizer = SGD(lr=lr,
                decay=lr / comms_round,
                momentum=0.9
               )

#initialize global model
smlp_global = SimpleMLP()
global_model = smlp_global.build(784, 10)

#commence global training loop
for comm_round in range(comms_round):

    # get the global model's weights - will serve as the initial weights for all local models
    global_weights = global_model.get_weights()

    #initial list to collect local model weights after scalling
    scaled_local_weight_list = list()

    #randomize client data - using keys
    client_names= list(clients_batched.keys())
    random.shuffle(client_names)

    #loop through each client and create new local model
    for client in client_names:
        smlp_local = SimpleMLP()
        local_model = smlp_local.build(784, 10)
        local_model.compile(loss=loss,
                      optimizer=optimizer,
                      metrics=metrics)

        #set local model weight to the weight of the global model
        local_model.set_weights(global_weights)

        #fit local model with client's data
        local_model.fit(clients_batched[client], epochs=1, verbose=0)

        #scale the model weights and add to list
        scaling_factor = weight_scalling_factor(clients_batched, client)
        scaled_weights = scale_model_weights(local_model.get_weights(), scaling_factor)
        scaled_local_weight_list.append(scaled_weights)

        #clear session to free memory after each communication round
        K.clear_session()

    #to get the average over all the local model, we simply take the sum of the scaled weights
    average_weights = sum_scaled_weights(scaled_local_weight_list)

    #update global model
    global_model.set_weights(average_weights)

    #test global model and print out metrics after each communications round
    for(X_test, Y_test) in test_batched:
        global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)
smlp_SGD = SimpleMLP()
SGD_model = smlp_SGD.build(784, 10)

SGD_model.compile(loss=loss,
              optimizer=optimizer,
              metrics=metrics)

# fit the SGD training data to model
_ = SGD_model.fit(SGD_dataset, epochs=100, verbose=0)

#test the SGD global model and print out metrics
for(X_test, Y_test) in test_batched:
        SGD_acc, SGD_loss = test_model(X_test, Y_test, SGD_model, 1)
</code>```

and second fl_mnist_implementation_tutorial_utils.py

```<code>import NumPy as np
import random
import cv2
import os
from imutils import paths
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score

import TensorFlow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import backend as K

def load(paths, verbose=-1):
    '''expects images for each class in separate dir,
    e.g all digits in 0 class in the directory named 0 '''
    data = list()
    labels = list()
    # loop over the input images
    for (i, imgpath) in enumerate(paths):
        # load the image and extract the class labels
        im_gray = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)
        image = np.array(im_gray).flatten()
        label = imgpath.split(os.path.sep)[-2]
        # scale the image to [0, 1] and add to list
        data.append(image/255)
        labels.append(label)
        # show an update every `verbose` images
        if verbose > 0 and i > 0 and (i + 1) % verbose == 0:
            print("[INFO] processed {}/{}".format(i + 1, len(paths)))
    # return a tuple of the data and labels
    return data, labels

def create_clients(image_list, label_list, num_clients=10, initial='clients'):
    ''' return: a dictionary with keys clients' names and value as
                data shards - tuple of images and label lists.
        args:
            image_list: a list of numpy arrays of training images
            label_list:a list of binarized labels for each image
            num_client: number of fedrated members (clients)
            initials: the clients'name prefix, e.g, clients_1

    '''

    #create a list of client names
    client_names = ['{}_{}'.format(initial, i+1) for i in range(num_clients)]

    #randomize the data
    data = list(zip(image_list, label_list))
    random.shuffle(data)

    #shard data and place at each client
    size = len(data)//num_clients
    shards = [data[i:i + size] for i in range(0, size*num_clients, size)]

    #number of clients must equal number of shards
    assert(len(shards) == len(client_names))

    return {client_names[i] : shards[i] for i in range(len(client_names))}

def batch_data(data_shard, bs=32):
    '''Takes in a clients data shard and create a tfds object off it
    args:
        shard: a data, label constituting a client's data shard
        bs:batch size
    return:
        tfds object'''
    #seperate shard into data and labels lists
    data, label = zip(*data_shard)
    dataset = tf.data.Dataset.from_tensor_slices((list(data), list(label)))
    return dataset.shuffle(len(label)).batch(bs)

class SimpleMLP:
    @staticmethod
    def build(shape, classes):
        model = Sequential()
        model.add(Dense(200, input_shape=(shape,)))
        model.add(Activation("relu"))
        model.add(Dense(200))
        model.add(Activation("relu"))
        model.add(Dense(classes))
        model.add(Activation("softmax"))
        return model

def weight_scalling_factor(clients_trn_data, client_name):
    client_names = list(clients_trn_data.keys())
    #get the bs
    bs = list(clients_trn_data[client_name])[0][0].shape[0]
    #first calculate the total training data points across clinets
    global_count = sum([tf.data.experimental.cardinality(clients_trn_data[client_name]).numpy() for client_name in client_names])*bs
    # get the total number of data points held by a client
    local_count = tf.data.experimental.cardinality(clients_trn_data[client_name]).numpy()*bs
    return local_count/global_count

def scale_model_weights(weight, scalar):
    '''function for scaling a models weights'''
    weight_final = []
    steps = len(weight)
    for i in range(steps):
        weight_final.append(scalar * weight[i])
    return weight_final

def sum_scaled_weights(scaled_weight_list):
    '''Return the sum of the listed scaled weights. The is equivalent to scaled avg of the weights'''
    avg_grad = list()
    #get the average grad accross all client gradients
    for grad_list_tuple in zip(*scaled_weight_list):
        layer_mean = tf.math.reduce_sum(grad_list_tuple, axis=0)
        avg_grad.append(layer_mean)

    return avg_grad

def test_model(X_test, Y_test,  model, comm_round):
    cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
    #logits = model.predict(X_test, batch_size=100)
    logits = model.predict(X_test)
    loss = cce(Y_test, logits)
    acc = accuracy_score(tf.argmax(logits, axis=1), tf.argmax(Y_test, axis=1))
    print('comm_round: {} | global_acc: {:.3%} | global_loss: {}'.format(comm_round, acc, loss))
    return acc, loss
</code>```

答:
You forgot to add \n in this line:

```<code>global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)
</code>```

So, this line should be two lines like so:

```<code>global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)

SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)
</code>```

Title: federated learning implementing

Body:
I new in python and machine learning. I tried to implement the following code for federated learning with the MNIST dataset but it doesn't work !! it tried to train a model in a distributed way in local workers. the jpeg version of the MNIST data set is using here. It consists of 42000 digit images with each class kept in a separate folder. I will load the data into memory using this code snippet and keep 10% of the data for testing the trained global model later on.
The following error appears when i implement the following fl_implemetation.py

(base) C:\python1>fl_implemetation.py

  File "C:\python1\fl_implemetation.py", line 112
    global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)
                                                                                ^
SyntaxError: invalid syntax
 there are two python files, first **fl_implemetation.py**.

The original code I am using can be found here:
https://github.com/datafrick/tutorial

import NumPy as np
import random
import cv2
import os
from imutils import paths
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score

import TensorFlow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import backend as K

from fl_mnist_implementation_tutorial_utils import *

#declear path to your mnist data folder
img_path = '/path/to/your/training/dataset'

#get the path list using the path object
image_paths = list(paths.list_images(img_path))

#apply our function
image_list, label_list = load(image_paths, verbose=10000)

#binarize the labels
lb = LabelBinarizer()
label_list = lb.fit_transform(label_list)

#split data into training and test set
X_train, X_test, y_train, y_test = train_test_split(image_list,
                                                    label_list,
                                                    test_size=0.1,
                                                    random_state=42)

#create clients
clients = create_clients(X_train, y_train, num_clients=10, initial='client')

#process and batch the training data for each client
clients_batched = dict()
for (client_name, data) in clients.items():
    clients_batched[client_name] = batch_data(data)

#process and batch the test set
test_batched = tf.data.Dataset.from_tensor_slices((X_test, y_test)).batch(len(y_test))

comms_round = 100

#create optimizer
lr = 0.01
loss='categorical_crossentropy'
metrics = ['accuracy']
optimizer = SGD(lr=lr,
                decay=lr / comms_round,
                momentum=0.9
               )

#initialize global model
smlp_global = SimpleMLP()
global_model = smlp_global.build(784, 10)

#commence global training loop
for comm_round in range(comms_round):

    # get the global model's weights - will serve as the initial weights for all local models
    global_weights = global_model.get_weights()

    #initial list to collect local model weights after scalling
    scaled_local_weight_list = list()

    #randomize client data - using keys
    client_names= list(clients_batched.keys())
    random.shuffle(client_names)

    #loop through each client and create new local model
    for client in client_names:
        smlp_local = SimpleMLP()
        local_model = smlp_local.build(784, 10)
        local_model.compile(loss=loss,
                      optimizer=optimizer,
                      metrics=metrics)

        #set local model weight to the weight of the global model
        local_model.set_weights(global_weights)

        #fit local model with client's data
        local_model.fit(clients_batched[client], epochs=1, verbose=0)

        #scale the model weights and add to list
        scaling_factor = weight_scalling_factor(clients_batched, client)
        scaled_weights = scale_model_weights(local_model.get_weights(), scaling_factor)
        scaled_local_weight_list.append(scaled_weights)

        #clear session to free memory after each communication round
        K.clear_session()

    #to get the average over all the local model, we simply take the sum of the scaled weights
    average_weights = sum_scaled_weights(scaled_local_weight_list)

    #update global model
    global_model.set_weights(average_weights)

    #test global model and print out metrics after each communications round
    for(X_test, Y_test) in test_batched:
        global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)
smlp_SGD = SimpleMLP()
SGD_model = smlp_SGD.build(784, 10)

SGD_model.compile(loss=loss,
              optimizer=optimizer,
              metrics=metrics)

# fit the SGD training data to model
_ = SGD_model.fit(SGD_dataset, epochs=100, verbose=0)

#test the SGD global model and print out metrics
for(X_test, Y_test) in test_batched:
        SGD_acc, SGD_loss = test_model(X_test, Y_test, SGD_model, 1)

and second fl_mnist_implementation_tutorial_utils.py

import NumPy as np
import random
import cv2
import os
from imutils import paths
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score

import TensorFlow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import backend as K

def load(paths, verbose=-1):
    '''expects images for each class in separate dir,
    e.g all digits in 0 class in the directory named 0 '''
    data = list()
    labels = list()
    # loop over the input images
    for (i, imgpath) in enumerate(paths):
        # load the image and extract the class labels
        im_gray = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)
        image = np.array(im_gray).flatten()
        label = imgpath.split(os.path.sep)[-2]
        # scale the image to [0, 1] and add to list
        data.append(image/255)
        labels.append(label)
        # show an update every `verbose` images
        if verbose > 0 and i > 0 and (i + 1) % verbose == 0:
            print("[INFO] processed {}/{}".format(i + 1, len(paths)))
    # return a tuple of the data and labels
    return data, labels

def create_clients(image_list, label_list, num_clients=10, initial='clients'):
    ''' return: a dictionary with keys clients' names and value as
                data shards - tuple of images and label lists.
        args:
            image_list: a list of numpy arrays of training images
            label_list:a list of binarized labels for each image
            num_client: number of fedrated members (clients)
            initials: the clients'name prefix, e.g, clients_1

    '''

    #create a list of client names
    client_names = ['{}_{}'.format(initial, i+1) for i in range(num_clients)]

    #randomize the data
    data = list(zip(image_list, label_list))
    random.shuffle(data)

    #shard data and place at each client
    size = len(data)//num_clients
    shards = [data[i:i + size] for i in range(0, size*num_clients, size)]

    #number of clients must equal number of shards
    assert(len(shards) == len(client_names))

    return {client_names[i] : shards[i] for i in range(len(client_names))}

def batch_data(data_shard, bs=32):
    '''Takes in a clients data shard and create a tfds object off it
    args:
        shard: a data, label constituting a client's data shard
        bs:batch size
    return:
        tfds object'''
    #seperate shard into data and labels lists
    data, label = zip(*data_shard)
    dataset = tf.data.Dataset.from_tensor_slices((list(data), list(label)))
    return dataset.shuffle(len(label)).batch(bs)

class SimpleMLP:
    @staticmethod
    def build(shape, classes):
        model = Sequential()
        model.add(Dense(200, input_shape=(shape,)))
        model.add(Activation("relu"))
        model.add(Dense(200))
        model.add(Activation("relu"))
        model.add(Dense(classes))
        model.add(Activation("softmax"))
        return model

def weight_scalling_factor(clients_trn_data, client_name):
    client_names = list(clients_trn_data.keys())
    #get the bs
    bs = list(clients_trn_data[client_name])[0][0].shape[0]
    #first calculate the total training data points across clinets
    global_count = sum([tf.data.experimental.cardinality(clients_trn_data[client_name]).numpy() for client_name in client_names])*bs
    # get the total number of data points held by a client
    local_count = tf.data.experimental.cardinality(clients_trn_data[client_name]).numpy()*bs
    return local_count/global_count

def scale_model_weights(weight, scalar):
    '''function for scaling a models weights'''
    weight_final = []
    steps = len(weight)
    for i in range(steps):
        weight_final.append(scalar * weight[i])
    return weight_final

def sum_scaled_weights(scaled_weight_list):
    '''Return the sum of the listed scaled weights. The is equivalent to scaled avg of the weights'''
    avg_grad = list()
    #get the average grad accross all client gradients
    for grad_list_tuple in zip(*scaled_weight_list):
        layer_mean = tf.math.reduce_sum(grad_list_tuple, axis=0)
        avg_grad.append(layer_mean)

    return avg_grad

def test_model(X_test, Y_test,  model, comm_round):
    cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
    #logits = model.predict(X_test, batch_size=100)
    logits = model.predict(X_test)
    loss = cce(Y_test, logits)
    acc = accuracy_score(tf.argmax(logits, axis=1), tf.argmax(Y_test, axis=1))
    print('comm_round: {} | global_acc: {:.3%} | global_loss: {}'.format(comm_round, acc, loss))
    return acc, loss

Body:
You forgot to add \n in this line:

global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)

So, this line should be two lines like so:

global_acc, global_loss = test_model(X_test, Y_test, global_model, comm_round)

SGD_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(len(y_train)).batch(320)


问:
JPlayer issue in IE9
i think there is a problem in jquery.jplayer.min.js file which one i am using.

My jplayer is not working in only IE9.

its working in all other browser.

答: The problem is IE9 like always jaa, try playing ogg files or m4a and that works</p>

ContentLicense: CC BY-SA 3.0

Title: JPlayer issue in IE9


问:
How to loop multiple form input and assign into sql query in php?
```<code>public function add_employee($input)
{
    $key_array = null;
    $value_array = null;
    $bind_array = null;
    foreach ($input as $column => $value) {
        if ($value) {
            #$bind_array => ?, ?, ?;
            #$value_array => [$value1, $value2, $value3];
            #$key_array => column1, column2, column3;
        }
    }
    $sql = "INSERT INTO ol_employee ($key_array) VALUES ($bind_array)";
    $this->db->query($sql, $value_array);
}
</code>```

Refer to comment in the function, how to achieve that output?
the idea is, from the input POST i get which over 27 fields, i just want to fill in into the $sql query i prepared as you can see. I don't think writing each table column manually is a good way.

im using Codeigniter 4 php framework + postgresql.

答:
According to CodeIgniter 4 documentation, you can do this inside your loop for each employee:</p>

```<code>$data = [
    'title' => $title,
    'name'  => $name,
    'date'  => $date
];

$db->table('mytable')->insert($data);
</code>```

Body:
public function add_employee($input)
{
    $key_array = null;
    $value_array = null;
    $bind_array = null;
    foreach ($input as $column => $value) {
        if ($value) {
            #$bind_array => ?, ?, ?;
            #$value_array => [$value1, $value2, $value3];
            #$key_array => column1, column2, column3;
        }
    }
    $sql = "INSERT INTO ol_employee ($key_array) VALUES ($bind_array)";
    $this->db->query($sql, $value_array);
}

Refer to comment in the function, how to achieve that output?
the idea is, from the input POST i get which over 27 fields, i just want to fill in into the $sql query i prepared as you can see. I don't think writing each table column manually is a good way.

im using Codeigniter 4 php framework + postgresql.

Body:
According to CodeIgniter 4 documentation, you can do this inside your loop for each employee:

$data = [
    'title' => $title,
    'name'  => $name,
    'date'  => $date
];

$db->table('mytable')->insert($data);


问:
Keep pandas index while applying sklearn
I have a dataset which has a DateTime index and I'm using PCA from sklearn to reduce the number of dimensions.

The following question bugs me - will PCA keep the order of the points in my series so that I can reuse the index from the original dataframe?

```<code>df = pd.DataFrame(...)
df2 = pca.fit_transform(df)
df2.index = df.index
</code>```

Moreover, is there a better (safer) approach than doing this?

答:
Moreover, is there a better (safer) approach than doing this?

What you do is safe. But a cleaner way to do this is to wrap the output in either a DataFrame or Series and provide the original index. In your example:

df = pd.DataFrame(...)
df2 = pd.DataFrame(pca.fit_transform(df), index=df.index)
```

<p>This is very useful when dealing with prediction vectors (np.ndarrays) out of a sci-kit learn model:</p>

<pre class="lang-py prettyprint-override"><code>y_pred = pd.Series(clf.predict(X_train), index=X_train.index)
</code>```

This is important when you have a more complicated index, like a MultiIndex.

Body:
I have a dataset which has a DateTime index and I'm using PCA from sklearn to reduce the number of dimensions.

The following question bugs me - will PCA keep the order of the points in my series so that I can reuse the index from the original dataframe?

df = pd.DataFrame(...)
df2 = pca.fit_transform(df)
df2.index = df.index

Moreover, is there a better (safer) approach than doing this?

Body:
Moreover, is there a better (safer) approach than doing this?

What you do is safe. But a cleaner way to do this is to wrap the output in either a DataFrame or Series and provide the original index. In your example:

df = pd.DataFrame(...)
df2 = pd.DataFrame(pca.fit_transform(df), index=df.index)

This is very useful when dealing with prediction vectors (np.ndarrays) out of a sci-kit learn model:

y_pred = pd.Series(clf.predict(X_train), index=X_train.index)

This is important when you have a more complicated index, like a MultiIndex.


答:
You can use array and implode function first make array of key_array, value_array and bind_array then use implode() and use in sql like following </p>

```<code>public function add_employee($input)
{
    $key_array = array();
    $value_array = array();
    $bind_array = array();
    foreach ($input as $column => $value) {
        if ($value) {
            $bind_array[] = '?';
            $value_array[] = $value;
            $key_array[] = $column;
        }
    }

    $binds = implode(",",$bind_array);
    $keys = implode(",",$key_array);
    $values = implode(",",$value_array);
    $sql = "INSERT INTO ol_employee ($keys) VALUES ($binds)";
    $this->db->query($sql,$values);
}
</code>```

Title: How to loop multiple form input and assign into sql query in php?

Body:
You can use array and implode function first make array of key_array, value_array and bind_array then use implode() and use in sql like following

public function add_employee($input)
{
    $key_array = array();
    $value_array = array();
    $bind_array = array();
    foreach ($input as $column => $value) {
        if ($value) {
            $bind_array[] = '?';
            $value_array[] = $value;
            $key_array[] = $column;
        }
    }

    $binds = implode(",",$bind_array);
    $keys = implode(",",$key_array);
    $values = implode(",",$value_array);
    $sql = "INSERT INTO ol_employee ($keys) VALUES ($binds)";
    $this->db->query($sql,$values);
}


问:
switch while won't loop
This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).</p>

```<code>static void Main(string[] args)
    {
        int minutos_restantes = 480;
        int opcion;
        int valorComercial = 0;
        Tarea[] listado_tareas = new Tarea[10];

        CrearTareas(ref listado_tareas);

        Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
        opcion = Convert.ToInt32(Console.ReadLine());

        switch (opcion)
        {
            case 1:
                Imprimirtareas(listado_tareas);
                break;

            case 2:
                Console.WriteLine("Seleccionar número de tarea: ");
                int n = Convert.ToInt32(Console.ReadLine())-1;

                if (n < 0 || n > 10)
                {
                    Console.WriteLine("TAREA INEXISTENTE");
                }

                else if (listado_tareas[n].realizada == true)
                {
                    Console.WriteLine("TAREA YA REALIZADA");
                }

                else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
                {
                    Console.WriteLine("TIEMPO INSUFICIENTE");
                }

                else
                {
                    listado_tareas[n].realizada = true;
                    minutos_restantes -= listado_tareas[n].tiempo;
                }

                break;
        } while (opcion != 3) ;

    }
</code>```

答:
You should do :-</p>

```<code>while (condition)
{
     switch
     {

     }
}
</code>```

Title: switch while won't loop

Body:
This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).

static void Main(string[] args)
    {
        int minutos_restantes = 480;
        int opcion;
        int valorComercial = 0;
        Tarea[] listado_tareas = new Tarea[10];

        CrearTareas(ref listado_tareas);

        Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
        opcion = Convert.ToInt32(Console.ReadLine());

        switch (opcion)
        {
            case 1:
                Imprimirtareas(listado_tareas);
                break;

            case 2:
                Console.WriteLine("Seleccionar número de tarea: ");
                int n = Convert.ToInt32(Console.ReadLine())-1;

                if (n < 0 || n > 10)
                {
                    Console.WriteLine("TAREA INEXISTENTE");
                }

                else if (listado_tareas[n].realizada == true)
                {
                    Console.WriteLine("TAREA YA REALIZADA");
                }

                else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
                {
                    Console.WriteLine("TIEMPO INSUFICIENTE");
                }

                else
                {
                    listado_tareas[n].realizada = true;
                    minutos_restantes -= listado_tareas[n].tiempo;
                }

                break;
        } while (opcion != 3) ;

    }

Body:
You should do :-

while (condition)
{
     switch
     {

     }
}


问:
How do I create an array of pointers?
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:

```<code>Student * db = new Student[5];
</code>```

But each element in that array is the student object, not a pointer to the student object.
Thanks.

答:
```<code>Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];
</code>```

OwnerDisplayName: chustar

ContentLicense: CC BY-SA 2.5

Title: How do I create an array of pointers?

Body:
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:

Student * db = new Student[5];

But each element in that array is the student object, not a pointer to the student object.
Thanks.

OwnerDisplayName: Mehrdad Afshari

LastEditorDisplayName: Mehrdad Afshari


问:
Advanced Transfer Project Standards Functionality Using Revit API
I would like to create Revit plugin using Revit API for transferring project standards between multiple Revit projects. Is this possible using Revit API?</p>

答:
Does this help at all?

http://autodesk-revit.blogspot.com/2008/11/managing-project-standards.html


问:
404 error in spring cloud gateway for every alternate request
I am encountering a very peculiar problem in spring cloud gateway. Every alternate request returns a 404. This happens across all services I've configured in the api-gateway without exception. I don't even know where to start to debug this problem.

Here's my application.yml file for common config.

```<code>server:
  port: 8080
  ssl:
    enabled: true
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: pkcs12
    key-alias: tomcat

security:
  require-ssl=true:
logging:
  level:
    org:
      springframework:
        cloud.gateway: DEBUG
        http.server.reactive: DEBUG
        web.reactive: DEBUG

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true
</code>```

Here's my java config file

```<code>
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
                                                            ReactiveClientRegistrationRepository clientRegistrationRepository) {
        // Authenticate through configured OpenID Provider
        http.oauth2Login();
        // Also logout at the OpenID Connect provider
        http.logout(logout -> logout.logoutSuccessHandler(new OidcClientInitiatedServerLogoutSuccessHandler(
                clientRegistrationRepository)));
        // Require authentication for all requests
        http.authorizeExchange().anyExchange().authenticated();
        // Allow showing /home within a frame
        http.headers().frameOptions().mode(Mode.SAMEORIGIN);
        // Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
        http.csrf().disable();
        return http.build();
    }
}
</code>```

Here's the spring profile specific config file that gets loaded on top of the common application.yml file.

```<code>spring:
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuerUri: http://localhost:9080/auth/realms/mylocal
            userNameAttribute: preferred_username
        registration:
          keycloak:
            clientId: api-gateway-client
            clientSecret: abcdefgh-ijkl-mnop-qrst-uvwxyz5d6a9
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      routes:
        - id: news
          uri: http://localhost:8082/news
          predicates:
            - Path= /news/**
        - id: customers
          uri: http://localhost:8083/customers
          predicates:
            - Path= /boards/**
        - id: search
          uri: http://localhost:8085/search
          predicates:
            - Path= /search/**
</code>```

答: Hey i got the issue recently too, I figure out that it was the load balancing the issue. Make sure that your spring.application.name of the microservice that you try to contact are all in capital letter (EXAMPLE) especially if you use Eureka. (hope it helps)</p>

Body:
I am encountering a very peculiar problem in spring cloud gateway. Every alternate request returns a 404. This happens across all services I've configured in the api-gateway without exception. I don't even know where to start to debug this problem.

Here's my application.yml file for common config.

server:
  port: 8080
  ssl:
    enabled: true
    key-store: classpath:keystore.p12
    key-store-password: password
    key-store-type: pkcs12
    key-alias: tomcat

security:
  require-ssl=true:
logging:
  level:
    org:
      springframework:
        cloud.gateway: DEBUG
        http.server.reactive: DEBUG
        web.reactive: DEBUG

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true

Here's my java config file

@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
                                                            ReactiveClientRegistrationRepository clientRegistrationRepository) {
        // Authenticate through configured OpenID Provider
        http.oauth2Login();
        // Also logout at the OpenID Connect provider
        http.logout(logout -> logout.logoutSuccessHandler(new OidcClientInitiatedServerLogoutSuccessHandler(
                clientRegistrationRepository)));
        // Require authentication for all requests
        http.authorizeExchange().anyExchange().authenticated();
        // Allow showing /home within a frame
        http.headers().frameOptions().mode(Mode.SAMEORIGIN);
        // Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
        http.csrf().disable();
        return http.build();
    }
}

Here's the spring profile specific config file that gets loaded on top of the common application.yml file.

spring:
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuerUri: http://localhost:9080/auth/realms/mylocal
            userNameAttribute: preferred_username
        registration:
          keycloak:
            clientId: api-gateway-client
            clientSecret: abcdefgh-ijkl-mnop-qrst-uvwxyz5d6a9
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      routes:
        - id: news
          uri: http://localhost:8082/news
          predicates:
            - Path= /news/**
        - id: customers
          uri: http://localhost:8083/customers
          predicates:
            - Path= /boards/**
        - id: search
          uri: http://localhost:8085/search
          predicates:
            - Path= /search/**


问:
× TypeError: Cannot read property 'map' of undefined. found error
Can anyone pls help me out with this problem?

const Users = ({ users, loading }) => {
  if (loading) {
    return <Spinner />
  } else {
    return (

        {users.map((user) => (
          <UserItem key={users.id} user={user} />
        ))}

    )
  }
}
```

答:
Inside the map, you should use user not users so the code will be

```<code>{ users.map((user) => (
          <UserItem key={user.id} user={user} />
))}

Because, you are passing user as a argument for callback function not users.
</code>```

Body:
Inside the map, you should use user not users so the code will be

{ users.map((user) => (
          <UserItem key={user.id} user={user} />
))}

Because, you are passing user as a argument for callback function not users.


问:
Lambda(private subnet) to Lambda(public subnet) invocation timing out
I have 2 lambdas, both inside my VPC. There are 4 subnets inside my VPC, 2 are public and 2 are private.

I have one lambda inside one private subnet and other one inside public subnet. When I am trying to call the lambda in private subnet from the one in public subnet, it times out. I am using the boto3 to make lambda to lambda call as given here.

However, I am able to call the lambda from public subnet to a new lambda created in other public subnet inside the same VPC.

There is no NAT attached to the public subnet. Why this might be happening?

答:
The call from public subnet times out because lambda function in a VPC does not have public IP nor internet access. From docs:

Connecting a function to a public subnet does not give it internet access or a public IP address.

Also, you can't call lambda through its elastic network interface (ENI) when it is in a VPC. The VPC functionality for lambda is for your functions to call private resources in the VPC, not the other way around.

In other words, the only reason to put a lambda in a VPC is to access its private resources (e.g. RDS in private subnet). It doesn't not allow, e.g., a private instance in a private subnet to call your lambda function without NAT gateway/instance.


问:
Too many GetRecords count compared to PutRecords in Kinesis Stream resulting duplicate records
I have a Kinesis Stream that has three shards and the Producer applications write to the stream with a random partition key. In Kinesis Metric, I found that the count of GetRecords.Records is almost double to that of PutRecords.Records count.

To be precise count (in a minute):

PutRecords.Records: 10749

GetRecords.Records: 21496

Because of this, the Kinesis Record Processor which is lambda in my case, is getting a lot of duplicate records.

AWS document does suggest there would be some duplicates by “at least once” delivery mechanism of Kinesis stream. But almost the double of GetRecords is not very appropriate. Here is my SAM template for the processor lambda.

```<code>  MyStream:
  Type: AWS::Kinesis::Stream
  Properties:
    Name: my-stream
    ShardCount: 3

  MyStreamProcessorLambda:
   Type: AWS::Serverless::Function
   Properties:
    FunctionName: my-stream-processor-lambda
   ...
   ...
   Events:
    Stream:
      Type: Kinesis
      Properties:
        Stream: !Ref MyStream
        BatchSize: 10000
        StartingPosition: LATEST
        MaximumBatchingWindowInSeconds: 300
</code>```

The processor lambda is now, idempotent by enforcing a DB constraint such that same Record from the Batch will never be inserted in DB. Also the Error Rate of Lambda is 0. (No errors/ retries by the lambda)

Also the GetRecords.IteratorAgeMilliseconds  in Stream Metrics is 0 and Read/Write ThroughputExceeded is 0.

Thus, I would like to get rid of those Duplicate records in the Batch, the lambda is processing.

Any configuration that have gone wrong here ?

答: It seems in Kinesis enhanced fan-out consumer, the SubscribeToShard also get all Records from GetRecords call. This is the reason the GetRecords count is almost twice as that of PutRecords.

Body:
I have a Kinesis Stream that has three shards and the Producer applications write to the stream with a random partition key. In Kinesis Metric, I found that the count of GetRecords.Records is almost double to that of PutRecords.Records count.

To be precise count (in a minute):

PutRecords.Records: 10749

GetRecords.Records: 21496

Because of this, the Kinesis Record Processor which is lambda in my case, is getting a lot of duplicate records.

AWS document does suggest there would be some duplicates by “at least once” delivery mechanism of Kinesis stream. But almost the double of GetRecords is not very appropriate. Here is my SAM template for the processor lambda.

  MyStream:
  Type: AWS::Kinesis::Stream
  Properties:
    Name: my-stream
    ShardCount: 3

  MyStreamProcessorLambda:
   Type: AWS::Serverless::Function
   Properties:
    FunctionName: my-stream-processor-lambda
   ...
   ...
   Events:
    Stream:
      Type: Kinesis
      Properties:
        Stream: !Ref MyStream
        BatchSize: 10000
        StartingPosition: LATEST
        MaximumBatchingWindowInSeconds: 300

The processor lambda is now, idempotent by enforcing a DB constraint such that same Record from the Batch will never be inserted in DB. Also the Error Rate of Lambda is 0. (No errors/ retries by the lambda)

Also the GetRecords.IteratorAgeMilliseconds  in Stream Metrics is 0 and Read/Write ThroughputExceeded is 0.

Thus, I would like to get rid of those Duplicate records in the Batch, the lambda is processing.

Any configuration that have gone wrong here ?


问:
How to set up multiple brokers on the Kafka Cluster with jhipster
I created a basic app with jhipster and added Apache Kafka. I have no problem producing and consuming even with another solution (from my app to a php client for kafka).
Now, I want to create multiple brokers on the cluster, but from java not the .sh files.

I know the cluster is setup with the server.properties file where the id of the brokers, the log dir and other things are implied. But in my jhipster app the broker id is declared in the kafka.yml so I guess I have to edit the .yml files to declare another broker.

```<code>version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.2.1
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
      ZOOKEEPER_SYNC_LIMIT: 2
    ports:
      - 2181:2181
  kafka:
    image: confluentinc/cp-kafka:5.2.1
    environment:
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_BROKER_ID: 2
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    ports:
      - 9092:9092
</code>```

The goal is to have one jhipster app with kafka, creating multiple brokers in the cluster instead of one. Therefore I would have multiple topics.
I don't have any results

答:
With this docker-compose.yml you get a cluster with three brokers. The brokers are accessible from inside docker as kafka1:9092, kafka2:9092, kafka3:9092 and from docker host as localhost:19092,localhost:29092,localhost:39092:

```<code>version: "3.7"
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.4.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka1:
    image: confluentinc/cp-server:5.4.0
    hostname: kafka1
    container_name: kafka1
    depends_on:
      - zookeeper
    ports:
      - "19092:19092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP:PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka1:9092,PLAINTEXT_HOST://localhost:19092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'

  kafka2:
    image: confluentinc/cp-server:5.4.0
    hostname: kafka2
    container_name: kafka2
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 102
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka2:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'

  kafka3:
    image: confluentinc/cp-server:5.4.0
    hostname: kafka3
    container_name: kafka3
    depends_on:
      - zookeeper
    ports:
      - "39092:39092"
    environment:
      KAFKA_BROKER_ID: 3
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka3:9092,PLAINTEXT_HOST://localhost:39092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'
</code>```

Body:
I created a basic app with jhipster and added Apache Kafka. I have no problem producing and consuming even with another solution (from my app to a php client for kafka).
Now, I want to create multiple brokers on the cluster, but from java not the .sh files.

I know the cluster is setup with the server.properties file where the id of the brokers, the log dir and other things are implied. But in my jhipster app the broker id is declared in the kafka.yml so I guess I have to edit the .yml files to declare another broker.

version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.2.1
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
      ZOOKEEPER_SYNC_LIMIT: 2
    ports:
      - 2181:2181
  kafka:
    image: confluentinc/cp-kafka:5.2.1
    environment:
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_BROKER_ID: 2
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    ports:
      - 9092:9092

The goal is to have one jhipster app with kafka, creating multiple brokers in the cluster instead of one. Therefore I would have multiple topics.
I don't have any results

Body:
With this docker-compose.yml you get a cluster with three brokers. The brokers are accessible from inside docker as kafka1:9092, kafka2:9092, kafka3:9092 and from docker host as localhost:19092,localhost:29092,localhost:39092:

version: "3.7"
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.4.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka1:
    image: confluentinc/cp-server:5.4.0
    hostname: kafka1
    container_name: kafka1
    depends_on:
      - zookeeper
    ports:
      - "19092:19092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP:PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka1:9092,PLAINTEXT_HOST://localhost:19092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'

  kafka2:
    image: confluentinc/cp-server:5.4.0
    hostname: kafka2
    container_name: kafka2
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 102
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka2:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'

  kafka3:
    image: confluentinc/cp-server:5.4.0
    hostname: kafka3
    container_name: kafka3
    depends_on:
      - zookeeper
    ports:
      - "39092:39092"
    environment:
      KAFKA_BROKER_ID: 3
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka3:9092,PLAINTEXT_HOST://localhost:39092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_CONFLUENT_LICENSE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'


问:
Command terminal
using terminal windows, or cmd, powershell, there is a problem with the fact that I can not install using the script. that is: there is a 'php init' command after entering it, you must select one of two values. but the command line simply ignores all this and asks for an already new command. and she just stops that team.
how to deal with this?

Yes indeed. Data must be obtained in a new team. The php command should be open, but it should be completed. Here is an example of CMD work

```<code>C:\wamp64\www\yiip> php init
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?

[0] Development
[1] Production

Your choice [0-1, or "q" to quit] Quit initialization.
PS C:\wamp64\www\yiip>
</code>```

Gif work CMD terminal

答: I don't really understand but maybe php is not installed as a path variable? </p>

Title: Command terminal

Body:
using terminal windows, or cmd, powershell, there is a problem with the fact that I can not install using the script. that is: there is a 'php init' command after entering it, you must select one of two values. but the command line simply ignores all this and asks for an already new command. and she just stops that team.
how to deal with this?

Yes indeed. Data must be obtained in a new team. The php command should be open, but it should be completed. Here is an example of CMD work

C:\wamp64\www\yiip> php init
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?

[0] Development
[1] Production

Your choice [0-1, or "q" to quit] Quit initialization.
PS C:\wamp64\www\yiip>

Gif work CMD terminal


问:
Passing multiple items from selectbox is not working in laravel
In my laravel project, am showing select box which contains various clinics, each clinic have api_key and id . I want to pass both id and api_key to Laravel Controller when a form is submitted.
But now am getting only api_key  .ID is not getting.

Following is my code in view page

```<code><form method="post"  action="{{ route('viewcode') }}" name="cliniclist" id="cliniclist" enctype="multipart/form-data" novalidate>
{{ csrf_field() }}
<select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
         @foreach($clinics as$clinic)
            <option value="{!! $clinic->api_key !!}" id="{!! $clinic->api_key !!}" clinic_key="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
         @endforeach
 </select>

<div class="col-xs-12 col-sm-12 col-md-12 form-action">
      <button type="submit" class="btn btn-fill btn-info">Submit</button>
          <a href="" class="btn btn-default btn-fill">Cancel</a>
 </div>

</form>
</code>```

Here in my code am printing clinic id in clinic_key attribute

Following is my code in controller

```<code>public function store(Request $request)
{
    echo $request->clinic_key;
    die();
    $clinic_api_key = $request->clinic_id;
    return view('locations.viewcode')->with(['clinic_api' => $clinic_api_key]);
}
</code>```

What is the problem here

答:
You can do it simply like

```<code><option value="{!! $clinic->api_key.'-'.$clinic->id !!}">{!! $clinic->clinicName !!}</option>
</code>```

And inside controller do it this way

```<code>$split = explode("-",$request->clinic_id);
$clinic_api_key = $split[0];
$clinic_id = $split[1];
</code>```

Updated Answer. With little jquery you can do in this way.

```<code><form method="post"  action="{{ route('viewcode') }}" name="cliniclist" id="cliniclist" enctype="multipart/form-data" novalidate>
            {{ csrf_field() }}
            <select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
                @foreach($clinics as$clinic)
                    <option value="{!! $clinic->api_key !!}" data-clinic_id="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
                @endforeach
            </select>
            <input type="hidden" name="api_key" id="api_key">
            <input type="hidden" name="id" id="id">

            <div class="col-xs-12 col-sm-12 col-md-12 form-action">
                <button type="submit" class="btn btn-fill btn-info">Submit</button>
                <a href="" class="btn btn-default btn-fill">Cancel</a>
            </div>

        </form>
</code>```

Jquery Code, as you can see i have placed two hidden inputs inside your form, so you will access these two inputs inside your controller except select name.

```<code>$(document).on('change','#clinic_id',function(){
            var clinic_api_key = $('option:selected',this).val();
            var clinic_id = $('option:selected',this).data('clinic_id');

            $("#api_key").val(clinic_api_key);
            $("#id").val(clinic_id);
        });
</code>```

Now in controller

```<code>$request->api_key;
$request->id;
</code>```

Body:
In my laravel project, am showing select box which contains various clinics, each clinic have api_key and id . I want to pass both id and api_key to Laravel Controller when a form is submitted.
But now am getting only api_key  .ID is not getting.

Following is my code in view page

<form method="post"  action="{{ route('viewcode') }}" name="cliniclist" id="cliniclist" enctype="multipart/form-data" novalidate>
{{ csrf_field() }}
<select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
         @foreach($clinics as$clinic)
            <option value="{!! $clinic->api_key !!}" id="{!! $clinic->api_key !!}" clinic_key="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
         @endforeach
 </select>

      <button type="submit" class="btn btn-fill btn-info">Submit</button>
          Cancel

</form>

Here in my code am printing clinic id in clinic_key attribute

Following is my code in controller

public function store(Request $request)
{
    echo $request->clinic_key;
    die();
    $clinic_api_key = $request->clinic_id;
    return view('locations.viewcode')->with(['clinic_api' => $clinic_api_key]);
}

What is the problem here

Body:
You can do it simply like

<option value="{!! $clinic->api_key.'-'.$clinic->id !!}">{!! $clinic->clinicName !!}</option>

And inside controller do it this way

$split = explode("-",$request->clinic_id);
$clinic_api_key = $split[0];
$clinic_id = $split[1];

Updated Answer. With little jquery you can do in this way.

<form method="post"  action="{{ route('viewcode') }}" name="cliniclist" id="cliniclist" enctype="multipart/form-data" novalidate>
            {{ csrf_field() }}
            <select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
                @foreach($clinics as$clinic)
                    <option value="{!! $clinic->api_key !!}" data-clinic_id="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
                @endforeach
            </select>
            <input type="hidden" name="api_key" id="api_key">
            <input type="hidden" name="id" id="id">

            <div class="col-xs-12 col-sm-12 col-md-12 form-action">
                <button type="submit" class="btn btn-fill btn-info">Submit</button>
                <a href="" class="btn btn-default btn-fill">Cancel</a>
            </div>

        </form>

Jquery Code, as you can see i have placed two hidden inputs inside your form, so you will access these two inputs inside your controller except select name.

$(document).on('change','#clinic_id',function(){
            var clinic_api_key = $('option:selected',this).val();
            var clinic_id = $('option:selected',this).data('clinic_id');

            $("#api_key").val(clinic_api_key);
            $("#id").val(clinic_id);
        });

Now in controller

$request->api_key;
$request->id;


问:
Customize default message behavior in MS Teams
Overview:

Before I go too deep into the documentation, I wanted to ask a few basic questions.

My goal of all this is to customize the default message notifications, which appear in the lower right hand corner of the screen, specifically when chatting in MS Teams. Note I am interested only in Windows, not mobile.

Use case:

I send the GitHub Bot a bogus chat message, just to show a notification coming in for demonstration purposes:

This notification will disappear after some predetermined amount of time (around ~15s, at least on my machine)

Question(s):

Would it be possible to create a message extension of sorts, which wraps the default messaging behavior?

For example, I would want to:

Let the notification sit in the lower right hand corner until acted
upon, rather than have it disappear. Or, is this the behavior of the
OS, rather than Teams?

Change the color, and format of the message. Effectively, intercept
the message, and display it in different format, font, color, icon
etc.

I only see notifications in the lower right hand corner, if and only
if Teams is minimized, or out of view. Would it be possible, if
intercepted, to display the notification, regardless if Teams has
focus, and is in the foreground. For example, if I am in Teams, and
a notification appears (say someone sends me a message), the ‘Chat’
icon in the upper left hand corner will display an alert. I would
like to also have the notification appear in the lower right hand
corner of the screen.

Lastly, say for example Teams is in the foreground, and you receive
a notification. By default, the Teams icon in the toolbar will
flicker and update the badge number on the icon. Is there any way
for a developer to update the icon, or possibly draw additional
attention to the icon, aside from the red badge.

Note that these are all things I would like to do from a personal standpoint. The odds of another developer wanting these sort of changes are slim to none, which is why I would like to build something myself, opposed to a file feature request.

Of course, anything is possible, but I don’t want to hack something together that will break in a week. I’d rather see if I can build upon whatever API’s are out there to do this sort of thing.

Note that I'm not looking for a solution, but rather a brief yes or no for the questions above, and possibly a pointer to specific documentation that could aid in my investigation.

Thanks!

答:
Just to circle back on this. I spoke to one of their support devs, who was extremely helpful.

I've summarized his response below for reference.

Note that the list below corresponds to the order of questions asked above:

It behaves as per OS. On Windows, notifications will show in the bottom right corner of your screen, then move to the
  Action Center. On Mac OS, these show up in the top right corner of
  your screen, then move to the Control Center.

You could change the notification text if you are sending it from a user app. But not all notification are shown from Teams. Font, color
  and icon are displayed as per Teams theme and cannot be modified.

This is currently not possible. A Custom App inside a team has limited access (scope). For example if you have installed an app inside
  a teams channel, then it has limited scope to send or receive
  operations only inside that channel.

This is also not possible.

So in summary, in relation to the original posted question, it is not possible at this time to customize the default Message behavior in Teams.

Also, I was using the terms Message and Notification interchangeably, which is incorrect.

It would appear as though Notifications are really what the OS displays, and as such, defines it's default behavior. The application, in this case MS-Teams, controls the visual display characteristics of that Notification, for example color/font/icon, based on the UI theme of teams.

Conversely, Messages or Message Extensions, are quite different from Notifications.
Using Message Extension, the user can search, or initiate actions, in an external system from the compose message area, the command box, or directly from a message. You can then send the results of that interaction back to the Microsoft Teams client, typically in the form of a richly formatted card.


问:
MySQL Group from quarters to periods
I have a table like this:

```<code>Person smallint(5)  act_time datetime
1   2020-05-29 07:00:00
1   2020-05-29 07:15:00
1   2020-05-29 07:30:00
2   2020-05-29 07:15:00
2   2020-05-29 07:30:00
1   2020-05-29 10:30:00
1   2020-05-29 10:45:00
</code>```

The table above is an example with 2 different persons and there is a row for each quarter they are at work...

What is the best way in MySQL to "convert" this table to another table where there is a column for "person", a column for "start" and one for "stop".

So the result is like:

```<code>Person  Start   Stop
1   2020-05-29 07:00:00   2020-05-29 07:45:00
2   2020-05-29 07:15:00   2020-05-29 07:45:00
1   2020-05-29 10:30:00   2020-05-29 11:00:00
</code>```

I have tried with a left join to the same original table but it didn't work...

Thanks.

Thanks for your reply. I have now tried it with the table above - and it unfortunately doesn't give that result...
My sql string is:

```<code>select person,min(act_time) start_date,max(act_time) end_date from (select t.*,row_number() over(order by act_time) rn1,row_number() over(partition by person order by act_time) rn2 from test t) t group by person, rn1 - rn2 order by min(act_time)

But the result it generates is:
1 29-05-2020 07:00:00 29-05-2020 07:15:00
2 29-05-2020 07:15:00 29-05-2020 07:15:00
1 29-05-2020 07:30:00 29-05-2020 07:30:00
2 29-05-2020 07:30:00 29-05-2020 07:30:00
1 29-05-2020 10:30:00 29-05-2020 10:45:00
</code>```

It should be like the result with 3 rows. So when there is a gap in more than 15 minutes between to rows with the same person it should create a new row.

答:
This is a gaps-and-islands problem.  I'm not sure why GMB's solution doesn't work, but this should:</p>

```<code>select person, min(act_date) as start_date,
       max(act_date) + interval 15 minute as end_date
from (select t.*,
             sum(case when prev_act_date >= act_date - interval 15 minute then 0 else 1 end) over
                 (partition by person order by act_date) as grp
      from (select t.*,
                   lag(act_date) over (partition by person order by act_date) as prev_act_date
            from t
           ) t
     ) t
group by person, grp
order by min(act_date)
</code>```

Title: MySQL Group from quarters to periods

Body:
I have a table like this:

Person smallint(5)  act_time datetime
1   2020-05-29 07:00:00
1   2020-05-29 07:15:00
1   2020-05-29 07:30:00
2   2020-05-29 07:15:00
2   2020-05-29 07:30:00
1   2020-05-29 10:30:00
1   2020-05-29 10:45:00

The table above is an example with 2 different persons and there is a row for each quarter they are at work...

What is the best way in MySQL to "convert" this table to another table where there is a column for "person", a column for "start" and one for "stop".

So the result is like:

Person  Start   Stop
1   2020-05-29 07:00:00   2020-05-29 07:45:00
2   2020-05-29 07:15:00   2020-05-29 07:45:00
1   2020-05-29 10:30:00   2020-05-29 11:00:00

I have tried with a left join to the same original table but it didn't work...

Thanks.

Thanks for your reply. I have now tried it with the table above - and it unfortunately doesn't give that result...
My sql string is:

select person,min(act_time) start_date,max(act_time) end_date from (select t.*,row_number() over(order by act_time) rn1,row_number() over(partition by person order by act_time) rn2 from test t) t group by person, rn1 - rn2 order by min(act_time)

But the result it generates is:
1 29-05-2020 07:00:00 29-05-2020 07:15:00
2 29-05-2020 07:15:00 29-05-2020 07:15:00
1 29-05-2020 07:30:00 29-05-2020 07:30:00
2 29-05-2020 07:30:00 29-05-2020 07:30:00
1 29-05-2020 10:30:00 29-05-2020 10:45:00

It should be like the result with 3 rows. So when there is a gap in more than 15 minutes between to rows with the same person it should create a new row.

Body:
This is a gaps-and-islands problem.  I'm not sure why GMB's solution doesn't work, but this should:

select person, min(act_date) as start_date,
       max(act_date) + interval 15 minute as end_date
from (select t.*,
             sum(case when prev_act_date >= act_date - interval 15 minute then 0 else 1 end) over
                 (partition by person order by act_date) as grp
      from (select t.*,
                   lag(act_date) over (partition by person order by act_date) as prev_act_date
            from t
           ) t
     ) t
group by person, grp
order by min(act_date)


问:
gcc unable to find "windows.h, winsock2.h and ws2tcpip.h" header files even after installing mingw package on Linux
I am trying to create a c/c++ program using winsock2.h, windows.h and ws2tcpip.h in Linux. But I get the following error messages:

cannot open source file "winsock2.h"C/C++(1696)

Likewise for windows.h

cannot open source file "windows.h"C/C++(1696)

I have already installed Mingw on my system using this command

```<code>mingw-w64-common mingw-w64-i686-dev mingw-w64-tools mingw-w64-x86-64-dev
</code>```

My Program

```<code>#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")

 int main() { return 0; }
</code>```

VSC ver - 1.45.1

OS - Debian

答:
The message format cannot open source file "winsock2.h"C/C++(1696) doesn't look like to me like something GCC would say.
Is it possible that while you installed MinGW-w64 you are not using its GCC compiler?
For MinGW-w64 to work you need to actualy us it's toolchain (compiler, linker).

Body:
I am trying to create a c/c++ program using winsock2.h, windows.h and ws2tcpip.h in Linux. But I get the following error messages:

cannot open source file "winsock2.h"C/C++(1696)

Likewise for windows.h

cannot open source file "windows.h"C/C++(1696)

I have already installed Mingw on my system using this command

mingw-w64-common mingw-w64-i686-dev mingw-w64-tools mingw-w64-x86-64-dev

My Program

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")

 int main() { return 0; }

VSC ver - 1.45.1

OS - Debian


问:
Why does mysql_query() return TRUE with a SELECT statement?
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

```<code>if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}
</code>```

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

答:
If webbiedave isn't on the right track, there's only one codepath that allows for this situation in the php source:

```<code>#if MYSQL_VERSION_ID < 32224
#define PHP_MYSQL_VALID_RESULT(mysql)       \
    (mysql_num_fields(mysql)>0)
#else
#define PHP_MYSQL_VALID_RESULT(mysql)       \
    (mysql_field_count(mysql)>0)
#endif
</code>```

...

```<code>if (!mysql_result) {
    if (PHP_MYSQL_VALID_RESULT(mysql->conn)) { /* query should have returned rows */
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to save result set");
        RETURN_FALSE;
    } else {
        RETURN_TRUE; // <<< this case
    }
}
</code>```

I would consider this a bug. Especially since there's no real way to verify this - mysql_num_fields in the PHP code uses the resource that you're not getting, not the connection.

Although it's still weird that the C version of mysql_query returns zero on lost connection - if you're able to, try the following patch and reinstall the mysql extension:

```<code>Index: ext/mysql/php_mysql.c
===================================================================
--- ext/mysql/php_mysql.c       (revision 311719)
+++ ext/mysql/php_mysql.c       (working copy)
@@ -1485,6 +1485,9 @@
                if (PHP_MYSQL_VALID_RESULT(mysql->conn)) { /* query should have returned rows */
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to save result set");
                        RETURN_FALSE;
+               } else if( mysql_errno(mysql->conn) != 0 ) {
+                       php_error_docref("http://www.mysql.com/doc" TSRMLS_CC, E_WARNING, "%s", mysql_error(mysql->conn));
+                       RETURN_FALSE;
                } else {
                        RETURN_TRUE;
                }
</code>```

Body:
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

Body:
If webbiedave isn't on the right track, there's only one codepath that allows for this situation in the php source:

#if MYSQL_VERSION_ID < 32224
#define PHP_MYSQL_VALID_RESULT(mysql)       \
    (mysql_num_fields(mysql)>0)
#else
#define PHP_MYSQL_VALID_RESULT(mysql)       \
    (mysql_field_count(mysql)>0)
#endif

...

if (!mysql_result) {
    if (PHP_MYSQL_VALID_RESULT(mysql->conn)) { /* query should have returned rows */
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to save result set");
        RETURN_FALSE;
    } else {
        RETURN_TRUE; // <<< this case
    }
}

I would consider this a bug. Especially since there's no real way to verify this - mysql_num_fields in the PHP code uses the resource that you're not getting, not the connection.

Although it's still weird that the C version of mysql_query returns zero on lost connection - if you're able to, try the following patch and reinstall the mysql extension:

Index: ext/mysql/php_mysql.c
===================================================================
--- ext/mysql/php_mysql.c       (revision 311719)
+++ ext/mysql/php_mysql.c       (working copy)
@@ -1485,6 +1485,9 @@
                if (PHP_MYSQL_VALID_RESULT(mysql->conn)) { /* query should have returned rows */
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to save result set");
                        RETURN_FALSE;
+               } else if( mysql_errno(mysql->conn) != 0 ) {
+                       php_error_docref("http://www.mysql.com/doc" TSRMLS_CC, E_WARNING, "%s", mysql_error(mysql->conn));
+                       RETURN_FALSE;
                } else {
                        RETURN_TRUE;
                }


问:
Summing values based on multiple criteria. Columns are different sizes
I have a Google Sheet (Test Sheet 2) with two sheets in it, Sheet 1 and Sheet 2.  Sheet 2 is where all of the data is and I need to get the sums of the counts of that column based on three criteria into sheet 1 column C.  The name, week, year and count need to match up.  I used the formula

```<code>=arrayformula(iferror(vlookup(A2:A&2020&B2:B, {Sheet2!A2:A&Sheet2!B2:B&Sheet2!C2:C, Sheet2!D2:D}, 2, FALSE)))
</code>```

but that only works for unique rows.  In the example sheet I am providing, the formula works well for Bill, Lisa, Katie and Jon because they all have one value for 'count' from Sheet2 when the parameters of name, week and year match up.  But Mike has two rows matching the criteria.  This formula returns the first match which is 3.  The other value is 4 so I would like the count in Sheet1 to show 7 instead of 3.  I need it to add them up.

I also tried to use sumifs but the columns are two different sizes so that didn't work.

Any idea? I did try to combine sumif with the above formula but that did not work either.

Link to Test Sheet

答:
Solution with ARRAYFORMULA and SUMIF

If you need to use ARRAYFORMULA to improve the performances you can use this tweak of the SUMIF statement: basically you can concatenate the conditions to make them create a single AND condition.

This would be a possible solution for the formula in your comment:

```<code>=ARRAYFORMULA(SUMIF(Sheet2!A2:A&Sheet2!B2:B,A2:A&2020,Sheet2!D2:D))
</code>```

Solution with SUMIFS

If you are looking for a solution with the SUMIFS formula you can use this:

```<code>SUMIFS('sum_range', 'criteria_range', condition, ['criteria_range_2', condition_2])
</code>```

In your case this will translate to:

```<code>=SUMIFS(Sheet2!D2:D, Sheet2!A2:A, A2, Sheet2!B2:B, 2020)
</code>```

In this case the ranges dimensions won't affect the formula execution.
Just drag this formula for the Sheet1 table column and you will get the results. The drawback is that you cannot use ARRAYFORMULA with SUMIFS. Performance wise, if you have a lot of rows in the Sheet1 I suggest using the ARRAYFORMULA solution, since this will trigger a lot of formula calls instead of just one.

Body:
I have a Google Sheet (Test Sheet 2) with two sheets in it, Sheet 1 and Sheet 2.  Sheet 2 is where all of the data is and I need to get the sums of the counts of that column based on three criteria into sheet 1 column C.  The name, week, year and count need to match up.  I used the formula

=arrayformula(iferror(vlookup(A2:A&2020&B2:B, {Sheet2!A2:A&Sheet2!B2:B&Sheet2!C2:C, Sheet2!D2:D}, 2, FALSE)))

but that only works for unique rows.  In the example sheet I am providing, the formula works well for Bill, Lisa, Katie and Jon because they all have one value for 'count' from Sheet2 when the parameters of name, week and year match up.  But Mike has two rows matching the criteria.  This formula returns the first match which is 3.  The other value is 4 so I would like the count in Sheet1 to show 7 instead of 3.  I need it to add them up.

I also tried to use sumifs but the columns are two different sizes so that didn't work.

Any idea? I did try to combine sumif with the above formula but that did not work either.

Link to Test Sheet

Body:
Solution with ARRAYFORMULA and SUMIF

If you need to use ARRAYFORMULA to improve the performances you can use this tweak of the SUMIF statement: basically you can concatenate the conditions to make them create a single AND condition.

This would be a possible solution for the formula in your comment:

=ARRAYFORMULA(SUMIF(Sheet2!A2:A&Sheet2!B2:B,A2:A&2020,Sheet2!D2:D))

Solution with SUMIFS

If you are looking for a solution with the SUMIFS formula you can use this:

SUMIFS('sum_range', 'criteria_range', condition, ['criteria_range_2', condition_2])

In your case this will translate to:

=SUMIFS(Sheet2!D2:D, Sheet2!A2:A, A2, Sheet2!B2:B, 2020)

In this case the ranges dimensions won't affect the formula execution.
Just drag this formula for the Sheet1 table column and you will get the results. The drawback is that you cannot use ARRAYFORMULA with SUMIFS. Performance wise, if you have a lot of rows in the Sheet1 I suggest using the ARRAYFORMULA solution, since this will trigger a lot of formula calls instead of just one.