问:
NodeJS Express Mongoose how to make a get query with parameteres
I'm writing a node js method which I want to find vlaues which match the imei.name parameter passed in, and the test field is empty.

This is the method which I tried to use:

```<code>router.get('/gettdata/', (req, res, next) => {

    let aa=req.query.imei;
    console.log(aa);
    Post.findOne( {imei:{"imei.name":req.body},
  test:{$exists:false}
  }

    )
      .then((posts) => {
        res.json(posts);
        console.log(posts);
      })
      .catch(err => console.log(err))
  });
</code>```

it returns an empty field despite it exists when I use only

```<code>Post.findOne( {"imei.name":req.body})
</code>```

it works and when I use only

```<code>Post.findOne(
  test:{$exists:false}
 )
</code>```

it works but the problem is using them two in one time

```<code>{
        "_id" : ObjectId("5eb7f90fb88d8d4d94184333"),
        "imei" : {
                "name" : "bokhhjbr",
                "modele" : "5486"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eb7fb9cb88d8d4d94184334"),
        "imei" : {
                "name" : "865566048694354",
                "modele" : "CPH1803"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eba73395fd8dd073065efdf"),
        "imei" : {
                "name" : "bok55555555555hjbr",
                "modele" : "5486"
        },
        "createdAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "updatedAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f93c0c93ec1c785358ab"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "updatedAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f9420c93ec1c785358ac"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "updatedAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "__v" : 0
}
</code>```

and that's my database shown in cmd.

I need some help - thank you

答:
Use the req.params

```<code>router.get('/gettdata/:imei', (req, res, next) => {

   console.log(req.params.imei);

})
</code>```

You pass the parameters like this:

http://url.com/gettdata/test

You will see test in the console.

```<code>/gettdata/:imei/:parameter2/:parameter3
</code>```

Then you pass it like this

Body:
I'm writing a node js method which I want to find vlaues which match the imei.name parameter passed in, and the test field is empty.

This is the method which I tried to use:

router.get('/gettdata/', (req, res, next) => {

    let aa=req.query.imei;
    console.log(aa);
    Post.findOne( {imei:{"imei.name":req.body},
  test:{$exists:false}
  }

    )
      .then((posts) => {
        res.json(posts);
        console.log(posts);
      })
      .catch(err => console.log(err))
  });

it returns an empty field despite it exists when I use only

Post.findOne( {"imei.name":req.body})

it works and when I use only

Post.findOne(
  test:{$exists:false}
 )

it works but the problem is using them two in one time

{
        "_id" : ObjectId("5eb7f90fb88d8d4d94184333"),
        "imei" : {
                "name" : "bokhhjbr",
                "modele" : "5486"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eb7fb9cb88d8d4d94184334"),
        "imei" : {
                "name" : "865566048694354",
                "modele" : "CPH1803"
        },
        "__v" : 0
}
{
        "_id" : ObjectId("5eba73395fd8dd073065efdf"),
        "imei" : {
                "name" : "bok55555555555hjbr",
                "modele" : "5486"
        },
        "createdAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "updatedAt" : ISODate("2020-05-12T09:58:17.203Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f93c0c93ec1c785358ab"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "updatedAt" : ISODate("2020-05-29T11:59:56.441Z"),
        "__v" : 0
}
{
        "_id" : ObjectId("5ed0f9420c93ec1c785358ac"),
        "imei" : {
                "name" : "865566048694354"
        },
        "test" : {
                "tactileState" : "1",
                "pixelState" : "1",
                "greyState" : "1"
        },
        "createdAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "updatedAt" : ISODate("2020-05-29T12:00:02.040Z"),
        "__v" : 0
}

and that's my database shown in cmd.

I need some help - thank you

Body:
Use the req.params

router.get('/gettdata/:imei', (req, res, next) => {

   console.log(req.params.imei);

})

You pass the parameters like this:

http://url.com/gettdata/test

You will see test in the console.

/gettdata/:imei/:parameter2/:parameter3

Then you pass it like this


来源: stackexchange

问:
C# DateTime to UTC Time without changing the time
How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

```<code>DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm
</code>```

答:
You can use the overloaded constructor of DateTime:

```<code>DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm

Body:
You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);


答:
For the sake of completeness, here is a solution using dcast():

```<code>library(data.table)
dcast(setDT(haves), ... ~ x, value.var = paste0("number_", 1:2), fill = 0)
</code>```

```<code>   id factor1 factor2 age      date1     y number_1_0 number_1_1 number_1_2 number_1_3 number_2_0 number_2_1
1:  1      f1      f2   2 2014-07-01 554.5          3          2          1          0         45         44
2:  1      f1      f2   9 2015-02-01 616.0         11          0          0         10         53          0
   number_2_2 number_2_3
1:         43          0
2:          0         52
</code>```

pivot_wider() also has a parameter to fill in missing values. So, there is no need for a separate call to replace(is.na(.), 0):

```<code>library(tidyr)
haves %>%
  pivot_wider(names_from = x, values_from = starts_with("number_"), values_fill = 0)
</code>```

```<code># A tibble: 2 x 14
     id factor1 factor2   age date1          y number_1_2 number_1_1 number_1_0 number_1_3 number_2_2 number_2_1
  <dbl> <chr>   <chr>   <dbl> <date>     <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
1     1 f1      f2          2 2014-07-01  554.          1          2          3          0         43         44
2     1 f1      f2          9 2015-02-01  616           0          0         11         10          0          0
# ... with 2 more variables: number_2_0 <dbl>, number_2_3 <dbl>
</code>```

Note that the column order after reshaping is different. While dcast() orders columns by value of x, i.e. 0, 1, 2, 3, pivot_wider() orders columns by appearance, i.e., 2, 1, 0, 3.

ContentLicense: CC BY-SA 4.0

Title: cast/spread 2 columns based on one shared factor

Body:
I am struggling with this - sorry. This is my haves:

library(dplyr)
library(reshape2)

haves <- data.frame(
    id = c(1, 1, 1, 1, 1)
    , factor1 = c("f1", "f1", "f1", "f1", "f1")
    , factor2 = c("f2", "f2", "f2", "f2", "f2")
    , number_1 = c(1,2,3,10,11)
    , number_2 = c(43,44,45,52,53)
    , age = c(2, 2, 2, 9, 9)
    , date1 = c(as.Date("2014-07-01"), as.Date("2014-07-01"), as.Date("2014-07-01"), as.Date("2015-02-01"), as.Date("2015-02-01"))
    , y = c(554.5, 554.5, 554.5, 616, 616)
    , x = c(2,1,0,3,0)
)

haves

  id factor1 factor2 number_1 number_2 age      date1     y x
1  1      f1      f2        1       43   2 2014-07-01 554.5 2
2  1      f1      f2        2       44   2 2014-07-01 554.5 1
3  1      f1      f2        3       45   2 2014-07-01 616.0 0
4  1      f1      f2       10       52   9 2015-02-01 616.0 3
5  1      f1      f2       11       53   9 2015-02-01 616.0 0

I want to cast/spread the values in number_1 and number_2 according to x to get this:

Body:
For the sake of completeness, here is a solution using dcast():

library(data.table)
dcast(setDT(haves), ... ~ x, value.var = paste0("number_", 1:2), fill = 0)

   id factor1 factor2 age      date1     y number_1_0 number_1_1 number_1_2 number_1_3 number_2_0 number_2_1
1:  1      f1      f2   2 2014-07-01 554.5          3          2          1          0         45         44
2:  1      f1      f2   9 2015-02-01 616.0         11          0          0         10         53          0
   number_2_2 number_2_3
1:         43          0
2:          0         52

pivot_wider() also has a parameter to fill in missing values. So, there is no need for a separate call to replace(is.na(.), 0):

library(tidyr)
haves %>%
  pivot_wider(names_from = x, values_from = starts_with("number_"), values_fill = 0)

# A tibble: 2 x 14
     id factor1 factor2   age date1          y number_1_2 number_1_1 number_1_0 number_1_3 number_2_2 number_2_1
  <dbl> <chr>   <chr>   <dbl> <date>     <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
1     1 f1      f2          2 2014-07-01  554.          1          2          3          0         43         44
2     1 f1      f2          9 2015-02-01  616           0          0         11         10          0          0
# ... with 2 more variables: number_2_0 <dbl>, number_2_3 <dbl>

Note that the column order after reshaping is different. While dcast() orders columns by value of x, i.e. 0, 1, 2, 3, pivot_wider() orders columns by appearance, i.e., 2, 1, 0, 3.


问:
How to add header to a bokeh dashboard in python?
I created a dashboard in bokeh, but how I can I ad a universal header to it?

I did a lot of research before, but it seems like nobody asked this simple question before.

Thanks for helping me :)

答: Just wrap your dashboard in a column where the first item is a Div with the header text.


问:
Flutter images not loaded (EXCEPTION: resolving an image codec)
When I try to run images assets doesn't get properly loaded, I am getting an exception:

The following assertion was thrown resolving an image codec: Unable to load asset: /images/p8.png`

Some weeks ago it was working and now it stopped. I tried to run from different pc and mac too (with simulator) anв still no images can be loaded. Fonts instead are properly loaded.

This is how I load the images, they are rendered inside a GridView
Below is the code:

```<code>return new Expanded(
      child: new GridView.count(
          crossAxisCount: 2,
          padding: const EdgeInsets.fromLTRB(16.0, 25.0, 16.0, 4.0),
          children: <Widget>[
            new MaterialButton(
              onPressed: () {
                Navigator.of(context).pushNamed('/biliardo');
              },
              child: new Column(
                children: <Widget>[
                  new Image(
                    //parte importante, definire gli asset per trovarli più velocemnte
                    //si inseriscono nel pubspec.yaml
                    image: new AssetImage('/images/p8.png'),
                    height: 100.0,
                    width: 100.0,
                  ),
                  new Text(
                    "BILIARDO",
                    style: new TextStyle(
                      color: (darkTheme) ? Colors.blue : Colors.black,
                    ),
                  )
                ],
              ),
            ),

            .....

    );
</code>```

pubsec.yaml file code:

```<code>flutter:
  uses-material-design: true
  assets:
    - images/emptyBall.png
    - images/p1.png
    - images/p2.png
    - images/p3.png
    - images/p4.png
    - images/p5.png
    - images/p6.png
    - images/p7.png
    - images/p8.png
    - images/p9.png
    - images/p10.png
    - images/p11.png
    - images/p12.png
    - images/p13.png
    - images/p14.png
    - images/p15.png
    - images/basket.png
    - images/volley.png
    - images/tennis.png
    - images/rugby.png
    - images/numbers.png
  fonts:
    - family: ShotClock
      fonts:
        - asset: utils/ShotClock.ttf
</code>```

Logs

flutter analyze

```<code>Analyzing D:\Android\AndroidStudioProjects\flutter_app...
No issues found!
Ran in 5.2s
</code>```

flutter -v run

```<code>https://docs.google.com/document/d/133Z7029VGJXBDCYLgCrj09F9cLbvIQQ5X8yBS4pPC7I/edit?usp=sharing
</code>```

Flutter Doctor

flutter doctor -v

```<code>[√] Flutter (Channel beta, v0.3.1, on Microsoft Windows [Versione 10.0.16299.371], locale it-IT)
    • Flutter version 0.3.1 at C:\Program Files\Flutter\flutter
    • Framework revision 12bbaba9ae (12 days ago), 2018-04-19 23:36:15 -0700
    • Engine revision 09d05a3891
    • Dart version 2.0.0-dev.48.0.flutter-fe606f890b

[√] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at C:\Users\Zanini\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
    • All Android licenses accepted.

[√] Android Studio (version 3.1)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 24.0.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)

[√] Connected devices (1 available)
    • Nexus 5X • 01cde5e7db8d4c14 • android-arm64 • Android 8.1.0 (API 27)

• No issues found!
</code>```

答: Besides the directory path make sure your image is valid, I have a png file which was not supported that was causing this error.. just make sure by opening the image in any image viewer to confirm the file is supported...</p>

Body:
When I try to run images assets doesn't get properly loaded, I am getting an exception:

The following assertion was thrown resolving an image codec: Unable to load asset: /images/p8.png`

Some weeks ago it was working and now it stopped. I tried to run from different pc and mac too (with simulator) anв still no images can be loaded. Fonts instead are properly loaded.

This is how I load the images, they are rendered inside a GridView
Below is the code:

return new Expanded(
      child: new GridView.count(
          crossAxisCount: 2,
          padding: const EdgeInsets.fromLTRB(16.0, 25.0, 16.0, 4.0),
          children: <Widget>[
            new MaterialButton(
              onPressed: () {
                Navigator.of(context).pushNamed('/biliardo');
              },
              child: new Column(
                children: <Widget>[
                  new Image(
                    //parte importante, definire gli asset per trovarli più velocemnte
                    //si inseriscono nel pubspec.yaml
                    image: new AssetImage('/images/p8.png'),
                    height: 100.0,
                    width: 100.0,
                  ),
                  new Text(
                    "BILIARDO",
                    style: new TextStyle(
                      color: (darkTheme) ? Colors.blue : Colors.black,
                    ),
                  )
                ],
              ),
            ),

            .....

    );

pubsec.yaml file code:

flutter:
  uses-material-design: true
  assets:
    - images/emptyBall.png
    - images/p1.png
    - images/p2.png
    - images/p3.png
    - images/p4.png
    - images/p5.png
    - images/p6.png
    - images/p7.png
    - images/p8.png
    - images/p9.png
    - images/p10.png
    - images/p11.png
    - images/p12.png
    - images/p13.png
    - images/p14.png
    - images/p15.png
    - images/basket.png
    - images/volley.png
    - images/tennis.png
    - images/rugby.png
    - images/numbers.png
  fonts:
    - family: ShotClock
      fonts:
        - asset: utils/ShotClock.ttf

Logs

flutter analyze

Analyzing D:\Android\AndroidStudioProjects\flutter_app...
No issues found!
Ran in 5.2s

flutter -v run

https://docs.google.com/document/d/133Z7029VGJXBDCYLgCrj09F9cLbvIQQ5X8yBS4pPC7I/edit?usp=sharing

Flutter Doctor

flutter doctor -v

[√] Flutter (Channel beta, v0.3.1, on Microsoft Windows [Versione 10.0.16299.371], locale it-IT)
    • Flutter version 0.3.1 at C:\Program Files\Flutter\flutter
    • Framework revision 12bbaba9ae (12 days ago), 2018-04-19 23:36:15 -0700
    • Engine revision 09d05a3891
    • Dart version 2.0.0-dev.48.0.flutter-fe606f890b

[√] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at C:\Users\Zanini\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
    • All Android licenses accepted.

[√] Android Studio (version 3.1)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 24.0.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)

[√] Connected devices (1 available)
    • Nexus 5X • 01cde5e7db8d4c14 • android-arm64 • Android 8.1.0 (API 27)

• No issues found!


问:
Uncaught TypeError: messagesRef.push is not a function
```<code>var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
 var email = getInputVal('email');
 var packageFields = getInputVal('packageFields');
 var name = getInputVal('name');
 var phone = getInputVal('phone');
 var date = getInputVal('date');

 //save messages
 saveMessage(email, packageFields, name, phone, date);

}

// function to get form values

function getInputVal(id) {
 return document.getElementById(id).value;
}

//save messages

function saveMessage(email, packageFields, name, phone, date) {
 var newMessagesRef = messagesRef.push();
 newMessagesRef.set({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
 });
}
</code>```

But It Gives The Error :

Uncaught TypeError: messagesRef.push is not a function at saveMessage (bookingSubmit.js:48) at HTMLDivElement.submitForm (bookingSubmit.js:35) saveMessage @ bookingSubmit.js:48 submitForm @ bookingSubmit.js:35

Why is this happening and how can i solve it?

Please Check For Any Other Kind Of Errors.

And Make Sure That The Code Should Work As Expected. Its Constantly giving errors and now I am Fed up with it.

答:
You are trying to add new document in the collection called BookingData.But while adding the data you are using a method push() associated with firebase Realtime Database.But the variable messageRef related with firebase firestore and there is no method called push() with firestore variable.

```<code>var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {

  messageRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

  }
</code>```

Body:
var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
 var email = getInputVal('email');
 var packageFields = getInputVal('packageFields');
 var name = getInputVal('name');
 var phone = getInputVal('phone');
 var date = getInputVal('date');

 //save messages
 saveMessage(email, packageFields, name, phone, date);

}

// function to get form values

function getInputVal(id) {
 return document.getElementById(id).value;
}

//save messages

function saveMessage(email, packageFields, name, phone, date) {
 var newMessagesRef = messagesRef.push();
 newMessagesRef.set({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
 });
}

But It Gives The Error :

Uncaught TypeError: messagesRef.push is not a function at saveMessage (bookingSubmit.js:48) at HTMLDivElement.submitForm (bookingSubmit.js:35) saveMessage @ bookingSubmit.js:48 submitForm @ bookingSubmit.js:35

Why is this happening and how can i solve it?

Please Check For Any Other Kind Of Errors.

And Make Sure That The Code Should Work As Expected. Its Constantly giving errors and now I am Fed up with it.

Body:
You are trying to add new document in the collection called BookingData.But while adding the data you are using a method push() associated with firebase Realtime Database.But the variable messageRef related with firebase firestore and there is no method called push() with firestore variable.

var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");

//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {

  messageRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

  }


问:
Next item in foreach SMARTY
I do slider on the website. On one slide I have two div. The data displayed on the SMARTY.

Slider div's

```<code>{foreach $slider as $sliderr}
    <div id="sliderBox">
<div id="showcase" class="showcase">
        <div class="showcase-slide">
            <div class="showcase-content">
{$sliderr.img}
            </div>
        </div>
        <div class="showcase-slide">
            <div class="showcase-content">
                {$sliderr.img} // ?? I need img+1
            </div>
        </div>
</div>
</div>
{/foreach}
</code>```

I need the next record from the table slider. How to read the next record SMARTY in a loop?

答:
I am using this. It can operate with infinite slider loop.

```<code>{foreach from = $slider key = f item = product}
</code>```

Name of next slide:

```<code>{if isset($slider[$f+1])}{$slider[$f+1].name}{else}{$slider[0].name}{/if}
</code>```

Name of previous slide:

```<code>{if isset($slider[$f-1])}{$slider[$f-1].name}{else}{$slider[($slider|count)-1].name}{/if}

{/foreach}
</code>```

Title: Next item in foreach SMARTY

Body:
I do slider on the website. On one slide I have two div. The data displayed on the SMARTY.

Slider div's

{foreach $slider as $sliderr}

{$sliderr.img}

                {$sliderr.img} // ?? I need img+1

{/foreach}

I need the next record from the table slider. How to read the next record SMARTY in a loop?

Body:
I am using this. It can operate with infinite slider loop.

{foreach from = $slider key = f item = product}

Name of next slide:

{if isset($slider[$f+1])}{$slider[$f+1].name}{else}{$slider[0].name}{/if}

Name of previous slide:

{if isset($slider[$f-1])}{$slider[$f-1].name}{else}{$slider[($slider|count)-1].name}{/if}

{/foreach}


问:
Pandas: How to find indexes of values between a range
I have a pandas dataframe with a series of numbers in the column 'Num'.

```<code>import pandas as pd

numbers = np.array([10,15,60,45,37,28])
df = pd.DataFrame(numbers, columns= ['Num'])
</code>```

I would find all the combinations of the indexes of values that satisfy the condition:

```<code>numbers1+numbers2+... >= 70% of df['Num'].sum()
</code>```

df['Num'].sum() = 195, so 136.5 is the 70%. Some combninations of values could be:

```<code>10+15+60
15+60
60+45+37
10+15+60+45+37+28
</code>```

and so on. I would take the indexes combinations and, at the end, get the combination(/s) that's over 70% with the lowest number of indexes.

Body:
I have a pandas dataframe with a series of numbers in the column 'Num'.

import pandas as pd

numbers = np.array([10,15,60,45,37,28])
df = pd.DataFrame(numbers, columns= ['Num'])

I would find all the combinations of the indexes of values that satisfy the condition:

numbers1+numbers2+... >= 70% of df['Num'].sum()

df['Num'].sum() = 195, so 136.5 is the 70%. Some combninations of values could be:

10+15+60
15+60
60+45+37
10+15+60+45+37+28

and so on. I would take the indexes combinations and, at the end, get the combination(/s) that's over 70% with the lowest number of indexes.

Body:
You can use itertools here:

import pandas as pd
import itertools
import numpy as np

numbers = np.array([10,15,60,45,37,28])
df = pd.DataFrame(numbers, columns= ['Num'])
total = int(df.sum())
list_n = list(df['Num'])
for L in range(0, len(list_n)+1):
    for subset in itertools.combinations(list_n, L):
        if sum(subset) > 0.7 * total:
            print(subset)

(60, 45, 37)
(10, 60, 45, 37)
(10, 60, 45, 28)
(15, 60, 45, 37)
(15, 60, 45, 28)
(15, 60, 37, 28)
(60, 45, 37, 28)
(10, 15, 60, 45, 37)
(10, 15, 60, 45, 28)
(10, 15, 60, 37, 28)
(10, 60, 45, 37, 28)
(15, 60, 45, 37, 28)
(10, 15, 60, 45, 37, 28)

Of course you could skip pandas altogether:

import itertools
import numpy as np

numbers = np.array([10,15,60,45,37,28])
total = sum(numbers)
for L in range(0, len(numbers)+1):
    for subset in itertools.combinations(numbers, L):
        if sum(subset) > 0.7 * total:
            print(subset)

(60, 45, 37)
(10, 60, 45, 37)
(10, 60, 45, 28)
(15, 60, 45, 37)
(15, 60, 45, 28)
(15, 60, 37, 28)
(60, 45, 37, 28)
(10, 15, 60, 45, 37)
(10, 15, 60, 45, 28)
(10, 15, 60, 37, 28)
(10, 60, 45, 37, 28)
(15, 60, 45, 37, 28)
(10, 15, 60, 45, 37, 28)


问:
Kotlin Retrofit Query Annotation parameters
So I have have this an interface for the NetworkConfig.kt class:

```<code>interface getProductList {
    @GET("stock")
    fun getProducts(@Query("outcode") stkOutcode: String): Call<OutletListPOJODataClasses>
}
</code>```

and this is a code snippet from the Activity I use to fetch url:

```<code>NetworkConfig().getProductListService()
        .getProducts() //What should i pass here ?
        .enqueue(object : Callback<ProductListPOJODataClasses> {

            override fun onFailure(call: Call<ProductListPOJODataClasses>, t: Throwable) {
                Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
            }

            override fun onResponse(
                call: Call<ProductListPOJODataClasses>,
                response: Response<ProductListPOJODataClasses>
            ) {
                binding.rvProductList.adapter = response.body()?.let { ProductListAdapter(it, this@ProductListFragment) }

                Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()
            }
        })
</code>```

And this is the data class I use:

```<code>data class ProductListPOJODataClassesDataItem(

    @field:SerializedName("stk_prodcode")
    val stkProdcode: String? = null,

    @field:SerializedName("stk_allqty")
    val stkAllqty: Int? = null,

    @field:SerializedName("pro_saleprice")
    val proSaleprice: Int? = null,

    @field:SerializedName("skt_lastupdate")
    val sktLastupdate: String? = null,

    @field:SerializedName("stk_outcode")
    val stkOutcode: String? = null,

    @field:SerializedName("pro_name")
    val proName: String? = null
)
</code>```

I'm quite new in using this library. What I want to know is what should I pass in the .getProducts() function above? If there's anything unclear, let me know.

答:
It should be

```<code>NetworkConfig().getProductListService()
    .getProducts(stkOutcode = stkOutcodeValue)
    ....
</code>```

where stkOutcodeValue (String type) should be known or a default value might be used, if applicable.

Thanks to @sonnet, the endpoint in this case is https://example.com/api/stock?outcode=stkOutcodeValue

Body:
So I have have this an interface for the NetworkConfig.kt class:

interface getProductList {
    @GET("stock")
    fun getProducts(@Query("outcode") stkOutcode: String): Call<OutletListPOJODataClasses>
}

and this is a code snippet from the Activity I use to fetch url:

NetworkConfig().getProductListService()
        .getProducts() //What should i pass here ?
        .enqueue(object : Callback<ProductListPOJODataClasses> {

            override fun onFailure(call: Call<ProductListPOJODataClasses>, t: Throwable) {
                Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
            }

            override fun onResponse(
                call: Call<ProductListPOJODataClasses>,
                response: Response<ProductListPOJODataClasses>
            ) {
                binding.rvProductList.adapter = response.body()?.let { ProductListAdapter(it, this@ProductListFragment) }

                Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()
            }
        })

And this is the data class I use:

data class ProductListPOJODataClassesDataItem(

    @field:SerializedName("stk_prodcode")
    val stkProdcode: String? = null,

    @field:SerializedName("stk_allqty")
    val stkAllqty: Int? = null,

    @field:SerializedName("pro_saleprice")
    val proSaleprice: Int? = null,

    @field:SerializedName("skt_lastupdate")
    val sktLastupdate: String? = null,

    @field:SerializedName("stk_outcode")
    val stkOutcode: String? = null,

    @field:SerializedName("pro_name")
    val proName: String? = null
)

I'm quite new in using this library. What I want to know is what should I pass in the .getProducts() function above? If there's anything unclear, let me know.

Body:
It should be

NetworkConfig().getProductListService()
    .getProducts(stkOutcode = stkOutcodeValue)
    ....

where stkOutcodeValue (String type) should be known or a default value might be used, if applicable.

Thanks to @sonnet, the endpoint in this case is https://example.com/api/stock?outcode=stkOutcodeValue


问:
Access ECAM on QEMU AArch64 virt device
I am trying to implement bare metal PCIE device discovery on QEMU AArch64 virt device. I know, that ECAM area is mapped to 0x3f000000 memory address, and I expect to see there this table.

But when I perform a reading of 4 bytes (MCFG signature) from 0x3f000000 address, I get a synchronous exception.

What am I doing wrong? Is there something I have to perform before accessing PCIE memory mapped area?

```<code>QEMU_CMD = qemu-system-aarch64 \
    -machine virt \
    -m 1024M \
    -cpu cortex-a53 \
    -serial stdio \
    -device virtio-gpu-pci \
    -vnc :0 \
    -netdev user,id=n1 -device virtio-net-pci,netdev=n1
</code>```

答:
You're looking at the wrong address. The virt board only puts the ECAM at the 0x3f00_0000 address if it is not using the physical address space above-4GB (which is not the default; QEMU only avoids highmem usage if the user passed -machine highmem=off).

You can check this by asking QEMU to dump the dtb instead of running the guest, by adding "-machine dumpdtb=/tmp/dump.dtb" to your commandline, then disassembling the dtb with "dtc -I dtb -O dts /tmp/dump.dtb | less", and looking at the dtb for the pci controller.

More generally, a guest running in the QEMU "virt" board should not hardcode any addresses of devices, but should always read the dtb that QEMU generates and passes to the guest to determine where in the address space devices are placed. If your code did this it wouldn't have run into this error.

Title: Access ECAM on QEMU AArch64 virt device

Body:
I am trying to implement bare metal PCIE device discovery on QEMU AArch64 virt device. I know, that ECAM area is mapped to 0x3f000000 memory address, and I expect to see there this table.

But when I perform a reading of 4 bytes (MCFG signature) from 0x3f000000 address, I get a synchronous exception.

What am I doing wrong? Is there something I have to perform before accessing PCIE memory mapped area?

QEMU_CMD = qemu-system-aarch64 \
    -machine virt \
    -m 1024M \
    -cpu cortex-a53 \
    -serial stdio \
    -device virtio-gpu-pci \
    -vnc :0 \
    -netdev user,id=n1 -device virtio-net-pci,netdev=n1


问:
Can I make a CSS grid with dynamic number of rows or columns?
What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let's assume there will always be four cells per row. Can I specify a grid with such a dynamic number of rows?

To make it easier, here's the Flexbox implementation:

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
.container .item {
  flex: 0 0 calc(25% - 1em);
  min-height: 120px;
  margin: 0.25em 0.5em;
}</code>```

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>```

P.S. Apparently, I wasn't clear enough the first time... I want to recreate this effect using the latest CSS Grid Layout.

答:
Simply use below code to generate grid columns automatically</p>

```<code>.container {
  display: grid;
  grid-auto-flow: column;
}
</code>```

Body:
What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let's assume there will always be four cells per row. Can I specify a grid with such a dynamic number of rows?

To make it easier, here's the Flexbox implementation:

const COLORS = [
  '#FE9',
  '#9AF',
  '#F9A',
  "#AFA",
  "#FA7"
];

function addItem(container, template) {
  let color = COLORS[_.random(COLORS.length - 1)];
  let num = _.random(10000);

  container.append(Mustache.render(template, { color, num }));
}

$(() => {
  const tmpl = $('#item_template').html()
  const container = $('#app');

  for(let i=0; i<5; i++) { addItem(container, tmpl); }

  $('#add_el').click(() => {
    addItem(container, tmpl);
  })

  container.on('click', '.del_el', (e) => {
    $(e.target).closest('.item').remove();
  });
});

.container {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
.container .item {
  flex: 0 0 calc(25% - 1em);
  min-height: 120px;
  margin: 0.25em 0.5em;
}

<button id="add_el">Add element</button>

<template id="item_template">

{{ num }}

      <button class="del_el">Delete</button>

</template>

P.S. Apparently, I wasn't clear enough the first time... I want to recreate this effect using the latest CSS Grid Layout.

Body:
Simply use below code to generate grid columns automatically

.container {
  display: grid;
  grid-auto-flow: column;
}


问:
Oh-my-zsh theme not rendering properly in IntelliJ
Cobalt2 theme does not render properly in the terminal in IntelliJ but works fine in the Mac terminal. How do I correct this?

答:
Thought I'd add for anyone Googling this "zsh themes being broken in IntelliJ" ...especially Powerlevel10k ... you can conditionally switch the theme to a compatible one for your IntelliJ console, and keep the nice one for your main terminal. In .zshrc :

```<code>if [[ $__INTELLIJ_COMMAND_HISTFILE__ ]]; then
  ZSH_THEME="robbyrussell"
else
  ZSH_THEME="powerlevel10k/powerlevel10k"
fi
</code>```

Hope that helps someone :-)

Body:
Thought I'd add for anyone Googling this "zsh themes being broken in IntelliJ" ...especially Powerlevel10k ... you can conditionally switch the theme to a compatible one for your IntelliJ console, and keep the nice one for your main terminal. In .zshrc :

if [[ $__INTELLIJ_COMMAND_HISTFILE__ ]]; then
  ZSH_THEME="robbyrussell"
else
  ZSH_THEME="powerlevel10k/powerlevel10k"
fi

Hope that helps someone :-)


问:
sql ex ru excercise data mismatch question 63
there are two tables

```<code>Passenger(ID_psg, name)
Pass_in_trip(trip_no, date, ID_psg, place)
</code>```

on which you should find the names of passangers who has travelled more than once on the exact same seat
more precisely the question is like this:

```<code>Find the names of different passengers that ever travelled more than once occupying seats with the same number
</code>```

both tabels are linked to eachother thropugh the id_psg
the column which contains the seat is place from pass_in_trip which contains
which passenger name was seated there via id_psg

my current code is :

```<code>with a(name, heret) as (
select pr.name , count(p.place) as heret from passenger pr
join pass_in_trip p on
pr.id_psg = p.id_psg
group by pr.name , p.place
)

select distinct name from a
where heret > 1
</code>```

on which i grouped the passengers names with their place(seat) ,
i got the correct result in the first database but it had data mismatch on the second one ,
can anyone help me to understand what is wrong in this situation?

答: Name isn't an integer, it is likely a string of some type. You will need to use a COUNT() with a group by quite likely. </p>

Body:
there are two tables

Passenger(ID_psg, name)
Pass_in_trip(trip_no, date, ID_psg, place)

on which you should find the names of passangers who has travelled more than once on the exact same seat
more precisely the question is like this:

Find the names of different passengers that ever travelled more than once occupying seats with the same number

both tabels are linked to eachother thropugh the id_psg
the column which contains the seat is place from pass_in_trip which contains
which passenger name was seated there via id_psg

my current code is :

with a(name, heret) as (
select pr.name , count(p.place) as heret from passenger pr
join pass_in_trip p on
pr.id_psg = p.id_psg
group by pr.name , p.place
)

select distinct name from a
where heret > 1

on which i grouped the passengers names with their place(seat) ,
i got the correct result in the first database but it had data mismatch on the second one ,
can anyone help me to understand what is wrong in this situation?


问:
How to perform function after Jquery (window).load is complete
I'm trying fade in a div after an iframe has loaded. The iframe is being called after the window has loaded.

I can load the iframe fine but I can't figure out how to make the div fadeIn after the load has completed. Thanks ahead for your assistance.

This is what I've tried but the load function following the html isn't happening

```<code>$(function() {
    $(window).load( function() {
        $("#ad").html("<iframe ... </iframe>").load(function(){
            $("#ad").fadeIn("normal");
        });
    });
});
</code>```

答:
You can get a handle on the iframe's window object and then check document.readyState to see if the load event has already fired. If it has, it will equal "complete".

Something like this:

```<code>$('<iframe>').attr('src', '/pow.html').appendTo(document.body);
var win = window[window.length - 1];

var fn = function () { console.log('loaded!') };
$(win).load(fn);
if (win.document.readyState === "complete") fn();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying fade in a div after an iframe has loaded. The iframe is being called after the window has loaded.

I can load the iframe fine but I can't figure out how to make the div fadeIn after the load has completed. Thanks ahead for your assistance.

This is what I've tried but the load function following the html isn't happening

$(function() {
    $(window).load( function() {
        $("#ad").html("<iframe ... ").load(function(){
            $("#ad").fadeIn("normal");
        });
    });
});

Body:
You can get a handle on the iframe's window object and then check document.readyState to see if the load event has already fired. If it has, it will equal "complete".

Something like this:

$('<iframe>').attr('src', '/pow.html').appendTo(document.body);
var win = window[window.length - 1];

var fn = function () { console.log('loaded!') };
$(win).load(fn);
if (win.document.readyState === "complete") fn();


问:
What is the difference between Pages and Shared and can we use different folders?
I am browsing and still learning about Blazor, but one thing I am unable to understand - why are there prepared folders for "Pages" and "Shared", and what's the difference between the two?

What is the difference between Pages and Shared?

Where do we stored our custom controls?

答:
Pages and components are essentially the same thing, except a page has one or more @page directives identifying which URL can be used to render them.

A @page directive will be turned into a [Microsoft.AspNetCore.Components.RouteAttribute("/XXX")] attribute on the component class that is generated from your razor file.

Blazor will reflect over your whole assembly for types that are decorated with [RouteAttribute]. This means pages can be wherever you want them to be.

The same is true for Components. The reason are able to put them in the Shared folder by default is because /_Imports.razor has a @using YouAppName.Shared in it. If you want to put your components in other namespaces you can either

Add the namespace to the _Imports.razor file

Add a @using WhateverNamespace to the top of your consuming page/component.

Include the namespace in the markup <WhateverNamespace.SomeComponent/>

https://blazor-university.com/routing/defining-routes/


问:
Styles for google places autocomplete not working
I'm working on Angular 9 and Ionic 5 and I'm using google places autocomplete for an address input. The autocomplete works fine and thanks to this I managed to edit the styles on my browser. Then I went to my stylesheet (scss) to put these styles into their respective classes (pac-container, pac-item, pac-icon, etc) and the styles just won't show up as I specified on the scss file. If I check the browser, none of my styles were in the pac classes.
My code goes as following:

profile.page.html

```<code><ion-item class="br-5 mt">
   <ion-icon name="home" slot="start" class="ion-align-self-center" color="primary"></ion-icon>
   <ion-input id="googlePlaces" placeholder="Dirección" formControlName="address" required type="text"></ion-input>
</ion-item>
</code>```

profile.page.scss

```<code>.pac-container{
    font-family: 'Open Sans';
}

.pac-item{
    margin-left:10px;
}

.pac-icon{
    display:none;
}
</code>```

profile.page.ts

```<code>declare var google: any;
export class ProfilePage implements OnInit {
constructor(){}
ionViewDidEnter() {
    this.activeGooglePlace();
  }
activeGooglePlace() {

    let input = document.getElementById('googlePlaces').getElementsByTagName('input')[0];
    let autocomplete = new google.maps.places.Autocomplete(input, { types: ['geocode'] });
    autocomplete.setComponentRestrictions({ 'country': ['cl'] });
    google.maps.event.addListener(autocomplete, 'place_changed', () => {
      let place = autocomplete.getPlace();
      this.profileForm.controls.latitude.setValue(place.geometry.location.lat());
      this.profileForm.controls.longitude.setValue(place.geometry.location.lng());
      this.profileForm.controls.address.setValue(place.formatted_address);
    });
  }
}
</code>```

I even tried checking the apk on my phone as I read some people couldn't make it work on localhost. But still, didn't work. Any ideas on how to solve this? Thanks in advance.

答: I was able to change it by adding all those classes in my theme variables.scss. Really ashamed I wasn't able to check that one out at first.</p>

Body:
I'm working on Angular 9 and Ionic 5 and I'm using google places autocomplete for an address input. The autocomplete works fine and thanks to this I managed to edit the styles on my browser. Then I went to my stylesheet (scss) to put these styles into their respective classes (pac-container, pac-item, pac-icon, etc) and the styles just won't show up as I specified on the scss file. If I check the browser, none of my styles were in the pac classes.
My code goes as following:

profile.page.html

<ion-item class="br-5 mt">
   <ion-icon name="home" slot="start" class="ion-align-self-center" color="primary"></ion-icon>
   <ion-input id="googlePlaces" placeholder="Dirección" formControlName="address" required type="text"></ion-input>
</ion-item>

profile.page.scss

.pac-container{
    font-family: 'Open Sans';
}

.pac-item{
    margin-left:10px;
}

.pac-icon{
    display:none;
}

profile.page.ts

declare var google: any;
export class ProfilePage implements OnInit {
constructor(){}
ionViewDidEnter() {
    this.activeGooglePlace();
  }
activeGooglePlace() {

    let input = document.getElementById('googlePlaces').getElementsByTagName('input')[0];
    let autocomplete = new google.maps.places.Autocomplete(input, { types: ['geocode'] });
    autocomplete.setComponentRestrictions({ 'country': ['cl'] });
    google.maps.event.addListener(autocomplete, 'place_changed', () => {
      let place = autocomplete.getPlace();
      this.profileForm.controls.latitude.setValue(place.geometry.location.lat());
      this.profileForm.controls.longitude.setValue(place.geometry.location.lng());
      this.profileForm.controls.address.setValue(place.formatted_address);
    });
  }
}

I even tried checking the apk on my phone as I read some people couldn't make it work on localhost. But still, didn't work. Any ideas on how to solve this? Thanks in advance.


问:
Problem passing function pointer to a class c++
I'm trying to implement a numerical ODE solver in c++ but I'm having troubles with function pointers (I'm still trying to understand how they works inside classes).
I have a parent class (ODEint) and subclasses in which I will implement different possible algorithms to solve an equation. I pass a function pointer to the parent class (the function represents the equation which is independent of the solver) but I need that function in the child class (different solvers threat that equation in different ways).

When I call the function via pointer in the child class I get the error

odeint.cpp:38:13: error: ‘((Euler*)this)->Euler::.ODEint::field’ cannot be used
    as a member pointer, since it is of type ‘pfunc {aka std::vector ()(double)}’
    (this->*field)(y);

Here are classes definitions

```<code>typedef vector<double> (*pfunc)(double*);

class ODEint {
protected:
    double h;
    int neq;
    double* init_cond;
    int nsteps;
    string method;
    vector<vector<double>> y;
    pfunc field;
public:
    ODEint(int neq, int nsteps, pfunc);
    void setInitCond(double* init_cond);
    void solveEq();
    virtual vector<double> advance(double h, double *y);
};

class Euler: public ODEint {
public:
    Euler(int neq, int nsteps, pfunc, double h);
    vector<double> advance(double h, double *y);
};
</code>```

And here is part of the classes implementation

```<code>ODEint::ODEint(int neq, int nsteps, pfunc field){
this->neq = neq;
this->nsteps = nsteps;
this->y.resize(nsteps);
this->field = field;
for (int i = 0; i < nsteps; i++){
    this->y[i].resize(neq);
}
}

Euler::Euler(int neq, int nsteps, pfunc field, double h) : ODEint(neq, nsteps, field){
this->h = h;
}

void ODEint::solveEq(){
int n;
cout << "Strarting solver..." << endl;
vector<double> x;
for (n = 0; n < this->nsteps; n++){
    x = y[n];
    y[n+1] = this->advance(this->h, &x[0]);
}
cout << "Solution termined. Nsteps: " << n << endl;
}

vector<double> Euler::advance(double h, double *y){
vector<double> ynext; ynext.resize(this->neq);
vector<double> f; f.resize(this->neq);
(this->*field)(y); <----------------------------------------------  here is the problem
for (int i = 0; i < this->neq; i++){
    ynext[i] = y[i] + h*f[i];
}
}
</code>```

Finally here is the main

```<code>vector<double> field(double *y){
vector<double> vf;
vf[0] = -y[0];
vf[1] = -y[1];
return vf;
}

int main(){

double init_cond[2] = {1.0, 2.0};
const int neq = 1;

Euler prova(neq, (int)1e4, field, 1e-4);
prova.setInitCond(&init_cond[0]);
prova.solveEq();
return 0;
}
</code>```

I know there may be other problems but I'm still learning c++ and actually the priority is to understand the reason of this error.
Thank you in advance and sorry if the code is a bit confused but as I said previously I'm a kind of beginner.

答:
Your example is a bit large, I didn't use it as-is. But I can spot a fix, with a smaller repro: (I kept your style)

```<code>#include <vector>
typedef std::vector<double> (*pfunc)(double*);

class Foo
{
public:
pfunc field;
};

std::vector<double> Bar(double*)
{
    return std::vector<double>{};
}

int main()
{
    Foo f;
    double x;

    f.field = &Bar;
    (&f)->field(&x);
}
</code>```

The only meaningful change I needed is to remove the * in front of the call to field().

Now, I will advise not using this pattern at all. The OOP way, IMO would be way cleaner here:

```<code>class BaseODE
{
    public:
        virtual std::vector<double> field(double*) = 0;

    // put the rest of the code here.
    // when field is called, the Euler version will be called.
};

class Euler:public BaseODE
{
    public:
        virtual std::vector<double> field(double*) override;
};
</code>```

Basically, you have no need yet for function pointers, lambdas, std::function or anything complex.

Body:
I'm trying to implement a numerical ODE solver in c++ but I'm having troubles with function pointers (I'm still trying to understand how they works inside classes).
I have a parent class (ODEint) and subclasses in which I will implement different possible algorithms to solve an equation. I pass a function pointer to the parent class (the function represents the equation which is independent of the solver) but I need that function in the child class (different solvers threat that equation in different ways).

When I call the function via pointer in the child class I get the error

odeint.cpp:38:13: error: ‘((Euler*)this)->Euler::.ODEint::field’ cannot be used
    as a member pointer, since it is of type ‘pfunc {aka std::vector ()(double)}’
    (this->*field)(y);

Here are classes definitions

typedef vector<double> (*pfunc)(double*);

class ODEint {
protected:
    double h;
    int neq;
    double* init_cond;
    int nsteps;
    string method;
    vector<vector<double>> y;
    pfunc field;
public:
    ODEint(int neq, int nsteps, pfunc);
    void setInitCond(double* init_cond);
    void solveEq();
    virtual vector<double> advance(double h, double *y);
};

class Euler: public ODEint {
public:
    Euler(int neq, int nsteps, pfunc, double h);
    vector<double> advance(double h, double *y);
};

And here is part of the classes implementation

ODEint::ODEint(int neq, int nsteps, pfunc field){
this->neq = neq;
this->nsteps = nsteps;
this->y.resize(nsteps);
this->field = field;
for (int i = 0; i < nsteps; i++){
    this->y[i].resize(neq);
}
}

Euler::Euler(int neq, int nsteps, pfunc field, double h) : ODEint(neq, nsteps, field){
this->h = h;
}

void ODEint::solveEq(){
int n;
cout << "Strarting solver..." << endl;
vector<double> x;
for (n = 0; n < this->nsteps; n++){
    x = y[n];
    y[n+1] = this->advance(this->h, &x[0]);
}
cout << "Solution termined. Nsteps: " << n << endl;
}

vector<double> Euler::advance(double h, double *y){
vector<double> ynext; ynext.resize(this->neq);
vector<double> f; f.resize(this->neq);
(this->*field)(y); <----------------------------------------------  here is the problem
for (int i = 0; i < this->neq; i++){
    ynext[i] = y[i] + h*f[i];
}
}

Finally here is the main

vector<double> field(double *y){
vector<double> vf;
vf[0] = -y[0];
vf[1] = -y[1];
return vf;
}

int main(){

double init_cond[2] = {1.0, 2.0};
const int neq = 1;

Euler prova(neq, (int)1e4, field, 1e-4);
prova.setInitCond(&init_cond[0]);
prova.solveEq();
return 0;
}

I know there may be other problems but I'm still learning c++ and actually the priority is to understand the reason of this error.
Thank you in advance and sorry if the code is a bit confused but as I said previously I'm a kind of beginner.

Body:
Your example is a bit large, I didn't use it as-is. But I can spot a fix, with a smaller repro: (I kept your style)

#include <vector>
typedef std::vector<double> (*pfunc)(double*);

class Foo
{
public:
pfunc field;
};

std::vector<double> Bar(double*)
{
    return std::vector<double>{};
}

int main()
{
    Foo f;
    double x;

    f.field = &Bar;
    (&f)->field(&x);
}

The only meaningful change I needed is to remove the * in front of the call to field().

Now, I will advise not using this pattern at all. The OOP way, IMO would be way cleaner here:

class BaseODE
{
    public:
        virtual std::vector<double> field(double*) = 0;

    // put the rest of the code here.
    // when field is called, the Euler version will be called.
};

class Euler:public BaseODE
{
    public:
        virtual std::vector<double> field(double*) override;
};

Basically, you have no need yet for function pointers, lambdas, std::function or anything complex.


问:
Problem C++ Reverse Polish Notation calculator
I have a problem with RPN.
I want the program to finish entering characters after pressing ENTER but something doesn't work because it doesn't write to vec.
I tried to solve the task:
The value of the expression recorded in Reverse Polish Notation should be determined. The expression will contain the following operators: +, -, * and / (integer division) and natural numbers not greater than one million. The result is in the type int.

Entrance
In the first and only line the phrase written in Reverse Polish Notation. Operators are separated from numbers by a space character. Expression length is less than 1000 characters.

Exit
The end value of the ONP expression.

```<code>#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int RPN(vector<string> &notation) {
  stack<int> s;
  for (string str : notation) {
    if (str == "+" or str == "-" or str == "/" or str == "*") {
      int a = s.top();
      s.pop();
      int b = s.top();
      s.pop();

      if (str == "-") {
        s.push(b - a);
        continue;
      }
      if (str == "+") {
        s.push(b + a);
        continue;
      }
      if (str == "/") {
        s.push(b / a);
        continue;
      }
      if (str == "*") {
        s.push(b * a);
        continue;
      }
    } else
      s.push(stoi(str));
  }
  return s.top();
}

int main() {
  vector<string> notation;

  while (true) {
    string sign;
    cin >> sign;
    if (cin.get() != 'n') {
      break;
    } else {
      notation.push_back(sign);
    }
  }
  for (auto i : notation)  // test, print vec
  {
    cout << i << endl;
    ;
  }
  cout << RPN(notation) << endl;
return 0;
}
</code>```

答:
Your code doesn't maintain precedence. It treats addition the same way it treats multiplication. If that's what you want, you can just perform each operation from left to right.

I suppose the goal of your program is to have some precedence and to perform for example multiplication before addition.

Here is a simple code that maintains precedence. The code assumes that the input is always correct and do not handle parentheses for simplicity.

```<code>#include <iostream>
#include <vector>
#include <stack>

int getPrecedence(std::string &o)
{
    if (o == "+" || o == "-")
        return 1;

    return 2;
}

int calculate(int a, int b, const std::string &operation)
{
    if (operation == "+")
        return a + b;
    if (operation == "-")
        return a - b;
    if (operation == "*")
        return a * b;
    if (operation == "/")
        return a / b;
    return -1;
}

void performOperation(std::stack<int> &numbers, std::stack<std::string> &operators) {
    int n1 = numbers.top();
    numbers.pop();
    int n2 = numbers.top();
    numbers.pop();
    std::string op = operators.top();
    operators.pop();

    numbers.push(calculate(n2, n1, op));
}

int RPN(std::vector<std::string> &notation) {

    std::stack<int> numbers;
    std::stack<std::string> operators;

    if (notation.empty())
        return 0;

    numbers.push(stoi(notation[0]));

    for (int i = 1; i < notation.size(); i+=2)
    {
        while (!operators.empty() && getPrecedence(operators.top()) >= getPrecedence(notation[i]))
            performOperation(numbers, operators);

        numbers.push(std::stoi(notation[i+1]));
        operators.push(notation[i]);
    }

    while (!operators.empty())
        performOperation(numbers, operators);

    return numbers.top();
}

std::vector<std::string> parse(const std::string& input)
{
    std::vector<std::string> vec;

    std::string current;

    for (char c : input)
    {
        if (isdigit(c))
            current += c;
        else if (c)
        {
            if (!current.empty())
            {
                vec.emplace_back(std::move(current));
                current = "";
            }

            if (c != ' ')
                vec.emplace_back(1, c);
        }
    }

    if (!current.empty())
        vec.push_back(std::move(current));

    return vec;
}

int main() {

    // This program doesn't validate input.
    // It assumes that the input is always correct.

    std::string input;
    std::getline(std::cin, input);
    std::vector<std::string> notation = parse(input);
    std::cout << RPN(notation) << '\n';
}
</code>```

Input:

```<code>1 + 2 + 3 * 3 + 3 / 3 + 5 - 4
</code>```

Output:

```<code>14
</code>```

For simplicity, I take the number of strings that the program will read before taking the input.

Update:

The above code assumes that the input is an infix expression. If the input is already in the RPN, the code would be like this:

```<code>#include <iostream>
#include <vector>
#include <stack>

int calculate(int a, int b, const std::string &operation)
{
    if (operation == "+")
        return a + b;
    if (operation == "-")
        return a - b;
    if (operation == "*")
        return a * b;
    if (operation == "/")
        return a / b;
    return -1;
}

bool isOperation(const std::string& op)
{
    return op == "+" || op == "-" || op == "*" || op == "/";
}

int RPN(std::vector<std::string> &notation) {

    std::stack<int> numbers;
    for (const auto& str : notation)
    {
        if (isOperation(str))
        {
            int n2 = numbers.top(); numbers.pop();
            int n1 = numbers.top(); numbers.pop();

            numbers.push(calculate(n1, n2, str));
        }
        else
            numbers.push(std::stoi(str));
    }

    return numbers.top();
}

std::vector<std::string> parse(const std::string& input)
{
    std::vector<std::string> vec;

    std::string current;

    for (char c : input)
    {
        if (isdigit(c))
            current += c;
        else if (c)
        {
            if (!current.empty())
            {
                vec.emplace_back(std::move(current));
                current = "";
            }

            if (c != ' ')
                vec.emplace_back(1, c);
        }
    }

    if (!current.empty())
        vec.push_back(std::move(current));

    return vec;
}

int main() {

    // This program doesn't validate input.
    // It assumes that the input is always correct.

    std::string input;
    std::getline(std::cin, input);
    std::vector<std::string> notation = parse(input);
    std::cout << RPN(notation) << '\n';
}
</code>```

Body:
I have a problem with RPN.
I want the program to finish entering characters after pressing ENTER but something doesn't work because it doesn't write to vec.
I tried to solve the task:
The value of the expression recorded in Reverse Polish Notation should be determined. The expression will contain the following operators: +, -, * and / (integer division) and natural numbers not greater than one million. The result is in the type int.

Entrance
In the first and only line the phrase written in Reverse Polish Notation. Operators are separated from numbers by a space character. Expression length is less than 1000 characters.

Exit
The end value of the ONP expression.

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int RPN(vector<string> &notation) {
  stack<int> s;
  for (string str : notation) {
    if (str == "+" or str == "-" or str == "/" or str == "*") {
      int a = s.top();
      s.pop();
      int b = s.top();
      s.pop();

      if (str == "-") {
        s.push(b - a);
        continue;
      }
      if (str == "+") {
        s.push(b + a);
        continue;
      }
      if (str == "/") {
        s.push(b / a);
        continue;
      }
      if (str == "*") {
        s.push(b * a);
        continue;
      }
    } else
      s.push(stoi(str));
  }
  return s.top();
}

int main() {
  vector<string> notation;

  while (true) {
    string sign;
    cin >> sign;
    if (cin.get() != 'n') {
      break;
    } else {
      notation.push_back(sign);
    }
  }
  for (auto i : notation)  // test, print vec
  {
    cout << i << endl;
    ;
  }
  cout << RPN(notation) << endl;
return 0;
}

Body:
Your code doesn't maintain precedence. It treats addition the same way it treats multiplication. If that's what you want, you can just perform each operation from left to right.

I suppose the goal of your program is to have some precedence and to perform for example multiplication before addition.

Here is a simple code that maintains precedence. The code assumes that the input is always correct and do not handle parentheses for simplicity.

#include <iostream>
#include <vector>
#include <stack>

int getPrecedence(std::string &o)
{
    if (o == "+" || o == "-")
        return 1;

    return 2;
}

int calculate(int a, int b, const std::string &operation)
{
    if (operation == "+")
        return a + b;
    if (operation == "-")
        return a - b;
    if (operation == "*")
        return a * b;
    if (operation == "/")
        return a / b;
    return -1;
}

void performOperation(std::stack<int> &numbers, std::stack<std::string> &operators) {
    int n1 = numbers.top();
    numbers.pop();
    int n2 = numbers.top();
    numbers.pop();
    std::string op = operators.top();
    operators.pop();

    numbers.push(calculate(n2, n1, op));
}

int RPN(std::vector<std::string> &notation) {

    std::stack<int> numbers;
    std::stack<std::string> operators;

    if (notation.empty())
        return 0;

    numbers.push(stoi(notation[0]));

    for (int i = 1; i < notation.size(); i+=2)
    {
        while (!operators.empty() && getPrecedence(operators.top()) >= getPrecedence(notation[i]))
            performOperation(numbers, operators);

        numbers.push(std::stoi(notation[i+1]));
        operators.push(notation[i]);
    }

    while (!operators.empty())
        performOperation(numbers, operators);

    return numbers.top();
}

std::vector<std::string> parse(const std::string& input)
{
    std::vector<std::string> vec;

    std::string current;

    for (char c : input)
    {
        if (isdigit(c))
            current += c;
        else if (c)
        {
            if (!current.empty())
            {
                vec.emplace_back(std::move(current));
                current = "";
            }

            if (c != ' ')
                vec.emplace_back(1, c);
        }
    }

    if (!current.empty())
        vec.push_back(std::move(current));

    return vec;
}

int main() {

    // This program doesn't validate input.
    // It assumes that the input is always correct.

    std::string input;
    std::getline(std::cin, input);
    std::vector<std::string> notation = parse(input);
    std::cout << RPN(notation) << '\n';
}

Input:

1 + 2 + 3 * 3 + 3 / 3 + 5 - 4

Output:

14

For simplicity, I take the number of strings that the program will read before taking the input.

Update:

The above code assumes that the input is an infix expression. If the input is already in the RPN, the code would be like this:

#include <iostream>
#include <vector>
#include <stack>

int calculate(int a, int b, const std::string &operation)
{
    if (operation == "+")
        return a + b;
    if (operation == "-")
        return a - b;
    if (operation == "*")
        return a * b;
    if (operation == "/")
        return a / b;
    return -1;
}

bool isOperation(const std::string& op)
{
    return op == "+" || op == "-" || op == "*" || op == "/";
}

int RPN(std::vector<std::string> &notation) {

    std::stack<int> numbers;
    for (const auto& str : notation)
    {
        if (isOperation(str))
        {
            int n2 = numbers.top(); numbers.pop();
            int n1 = numbers.top(); numbers.pop();

            numbers.push(calculate(n1, n2, str));
        }
        else
            numbers.push(std::stoi(str));
    }

    return numbers.top();
}

std::vector<std::string> parse(const std::string& input)
{
    std::vector<std::string> vec;

    std::string current;

    for (char c : input)
    {
        if (isdigit(c))
            current += c;
        else if (c)
        {
            if (!current.empty())
            {
                vec.emplace_back(std::move(current));
                current = "";
            }

            if (c != ' ')
                vec.emplace_back(1, c);
        }
    }

    if (!current.empty())
        vec.push_back(std::move(current));

    return vec;
}

int main() {

    // This program doesn't validate input.
    // It assumes that the input is always correct.

    std::string input;
    std::getline(std::cin, input);
    std::vector<std::string> notation = parse(input);
    std::cout << RPN(notation) << '\n';
}


问:
TFS vs open source alternatives?
We're currently in the process of setting up a source control/build/and more-server for .NET development and we're thinking about either utilizing the Team Foundation Server (which costs a lot of dough) or combining several open source options, such as SourceForge Enterprise/GForge and Subversion and CruiseControl.net and so on. Has anyone walked down the full blown OSS road or is it TFS only if you want to get it right and get to work soon?</p>

答: I thought I'd throw in a new perspective that can be taken with a grain of salt because I haven't tried it yet, but I plan on using Bitten for CI in an upcoming project. This runs atop Trac+SVN, both great tools that I've used for many projects successfully.</p>

OwnerDisplayName: Microserf

Title: TFS vs open source alternatives?

LastEditorDisplayName: Huppie


问:
error when input row height with vertical and horizontal merged cell table in word vba
I would like to use InputBox to set the given parameter to change the table row height on cursor now position or the highlighted area. I could do this when I highlighted multi-row by mouse, but I also would like to do the same thing when I just put my cursor in a specific single row in the word table. However, when it comes to a table with vertically merged cells, I couldn't do that. VBA would show the error message: Run time error:'5991'. Is there any way to modify the row height or column width among a table with vertical and horizontal merged cells table?

Here is the script I propose:

```<code>Sub TableChangeSelectedRowHeight()
PromptBottom = "Input Row Height for Selection _________ mm"
HeaderTop = "Adjust Row Height"
UserData = InputBox(PromptBottom, HeaderTop)

Dim ToPoint As Single
ToPoint = Application.CentimetersToPoints(UserData / 10)

If StrPtr(UserData) = 0 Then
    MsgBox "您取消輸入。"
ElseIf UserData = vbNullString Then
    MsgBox "您沒有輸入資料。"
    End
Else
If Selection.Information(wdWithInTable) = True And Selection.Rows.Count <> 1 Then 'for mutltiple row
        Selection.Cells.SetHeight RowHeight:=ToPoint, _
        HeightRule:=wdRowHeightAtLeast

ElseIf Selection.Information(wdWithInTable) = True And
    Selection.Rows.Count = 1 Then 'for single row
        aa = Selection.Cells(1).RowIndex
        Selection.Rows(aa).SetHeight RowHeight:=ToPoint, _
        HeightRule:=wdRowHeightAtLeast 'There are some problems here
Else
        MsgBox "The insertion point is not in a table."
End If

End If

End Sub
</code>```

and when I conduct the sub the following error message would show:

```<code>Run time error:5991
Cannot access individual rows in the collection because the table has vertically merged cells.
</code>```

答:
Try something along the lines of:</p>

```<code>Dim Cl As Cell, Rng As Range, r As Long
With Selection
  If .Information(wdWithInTable) = True Then
    For r = .Cells(1).RowIndex To .Cells(.Cells.Count).RowIndex
      Set Rng = Nothing
      With .Tables(1)
        For Each Cl In .Range.Cells
          With Cl
            If .RowIndex = r Then
              If Rng Is Nothing Then
                Set Rng = .Range
              Else
                Rng.End = .Range.End
              End If
            End If
          End With
        Next
        Rng.Cells.HeightRule = wdRowHeightAtLeast
        Rng.Cells.Height = CentimetersToPoints(UserData / 10)
      End With
    Next
  Else
    MsgBox "The insertion point is not in a table."
  End If
End With
</code>```

Body:
I would like to use InputBox to set the given parameter to change the table row height on cursor now position or the highlighted area. I could do this when I highlighted multi-row by mouse, but I also would like to do the same thing when I just put my cursor in a specific single row in the word table. However, when it comes to a table with vertically merged cells, I couldn't do that. VBA would show the error message: Run time error:'5991'. Is there any way to modify the row height or column width among a table with vertical and horizontal merged cells table?

Here is the script I propose:

Sub TableChangeSelectedRowHeight()
PromptBottom = "Input Row Height for Selection _________ mm"
HeaderTop = "Adjust Row Height"
UserData = InputBox(PromptBottom, HeaderTop)

Dim ToPoint As Single
ToPoint = Application.CentimetersToPoints(UserData / 10)

If StrPtr(UserData) = 0 Then
    MsgBox "您取消輸入。"
ElseIf UserData = vbNullString Then
    MsgBox "您沒有輸入資料。"
    End
Else
If Selection.Information(wdWithInTable) = True And Selection.Rows.Count <> 1 Then 'for mutltiple row
        Selection.Cells.SetHeight RowHeight:=ToPoint, _
        HeightRule:=wdRowHeightAtLeast

ElseIf Selection.Information(wdWithInTable) = True And
    Selection.Rows.Count = 1 Then 'for single row
        aa = Selection.Cells(1).RowIndex
        Selection.Rows(aa).SetHeight RowHeight:=ToPoint, _
        HeightRule:=wdRowHeightAtLeast 'There are some problems here
Else
        MsgBox "The insertion point is not in a table."
End If

End If

End Sub

and when I conduct the sub the following error message would show:

Run time error:5991
Cannot access individual rows in the collection because the table has vertically merged cells.

Body:
Try something along the lines of:

Dim Cl As Cell, Rng As Range, r As Long
With Selection
  If .Information(wdWithInTable) = True Then
    For r = .Cells(1).RowIndex To .Cells(.Cells.Count).RowIndex
      Set Rng = Nothing
      With .Tables(1)
        For Each Cl In .Range.Cells
          With Cl
            If .RowIndex = r Then
              If Rng Is Nothing Then
                Set Rng = .Range
              Else
                Rng.End = .Range.End
              End If
            End If
          End With
        Next
        Rng.Cells.HeightRule = wdRowHeightAtLeast
        Rng.Cells.Height = CentimetersToPoints(UserData / 10)
      End With
    Next
  Else
    MsgBox "The insertion point is not in a table."
  End If
End With


问:
How to resolve no access in Azure Data Factory 2 to Azure DevOps Repository
I am facing an issue on Azure Data Factory when I try to access the Azure DevOps Git Repository that I configured. The error message is: "Invalid GIT configuration. You need to gain access to the repository before you can publish any changes. Details: Authentication error - you do not have access to the provided Azure DevOps account."

I am using the same account on both DevOps and Data Factory. My Azure portal access is "Contributor" at the subscription level and my DevOps role is Project Administrator on the project.

Regards,
Tania

I've tried various combinations of creating the repository as new from Data Factory as well as using an existing one created (by myself) in Azure DevOps.

From https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles in the Open Feedback items a user mentions that "the Build-in role Data Factory Contributor this is not in Allow part:
Action:Microsoft.DataFactory/locations/configureFactoryRepo/action"
I investigated the the contributor role and it appears to have the Action allowed as "Read" ?

ADF Repo Settings

ADF Repo Error

答:
Verify the User configuration at Organization level:
The default is "Stakeholder" - it should be "Basic" actually.
Hope it is useful.</p>


问:
Android ViewPager: Call onStop() to set ExoPlayer instance to null
I am looking for a solution for my project, where I am working with ViewPager2, and I need some way to call onStop() when the user swipes, and I want to set ExoPlayer instance to null.

答:
Please try the following:-

Register viewpager page change callback:

```<code>   viewPager.registerOnPageChangeCallback(doppelgangerPageChangeCallback)
</code>```

Set pageChangeCallback listener:

```<code>      var pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
      override fun onPageSelected(position: Int) {
        releasePlayer()
      }    }
</code>```

3.Function to initialize and release player below:

```<code>        fun initializePlayer() {
             player = ExoPlayerFactory.newSimpleInstance(this);
             playerView.setPlayer(player);
        }

        fun releasePlayer() {
          if (player != null) {
            player.release();
            player = null;
          }
        }
</code>```

Body:
Please try the following:-

Register viewpager page change callback:

   viewPager.registerOnPageChangeCallback(doppelgangerPageChangeCallback)

Set pageChangeCallback listener:

      var pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
      override fun onPageSelected(position: Int) {
        releasePlayer()
      }    }

3.Function to initialize and release player below:

        fun initializePlayer() {
             player = ExoPlayerFactory.newSimpleInstance(this);
             playerView.setPlayer(player);
        }

        fun releasePlayer() {
          if (player != null) {
            player.release();
            player = null;
          }
        }


问:
How to restart apache2 service through jenkins build
While setting up deployment through jenkins for my django project, I got stuck where I had to restart apache2 service to reflect the new changes to the client side. I am not sure how to provide user password after running systemctl reload apache2.service command.

I tried below options but no luck.

1) systemctl reload apache2.service

Result:

```<code>Failed to reload apache2.service: Interactive authentication required.
See system logs and 'systemctl status apache2.service' for details.
Build step 'Execute shell' marked build as failure
</code>```

2) sudo systemctl reload apache2.service

Result :

```<code>sudo: no tty present and no askpass program specified
Build step 'Execute shell' marked build as failure
</code>```

3) Also not sure whether sshpass will help in this case

Attached screenshot taken from jenkins job.

答:
As noted in a comment before, you have an problem with permissions here.

I assume that your Jenkins instance is running under user "jenkins", which cannot execute admin (root) commands. So you need to login via SSH into the machine and make sure that the user "jenkins" can execute this command with sudo.

You can find help for editing the sudoers file here: How To Edit the Sudoers File on Ubuntu and CentOS. I would recommend you to only to allow certain commands.

If you decide that the "jenkins" user needs to enter a password use the following command:

```<code>echo password | sudo -S systemctl reload apache2.service
</code>```

Of cause you should store that password in a secure way and mask it within the build. The Jenkins Credentials Plugin can help you with this.

Body:
While setting up deployment through jenkins for my django project, I got stuck where I had to restart apache2 service to reflect the new changes to the client side. I am not sure how to provide user password after running systemctl reload apache2.service command.

I tried below options but no luck.

1) systemctl reload apache2.service

Result:

Failed to reload apache2.service: Interactive authentication required.
See system logs and 'systemctl status apache2.service' for details.
Build step 'Execute shell' marked build as failure

2) sudo systemctl reload apache2.service

Result :

sudo: no tty present and no askpass program specified
Build step 'Execute shell' marked build as failure

3) Also not sure whether sshpass will help in this case

Attached screenshot taken from jenkins job.

Body:
As noted in a comment before, you have an problem with permissions here.

I assume that your Jenkins instance is running under user "jenkins", which cannot execute admin (root) commands. So you need to login via SSH into the machine and make sure that the user "jenkins" can execute this command with sudo.

You can find help for editing the sudoers file here: How To Edit the Sudoers File on Ubuntu and CentOS. I would recommend you to only to allow certain commands.

If you decide that the "jenkins" user needs to enter a password use the following command:

echo password | sudo -S systemctl reload apache2.service

Of cause you should store that password in a secure way and mask it within the build. The Jenkins Credentials Plugin can help you with this.


问:
Msiexec /log with Datetime in UTC format
I build my own MSI from wsx code. When I run it with command

```<code>msiexec /i "test.msi" /quiet /norestart /qn /log "test.log"
</code>```

I have log file like that

```<code>Action start 10:19:28: INSTALL.
Action start 10:19:28: FindRelatedProducts.
Action ended 10:19:28: FindRelatedProducts. Return value 1.
Action start 10:19:28: SaveCmdLineValueINSTALLDIR.
Action ended 10:19:28: SaveCmdLineValueINSTALLDIR. Return value 1.
Action start 10:19:28: AppSearch.
</code>```

Date and Time in log file is local, but I need UTC format. Are there any solution?

答:
I had a quick look and investigated the log for 1) timestamps C style (no obvious ones) (how to interpret an MSI log), 2) the use of debugging logging also did not add much useful, then there is the issue of 3) system policies - maybe they can report all times in UTC? Not sure. Didn't find anything obvious. Times in the 4) event viewer seem to be local time, but you might be able to access it to get UTC versions.

What you definitely can do is to 5) use a custom action to write UTC time yourself directly into the start of the log. Would that help? (UTC Time VBScript).

```<code>strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_UTCTime")

For Each objItem in colItems
  Msgbox "UTC Time: " + CStr(objItem.Hour) + CStr(":") + CStr(objItem.Minute) + CStr(":") + CStr(objItem.Second)
Next
</code>```

Custom Action Snippets: Numerous constructs required in WiX source file to run VBScript custom actions:

```<code><Binary Id='UTC.vbs' SourceFile='UTC.vbs' />
<CustomAction Id='UTC.vbs' VBScriptCall='' BinaryKey='UTC.vbs' Execute='immediate' Return='ignore'/>

<InstallExecuteSequence>
    <Custom Action='UTC.vbs' Sequence='1' />
</InstallExecuteSequence>
</code>```

Write to Log: How to write to the MSI log file. The code required to write to the log file in terse form:

```<code>Const msiMessageTypeInfo = &H04000000
Set msgrec = Installer.CreateRecord(1)
msgrec.StringData(0) = "Log: [1]"
msgrec.StringData(1) = "write this to log"
Session.Message msiMessageTypeInfo, msgrec
</code>```

Links:

UTC Time Assignment in VBScript

Body:
I build my own MSI from wsx code. When I run it with command

msiexec /i "test.msi" /quiet /norestart /qn /log "test.log"

I have log file like that

Action start 10:19:28: INSTALL.
Action start 10:19:28: FindRelatedProducts.
Action ended 10:19:28: FindRelatedProducts. Return value 1.
Action start 10:19:28: SaveCmdLineValueINSTALLDIR.
Action ended 10:19:28: SaveCmdLineValueINSTALLDIR. Return value 1.
Action start 10:19:28: AppSearch.

Date and Time in log file is local, but I need UTC format. Are there any solution?

Body:
I had a quick look and investigated the log for 1) timestamps C style (no obvious ones) (how to interpret an MSI log), 2) the use of debugging logging also did not add much useful, then there is the issue of 3) system policies - maybe they can report all times in UTC? Not sure. Didn't find anything obvious. Times in the 4) event viewer seem to be local time, but you might be able to access it to get UTC versions.

What you definitely can do is to 5) use a custom action to write UTC time yourself directly into the start of the log. Would that help? (UTC Time VBScript).

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_UTCTime")

For Each objItem in colItems
  Msgbox "UTC Time: " + CStr(objItem.Hour) + CStr(":") + CStr(objItem.Minute) + CStr(":") + CStr(objItem.Second)
Next

Custom Action Snippets: Numerous constructs required in WiX source file to run VBScript custom actions:

<Binary Id='UTC.vbs' SourceFile='UTC.vbs' />
<CustomAction Id='UTC.vbs' VBScriptCall='' BinaryKey='UTC.vbs' Execute='immediate' Return='ignore'/>

<InstallExecuteSequence>
    <Custom Action='UTC.vbs' Sequence='1' />
</InstallExecuteSequence>

Write to Log: How to write to the MSI log file. The code required to write to the log file in terse form:

Const msiMessageTypeInfo = &H04000000
Set msgrec = Installer.CreateRecord(1)
msgrec.StringData(0) = "Log: [1]"
msgrec.StringData(1) = "write this to log"
Session.Message msiMessageTypeInfo, msgrec

Links:

UTC Time Assignment in VBScript


问:
Can managed code perform computations as fast as unmamanged?
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a no-brainier.

However, I would like to question that idea. When .NET first appeared, there were many people saying that .NET idea would not work because .NET programs were doomed to be super-slow. In reality this did not happen. Somebody did a good job with the VM, JIT, etc and we have decent performance for most tasks now. But not all. Microsoft never promised that .NET will be suitable for all task and admitted for some tasks you will still need C/C++.

Going back to the question of computationally heavy task - is there a way to write a .NET program so that it does not perform computations considerably worse that an unmanaged code using the same algorithms? I'd be happy with "constant" speed loss, but anything worse than that is going to be a problem.

What do you think? Can we be close in speed to unmanaged code for computations in managed code, or unmanaged code is the only viable answer? If we can, how? If we can't why?

Update:  a lot of good feedback here. I'm going to accept the most up-voted answer.

答:
You can use unsafe and pointers to get "raw" memory access, which can give you a significant speed boost at the cost of more responsibility for your stuff (remember to pin your objects). At that point, you're just shifting bytes.

Garbage Collection pressure could be an interesting thing, but there are tactics around that as well (object pooling).


问:
Can we return an array of `AccountID` in NEAR?
Suppose I have a struct

```<code>pub struct Test {
    pub participant: Set<AccountId>
}
</code>```

And I created a new account and inserted to participant using the insert function, I can get len of participant using len() method.
How can I get the address?

```<code>pub fn get_address(&self) -> Vec<AccountId> {
    self.participient.contains() // can't get data
}
</code>```

答:
You can do</p>

```<code>self.participant.to_vec()
</code>```

Body:
Suppose I have a struct

pub struct Test {
    pub participant: Set<AccountId>
}

And I created a new account and inserted to participant using the insert function, I can get len of participant using len() method.
How can I get the address?

pub fn get_address(&self) -> Vec<AccountId> {
    self.participient.contains() // can't get data
}

Body:
You can do

self.participant.to_vec()


问:
React Native fetch throws error when posting multipart/form-data
This is how I tried to POST an image as multipart/form-data to server.

```<code>var photo = { uri: this.state.avatarSource,
              type: 'multipart/form-data',
              name: 'photo.jpg', };
let formdata = new FormData();
formdata.append('attachment',photo);
fetch(url,
        { method: "POST",
          headers: { 'Content-Type': 'multipart/form-data' },
          body: formdata
        }).then((response) => response.json())
       .catch((error) => { alert("ERROR " + error) })
       .then((responseData) => { alert("Succes "+ responseData) }).done();
</code>```

But it shows an error : Expected dynamic type string but had type
  object

答:
I slightly modified the solution given by @unknown123. And it worked for me.
Here is the solution.

First, install npm package rn-fetch-blob

import RNFetchBlob from 'rn-fetch-blob';

RNFetchBlob.fetch('PUT', url, {'Content-Type': 'multipart/form-data'},
  Platform.OS === 'ios' ? RNFetchBlob.wrap(filePath) :
  `RNFetchBlob-${filePath}`)

Please note, in my case, I had different file paths for IOS and Android devices. We handle it in different ways using rn-fetch-blob

Sample filePath variable data for

IOS device -

"/Users/Niveditha/Library/Developer/CoreSimulator/Devices/B41EB910-F22B-4236-8286-E6BA3EA75C70/data/Containers/Data/Application/B88777C6-6B10-4095-AB67-BB11E045C1DE/tmp/react-native-image-crop-picker/img.jpg"

Android device -

"file:///storage/emulated/0/Android/data/com.uploadcameraroll/files/Pictures/img.jpg"

Body:
This is how I tried to POST an image as multipart/form-data to server.

var photo = { uri: this.state.avatarSource,
              type: 'multipart/form-data',
              name: 'photo.jpg', };
let formdata = new FormData();
formdata.append('attachment',photo);
fetch(url,
        { method: "POST",
          headers: { 'Content-Type': 'multipart/form-data' },
          body: formdata
        }).then((response) => response.json())
       .catch((error) => { alert("ERROR " + error) })
       .then((responseData) => { alert("Succes "+ responseData) }).done();

But it shows an error : Expected dynamic type string but had type
  object


问:
How to make the new elasticsearch node.js client only returns body in promises?
"The returned value of an API call will no longer be the body, statusCode, and headers for callbacks, and only the body for promises. The new returned value will be a unique object containing the body, statusCode, headers, warnings, and meta, for both callback and promises."

This is a problem if I stringify and store the result in redis (now I will need to JSON parse when I get the value back from redis). Is there anyway I can switch on "body only" mode on promises?

答:
Unforntunately, no.
There is no way to only receive only the body.
As you mentioned this would be the response,

```<code>{
  body: object | boolean
  statusCode: number
  headers: object
  warnings: [string]
  meta: object
}
</code>```

Best you can do it before you store the response in Redis you can store it like this,

```<code>const {body} = await client.search({
  index: 'my-index',
  body: { foo: 'bar' }
})
// Now you can store the body in Redis
</code>```

Or when you fetch the response object from Redis you can do this,

```<code>const {body}=JSON.parse(fetchFromRedis(id));
</code>```

Body:
Unforntunately, no.
There is no way to only receive only the body.
As you mentioned this would be the response,

{
  body: object | boolean
  statusCode: number
  headers: object
  warnings: [string]
  meta: object
}

Best you can do it before you store the response in Redis you can store it like this,

const {body} = await client.search({
  index: 'my-index',
  body: { foo: 'bar' }
})
// Now you can store the body in Redis

Or when you fetch the response object from Redis you can do this,

const {body}=JSON.parse(fetchFromRedis(id));


问:
How can I trigger a Leaflet map to reload everything including the overlay layers?
I'm having an issue right now with my map where I need to export it as an image with the overlay layers. I found a solution to do so using html2canvas, however there is a bug with it where if you pan the map at all, when taking the screenshot the layers will not display properly in the screenshot from html2canvas like so...

Yet if I just change the center of my map with  map.setView() it works fine. So my thought is, if I could just trigger the map to reload completely (including the layers) it would maybe overlay correctly. How can I trigger a Leaflet map to reload everything including the overlay layers?

I've looked through the documentation but haven't as of this second found a clear solution.

答:
We had the same problem today. It also happened with an export by dom-to-image-more/lealfet-easy-print plugin.

Try to disable zoomSnap or try to deactivate the fractional zoom functionality.


问:
How to add tags in Json configuration of AWS emr
How do i add --tags in json configuration of Amazon emr. I tried place it like below . But that doesn't work. This is my config.</p>

```<code> {
   "Name":"EMR",
   "LogUri":"------ ",
    "Tags": [
      {
         "Key": "Name",
         "Value": "Bigdata"
      }
   ],
   "Instances":{
      "InstanceGroups":[
         {
            "Name":"Master",
             ------
         },
         {
            "Name":"Slave",
            -----------
         },
         {
            "Name":"Task",
            ---------------
         }
      ],
      "TerminationProtected":false,
      "KeepJobFlowAliveWhenNoSteps":true,
  ------------------------------------------
  ------------------------------------------
   }
</code>```

答:
Tags should come under Properties.
AWS doc

YAML

myEMRCluster:
    Type: 'AWS::EMR::Cluster'
    Properties:
      Tags:
        - Key: <name>
          Value: <value>
```

<ul>
<li>JSON</li>
</ul>

```"myEMRCluster": {
    "Type": "AWS::EMR::Cluster",
    "Properties": {
        "Tags": [
            {
                "Key": "<name>",
                "Value": "<value>"
            }
        ]
    }
}
```

Body:
How do i add --tags in json configuration of Amazon emr. I tried place it like below . But that doesn't work. This is my config.

 {
   "Name":"EMR",
   "LogUri":"------ ",
    "Tags": [
      {
         "Key": "Name",
         "Value": "Bigdata"
      }
   ],
   "Instances":{
      "InstanceGroups":[
         {
            "Name":"Master",
             ------
         },
         {
            "Name":"Slave",
            -----------
         },
         {
            "Name":"Task",
            ---------------
         }
      ],
      "TerminationProtected":false,
      "KeepJobFlowAliveWhenNoSteps":true,
  ------------------------------------------
  ------------------------------------------
   }

Body:
Tags should come under Properties.
AWS doc

YAML

myEMRCluster:
    Type: 'AWS::EMR::Cluster'
    Properties:
      Tags:
        - Key: <name>
          Value: <value>

JSON

"myEMRCluster": {
    "Type": "AWS::EMR::Cluster",
    "Properties": {
        "Tags": [
            {
                "Key": "<name>",
                "Value": "<value>"
            }
        ]
    }
}


问:
Split string each Nth character and join it back with different separators
I try to use text wrapping in a sentence with different separators. This is exactly what I would like to get as an output:

```<code>'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'
</code>```

Here is my first attempt with .join() and wrap(), unsuccessful:

```<code>[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'
</code>```

Then, I have tried a for loop inside the separator, but without success too... :

```<code>[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'
</code>```

Maybe combining .split() and .join() function can be a better way to do what I would like, but I can't find how. Please, do you have any idea about how to achieve this?

答:
Here's a one liner you can try:</p>

```<code>text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
                for i, w in enumerate(wrap(sentence, 20))])
</code>```

Body:
I try to use text wrapping in a sentence with different separators. This is exactly what I would like to get as an output:

'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'

Here is my first attempt with .join() and wrap(), unsuccessful:

[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'

Then, I have tried a for loop inside the separator, but without success too... :

[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'

Maybe combining .split() and .join() function can be a better way to do what I would like, but I can't find how. Please, do you have any idea about how to achieve this?

Body:
Here's a one liner you can try:

text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
                for i, w in enumerate(wrap(sentence, 20))])


问:
php implode breaks on spaces

I have an array of strings, and these strings have spaces in them. For example:

```<code>$arr = array('bob', 'john smith', 'grease monkey', 'etc');
</code>```

Why is it when I try to $str = implode('|', $arr);, it stops at the first space it finds??
I'm left with a string like:

```<code>$str = "bob|john";
</code>```

If I try:

```<code>$arr = array('bob', 'john', 'grease monkey', 'etc');
</code>```

and implode, I get:

```<code>$str = "bob|john|grease";
</code>```

Edit: I'm actually trying to set it to the value of a hidden field:

```<code><input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />
</code>```

答:
Edit: I'm actually trying to set it to the value of a hidden field:

```<code><input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />
</code>```

You need to quote the value attribute:

```<code><input .. type="text" value="<?php echo implode('|', $myFields);?>" />
</code>```

Without doing that, the rendered HTML looks like:

```<code><input type="text" value=bob|john|grease monkey />
</code>```

Which the browser will handle as this:

```<code><input type="text" value="bob|john|grease" monkey />
</code>```

Title: php implode breaks on spaces

Body:
I have an array of strings, and these strings have spaces in them. For example:

$arr = array('bob', 'john smith', 'grease monkey', 'etc');

Why is it when I try to $str = implode('|', $arr);, it stops at the first space it finds??
I'm left with a string like:

$str = "bob|john";

If I try:

$arr = array('bob', 'john', 'grease monkey', 'etc');

and implode, I get:

$str = "bob|john|grease";

Edit: I'm actually trying to set it to the value of a hidden field:

<input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />

Body:
Edit: I'm actually trying to set it to the value of a hidden field:

<input id="hidLblFields" name="hidLblFields" type="text" value=<?php echo implode('|', $myFields);?> />

You need to quote the value attribute:

<input .. type="text" value="<?php echo implode('|', $myFields);?>" />

Without doing that, the rendered HTML looks like:

<input type="text" value=bob|john|grease monkey />

Which the browser will handle as this:

<input type="text" value="bob|john|grease" monkey />