问:
Constant validation accuracy in binary classification using ResNet50
I am training a deep learning network to classify thyroid nodules (binary classification as 0 or 1). Therefore, I am realizing that my model is with constant validation accuracy. I tried everything, changed the learning rate, some callbacks if the loss doesn't increse. So, I need help, some ideas to deal with it. I will give you a example with 10 epochs, but, even if I change to 100 epochs, it still with the same behavior. Here is the architecture's network code:</p>

```<code>callbacks = [
    EarlyStopping(patience=20, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0001, verbose=1),
]

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(2, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train_2d, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid_2d))

Train on 360 samples, validate on 46 samples
Epoch 1/10
342/360 [===========================>..] - ETA: 1s - loss: 0.7582 - accuracy: 0.5673
Epoch 00001: val_loss did not improve from 0.16301
360/360 [==============================] - 44s 123ms/sample - loss: 0.7706 - accuracy: 0.5583 - val_loss: 0.5528 - val_accuracy: 0.8043
Epoch 2/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5604 - accuracy: 0.7135
Epoch 00002: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5525 - accuracy: 0.7222 - val_loss: 0.5047 - val_accuracy: 0.8043
Epoch 3/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5056 - accuracy: 0.7485
Epoch 00003: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4993 - accuracy: 0.7500 - val_loss: 0.4946 - val_accuracy: 0.8043
Epoch 4/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5004 - accuracy: 0.7661
Epoch 00004: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5019 - accuracy: 0.7667 - val_loss: 0.4942 - val_accuracy: 0.8043
Epoch 5/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4967 - accuracy: 0.8070
Epoch 00005: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4897 - accuracy: 0.8083 - val_loss: 0.4952 - val_accuracy: 0.8043
Epoch 6/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4615 - accuracy: 0.7427
Epoch 00006: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4750 - accuracy: 0.7361 - val_loss: 0.4985 - val_accuracy: 0.8043
Epoch 7/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4119 - accuracy: 0.7924
Epoch 00007: val_loss did not improve from 0.16301
360/360 [==============================] - 40s 111ms/sample - loss: 0.4164 - accuracy: 0.7944 - val_loss: 0.4953 - val_accuracy: 0.8043
Epoch 8/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4182 - accuracy: 0.8158
Epoch 00008: val_loss did not improve from 0.16301
360/360 [==============================] - 20s 55ms/sample - loss: 0.4155 - accuracy: 0.8194 - val_loss: 0.4957 - val_accuracy: 0.8043
Epoch 9/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3892 - accuracy: 0.8304
Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 00009: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 57ms/sample - loss: 0.3853 - accuracy: 0.8278 - val_loss: 0.4997 - val_accuracy: 0.8043
Epoch 10/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3395 - accuracy: 0.8333
Epoch 00010: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 58ms/sample - loss: 0.3375 - accuracy: 0.8333 - val_loss: 0.5003 - val_accuracy: 0.8043
</code>```

答:
@AlexM4 is right that, for binary classification, you should use a single output unit with a sigmoid classification.

What's also worth pointing out is that, for multi-class classification, you shouldn't use a sigmoid activation but instead softmax, which produces a probability distribution over the possible classes (sigmoid could theoretically produce a probability of 1.0 for all classes, which makes no sense). That may be impeding your network's performance here.

Fixing the larger issue (moving to a single output unit) would obviate the need to fix the issue I just described, but it's worth keeping in mind for future experiments.

Body:
I am training a deep learning network to classify thyroid nodules (binary classification as 0 or 1). Therefore, I am realizing that my model is with constant validation accuracy. I tried everything, changed the learning rate, some callbacks if the loss doesn't increse. So, I need help, some ideas to deal with it. I will give you a example with 10 epochs, but, even if I change to 100 epochs, it still with the same behavior. Here is the architecture's network code:

callbacks = [
    EarlyStopping(patience=20, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0001, verbose=1),
]

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(2, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train_2d, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid_2d))

Train on 360 samples, validate on 46 samples
Epoch 1/10
342/360 [===========================>..] - ETA: 1s - loss: 0.7582 - accuracy: 0.5673
Epoch 00001: val_loss did not improve from 0.16301
360/360 [==============================] - 44s 123ms/sample - loss: 0.7706 - accuracy: 0.5583 - val_loss: 0.5528 - val_accuracy: 0.8043
Epoch 2/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5604 - accuracy: 0.7135
Epoch 00002: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5525 - accuracy: 0.7222 - val_loss: 0.5047 - val_accuracy: 0.8043
Epoch 3/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5056 - accuracy: 0.7485
Epoch 00003: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4993 - accuracy: 0.7500 - val_loss: 0.4946 - val_accuracy: 0.8043
Epoch 4/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5004 - accuracy: 0.7661
Epoch 00004: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5019 - accuracy: 0.7667 - val_loss: 0.4942 - val_accuracy: 0.8043
Epoch 5/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4967 - accuracy: 0.8070
Epoch 00005: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4897 - accuracy: 0.8083 - val_loss: 0.4952 - val_accuracy: 0.8043
Epoch 6/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4615 - accuracy: 0.7427
Epoch 00006: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4750 - accuracy: 0.7361 - val_loss: 0.4985 - val_accuracy: 0.8043
Epoch 7/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4119 - accuracy: 0.7924
Epoch 00007: val_loss did not improve from 0.16301
360/360 [==============================] - 40s 111ms/sample - loss: 0.4164 - accuracy: 0.7944 - val_loss: 0.4953 - val_accuracy: 0.8043
Epoch 8/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4182 - accuracy: 0.8158
Epoch 00008: val_loss did not improve from 0.16301
360/360 [==============================] - 20s 55ms/sample - loss: 0.4155 - accuracy: 0.8194 - val_loss: 0.4957 - val_accuracy: 0.8043
Epoch 9/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3892 - accuracy: 0.8304
Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 00009: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 57ms/sample - loss: 0.3853 - accuracy: 0.8278 - val_loss: 0.4997 - val_accuracy: 0.8043
Epoch 10/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3395 - accuracy: 0.8333
Epoch 00010: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 58ms/sample - loss: 0.3375 - accuracy: 0.8333 - val_loss: 0.5003 - val_accuracy: 0.8043


来源: stackexchange

问:
Handling Dollar Sign in Input numeric text
I'm running into an issue with my Python program.

In fact, I have a sales price input which can contain a dollar sign and must respect the following constraints :

It must be numeric

The sales price must be at least $100, including dollars and cents

The problem I'm facing is : if the user inputs a sales price including a dollar sign, how to "ignore" it in order to determine if the input is numeric ? The same issue applies when it comes to a decimal point.

Also, note that :

If the input is not a numeric entry, I would like it to prompt "price must be numeric".

If the entry is less than $100, I would like it to prompt "Price must be at least $100".

This is what I have so far :

```<code>salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])
</code>```

答:
This works fine:</p>

```<code>salesPrice= input("What is the sales price of the new phone? ")

if salesPrice.startswith("$"):

    amount = salesPrice.replace("$", "").strip()
    if amount.isnumeric():
        val = int(amount)
        if val < 100:
            print('Price must be at least $100')
        else:
            price=float(val)
    else:
        print('Price must be numeric')
else:
    if salesPrice.isnumeric():
        salesPrice = int(salesPrice)
        if salesPrice < 100:
            print('Price must be at least $100')
        else:
            price=float(salesPrice)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm running into an issue with my Python program.

In fact, I have a sales price input which can contain a dollar sign and must respect the following constraints :

It must be numeric

The sales price must be at least $100, including dollars and cents

The problem I'm facing is : if the user inputs a sales price including a dollar sign, how to "ignore" it in order to determine if the input is numeric ? The same issue applies when it comes to a decimal point.

Also, note that :

If the input is not a numeric entry, I would like it to prompt "price must be numeric".

If the entry is less than $100, I would like it to prompt "Price must be at least $100".

This is what I have so far :

salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])

Body:
This works fine:

salesPrice= input("What is the sales price of the new phone? ")

if salesPrice.startswith("$"):

    amount = salesPrice.replace("$", "").strip()
    if amount.isnumeric():
        val = int(amount)
        if val < 100:
            print('Price must be at least $100')
        else:
            price=float(val)
    else:
        print('Price must be numeric')
else:
    if salesPrice.isnumeric():
        salesPrice = int(salesPrice)
        if salesPrice < 100:
            print('Price must be at least $100')
        else:
            price=float(salesPrice)


问:
Flutter Firebase not loading data for the first time, but at the next tries it loads them many times
```<code>final databaseReference = Firestore.instance.collection("classrooms");
bool hany = false;
var names = new Map<String, dynamic>();
List nevek = [];
List IDS = [];

Future<void> getclasses() async {
  QuerySnapshot snapshot = await databaseReference.getDocuments();

  snapshot.documents.forEach((f) {
    IDS.add(f.documentID);
    x = (f.data.length);
    names.addAll(f.data);
    for (int i = 0; i < names.values.toList().length / x; i++) {
      nevek.add(names.values.toList()[i + 1]);
    }
  });
}

class ScrollableClassroom extends StatefulWidget {
  @override
  _ScrollableClassroomState createState() => _ScrollableClassroomState();
}

class _ScrollableClassroomState extends State<ScrollableClassroom> {
  @override
  void initState() {
    super.initState();
    IDS = [];
    names.clear();
    getclasses();
  }

  Widget build(BuildContext context) {
    print(nevek);
    print(IDS);

    return WillPopScope(
      onWillPop: () async => false,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Osztályok"),
          leading: Padding(
              padding: const EdgeInsets.only(left: 5.0),
              child: IconButton(
                  icon: Icon(Icons.exit_to_app, color: Colors.black38),
                  onPressed: () {
                    authService.signOut();
                    authService.loggedIn = false;
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => GoogleSignUp()));
                  })),
          actions: <Widget>[
            Padding(
                padding: const EdgeInsets.only(right: 5.0),
                child: Row(
                  children: <Widget>[
                    IconButton(
                        icon: Icon(Icons.add_circle_outline,
                            color: Colors.black38),
                        onPressed: null),
                    IconButton(
                        icon: Icon(Icons.search, color: Colors.black38),
                        onPressed: null),
                  ],
                )),
          ],
        ),
        body: ListView.builder(
          itemCount: nevek.length,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                onTap: () {
                  id = IDS[index];
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => InClassRoom()));
                },
                title: Text(nevek[index]),
              ),
            );
          },
        ),
      ),
    );
  }
}
</code>```

In the Listview, for the first time it shows nothing, but after a hot reload it works fine. However, if I do a second hot reload it shows everything, but twice. Another case is when I press the back button on the left side of the appbar, it takes you to the login screen. If you come back for the first time from the login screen it is fine, but if you do this once more it shows everything twice again. And after that three times, etc.

答:
Try this code:</p>

```<code>class ScrollableClassroom extends StatefulWidget {
  @override
  _ScrollableClassroomState createState() => _ScrollableClassroomState();
}

class _ScrollableClassroomState extends State<ScrollableClassroom> {

//moved from the Widget class
final databaseReference = Firestore.instance.collection("classrooms");
bool hany = false;
var names = new Map<String, dynamic>();
List nevek = [];
List IDS = [];

Future<void> getclasses() async {
  QuerySnapshot snapshot = await databaseReference.getDocuments();

  snapshot.documents.forEach((f) {
    IDS.add(f.documentID);
    x = (f.data.length);
    names.addAll(f.data);
    for (int i = 0; i < names.values.toList().length / x; i++) {
      nevek.add(names.values.toList()[i + 1]);
    }
  });
setState((){}); // <- this line tells the StetefulWidget that it's state has been changed and it needs to rebuild
}
...(the rest of the state class)
</code>```

Body:
final databaseReference = Firestore.instance.collection("classrooms");
bool hany = false;
var names = new Map<String, dynamic>();
List nevek = [];
List IDS = [];

Future<void> getclasses() async {
  QuerySnapshot snapshot = await databaseReference.getDocuments();

  snapshot.documents.forEach((f) {
    IDS.add(f.documentID);
    x = (f.data.length);
    names.addAll(f.data);
    for (int i = 0; i < names.values.toList().length / x; i++) {
      nevek.add(names.values.toList()[i + 1]);
    }
  });
}

class ScrollableClassroom extends StatefulWidget {
  @override
  _ScrollableClassroomState createState() => _ScrollableClassroomState();
}

class _ScrollableClassroomState extends State<ScrollableClassroom> {
  @override
  void initState() {
    super.initState();
    IDS = [];
    names.clear();
    getclasses();
  }

  Widget build(BuildContext context) {
    print(nevek);
    print(IDS);

    return WillPopScope(
      onWillPop: () async => false,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Osztályok"),
          leading: Padding(
              padding: const EdgeInsets.only(left: 5.0),
              child: IconButton(
                  icon: Icon(Icons.exit_to_app, color: Colors.black38),
                  onPressed: () {
                    authService.signOut();
                    authService.loggedIn = false;
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => GoogleSignUp()));
                  })),
          actions: <Widget>[
            Padding(
                padding: const EdgeInsets.only(right: 5.0),
                child: Row(
                  children: <Widget>[
                    IconButton(
                        icon: Icon(Icons.add_circle_outline,
                            color: Colors.black38),
                        onPressed: null),
                    IconButton(
                        icon: Icon(Icons.search, color: Colors.black38),
                        onPressed: null),
                  ],
                )),
          ],
        ),
        body: ListView.builder(
          itemCount: nevek.length,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                onTap: () {
                  id = IDS[index];
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => InClassRoom()));
                },
                title: Text(nevek[index]),
              ),
            );
          },
        ),
      ),
    );
  }
}

In the Listview, for the first time it shows nothing, but after a hot reload it works fine. However, if I do a second hot reload it shows everything, but twice. Another case is when I press the back button on the left side of the appbar, it takes you to the login screen. If you come back for the first time from the login screen it is fine, but if you do this once more it shows everything twice again. And after that three times, etc.

Body:
Try this code:

class ScrollableClassroom extends StatefulWidget {
  @override
  _ScrollableClassroomState createState() => _ScrollableClassroomState();
}

class _ScrollableClassroomState extends State<ScrollableClassroom> {

//moved from the Widget class
final databaseReference = Firestore.instance.collection("classrooms");
bool hany = false;
var names = new Map<String, dynamic>();
List nevek = [];
List IDS = [];

Future<void> getclasses() async {
  QuerySnapshot snapshot = await databaseReference.getDocuments();

  snapshot.documents.forEach((f) {
    IDS.add(f.documentID);
    x = (f.data.length);
    names.addAll(f.data);
    for (int i = 0; i < names.values.toList().length / x; i++) {
      nevek.add(names.values.toList()[i + 1]);
    }
  });
setState((){}); // <- this line tells the StetefulWidget that it's state has been changed and it needs to rebuild
}
...(the rest of the state class)


问:
to calculate driving distance between two coordinates on earth in php
Well i am working in a location based app and i need to find driving distance between two location on earth at the server end. i am coding the web service in php.

Till now i am able to calculate the aerial distance using the Haversine formula, but now i want to calculate the driving distance.

There can be possible duplicates for this question, but i was not able to find any help to calculate the "Driving distance" between two "coordinates" ie latitude and longitude instead of addresses in PHP

答:
This should get you started...</p>

```<code>$json = file_get_contents('http://maps.google.com/maps/nav?q=from:Buderim,Australia%20to:Brisbane,Australia');

$details = json_decode($json, TRUE);

var_dump($details['Directions']['Distance']['meters']);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This should get you started...

$json = file_get_contents('http://maps.google.com/maps/nav?q=from:Buderim,Australia%20to:Brisbane,Australia');

$details = json_decode($json, TRUE);

var_dump($details['Directions']['Distance']['meters']);


问:
Add active class after page loading
I am trying to add an active class after page load. Here is my script. This script is working when I click. But when the page is loaded, the active class disappear.

```<code><ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">

          <li class="nav-item">
            <a class="nav-link" href="{{url('/account')}}" target="_blank">
              <i class="fas fa-fw fa-tachometer-alt"> account</i>
          </li>
    </ul>

       $(document).ready(function(){
           $(".nav-item a").on("click", function(){  $(".nav-item").find(".active").removeClass("active");  $(this).parent().addClass("active");});
        });
</code>```

I am trying to work with localStorage function not succeed .please suggest me what I have to do.

答:
You can check if the url has the href or not then you can trigger the click event for the  which has matched href ..

Try the next code

```<code><ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
    <li class="nav-item">
         <a class="nav-link" href="{{url('/account')}}" target="_blank">
             <i class="fas fa-fw fa-tachometer-alt"> account</i>
         </a>
    </li>
</ul>

$(document).ready(function(){
    $(".nav-item a").on("click", function(){
         $(".nav-item.active").removeClass("active");
         $(this).parent().addClass("active");
    }).filter(function(){
        return window.location.href.indexOf($(this).attr('href').trim()) > -1;
    }).click();
});
</code>```

Note about the code above ^^^^^:

The code above won't work as expected IF you have url http://website.com/account/thing and you have two  with hrefs /account and /account/thing both of  will get selected

To avoid this you can use data attribute

```<code><ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
    <li class="nav-item">
         <a class="nav-link" href="{{url('/account')}}" data-href="http://website.com/account" target="_blank">
             <i class="fas fa-fw fa-tachometer-alt"> account</i>
         </a>
    </li>
</ul>

$(document).ready(function(){
    $(".nav-item a").on("click", function(){
         $(".nav-item.active").removeClass("active");
         $(this).parent().addClass("active");
    }).filter(function(){
        return window.location.href == $(this).attr('data-href').trim();
    }).click();
});
</code>```

Note about the code above ^^^^^:

In  add data-href="http://website.com/account" replace http://website.com/account with the full url

Title: Add active class after page loading

Body:
I am trying to add an active class after page load. Here is my script. This script is working when I click. But when the page is loaded, the active class disappear.

               account

       $(document).ready(function(){
           $(".nav-item a").on("click", function(){  $(".nav-item").find(".active").removeClass("active");  $(this).parent().addClass("active");});
        });

I am trying to work with localStorage function not succeed .please suggest me what I have to do.

Body:
You can check if the url has the href or not then you can trigger the click event for the <a> which has matched href ..

Try the next code

<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
    <li class="nav-item">
         <a class="nav-link" href="{{url('/account')}}" target="_blank">
             <i class="fas fa-fw fa-tachometer-alt"> account</i>
         </a>
    </li>
</ul>

$(document).ready(function(){
    $(".nav-item a").on("click", function(){
         $(".nav-item.active").removeClass("active");
         $(this).parent().addClass("active");
    }).filter(function(){
        return window.location.href.indexOf($(this).attr('href').trim()) > -1;
    }).click();
});

Note about the code above ^^^^^:

The code above won't work as expected IF you have url http://website.com/account/thing and you have two <a> with hrefs /account and /account/thing both of <a> will get selected

To avoid this you can use data attribute

<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
    <li class="nav-item">
         <a class="nav-link" href="{{url('/account')}}" data-href="http://website.com/account" target="_blank">
             <i class="fas fa-fw fa-tachometer-alt"> account</i>
         </a>
    </li>
</ul>

$(document).ready(function(){
    $(".nav-item a").on("click", function(){
         $(".nav-item.active").removeClass("active");
         $(this).parent().addClass("active");
    }).filter(function(){
        return window.location.href == $(this).attr('data-href').trim();
    }).click();
});

Note about the code above ^^^^^:

In <a> add data-href="http://website.com/account" replace http://website.com/account with the full url


问:
ifelse condition: is in top n
Usually when i need a subset on geom_label() i use ifelse() and i specify a number as below:

library(tidyverse)

data = starwars %>% filter(mass < 500)

data %>%
  ggplot(aes(x = mass, y = height, label = ifelse(birth_year > 100, name, NA))) +
  geom_point() +
  geom_label()
#> Warning: Removed 54 rows containing missing values (geom_label).
```

Created on 2020-05-31 by the reprex package (v0.3.0)

But with the dataset i'm working on, i need a dynamic solution, something like ifelse("birth_year is in top n", name, NA).

Thoughts?

答:
This is a more explicit approach. I assume you want to count the number of characters per birth year, per your example. In this case, we handle the ranking first, then add a column to the original dataset, then plot. The new 'label' field is either blank/NA or has members of the top set. I suppress the pesky missing data warning in the geom_label arguments.

```<code>data = starwars %>% filter(mass < 500)

# counts names per birthyear, returns vector of top 4
top4 <- data %>%
  drop_na(birth_year) %>%
  count(birth_year, sort = TRUE) %>%
  top_n(4) %>%
  pull(birth_year)

# adds column to data with the names from the top 4 birth years
data <- data %>%
  mutate(label = ifelse(birth_year %in% top4, name, NA))

# plots data with label, dropping NAs
data %>%
  ggplot(aes(x = mass, y = height, label = label)) +
  geom_point() +
  geom_label(na.rm = TRUE)
</code>```

Title: ifelse condition: is in top n

Body:
Usually when i need a subset on geom_label() i use ifelse() and i specify a number as below:

library(tidyverse)

data = starwars %>% filter(mass < 500)

data %>%
  ggplot(aes(x = mass, y = height, label = ifelse(birth_year > 100, name, NA))) +
  geom_point() +
  geom_label()
#> Warning: Removed 54 rows containing missing values (geom_label).

Created on 2020-05-31 by the reprex package (v0.3.0)

But with the dataset i'm working on, i need a dynamic solution, something like ifelse("birth_year is in top n", name, NA).

Thoughts?

Body:
This is a more explicit approach. I assume you want to count the number of characters per birth year, per your example. In this case, we handle the ranking first, then add a column to the original dataset, then plot. The new 'label' field is either blank/NA or has members of the top set. I suppress the pesky missing data warning in the geom_label arguments.

data = starwars %>% filter(mass < 500)

# counts names per birthyear, returns vector of top 4
top4 <- data %>%
  drop_na(birth_year) %>%
  count(birth_year, sort = TRUE) %>%
  top_n(4) %>%
  pull(birth_year)

# adds column to data with the names from the top 4 birth years
data <- data %>%
  mutate(label = ifelse(birth_year %in% top4, name, NA))

# plots data with label, dropping NAs
data %>%
  ggplot(aes(x = mass, y = height, label = label)) +
  geom_point() +
  geom_label(na.rm = TRUE)


问:
Sequelize not finding variables
I am at a complete loss as to what I'm doing wrong. I am trying to do a simple UPDATE function with Sequelize/mySQL and my command doesn't work as expected. Here is the command:

```<code>         await dataArr.map((e) => {
            Users.update(
                { account_status: -1 },
                {
                    returning: true,
                    where: { user_id: e.customer_id }
                }
            ).then((res) => {
                console.log(res);
                return res;
            });
        });
</code>```

when the command get executed the query looks like:

```<code>Executing (default): UPDATE `users` SET `account_status`=? WHERE `user_id` = ?
</code>```

as you can see the query is missing both the fixed value from account_status and the variable e.customer_id which is definitely being passed as I can console.log it. This has to be something really simple that I'm missing but I haven't found anyone with a similar problem.

答:
I think your error is in the {}. Also, are you sure you are passing along customer_id? Try something like this. Make sure you are passing 'e' to the function.

```<code>updateStatus: function(req, res, e) {

    Users
        .update(account_status: -1,
                    {
                        where: { user_id: e.customer_id }
                    }
                )
        .then..........
}

</code>```

Please clarify what 'e' is, and where it comes from. Maybe post more code, the lines above.

Title: Sequelize not finding variables

Body:
I am at a complete loss as to what I'm doing wrong. I am trying to do a simple UPDATE function with Sequelize/mySQL and my command doesn't work as expected. Here is the command:

         await dataArr.map((e) => {
            Users.update(
                { account_status: -1 },
                {
                    returning: true,
                    where: { user_id: e.customer_id }
                }
            ).then((res) => {
                console.log(res);
                return res;
            });
        });

when the command get executed the query looks like:

Executing (default): UPDATE `users` SET `account_status`=? WHERE `user_id` = ?

as you can see the query is missing both the fixed value from account_status and the variable e.customer_id which is definitely being passed as I can console.log it. This has to be something really simple that I'm missing but I haven't found anyone with a similar problem.

Body:
I think your error is in the {}. Also, are you sure you are passing along customer_id? Try something like this. Make sure you are passing 'e' to the function.

updateStatus: function(req, res, e) {

    Users
        .update(account_status: -1,
                    {
                        where: { user_id: e.customer_id }
                    }
                )
        .then..........
}

Please clarify what 'e' is, and where it comes from. Maybe post more code, the lines above.


问:
How to get Firebase serverTime?
For android:
We can get serverTime by:

```<code>Timestamp.now().getSeconds();
</code>```

Then for iOS we can get serverTime by:

```<code>Timestamp.init().seconds
</code>```

My problem:
Timestamp.now().getSeconds(); is 13 characters long, Timestamp.init().seconds is only 10 characters long.

Is there a way to get the 13 characters serverTime on xCode?

答:
I figured it out myself.

Swift has:

```<code>ServerValue.timestamp()
</code>```

Just didn't think of it, for some reason. Only needed it to be written to the server.

Title: How to get Firebase serverTime?

Body:
For android:
We can get serverTime by:

Timestamp.now().getSeconds();

Then for iOS we can get serverTime by:

Timestamp.init().seconds

My problem:
Timestamp.now().getSeconds(); is 13 characters long, Timestamp.init().seconds is only 10 characters long.

Is there a way to get the 13 characters serverTime on xCode?

Body:
I figured it out myself.

Swift has:

ServerValue.timestamp()

Just didn't think of it, for some reason. Only needed it to be written to the server.


问:
How to upload file and save it directly to MongoDB using GridFS
I have a Sinatra application hosted on heroku and I'm trying to enable file uploading. I know heroku doesn't allow saving to the file system so I'm trying to save the image to MongoDB using GridFS directly. But I don’t know how.
Using the code below, I'm able to save to file system

```<code>base_dir = Dir.pwd + "/static/images/channels/"
File.open("#{base_dir}" + params['logo'][:filename], "w") do |f|
  f.write(params['logo'][:tempfile].read)
end
</code>```

How do I save the file directly to MongoDB without first saving it to the file system?

答:
If your files are actually less than 16 mb, please try using this Converter that changes the image of format jpeg / png to a format of saving to mongodb, and you can see this as an easy alternative for gridfs ,

please follow this github repo for more details

https://github.com/saran-surya/Mongo-Image-Converter

Body:
I have a Sinatra application hosted on heroku and I'm trying to enable file uploading. I know heroku doesn't allow saving to the file system so I'm trying to save the image to MongoDB using GridFS directly. But I don’t know how.
Using the code below, I'm able to save to file system

base_dir = Dir.pwd + "/static/images/channels/"
File.open("#{base_dir}" + params['logo'][:filename], "w") do |f|
  f.write(params['logo'][:tempfile].read)
end

How do I save the file directly to MongoDB without first saving it to the file system?


问:
How do I set margins in an embedded Stack View in Xcode without getting constraint errors?
I have nested Stack Views and I am trying to set margins for the inner most Stack View but I'm getting Conflicting Constraints. I am trying to set the inside Stack View to 30 pixels from the top of the container Stack View and the conflict I get looks like this:

Stack View.top = top + 30

  top = Stack View.top

I've read through the Apple documentation on setting margins and do not see which setting to use to avoid the conflict. The hint only narrows down the issue to a "constant, relation, or priority of one of the given constraints." I am looking for a solution using the Interface Builder or in Swift.

答:
SOLVED: I found an answer in a related question (How to add leading padding to view added inside an UIStackView) that solved my problem, but I'm not sure this is the right way to do it. By changing the inner Stack View's Layout Margins from "Default" to "Fixed", the margins can be set without a Constraint Conflict.

To change the Layout Margin from Default to Fixed inside the Interface Builder, click on the Stack View > Size Inspector > Layout Margins > Fixed and then a new set of options will appear for you to add the margin values.

Fixed layout options image


答:
Use the following if you would like to handle any currency and not just dollars.

The regular expression code extracts the numbers and checks if it is less than 100 or not.

import re

input_price = input("What is the sales price of the new phone? ")
lst_find = re.findall('(\d+)', input_price)
if len(lst_find) != 0:
    price = int(lst_find[0])
    if price < 100:
        print('Price must be atleast $100')
else:
    print('Price must be numeric')
```

Title: Handling Dollar Sign in Input numeric text


问:
How do I get my div class "one" to be on the left side of the page?
I am trying to learn grid.  I am using grid areas and assigned my div class "two" appropriately as per css guidelines supposed to place elements as I had instructed it to "one two three" One being on the left side or margin of the page.  Unfortunately the elements are lining up directly beneath grid area two which is the center of the page.  Any instruction or pointers to obtain the goal would be great.</p>

```<code>@import url('https://fonts.googleapis.com/css2?
family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');
.grid {
display: grid;
grid-template-areas:
    "one two three"
    "one two three"
    "one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 310px);
}

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}

input[type="number"] {
width:40px;
}

.titles {
font-family: 'Bree Serif', serif;
}

.pizza {
text-align: center;
color: tomato;
}

.one {

grid-area: one;
}

.two {
text-align: center;
grid-area: two;
color: tomato;
}

.three {

grid-area: three;
}

h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}

<div class="pizza">
                    <h3>Pizza by the slice ($2)</h3><br>
                    <input type="number" id="numSlice">
                </div>
                <div class="two">
                    <h3 class="two">Toppings</h3>
                    <p class="titles">Per Pepperoni($0.25):</p>  <input type="number" id="numPepp">
                    <p class="titles">Per Meatball($0.35):</p>  <input type="number" id="numMeat">
                    <p class="titles">Per Mushhroom($0.40):</p>  <input type="number" id="numMush">
                    <p class="titles">Per Olive($0.20):</p>  <input type="number" id="numOlives">
                </div>

                <div class="one">
                    <h3 class="one">Sides</h3>
                    <p class="titles">Potato Salad($1.25):</p>  <input type="number" id="numPSalad">
                    <p class="titles">Humus($2.50):</p>  <input type="number" id="numHumus">
                    <p class="titles">Caesar Salad($3.50):</p>  <input type="number" id="numCSalad">
                    <p class="titles">Garden Salad($2.25):</p>  <input type="number" id="numGSalad">

                </div>
</code>```

答:
Please see the following code snippet for the code change.

I have wrapped class one and class two with class grid
.

I have removed class one and class two from the

I have removed the @import url('https://fonts.googleapis.com/css2?
family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap'); because there is error and causing the CSS not working.

.grid {
  display: grid;
  grid-template-areas: "one two three" "one two three" "one two three";
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: repeat(3, 310px);
}

.title {
  font-family: 'Chelsea Market', cursive;
  font-size: 30px;
  text-align: center;
  color: teal;
}

input[type="number"] {
  width: 40px;
}

.titles {
  font-family: 'Bree Serif', serif;
}

.pizza {
  text-align: center;
  color: tomato;
}

.one {
  grid-area: one;
}

.two {
  text-align: center;
  grid-area: two;
  color: tomato;
}

.three {
  grid-area: three;
}

h2 {
  font-size: 30px;
  font-family: 'Oswald', sans-serif;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pizza">
  <h3>Pizza by the slice ($2)</h3><br>
  <input type="number" id="numSlice">
</div>
<div class="grid">
  <div class="two">
    <h3>Toppings</h3>
    <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="numPepp">
    <p class="titles">Per Meatball($0.35):</p> <input type="number" id="numMeat">
    <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="numMush">
    <p class="titles">Per Olive($0.20):</p> <input type="number" id="numOlives">
  </div>

  <div class="one">
    <h3>Sides</h3>
    <p class="titles">Potato Salad($1.25):</p> <input type="number" id="numPSalad">
    <p class="titles">Humus($2.50):</p> <input type="number" id="numHumus">
    <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="numCSalad">
    <p class="titles">Garden Salad($2.25):</p> <input type="number" id="numGSalad">
  </div>
</div></code>```

Body:
I am trying to learn grid.  I am using grid areas and assigned my div class "two" appropriately as per css guidelines supposed to place elements as I had instructed it to "one two three" One being on the left side or margin of the page.  Unfortunately the elements are lining up directly beneath grid area two which is the center of the page.  Any instruction or pointers to obtain the goal would be great.

@import url('https://fonts.googleapis.com/css2?
family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');
.grid {
display: grid;
grid-template-areas:
    "one two three"
    "one two three"
    "one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 310px);
}

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}

input[type="number"] {
width:40px;
}

.titles {
font-family: 'Bree Serif', serif;
}

.pizza {
text-align: center;
color: tomato;
}

.one {

grid-area: one;
}

.two {
text-align: center;
grid-area: two;
color: tomato;
}

.three {

grid-area: three;
}

h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}

Pizza by the slice ($2)

                    <input type="number" id="numSlice">

Toppings

Per Pepperoni($0.25):
  <input type="number" id="numPepp">

Per Meatball($0.35):
  <input type="number" id="numMeat">

Per Mushhroom($0.40):
  <input type="number" id="numMush">

Per Olive($0.20):
  <input type="number" id="numOlives">

Sides

Potato Salad($1.25):
  <input type="number" id="numPSalad">

Humus($2.50):
  <input type="number" id="numHumus">

Caesar Salad($3.50):
  <input type="number" id="numCSalad">

Garden Salad($2.25):
  <input type="number" id="numGSalad">

Body:
Please see the following code snippet for the code change.

I have wrapped class one and class two with class grid <div>.

I have removed class one and class two from the <h3>

I have removed the @import url('https://fonts.googleapis.com/css2?
family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap'); because there is error and causing the CSS not working.

.grid {
  display: grid;
  grid-template-areas: "one two three" "one two three" "one two three";
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: repeat(3, 310px);
}

.title {
  font-family: 'Chelsea Market', cursive;
  font-size: 30px;
  text-align: center;
  color: teal;
}

input[type="number"] {
  width: 40px;
}

.titles {
  font-family: 'Bree Serif', serif;
}

.pizza {
  text-align: center;
  color: tomato;
}

.one {
  grid-area: one;
}

.two {
  text-align: center;
  grid-area: two;
  color: tomato;
}

.three {
  grid-area: three;
}

h2 {
  font-size: 30px;
  font-family: 'Oswald', sans-serif;
  text-align: center;
}

<div class="pizza">
  <h3>Pizza by the slice ($2)</h3><br>
  <input type="number" id="numSlice">
</div>
<div class="grid">
  <div class="two">
    <h3>Toppings</h3>
    <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="numPepp">
    <p class="titles">Per Meatball($0.35):</p> <input type="number" id="numMeat">
    <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="numMush">
    <p class="titles">Per Olive($0.20):</p> <input type="number" id="numOlives">
  </div>

  <div class="one">
    <h3>Sides</h3>
    <p class="titles">Potato Salad($1.25):</p> <input type="number" id="numPSalad">
    <p class="titles">Humus($2.50):</p> <input type="number" id="numHumus">
    <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="numCSalad">
    <p class="titles">Garden Salad($2.25):</p> <input type="number" id="numGSalad">
  </div>
</div>


问:
difference between tf.keras.losses.SparseCategoricalCrossentropy() vs "sparse_categorical_crossentropy" as loss
I'm implementing a multi class classification problem,

when I'm using my loss as tf.keras.losses.SparseCategoricalCrossentropy(), I'm getting very less accuracy

```<code>model.compile(optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=["accuracy"])
</code>```

And when I use loss as "sparse_categorical_crossentropy", I'm getting much higher accuracy

```<code>model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
</code>```

Does this have to do with batch size?

How to get same results as "sparse_categorical_crossentropy" using custom loss layer?

答:
it's because when you use

```<code>loss=tf.keras.losses.SparseCategoricalCrossentropy()
</code>```

metrics should

```<code>"sparse_categorical_accuracy" not "accuracy"
</code>```

Body:
I'm implementing a multi class classification problem,

when I'm using my loss as tf.keras.losses.SparseCategoricalCrossentropy(), I'm getting very less accuracy

model.compile(optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=["accuracy"])

And when I use loss as "sparse_categorical_crossentropy", I'm getting much higher accuracy

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

Does this have to do with batch size?

How to get same results as "sparse_categorical_crossentropy" using custom loss layer?

Body:
it's because when you use

loss=tf.keras.losses.SparseCategoricalCrossentropy()

metrics should

"sparse_categorical_accuracy" not "accuracy"


问:
how to define new operator in c++
I am literally rookie to C++ and I'm trying to learn it in a professional way. I got familiar with the basic of defining operators in c++, but I think there are some restrictions, like you can only define operators with defined symbols. That is to say, for example, if I want to define vectorized multiply (like what is in MATLAB), it couldn't be possible.
Does anyone know a way to define such operators?

A*B = returns a new matrix with new dimension compromised A and B
A.*B = returns a new matrix, which all of its members are result of multiplication of A(i,j)*B(i,j)

答:
In general, you can make a custom operator using a struct:

```<code>struct operation {
    T operator () (T const &a, T const &b) {
        //code
    }
};
</code>```

Where T is a data type.

For your case, the operator would look something like this:

```<code>struct matrix_multiplication {
    vector <vector<int>> operator () (vector <vector<int>> const &a, vector <vector<int>> const &b) {
        //insert multiplication operation here
    }
};
</code>```

Title: how to define new operator in c++

Body:
In general, you can make a custom operator using a struct:

struct operation {
    T operator () (T const &a, T const &b) {
        //code
    }
};

Where T is a data type.

For your case, the operator would look something like this:

struct matrix_multiplication {
    vector <vector<int>> operator () (vector <vector<int>> const &a, vector <vector<int>> const &b) {
        //insert multiplication operation here
    }
};


问:
Reformatting a string and placing parts of it in separate variables
I'm trying to format a string that is entered by a user, and then want to place parts of that string in three separate variables.

```<code>//This is the text the user enters
rgbInputTextField.text == "253, 254, 255" //(Or variations like "53 54 55" or "3,4,5")

//I'd like to place that string in three variables such that:
R == 253
G == 254
G == 255
</code>```

Am I approaching this completely wrong? The goal is to register the RGB input string from the user and convert it to a Hex value.

I'm able to convert to Hex once I have the R, G and B variables, but can't figure out how to place the rgbInputTextField String into those three separate variables. I've found many UIColor extensions that can convert a hex string to UIColor, but nothing that converts an rgb string (with variations) to hex/UIColor.

Appreciate any help!

答:
You can extract the numbers of the string using:

```<code>let string = "122, 255, 2"
var array = String(stringLiteral: string).components(separatedBy: CharacterSet.decimalDigits.inverted)
array = array.filter { $0 != "" }
</code>```

Resulting on: ["122", "255", "2"]

Body:
I'm trying to format a string that is entered by a user, and then want to place parts of that string in three separate variables.

//This is the text the user enters
rgbInputTextField.text == "253, 254, 255" //(Or variations like "53 54 55" or "3,4,5")

//I'd like to place that string in three variables such that:
R == 253
G == 254
G == 255

Am I approaching this completely wrong? The goal is to register the RGB input string from the user and convert it to a Hex value.

I'm able to convert to Hex once I have the R, G and B variables, but can't figure out how to place the rgbInputTextField String into those three separate variables. I've found many UIColor extensions that can convert a hex string to UIColor, but nothing that converts an rgb string (with variations) to hex/UIColor.

Appreciate any help!

Body:
You can extract the numbers of the string using:

let string = "122, 255, 2"
var array = String(stringLiteral: string).components(separatedBy: CharacterSet.decimalDigits.inverted)
array = array.filter { $0 != "" }

Resulting on: ["122", "255", "2"]


问:
Set constructor values without passing them values
I'm trying to set my setCell method but i have not been provided the values in the parameters in the testing file. this should print me a box with 20 rows and 30 columns using the '*' char but it is printing blank lines for me

```<code>    public Window(final int rows, final int cols, final char border)
   {
         //Initialize everything
         this.rows = rows;
         this.cols = cols;
         this.border = border;
         this.shapes = new ArrayList<Shape>();
         this.cells = new char[rows+2][cols+2];
         //Make a call to addBorders()
         addBorders(border);
   }

void setCell(final int row, final int col, final char ch)
   {
         //set the character at cells[row][col] to 'ch'
         cells[row][col]=ch;

   }

public void display()
   {
      for (int i=0; i < rows+2; i++)
      {
         for(int j=0; j<cols+2; j++)
            System.out.print(cells[i][j]);
         System.out.println();
      }
   }
</code>```

And my tester file is =>

```<code>public class HouseForSale
{
    public static void main(String [] args) throws Exception
    {
        //Create the window
        Window w = new Window(20, 30, '*');
        w.display();
    }
}
</code>```

答:
You need to call setrCell in your Constructor function( Window ). like below:</p>

```<code>public Window(final int rows, final int cols, final char border)
   {
         //Initialize everything
         this.rows = rows;
         this.cols = cols;
         this.border = border;
         this.shapes = new ArrayList<Shape>();
         this.cells = new char[rows+2][cols+2];

         for (int i=0; i < rows; i++)
            for(int j=0; j < cols; j++)
               setCell(i,j,ch);
         //Make a call to addBorders()
         addBorders(border);
}
</code>```

Body:
I'm trying to set my setCell method but i have not been provided the values in the parameters in the testing file. this should print me a box with 20 rows and 30 columns using the '*' char but it is printing blank lines for me

    public Window(final int rows, final int cols, final char border)
   {
         //Initialize everything
         this.rows = rows;
         this.cols = cols;
         this.border = border;
         this.shapes = new ArrayList<Shape>();
         this.cells = new char[rows+2][cols+2];
         //Make a call to addBorders()
         addBorders(border);
   }

void setCell(final int row, final int col, final char ch)
   {
         //set the character at cells[row][col] to 'ch'
         cells[row][col]=ch;

   }

public void display()
   {
      for (int i=0; i < rows+2; i++)
      {
         for(int j=0; j<cols+2; j++)
            System.out.print(cells[i][j]);
         System.out.println();
      }
   }

And my tester file is =>

public class HouseForSale
{
    public static void main(String [] args) throws Exception
    {
        //Create the window
        Window w = new Window(20, 30, '*');
        w.display();
    }
}

Body:
You need to call setrCell in your Constructor function( Window ). like below:

public Window(final int rows, final int cols, final char border)
   {
         //Initialize everything
         this.rows = rows;
         this.cols = cols;
         this.border = border;
         this.shapes = new ArrayList<Shape>();
         this.cells = new char[rows+2][cols+2];

         for (int i=0; i < rows; i++)
            for(int j=0; j < cols; j++)
               setCell(i,j,ch);
         //Make a call to addBorders()
         addBorders(border);
}


问:
images won't display after retrieving file location from SQL table using php
Each row in the SQL table represents a user. There are 5 columns related to images: image1, image2, image3, image4, and image5. columns image[1-5] represent the image file directories. All the image columns are of the "text" type.

The problem is that when I type in the directory it will display but using the row variable will not work. For example, echo ' '; will display the picture but echo ' '; where $row['image1'] = "images/img1.jpg" will not work and I will see a torn page icon instead of a picture.

Here is the form script:

```<code><form action="dbpform.php" method="POST" enctype="multipart/form-data">

<input type="text" name="url"><br>

 <input name="uploadedfile1" type="file" /><br />
  <input name="uploadedfile2" type="file" /><br />
   <input name="uploadedfile3" type="file" /><br />
    <input name="uploadedfile4" type="file" /><br />
     <input name="uploadedfile5" type="file" /><br />

<textarea name="comment" id="comment" cols="55" rows="7" wrap="VIRTUAL"></textarea><br>

<input type="submit" name="submit" value="Submit">

</form>

<?php
mysql_connect ("","","") or die(mysql_error());
mysql_select_db ("") or die(mysql_error());

$url = $_POST['url'];
$comment = $_POST['comment'];

$target_path1 = "images/";
$target_path1 = $target_path1 . basename( $_FILES['uploadedfile1']['name']);

$target_path2 = "images/";
$target_path2 = $target_path2 . basename( $_FILES['uploadedfile2']['name']);

$target_path3 = "images/";
$target_path3 = $target_path3 . basename( $_FILES['uploadedfile3']['name']);

$target_path4 = "images/";
$target_path4 = $target_path4 . basename( $_FILES['uploadedfile4']['name']);

$target_path5 = "images/";
$target_path5 = $target_path5 . basename( $_FILES['uploadedfile5']['name']);

if ( isset( $_POST['submit'] ) )
{

move_uploaded_file($_FILES['uploadedfile1']['tmp_name'], $target_path1);
move_uploaded_file($_FILES['uploadedfile2']['tmp_name'], $target_path2);
move_uploaded_file($_FILES['uploadedfile3']['tmp_name'], $target_path3);
move_uploaded_file($_FILES['uploadedfile4']['tmp_name'], $target_path4);
move_uploaded_file($_FILES['uploadedfile5']['tmp_name'], $target_path5);

mysql_query ("INSERT INTO dbp VALUES ('','$url', '$target_path1', '$target_path2','$target_path3','$target_path4','$target_path5','$comment')");
}

?>
</code>```

Here is the output script:

```<code><?php

mysql_connect ("","","") or die(mysql_error());
mysql_select_db ("") or die(mysql_error());

$defaultqry = mysql_query ("SELECT * FROM dbp");

while($row = mysql_fetch_assoc($defaultqry))
{

echo $row['comment'];

echo '<img src= "$row[image1]" /> ';
echo '<img src= "$row[image2]" /> ';
echo '<img src= "$row[image3]" /> ';
echo '<img src= "$row[image4]" /> ';
echo '<img src= "$row[image5]" /> ';

echo "<br><br>";

}
?>
</code>```

答:
You've left out some quotation marks.  It's interpreting the image1 in $row[image1] as a constant, probably generating an error message, which is causing your image to show up as not available.

Try something like this:

```<code>echo '<img src= "'.$row['image1'].'" /> ';
echo '<img src= "'.$row['image2'].'" /> ';
echo '<img src= "'.$row['image3'].'" /> ';
echo '<img src= "'.$row['image4'].'" /> ';
echo '<img src= "'.$row['image5'].'" /> ';
</code>```

Body:
Each row in the SQL table represents a user. There are 5 columns related to images: image1, image2, image3, image4, and image5. columns image[1-5] represent the image file directories. All the image columns are of the "text" type.

The problem is that when I type in the directory it will display but using the row variable will not work. For example, echo ' '; will display the picture but echo ' '; where $row['image1'] = "images/img1.jpg" will not work and I will see a torn page icon instead of a picture.

Here is the form script:

<form action="dbpform.php" method="POST" enctype="multipart/form-data">

<input type="text" name="url">

 <input name="uploadedfile1" type="file" />

  <input name="uploadedfile2" type="file" />

   <input name="uploadedfile3" type="file" />

    <input name="uploadedfile4" type="file" />

     <input name="uploadedfile5" type="file" />

<textarea name="comment" id="comment" cols="55" rows="7" wrap="VIRTUAL"></textarea>

<input type="submit" name="submit" value="Submit">

</form>

<?php
mysql_connect ("","","") or die(mysql_error());
mysql_select_db ("") or die(mysql_error());

$url = $_POST['url'];
$comment = $_POST['comment'];

$target_path1 = "images/";
$target_path1 = $target_path1 . basename( $_FILES['uploadedfile1']['name']);

$target_path2 = "images/";
$target_path2 = $target_path2 . basename( $_FILES['uploadedfile2']['name']);

$target_path3 = "images/";
$target_path3 = $target_path3 . basename( $_FILES['uploadedfile3']['name']);

$target_path4 = "images/";
$target_path4 = $target_path4 . basename( $_FILES['uploadedfile4']['name']);

$target_path5 = "images/";
$target_path5 = $target_path5 . basename( $_FILES['uploadedfile5']['name']);

if ( isset( $_POST['submit'] ) )
{

move_uploaded_file($_FILES['uploadedfile1']['tmp_name'], $target_path1);
move_uploaded_file($_FILES['uploadedfile2']['tmp_name'], $target_path2);
move_uploaded_file($_FILES['uploadedfile3']['tmp_name'], $target_path3);
move_uploaded_file($_FILES['uploadedfile4']['tmp_name'], $target_path4);
move_uploaded_file($_FILES['uploadedfile5']['tmp_name'], $target_path5);

mysql_query ("INSERT INTO dbp VALUES ('','$url', '$target_path1', '$target_path2','$target_path3','$target_path4','$target_path5','$comment')");
}

?>

Here is the output script:

<?php

mysql_connect ("","","") or die(mysql_error());
mysql_select_db ("") or die(mysql_error());

$defaultqry = mysql_query ("SELECT * FROM dbp");

while($row = mysql_fetch_assoc($defaultqry))
{

echo $row['comment'];

echo ' ';
echo ' ';
echo ' ';
echo ' ';
echo ' ';

echo "

";

}
?>

Body:
You've left out some quotation marks.  It's interpreting the image1 in $row[image1] as a constant, probably generating an error message, which is causing your image to show up as not available.

Try something like this:

echo '<img src= "'.$row['image1'].'" /> ';
echo '<img src= "'.$row['image2'].'" /> ';
echo '<img src= "'.$row['image3'].'" /> ';
echo '<img src= "'.$row['image4'].'" /> ';
echo '<img src= "'.$row['image5'].'" /> ';


问:
React Hooks/Next.js and Multer: 401 Unauthorized, Error while uploading image to MongoDB Atlas
I've tried numerous configurations and been pulling my hair out for a couple days now. However no matter what I do when I try to hit /users/uploadmulter I get an authorized error.

On mongoDB atlas I've tried creating a new collection.

Moving the route declaration in my users file (that way I know it's not an express config issue as other operations work i.e. make a user, get new password etc.)

Anyway, here is my React component:

```<code>import { useState, useEffect } from 'react';

import { Card, Icon, Image, Segment, Form } from 'semantic-ui-react';

import axios from 'axios';

function ImageUploader() {
  var [defaultImage, setDefaultImage] = useState(
    require('../../assets/images/placeholder.jpg')
  );
  var [userAvatar, setUserAvatar] = useState(defaultImage);

  useEffect(() => {
    setUserAvatar(userAvatar);
  }, [userAvatar]);

  function fileUploader(e) {
    console.log('event fileUploader ', e);
    var imageFormObj = new FormData();

    console.log('e.target.files[0] ', e.target.files[0]);

    imageFormObj.append('avatar', 'multer-image-' + Date.now());
    imageFormObj.append('imageData', e.target.files[0]);
    setUserAvatar(URL.createObjectURL(e.target.files[0]));

    console.log('userAvatar ', userAvatar);
    console.log('imageFormObj ', imageFormObj);

    axios
      .post('http://localhost:8016/users/uploadmulter', imageFormObj)
      .then(data => {
        if (data.data.success) {
          alert('Image has been successfully uploaded using multer');
        }
      })
      .catch(err => {
        alert('Error while uploading image using multer');
      });
  }

  return (
    <>
      <Segment>
        <Card fluid>
          <Image src={userAvatar} alt="upload-image" />
          <Segment>
            <Form encType="multipart/form-data">
              <Form.Field>
                <input
                  placeholder="Name of image"
                  className="process__upload-btn"
                  type="file"
                  name="avatar"
                  content="Edit your Avatar!"
                  onChange={e => fileUploader(e)}
                />
                {/* <Button
                  content="Edit your Avatar!"
                  labelPosition="left"
                  icon="file"
                  onClick={e => fileUploader(e)}
                /> */}
              </Form.Field>
            </Form>
          </Segment>
          <Card.Content>
            <Card.Header>Charly</Card.Header>
            <Card.Meta>
              <span className="date">Joined in 2015</span>
            </Card.Meta>
            <Card.Description>Charly</Card.Description>
          </Card.Content>
          <Card.Content extra>
            <a>
              <Icon name="user" />
              22 Friends
            </a>
          </Card.Content>
        </Card>
      </Segment>
    </>
  );
}

export default ImageUploader;
</code>```

And this is my route which handles sending the data to MongoDB Atlas:

```<code>var router = require('express').Router();
var Image = require('../models/UserImagesSchema');
var multer = require('multer');

  var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname);
  }
});

var upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  }
});

/*
stores image in uploads folder
using mulkter and creates a reference to the file
*/

router.post(upload.single('imageData'), (req, res, next) => {
  console.log(req.body);
  var newImage = new Image({
    avatar: {
      imageName: req.body.avatar,
      imageData: req.file.path
    }
  });

  newImage
    .save()
    .then(result => {
      console.log(result);
      res.status(200).json({
        success: true,
        document: result
      });
    })
    .catch(err => next(err));
});

module.exports = router;
</code>```

This is my Schema:

```<code>var mongoose = require('mongoose');

/* Image Schema for storing images in the mongodb database */

var UserImagesSchema = new mongoose.Schema({
  avatar: {
    _userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
    imageName: { type: String, default: 'none', required: true },
    imageData: {
      data: Buffer,
      contentType: String
    }
  }
});

module.exports = mongoose.model('UserImages', UserImagesSchema);
</code>```

This is the app/server file for express:

```<code>var express = require('express');

require('dotenv').config();
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var cors = require('cors');

var nextJS = require('next');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var auth = require('./lib/auth');
var HttpStatus = require('http-status-codes');
var compression = require('compression');
var helmet = require('helmet');

var PORT = process.env.PORT || 8016;

var { isBlockedPage, isInternalUrl } = require('next-server/dist/server/utils');

function NODE_ENVSetter(ENV) {
  var environment,
    environments = {
      production: () => {
        environment = process.env.MONGODB_URI;
        console.log(`We are currently in the production environment: ${environment}`);
        return environment;
      },
      test: () => {
        environment = process.env.TEST_DB_DSN;
        console.log(`We are currently in the test environment: ${environment}`);
        return environment;
      },
      default: () => {
        environment = process.env.DEVELOPMENT_DB_DSN;
        console.log(`We are currently in the development environment: ${environment}`);
        return environment;
      }
    };
  (environments[ENV] || environments['default'])();

  return environment;
}

var db = NODE_ENVSetter('development');
var mongoose = require('mongoose');

function errorHandler(err, req, res, next) {
  // Set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Log error
  console.error(err.stack);

  // Render the error page
  res.status(err.status || 500);

  // Default error message by HTTP code
  res.render('error', {
    title: HttpStatus.getStatusText(err.status),
    message: HttpStatus.getStatusText(err.status)
  });
}

function start() {
  const dev = process.env.NODE_ENV !== 'production';
  const app = nextJS({ dev });
  const server = express();
  // const proxy = createProxyMiddleware(options);

  app
    .prepare()
    .then(() => {
      mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
      mongoose.Promise = global.Promise;

      mongoose.connection
        .on('connected', () => {
          console.log(`Mongoose connection open on ${db}`);
        })
        .on('error', err => {
          console.log(`Connection error: ${err.message}`);
        });
    })
    .catch(err => {
      console.error(err);
    });

  server.use(
    session({
      secret: 'very secret 12345',
      resave: false,
      saveUninitialized: false,
      store: new MongoStore({ mongooseConnection: mongoose.connection })
    })
  );

  server.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    );
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', '*'); // enables all the methods to take place
    return next();
  });

  server.set('view engine', 'html');
  server.use(cors());

  server.use(morgan('dev'));
  server.use('/uploads', express.static('uploads'));
  server.use(bodyParser.json({ limit: '50mb' }));
  server.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
  server.use(cookieParser());
  server.use(express.static(path.join(__dirname + 'uploads')));

  server.use(compression());
  server.use(helmet());
  server.use(auth.initialize);
  server.use(auth.session);
  server.use(auth.setUser);
  // console.log('auth.setUser ', auth.setUser);

  server.use('/users', require('./users'));

  // Redirect all requests to main entrypoint pages/index.js
  server.get('/*', async (req, res, next) => {
    try {
      // @NOTE code duplication from here
      // https://github.com/zeit/next.js/blob/cc6fe5fdf92c9c618a739128fbd5192a6d397afa/packages/next-server/server/next-server.ts#L405
      const pathName = req.originalUrl;
      if (isInternalUrl(req.url)) {
        return app.handleRequest(req, res, req.originalUrl);
      }

      if (isBlockedPage(pathName)) {
        return app.render404(req, res, req.originalUrl);
      }

      // Provide react-router static router with a context object
      // https://reacttraining.com/react-router/web/guides/server-rendering
      req.locals = {};
      req.locals.context = {};
      const html = await app.renderToHTML(req, res, '/', {});

      // Handle client redirects
      const context = req.locals.context;
      if (context.url) {
        return res.redirect(context.url);
      }

      // Handle client response statuses
      if (context.status) {
        return res.status(context.status).send();
      }

      // Request was ended by the user
      if (html === null) {
        return;
      }

      app.sendHTML(req, res, html);
    } catch (e) {
      next(e);
    }
  });

  // catch 404 and forward to error handler
  server.use(function(req, res, next) {
    next(createError(404));
  });

  // error handler
  server.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.errorStatus = err.status;
    res.locals.errorMessage = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    console.log('err.status ', err.status);
    res.status(401).send(err.message);
  });

  if (process.env.NODE_ENV === 'production') {
    server.use(express.static('.next/static'));

    server.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, '.next/static', 'index.html'));
    });

    server.listen(PORT, err => {
      if (err) throw err;
      console.log(
        `> Ready and listening on PORT:${PORT} in the ${process.env.NODE_ENV} environment`
      );
    });
  } else {
    server.listen(PORT, err => {
      if (err) throw err;
      console.log(`> Ready and listening on http://localhost:${PORT}`);
    });
  }
}

start();
</code>```

答:
If your files are actually less than 16 mb, please try using this Converter that changes the image of format jpeg / png to a format of saving to mongodb, and you can see this as an easy alternative for gridfs ,

please follow this github repo for more details, please try this method,

https://github.com/saran-surya/Mongo-Image-Converter

Body:
I've tried numerous configurations and been pulling my hair out for a couple days now. However no matter what I do when I try to hit /users/uploadmulter I get an authorized error.

On mongoDB atlas I've tried creating a new collection.

Moving the route declaration in my users file (that way I know it's not an express config issue as other operations work i.e. make a user, get new password etc.)

Anyway, here is my React component:

import { useState, useEffect } from 'react';

import { Card, Icon, Image, Segment, Form } from 'semantic-ui-react';

import axios from 'axios';

function ImageUploader() {
  var [defaultImage, setDefaultImage] = useState(
    require('../../assets/images/placeholder.jpg')
  );
  var [userAvatar, setUserAvatar] = useState(defaultImage);

  useEffect(() => {
    setUserAvatar(userAvatar);
  }, [userAvatar]);

  function fileUploader(e) {
    console.log('event fileUploader ', e);
    var imageFormObj = new FormData();

    console.log('e.target.files[0] ', e.target.files[0]);

    imageFormObj.append('avatar', 'multer-image-' + Date.now());
    imageFormObj.append('imageData', e.target.files[0]);
    setUserAvatar(URL.createObjectURL(e.target.files[0]));

    console.log('userAvatar ', userAvatar);
    console.log('imageFormObj ', imageFormObj);

    axios
      .post('http://localhost:8016/users/uploadmulter', imageFormObj)
      .then(data => {
        if (data.data.success) {
          alert('Image has been successfully uploaded using multer');
        }
      })
      .catch(err => {
        alert('Error while uploading image using multer');
      });
  }

  return (
    <>
      <Segment>
        <Card fluid>
          <Image src={userAvatar} alt="upload-image" />
          <Segment>
            <Form encType="multipart/form-data">
              <Form.Field>
                <input
                  placeholder="Name of image"
                  className="process__upload-btn"
                  type="file"
                  name="avatar"
                  content="Edit your Avatar!"
                  onChange={e => fileUploader(e)}
                />
                {/* <Button
                  content="Edit your Avatar!"
                  labelPosition="left"
                  icon="file"
                  onClick={e => fileUploader(e)}
                /> */}
              </Form.Field>
            </Form>
          </Segment>
          <Card.Content>
            <Card.Header>Charly</Card.Header>
            <Card.Meta>
              Joined in 2015
            </Card.Meta>
            <Card.Description>Charly</Card.Description>
          </Card.Content>
          <Card.Content extra>

              <Icon name="user" />
              22 Friends

          </Card.Content>
        </Card>
      </Segment>
    </>
  );
}

export default ImageUploader;

And this is my route which handles sending the data to MongoDB Atlas:

var router = require('express').Router();
var Image = require('../models/UserImagesSchema');
var multer = require('multer');

  var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname);
  }
});

var upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  }
});

/*
stores image in uploads folder
using mulkter and creates a reference to the file
*/

router.post(upload.single('imageData'), (req, res, next) => {
  console.log(req.body);
  var newImage = new Image({
    avatar: {
      imageName: req.body.avatar,
      imageData: req.file.path
    }
  });

  newImage
    .save()
    .then(result => {
      console.log(result);
      res.status(200).json({
        success: true,
        document: result
      });
    })
    .catch(err => next(err));
});

module.exports = router;

This is my Schema:

var mongoose = require('mongoose');

/* Image Schema for storing images in the mongodb database */

var UserImagesSchema = new mongoose.Schema({
  avatar: {
    _userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
    imageName: { type: String, default: 'none', required: true },
    imageData: {
      data: Buffer,
      contentType: String
    }
  }
});

module.exports = mongoose.model('UserImages', UserImagesSchema);

This is the app/server file for express:

var express = require('express');

require('dotenv').config();
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var cors = require('cors');

var nextJS = require('next');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var auth = require('./lib/auth');
var HttpStatus = require('http-status-codes');
var compression = require('compression');
var helmet = require('helmet');

var PORT = process.env.PORT || 8016;

var { isBlockedPage, isInternalUrl } = require('next-server/dist/server/utils');

function NODE_ENVSetter(ENV) {
  var environment,
    environments = {
      production: () => {
        environment = process.env.MONGODB_URI;
        console.log(`We are currently in the production environment: ${environment}`);
        return environment;
      },
      test: () => {
        environment = process.env.TEST_DB_DSN;
        console.log(`We are currently in the test environment: ${environment}`);
        return environment;
      },
      default: () => {
        environment = process.env.DEVELOPMENT_DB_DSN;
        console.log(`We are currently in the development environment: ${environment}`);
        return environment;
      }
    };
  (environments[ENV] || environments['default'])();

  return environment;
}

var db = NODE_ENVSetter('development');
var mongoose = require('mongoose');

function errorHandler(err, req, res, next) {
  // Set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Log error
  console.error(err.stack);

  // Render the error page
  res.status(err.status || 500);

  // Default error message by HTTP code
  res.render('error', {
    title: HttpStatus.getStatusText(err.status),
    message: HttpStatus.getStatusText(err.status)
  });
}

function start() {
  const dev = process.env.NODE_ENV !== 'production';
  const app = nextJS({ dev });
  const server = express();
  // const proxy = createProxyMiddleware(options);

  app
    .prepare()
    .then(() => {
      mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
      mongoose.Promise = global.Promise;

      mongoose.connection
        .on('connected', () => {
          console.log(`Mongoose connection open on ${db}`);
        })
        .on('error', err => {
          console.log(`Connection error: ${err.message}`);
        });
    })
    .catch(err => {
      console.error(err);
    });

  server.use(
    session({
      secret: 'very secret 12345',
      resave: false,
      saveUninitialized: false,
      store: new MongoStore({ mongooseConnection: mongoose.connection })
    })
  );

  server.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    );
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', '*'); // enables all the methods to take place
    return next();
  });

  server.set('view engine', 'html');
  server.use(cors());

  server.use(morgan('dev'));
  server.use('/uploads', express.static('uploads'));
  server.use(bodyParser.json({ limit: '50mb' }));
  server.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
  server.use(cookieParser());
  server.use(express.static(path.join(__dirname + 'uploads')));

  server.use(compression());
  server.use(helmet());
  server.use(auth.initialize);
  server.use(auth.session);
  server.use(auth.setUser);
  // console.log('auth.setUser ', auth.setUser);

  server.use('/users', require('./users'));

  // Redirect all requests to main entrypoint pages/index.js
  server.get('/*', async (req, res, next) => {
    try {
      // @NOTE code duplication from here
      // https://github.com/zeit/next.js/blob/cc6fe5fdf92c9c618a739128fbd5192a6d397afa/packages/next-server/server/next-server.ts#L405
      const pathName = req.originalUrl;
      if (isInternalUrl(req.url)) {
        return app.handleRequest(req, res, req.originalUrl);
      }

      if (isBlockedPage(pathName)) {
        return app.render404(req, res, req.originalUrl);
      }

      // Provide react-router static router with a context object
      // https://reacttraining.com/react-router/web/guides/server-rendering
      req.locals = {};
      req.locals.context = {};
      const html = await app.renderToHTML(req, res, '/', {});

      // Handle client redirects
      const context = req.locals.context;
      if (context.url) {
        return res.redirect(context.url);
      }

      // Handle client response statuses
      if (context.status) {
        return res.status(context.status).send();
      }

      // Request was ended by the user
      if (html === null) {
        return;
      }

      app.sendHTML(req, res, html);
    } catch (e) {
      next(e);
    }
  });

  // catch 404 and forward to error handler
  server.use(function(req, res, next) {
    next(createError(404));
  });

  // error handler
  server.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.errorStatus = err.status;
    res.locals.errorMessage = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    console.log('err.status ', err.status);
    res.status(401).send(err.message);
  });

  if (process.env.NODE_ENV === 'production') {
    server.use(express.static('.next/static'));

    server.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, '.next/static', 'index.html'));
    });

    server.listen(PORT, err => {
      if (err) throw err;
      console.log(
        `> Ready and listening on PORT:${PORT} in the ${process.env.NODE_ENV} environment`
      );
    });
  } else {
    server.listen(PORT, err => {
      if (err) throw err;
      console.log(`> Ready and listening on http://localhost:${PORT}`);
    });
  }
}

start();


问:
getting a performance hit for nested for loop in C#
I have an array of string, a total of(100k). I need to check if the same string has occurred previously, if it occurs all I have to do is return that string. I have written the code using nested for loops, but unfortunately I am getting bad performance. It takes 1.9 mins to process the function correctly for (string[100K]) whereas I am expecting it to finish it within a couple of seconds.

My concern is not the logic. My concern is the LOOP. How to increase the efficiency of the loop.

```<code>public string StartMatchingProcess(string[]inputArray)
{
    string[] stringArray = inputArray;
    string result = string.Empty;

    for (long i = 0; i < stringArray.Length; i++)
    {
        for (long j = 0; j <= i; j++)
        {
            if(i == j) break;

            if (IsPrefix(stringArray[i], stringArray[j]))
            {
                return stringArray[i];
            }
        }
    }
    Console.WriteLine("GOOD SET");
    return result;
}

public bool IsPrefix(string string1,string string2)
{
    if (AreString1ValuesValid(string1, string2))
    {
        if (string1 == string2.Substring(0, string1.Length))
        {
            Console.WriteLine("BAD SET");
            Console.WriteLine(string1);
            return true;
        }
    }
    else if (AreString2ValuesValid(string1, string2))
    {
        if (string2 == string1.Substring(0, string2.Length))
        {
            Console.WriteLine("BAD SET");
            Console.WriteLine(string1);
            return true;
        }
    }
    return false;
}

public bool AreString1ValuesValid(string string1, string string2)
        => string1.Length <= string2.Length;

public bool AreString2ValuesValid(string string1, string string2)
       => string2.Length <= string1.Length;
</code>```

答:
Here is a complete solution using linq.</p>

```<code>public class Node
    {
        public char letter { get; }
        public int Index { get; set; }
        public List<Node> ChildList { get; set; } = new List<Node>();

        public Node(char item, int index)
        {
            Index = index;
            letter = item;
        }
    }

    public class NoPrefixSet
    {
        public Dictionary<char, Node> ParentNode { get; set; } = new Dictionary<char, Node>();

        public string GenerateNodes(string[] inputArray)
        {
            for (int i = 0; i < inputArray.Length; i++)
            {
                if (IsWordPrefix(inputArray[i]))
                {
                    Console.WriteLine("BAD SET");
                    Console.WriteLine(inputArray[i]);
                    return inputArray[i];

                }
            }
            Console.WriteLine("Good Set");
            return "Good Set";
        }

        private void InsertNodeInParent(char item)
            => ParentNode.Add(item, new Node(item, 0));

        private bool IsWordPrefix(string word)
        {
            //Check parent
            Node parentNode = null;
            bool hasNotInserted = false;
            int similarCounter = 0;
            if (!ParentNode.Any(a => a.Key == word[0]))
            {
                InsertNodeInParent(word[0]);
            }
            parentNode = ParentNode.Where(a => a.Key == word[0]).FirstOrDefault().Value;

            for (int letterIndex = 0; letterIndex < word.Length; letterIndex++)
            {
                if (!parentNode.ChildList.Any(a => a.letter == word[letterIndex]))
                {
                    parentNode.ChildList.Add(new Node(word[letterIndex], letterIndex));
                }
                else
                {
                    if (!parentNode.ChildList.Where(a => a.letter == word[letterIndex]).First().ChildList.Any() || word.Length == letterIndex+1)
                    {
                        if (similarCounter == letterIndex)
                            return hasNotInserted = true;
                    }
                    similarCounter++;

                }
                parentNode = parentNode.ChildList.Where(a => a.letter == word[letterIndex] && a.Index == letterIndex).First();
            }

            return hasNotInserted;
        }

        public void ReadInput()
        {
            long data = Convert.ToInt64(Console.ReadLine());
            string[] stringArray = new string[data];
            for (long i = 0; i < data; i++)
            {
                stringArray[i] = Console.ReadLine();
            }
            GenerateNodes(stringArray);
        }
    }
</code>```

Body:
I have an array of string, a total of(100k). I need to check if the same string has occurred previously, if it occurs all I have to do is return that string. I have written the code using nested for loops, but unfortunately I am getting bad performance. It takes 1.9 mins to process the function correctly for (string[100K]) whereas I am expecting it to finish it within a couple of seconds.

My concern is not the logic. My concern is the LOOP. How to increase the efficiency of the loop.

public string StartMatchingProcess(string[]inputArray)
{
    string[] stringArray = inputArray;
    string result = string.Empty;

    for (long i = 0; i < stringArray.Length; i++)
    {
        for (long j = 0; j <= i; j++)
        {
            if(i == j) break;

            if (IsPrefix(stringArray[i], stringArray[j]))
            {
                return stringArray[i];
            }
        }
    }
    Console.WriteLine("GOOD SET");
    return result;
}

public bool IsPrefix(string string1,string string2)
{
    if (AreString1ValuesValid(string1, string2))
    {
        if (string1 == string2.Substring(0, string1.Length))
        {
            Console.WriteLine("BAD SET");
            Console.WriteLine(string1);
            return true;
        }
    }
    else if (AreString2ValuesValid(string1, string2))
    {
        if (string2 == string1.Substring(0, string2.Length))
        {
            Console.WriteLine("BAD SET");
            Console.WriteLine(string1);
            return true;
        }
    }
    return false;
}

public bool AreString1ValuesValid(string string1, string string2)
        => string1.Length <= string2.Length;

public bool AreString2ValuesValid(string string1, string string2)
       => string2.Length <= string1.Length;

Body:
Here is a complete solution using linq.

public class Node
    {
        public char letter { get; }
        public int Index { get; set; }
        public List<Node> ChildList { get; set; } = new List<Node>();

        public Node(char item, int index)
        {
            Index = index;
            letter = item;
        }
    }

    public class NoPrefixSet
    {
        public Dictionary<char, Node> ParentNode { get; set; } = new Dictionary<char, Node>();

        public string GenerateNodes(string[] inputArray)
        {
            for (int i = 0; i < inputArray.Length; i++)
            {
                if (IsWordPrefix(inputArray[i]))
                {
                    Console.WriteLine("BAD SET");
                    Console.WriteLine(inputArray[i]);
                    return inputArray[i];

                }
            }
            Console.WriteLine("Good Set");
            return "Good Set";
        }

        private void InsertNodeInParent(char item)
            => ParentNode.Add(item, new Node(item, 0));

        private bool IsWordPrefix(string word)
        {
            //Check parent
            Node parentNode = null;
            bool hasNotInserted = false;
            int similarCounter = 0;
            if (!ParentNode.Any(a => a.Key == word[0]))
            {
                InsertNodeInParent(word[0]);
            }
            parentNode = ParentNode.Where(a => a.Key == word[0]).FirstOrDefault().Value;

            for (int letterIndex = 0; letterIndex < word.Length; letterIndex++)
            {
                if (!parentNode.ChildList.Any(a => a.letter == word[letterIndex]))
                {
                    parentNode.ChildList.Add(new Node(word[letterIndex], letterIndex));
                }
                else
                {
                    if (!parentNode.ChildList.Where(a => a.letter == word[letterIndex]).First().ChildList.Any() || word.Length == letterIndex+1)
                    {
                        if (similarCounter == letterIndex)
                            return hasNotInserted = true;
                    }
                    similarCounter++;

                }
                parentNode = parentNode.ChildList.Where(a => a.letter == word[letterIndex] && a.Index == letterIndex).First();
            }

            return hasNotInserted;
        }

        public void ReadInput()
        {
            long data = Convert.ToInt64(Console.ReadLine());
            string[] stringArray = new string[data];
            for (long i = 0; i < data; i++)
            {
                stringArray[i] = Console.ReadLine();
            }
            GenerateNodes(stringArray);
        }
    }


问:
Using files for for shared memory IPC
In my application, there is one process which writes data to a file, and then, in response to receiving a request, will send (some) of that data via the network to the requesting process.  The basis of this question is to see if we can speed up communication when both processes happen to be on the same host.  (In my case, the processes are Java, but I think this discussion can apply more broadly.)

There are a few projects out there which use the MappedByteBuffers returned by Java's FileChannel.map() as a way to have shared memory IPC between JVMs on the same host (see Chronicle Queue, Aeron IPC, etc.).

One approach to speeding up same-host communication would be to have my application use one of those technologies to provide the request-response pathway for same-host communication, either in conjunction with the existing mechanism for writing to the data file, or by providing a unified means of both communication and writing to the file.

Another approach would be to allow the requesting process to have direct access to the data file.

I tend to favor the second approach - assuming it would be correct - as it would be easier to implement, and seems more efficient than copying/transmitting a copy of the data for each request (assuming we didn't replace the existing mechanism for writing to the file).

Essentially, I'd like to understanding what exactly occurs when two processes have access to the same file, and use it to communicate, specifically Java (1.8) and Linux (3.10).

From my understanding, it seems like if two processes have the same file open at the same time, the "communication" between them will essentially be via "shared memory".

Note that this question is not concerned with the performance implication of using a MappedByteBuffer or not - it seem highly likely that a using mapped buffers, and the reduction in copying and system calls, will reduce overhead compared to reading and writing the file, but that might require significant changes to the application.

Here is my understanding:

When Linux loads a file from disk, it copies the contents of that file to pages in memory.  That region of memory is called the page cache.  As far as I can tell, it does this regardless of which Java method (FileInputStream.read(), RandomAccessFile.read(), FileChannel.read(), FileChannel.map()) or native method is used to read the file (obseved with "free" and monitoring the "cache" value).

If another process attempts to load the same file (while it is still resident in the cache) the kernel detects this and doesn't need to reload the file.  If the page cache gets full, pages will get evicted  - dirty ones being written back out to the disk.  (Pages also get written back out if there is an explicit flush to disk, and periodically, with a kernel thread).

Having a (large) file already in the cache is a significant performance boost, much more so than the differences based on which Java methods we use to open/read that file.

If a file is loaded using the mmap system call (C) or via FileChannel.map() (Java), essentially the file's pages (in the cache) are loaded directly into the process' address space.  Using other methods to open a file, the file is loaded into pages not in the process' address space, and then the various methods to read/write that file copy some bytes from/to those pages into a buffer in the process' address space.  There is an obvious performance benefit avoiding that copy, but my question isn't concerned with performance.

So in summary, if I understand correctly - while mapping offer a performance advantage, it doesn't seem like it offers any "shared memory" functionality that we don't already get just from the nature of the Linux and the page cache.

So, please let me know where my understanding is off.

Thanks.

答:
My question is, on Java (1.8) and Linux (3.10), are MappedByteBuffers really necessary for implementing shared memory IPC, or would any access to a common file provide the same functionality?

It depends on why you want to implement shared memory IPC.

You can clearly implement IPC without shared memory; e.g. over sockets.  So, if you are not doing it for performance reasons, it is not necessary to do shared memory IPC at all!

So performance has to be at the root of any discussion.

Access using files via the Java classic io or nio APIs does not provide shared memory functionality or performance.

The main difference between regular file I/O or Socket I/O versus shared memory IPC is that the former requires the applications to explicitly make read and write syscalls to send and receive messages.  This entails extra syscalls, and entails the kernel copying data.  Furthermore, if there are multiple threads you either need a separate "channel" between each  thread pair or something to multiplexing multiple "conversations" over a shared channel.  The latter can lead to the shared channel becoming a concurrency bottleneck.

Note that these overheads are orthogonal to the Linux page cache.

By contrast, with IPC implemented using shared memory, there are no read and write syscalls, and no extra copy step.  Each "channel" can simply use a separate area of the mapped buffer.  A thread in one process writes data into the shared memory and it is almost immediately visible to the second process.

The caveat is that the processes need to 1) synchronize, and 2) implement memory barriers to ensure that the reader doesn't see stale data.  But these can both be implemented without syscalls.

In the wash-up, shared memory IPC using memory mapped files >>is<< faster than using conventional files or sockets, and that is why people do it.

You also implicitly asked if shared memory IPC can be implemented without memory mapped files.

A practical way would be to create a memory-mapped file for a file that lives in a memory-only file system; e.g. a "tmpfs" in Linux.

Technically, that is still a memory-mapped file.  However, you don't incur overheads of flushing data to disk, and you avoid the potential security concern of private IPC data ending up on disk.

You could in theory implement a shared segment between two processes by doing the following:

In the parent process, use mmap to create a segment with MAP_ANONYMOUS | MAP_SHARED.

Fork child processes.  These will end up all sharing the segment with each other and the parent process.

However, implementing that for a Java process would be ... challenging.  AFAIK, Java does not support this.

Reference:

What is the purpose of MAP_ANONYMOUS flag in mmap system call?

Title: Using files for for shared memory IPC