问:
f# read xls file - how to parse a value2 object
I tried to use F# read a xls file as below

```<code>open Microsoft.Office.Interop.Excel
let app = ApplicationClass(Visible = false)
let book = app.Workbooks.Open "test.xls"
let sheet = book.Worksheets.[1] :?> _Worksheet
let vals = sheet.UsedRange.Value2
</code>```

The problem is how can I parse vals into a F# type? in fsx.exe, the vals showed as

```<code>'val vals: obj = [bound1
                  bound2
                  ["colname1"; "colname2"; ...]
                  [1234,5678,]...]
</code>```

I wanted to retrieve the string represetation first, but
printfn "%A" vals.ToString();; shows "System.Object[,]" only. If I then try to access vals.[1,1], I got error The field,constructor or member 'item' is not defined

thanks,

答:
The type of Value2 is obj. If the range represents just a single cell, the actual type will be some primitive type (int, float, decimal, string). If the range represents several cells (your case), then the returned value is a two-dimensional .NET array of type obj[,].

You can cast the value returned by Value2 to an array and access it using indexers:

```<code>let vals = sheet.UsedRange.Value2 :?> obj[,]
vals.[1, 1]
</code>```

Note that the returned array is 1-based (and not zero based as usual). The indexer again returns obj, so you need to cast the values to their actual type. Depending on your sheet, this will be probably float or string:

```<code>let firstTitle = vals.[1, 1] :?> string
let firstValue = vals.[2, 1] :?> float
</code>```

(Assuming you have a title in A1 and a number in A2)

Body:
I tried to use F# read a xls file as below

open Microsoft.Office.Interop.Excel
let app = ApplicationClass(Visible = false)
let book = app.Workbooks.Open "test.xls"
let sheet = book.Worksheets.[1] :?> _Worksheet
let vals = sheet.UsedRange.Value2

The problem is how can I parse vals into a F# type? in fsx.exe, the vals showed as

'val vals: obj = [bound1
                  bound2
                  ["colname1"; "colname2"; ...]
                  [1234,5678,]...]

I wanted to retrieve the string represetation first, but
printfn "%A" vals.ToString();; shows "System.Object[,]" only. If I then try to access vals.[1,1], I got error The field,constructor or member 'item' is not defined

thanks,

Body:
The type of Value2 is obj. If the range represents just a single cell, the actual type will be some primitive type (int, float, decimal, string). If the range represents several cells (your case), then the returned value is a two-dimensional .NET array of type obj[,].

You can cast the value returned by Value2 to an array and access it using indexers:

let vals = sheet.UsedRange.Value2 :?> obj[,]
vals.[1, 1]

Note that the returned array is 1-based (and not zero based as usual). The indexer again returns obj, so you need to cast the values to their actual type. Depending on your sheet, this will be probably float or string:

let firstTitle = vals.[1, 1] :?> string
let firstValue = vals.[2, 1] :?> float

(Assuming you have a title in A1 and a number in A2)


来源: stackexchange

问:
$out ,$projection in mongodb
i want to save records in a new collection using either $out or $merge.

```<code>     **/////collection 2- reservationdeatils////**
         "_id":ObjectId("5e4a898947363e964a886420"),
         "phoneNo" : 98765#####,
         "name" : "name1",
         "userId":ObjectId("5e1efac668c3c811c83263cc"),
         "approversId":ObjectId("5e1efad268c3c811c83263cd")
         "bookedForDate":ISODate("2020-02-20T07:23:36.130Z"),
         "bookingDetails" : [
                    {    "_id" : ObjectId("5e44f471d1868d2a54aac12d"),
                         "seatsBooked" : 15,
                         "floorId" : "#IKE01",
                      },
                    {   "_id" : ObjectId("5e44f471d1868d2a54aac12c"),
                        "seatsBooked" : 35,
                        "floorId" : "#HKE04",
                    }
                 ],
     **/////collection 2-priceDetails////**
          {
           "_id" : ObjectId("5e1efb0168c3c811c83263ce"),
           "floorId" : "#IKE01",
           "weekday" : "monday",
            "pricePoint" : 589,
         }
         {
           "_id" : ObjectId("5e2694db54e532a4eb92b477"),
           "floorId" : "#IKE02",
           "weekday" : "thursday",
          "pricePoint" : 699
         }
        {
         "_id" : ObjectId("5e2694f954e532a4eb92b478"),
         "floorId" : "#HKE04",
         "weekday" : "monday",
         "pricePoint" : 579
        }
      **/////collection 3- discount////**
        {
        "_id" :  ObjectId("5e427de64617181a4ce38893"),
        "userId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
        "approversId" : ObjectId("5e1d82156a67173cb877f67d"),
        "floorId" : "#IKE01",
        "weekday" : "monday",
        "discount" : 20%,
       },
       {
        "_id" :  ObjectId("5e4281e7fec2e01a4c60b406"),
        "userId" : ObjectId("5e1efac668c3c811c83263cc"),
        "approversId" : ObjectId("5e1efad268c3c811c83263cd"),
        "floorId" : "#IKE01",
        "weekday" : "monday",
        "discount" : 24%,
     }
</code>```

Now below is the query i have tried :

```<code>     db.reservationdeatils.aggregate([
    {
       '$match': {
          'approverId': ObjectId('5e1efad268c3c811c83263cd'),
          'userId': ObjectId('5e1efac668c3c811c83263cc'),
          'bookedForDate': ISODate("2020-02-11T18:30:00Z"),
        }
     },
     {
      '$unwind': {
          'path': '$bookingDetails',
       },
     },
       {
        $lookup:
         {
          from: 'priceDetails',
          let: { floorId: '$bookingDetails.floorId' },
          pipeline: [
              {
                  $match: {
                      weekday: 'monday',
                      $expr: {
                          $eq: ["$floorId", "$$floorId"]
                      }
                  }
              }
          ], as: 'priceDetails'
      }
  },
  { '$unwind': '$priceDetails' },
    {
      $lookup:
      {
          from: 'discount',
          let: { floorId: '$bookingDetails.floorId' },
          pipeline: [
              {
                  $match: {
                      weekday: 'monday',
                      $expr: {
                          $eq: ["$floorId", "$$floorId"]
                      }
                  }
              }
          ], as: 'discounts'
      }
  },
  { '$unwind': '$discounts' },

  {
      '$group': {
          '_id': {
              'floorId': '$bookingDetails.floorId',
              'date': '$bookedForDate',
              'price': '$priceDetails.pricePoint',
              'discount': '$discounts.discount'
          },
          'seatsBooked': {
              '$sum': '$bookingDetails.seatsBooked'
          },
       }
   },
     {
      '$project': {
            'amount': {
              '$multiply':
                   [
                     '$seatsBooked',
                        {'$subtract':
                              ['$_id.pricePoint',
                                 { '$multiply':
                                   ['$_id.pricePoint',
                                      { '$divide':
                                        ['$_id.discount', 100]
                                   }]
                               }]
                            }]
                         },
                     },
                   },
      {
          $group: {
           _id: null,
            totalAmount: {
            $sum: "$amount"
          }
      }
  },
    {
      '$project': {
          _id:0,
          totalAmount:1,
          bookedForDate:1,
          'floorId':'$priceDetails.floorId'
       }
     },{'$merge':'invoice'}
  ]).pretty()
</code>```

i have been able to achieve the totalAmount but what i want to achieve is that i want to save these fields into "invoice" collection "userId","approversId","floorId","sum","totalSum","bookedForDate","name" BUT 1:whenever i use $out instead of $merge the previous document gets replaces which i dont want, 2: if i use $merge everytime i run the query a new document is created and that too only with _id:ObjectId(5e4a899c47363e964a88642f),totalBill:#### these fields , any suggestion how can i achieve this

答:
You are going in a good direction you just need to look at the $group aggregation.

One more thing I have used the discount as int value, not in percentage.

"discount" : 24

I have updated the query:

```<code>db.reservationdeatils.aggregate([
{
  $match: {
    "userId" : ObjectId("5e1efac668c3c811c83263cc"),
    "approversId" : ObjectId("5e1efad268c3c811c83263cd"),
    "bookedForDate" : ISODate("2020-02-20T07:23:36.130Z")
   }
},
{
 $unwind: {
     path: "$bookingDetails",
  },
},
{
 $lookup:
  {
   from: "priceDetails",
   let: { floorId: "$bookingDetails.floorId" },
   pipeline: [
       {
           $match: {
               weekday: "monday",
               $expr: {
                   $eq: ["$floorId", "$$floorId"]
               }
           }
       }
   ],
   as: "priceDetails"
  }
},
{
  $unwind: "$priceDetails"
},
{
 $lookup:
 {
     from: "discount",
     let: { floorId: "$bookingDetails.floorId" },
     pipeline: [
         {
             $match: {
                 weekday: "monday",
                 $expr: {
                     $eq: ["$floorId", "$$floorId"]
                 }
             }
         }
     ],
     as: "discounts"
 }
}
,
{
  $unwind: "$discounts"
}
,
{
 $group: {
     "_id": {
         "floorId": "$bookingDetails.floorId",
         "date": "$bookedForDate",
         "price": "$priceDetails.pricePoint",
         "discount": "$discounts.discount"
     },
     "price":{
      $first:"$priceDetails.pricePoint"
     },
     "discount":{
      $first:"$discounts.discount"
     },
     "seatsBooked": {
         $sum: "$bookingDetails.seatsBooked"
     },
  }
}
,
{
$project: {
  "amount": {
    $multiply:
      [
        "$seatsBooked",
        {
          $subtract:[
            "$price",
            {
              $multiply:[
                "$price",
                {
                  $divide:[
                    "$discount",
                    100
                  ]
                }
              ]
            }
          ]
        }
      ]
  },
},
}
,
{
 $group: {
  "_id": null,
   "totalAmount": {
   $sum: "$amount"
   }
  }
},
{
 $project: {
     "_id":0,
     "totalAmount":1,
     "bookedForDate":1,
     "floorId":"$priceDetails.floorId"
  }
},
{
  $out:"invoice"
}
]).pretty()

</code>```

This will help you.

ContentLicense: CC BY-SA 4.0

Title: $out ,$projection in mongodb

Body:
i want to save records in a new collection using either $out or $merge.

     **/////collection 2- reservationdeatils////**
         "_id":ObjectId("5e4a898947363e964a886420"),
         "phoneNo" : 98765#####,
         "name" : "name1",
         "userId":ObjectId("5e1efac668c3c811c83263cc"),
         "approversId":ObjectId("5e1efad268c3c811c83263cd")
         "bookedForDate":ISODate("2020-02-20T07:23:36.130Z"),
         "bookingDetails" : [
                    {    "_id" : ObjectId("5e44f471d1868d2a54aac12d"),
                         "seatsBooked" : 15,
                         "floorId" : "#IKE01",
                      },
                    {   "_id" : ObjectId("5e44f471d1868d2a54aac12c"),
                        "seatsBooked" : 35,
                        "floorId" : "#HKE04",
                    }
                 ],
     **/////collection 2-priceDetails////**
          {
           "_id" : ObjectId("5e1efb0168c3c811c83263ce"),
           "floorId" : "#IKE01",
           "weekday" : "monday",
            "pricePoint" : 589,
         }
         {
           "_id" : ObjectId("5e2694db54e532a4eb92b477"),
           "floorId" : "#IKE02",
           "weekday" : "thursday",
          "pricePoint" : 699
         }
        {
         "_id" : ObjectId("5e2694f954e532a4eb92b478"),
         "floorId" : "#HKE04",
         "weekday" : "monday",
         "pricePoint" : 579
        }
      **/////collection 3- discount////**
        {
        "_id" :  ObjectId("5e427de64617181a4ce38893"),
        "userId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
        "approversId" : ObjectId("5e1d82156a67173cb877f67d"),
        "floorId" : "#IKE01",
        "weekday" : "monday",
        "discount" : 20%,
       },
       {
        "_id" :  ObjectId("5e4281e7fec2e01a4c60b406"),
        "userId" : ObjectId("5e1efac668c3c811c83263cc"),
        "approversId" : ObjectId("5e1efad268c3c811c83263cd"),
        "floorId" : "#IKE01",
        "weekday" : "monday",
        "discount" : 24%,
     }

Now below is the query i have tried :

     db.reservationdeatils.aggregate([
    {
       '$match': {
          'approverId': ObjectId('5e1efad268c3c811c83263cd'),
          'userId': ObjectId('5e1efac668c3c811c83263cc'),
          'bookedForDate': ISODate("2020-02-11T18:30:00Z"),
        }
     },
     {
      '$unwind': {
          'path': '$bookingDetails',
       },
     },
       {
        $lookup:
         {
          from: 'priceDetails',
          let: { floorId: '$bookingDetails.floorId' },
          pipeline: [
              {
                  $match: {
                      weekday: 'monday',
                      $expr: {
                          $eq: ["$floorId", "$$floorId"]
                      }
                  }
              }
          ], as: 'priceDetails'
      }
  },
  { '$unwind': '$priceDetails' },
    {
      $lookup:
      {
          from: 'discount',
          let: { floorId: '$bookingDetails.floorId' },
          pipeline: [
              {
                  $match: {
                      weekday: 'monday',
                      $expr: {
                          $eq: ["$floorId", "$$floorId"]
                      }
                  }
              }
          ], as: 'discounts'
      }
  },
  { '$unwind': '$discounts' },

  {
      '$group': {
          '_id': {
              'floorId': '$bookingDetails.floorId',
              'date': '$bookedForDate',
              'price': '$priceDetails.pricePoint',
              'discount': '$discounts.discount'
          },
          'seatsBooked': {
              '$sum': '$bookingDetails.seatsBooked'
          },
       }
   },
     {
      '$project': {
            'amount': {
              '$multiply':
                   [
                     '$seatsBooked',
                        {'$subtract':
                              ['$_id.pricePoint',
                                 { '$multiply':
                                   ['$_id.pricePoint',
                                      { '$divide':
                                        ['$_id.discount', 100]
                                   }]
                               }]
                            }]
                         },
                     },
                   },
      {
          $group: {
           _id: null,
            totalAmount: {
            $sum: "$amount"
          }
      }
  },
    {
      '$project': {
          _id:0,
          totalAmount:1,
          bookedForDate:1,
          'floorId':'$priceDetails.floorId'
       }
     },{'$merge':'invoice'}
  ]).pretty()

i have been able to achieve the totalAmount but what i want to achieve is that i want to save these fields into "invoice" collection "userId","approversId","floorId","sum","totalSum","bookedForDate","name" BUT 1:whenever i use $out instead of $merge the previous document gets replaces which i dont want, 2: if i use $merge everytime i run the query a new document is created and that too only with _id:ObjectId(5e4a899c47363e964a88642f),totalBill:#### these fields , any suggestion how can i achieve this

Body:
You are going in a good direction you just need to look at the $group aggregation.

One more thing I have used the discount as int value, not in percentage.

"discount" : 24

I have updated the query:

db.reservationdeatils.aggregate([
{
  $match: {
    "userId" : ObjectId("5e1efac668c3c811c83263cc"),
    "approversId" : ObjectId("5e1efad268c3c811c83263cd"),
    "bookedForDate" : ISODate("2020-02-20T07:23:36.130Z")
   }
},
{
 $unwind: {
     path: "$bookingDetails",
  },
},
{
 $lookup:
  {
   from: "priceDetails",
   let: { floorId: "$bookingDetails.floorId" },
   pipeline: [
       {
           $match: {
               weekday: "monday",
               $expr: {
                   $eq: ["$floorId", "$$floorId"]
               }
           }
       }
   ],
   as: "priceDetails"
  }
},
{
  $unwind: "$priceDetails"
},
{
 $lookup:
 {
     from: "discount",
     let: { floorId: "$bookingDetails.floorId" },
     pipeline: [
         {
             $match: {
                 weekday: "monday",
                 $expr: {
                     $eq: ["$floorId", "$$floorId"]
                 }
             }
         }
     ],
     as: "discounts"
 }
}
,
{
  $unwind: "$discounts"
}
,
{
 $group: {
     "_id": {
         "floorId": "$bookingDetails.floorId",
         "date": "$bookedForDate",
         "price": "$priceDetails.pricePoint",
         "discount": "$discounts.discount"
     },
     "price":{
      $first:"$priceDetails.pricePoint"
     },
     "discount":{
      $first:"$discounts.discount"
     },
     "seatsBooked": {
         $sum: "$bookingDetails.seatsBooked"
     },
  }
}
,
{
$project: {
  "amount": {
    $multiply:
      [
        "$seatsBooked",
        {
          $subtract:[
            "$price",
            {
              $multiply:[
                "$price",
                {
                  $divide:[
                    "$discount",
                    100
                  ]
                }
              ]
            }
          ]
        }
      ]
  },
},
}
,
{
 $group: {
  "_id": null,
   "totalAmount": {
   $sum: "$amount"
   }
  }
},
{
 $project: {
     "_id":0,
     "totalAmount":1,
     "bookedForDate":1,
     "floorId":"$priceDetails.floorId"
  }
},
{
  $out:"invoice"
}
]).pretty()

This will help you.


问:
Problem Using Active Reports in Angular 8
i tried to use Active Reports in Angular 8 and i did all the steps needed from this website,https://www.grapecity.com/activereportsjs/docs/GettingStarted/QuickStart/QuickStart-Angular
Still i get this error when i try to compile my app :

```<code>ERROR in The target entry-point "@grapecity/activereports-angular" has missing dependencies:
 - rdlx-model
 - @grapecity/ar-js-viewer/ExportPanel
 - @grapecity/viewer-core
 - @grapecity/ar-js-viewer
 - @grapecity/viewer-core/features/search
</code>```

and this is my code :

In App.Component.Html

```<code>gc-activereports-viewer [height]="height" [availableExports]="availableExports" (documentLoaded)="onDocumentLoaded($event)" #reportviewer></gc-activereports-viewer
</code>```

In App.Module.Ts

```<code>  import { BrowserModule } from '@angular/platform-browser';<br />
   import { NgModule } from '@angular/core';<br />
   import { ActiveReportsModule } from '@grapecity/activereports-angular';
   import { AppComponent } from './app.component';

   @NgModule({<br />
     declarations: [<br />
       AppComponent<br />
     ],<br />
     imports: [
       BrowserModule,
       ActiveReportsModule
     ],
     providers: [],
     bootstrap: [AppComponent]
   })<br />
   export class AppModule { }
</code>```

In App.Component.Ts

 i used the exact same Code from the website.(Grapecity.com)
and the rest of the steps;
i used to run this Command as adminstrator **npm install @grapecity/activereports-angular** and it didn't work either

**CMD page shows me this message :

```<code>**<br /> D:\Angular Projects\Reporter-so>  npm install @grapecity/activereports-angular<br />
npm WARN @grapecity/activereports-angular@1.1.0 requires a peer of @angular/common@^7.0.0 || ^8.0.0 but none is installed. You must install peer dependencies yourself.<br />
npm WARN @grapecity/activereports-angular@1.1.0 requires a peer of @angular/core@^7.0.0 || ^8.0.0 but none is installed. You must install peer dependencies yourself.<br />
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):<br />
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
</code>```

答:
Write this code in tsconfig.app.json</p>

```<code>"angularCompilerOptions": {
    "enableIvy": false
  }
</code>```

Body:
i tried to use Active Reports in Angular 8 and i did all the steps needed from this website,https://www.grapecity.com/activereportsjs/docs/GettingStarted/QuickStart/QuickStart-Angular
Still i get this error when i try to compile my app :

ERROR in The target entry-point "@grapecity/activereports-angular" has missing dependencies:
 - rdlx-model
 - @grapecity/ar-js-viewer/ExportPanel
 - @grapecity/viewer-core
 - @grapecity/ar-js-viewer
 - @grapecity/viewer-core/features/search

and this is my code :

In App.Component.Html

gc-activereports-viewer [height]="height" [availableExports]="availableExports" (documentLoaded)="onDocumentLoaded($event)" #reportviewer></gc-activereports-viewer

In App.Module.Ts

  import { BrowserModule } from '@angular/platform-browser';

   import { NgModule } from '@angular/core';

   import { ActiveReportsModule } from '@grapecity/activereports-angular';
   import { AppComponent } from './app.component';

   @NgModule({

     declarations: [

       AppComponent

     ],

     imports: [
       BrowserModule,
       ActiveReportsModule
     ],
     providers: [],
     bootstrap: [AppComponent]
   })

   export class AppModule { }

In App.Component.Ts

 i used the exact same Code from the website.(Grapecity.com)
and the rest of the steps;
i used to run this Command as adminstrator **npm install @grapecity/activereports-angular** and it didn't work either

**CMD page shows me this message :

**
 D:\Angular Projects\Reporter-so>  npm install @grapecity/activereports-angular

npm WARN @grapecity/activereports-angular@1.1.0 requires a peer of @angular/common@^7.0.0 || ^8.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN @grapecity/activereports-angular@1.1.0 requires a peer of @angular/core@^7.0.0 || ^8.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

Body:
Write this code in tsconfig.app.json

"angularCompilerOptions": {
    "enableIvy": false
  }


问:
Android: Clear old activity instance from history stack
I have the following simple scenario:

One Activity called ListCarsActivity.kt where list of cars are displayed. When the user click on the FloatingActionButton, it opens another activity called AddCarActivity.kt

When the user click on the Add Car button, I start a new intent to go to the initial activity ListCarsActivity.kt where the added car is now displayed.

Problem: From now, when I click on the Back button, the ListCarsActivity is displayed a second time.

How to clear the old entry of ListCarsActivity from the History stack?

答: use finish() after startActivity(intent) to finish the activity in which you are starting another activity


问:
Is it possible to change NavigationView's settings item's icon and text?
Basically when using NavigationView, the settings item always shows up as a gear icon and a text of "Settings". Is it possible to change these two things? </p>

答:
My answer is based on @Andreas Fredriksson answer, but contains the Icon change as well:</p>

```<code>private void Navigation_Loaded(object sender, RoutedEventArgs e)
{
      var settings = (NavigationViewItem)Navigation.SettingsItem;
      settings.Content = "Help";
      settings.Icon = new SymbolIcon((Symbol)0xE897);
}
</code>```

Body:
My answer is based on @Andreas Fredriksson answer, but contains the Icon change as well:

private void Navigation_Loaded(object sender, RoutedEventArgs e)
{
      var settings = (NavigationViewItem)Navigation.SettingsItem;
      settings.Content = "Help";
      settings.Icon = new SymbolIcon((Symbol)0xE897);
}


问:
2D ARRAY (MATRIX) - Segmentation Fault (CORE DUMPED)
I have created the following program which takes user's input of an nxn array and prints it. My code has three functions namely for memory allocation for a 2D array, user data input and displaying stored data. While 1x1 to 4x4 matrix works fine, 5x5 and above matrix results in </p>

```<code>    Segmentation fault (core dumped)
</code>```

<p>Why is it so? What am I doing wrong ?
The following is my code- </p>

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

int ** allocateMemory(int, int);
void createMatrix(int **, int, int);
void displayMatrix(int **, int, int);

int main()
{
  int sizeA, sizeB;

  printf("\nMatrix type(a x b): ");
  scanf("%d %d", &sizeA, &sizeB);
  printf("You entered: %d x %d\n", sizeA, sizeB);
  int ** arrayA;

  arrayA = allocateMemory(sizeA, sizeB);
  printf("\nMATRIX A\n");
  createMatrix(arrayA, sizeA, sizeB);
  displayMatrix(arrayA, sizeA, sizeB);

  getchar();
  free(arrayA);
  printf("\n");
  return 0;
}

/*-----------------------------------------*/
/* FUNCTION TO ALLOCATE MEMORY TO AN ARRAY */
/*-----------------------------------------*/

int ** allocateMemory(int r, int c)          //r - rows, c - columns
{
  int ** ptr;
  ptr = (int **) malloc(r*sizeof(int));
  for(int i = 0; i < r; i++){
    ptr[i] = (int *) malloc(c*sizeof(int));
  }
  return ptr;
}

/*-----------------------------*/
/* FUNCTION TO CREATE A MATRIX */
/*-----------------------------*/

void createMatrix(int ** array, int r, int c)
{
  printf("\nEnter matrix values: \n");
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      scanf("%d", &array[i][j]);
    }
  }
  printf("Array Created.");
  printf("\n");
}

/*----------------------------*/
/* FUNCTION TO DISPLAY MATRIX */
/*----------------------------*/

void displayMatrix(int ** array, int r, int c)
{
  printf("\n");
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      printf("%5d  ", *(*(array + i) + j));
    }
    printf("\n");
  }
}
</code>```

答:
In allocateMemory() you have

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

That line is wrong, because you want t allocate memory for an array of pointers, so it shoud be

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

or

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

If sizeof(int) < sizeof(int *) (as it is in general on 64bit platforms) you don't allocate enough memory which invokes Undefined Behaviour. And "Undefined" means that anything might happen, including that the codes seems to run flawlessly (at least for certain values of r and c in your case)

Off topic:

you might to want to read about why you should not cast the result of malloc()

Body:
I have created the following program which takes user's input of an nxn array and prints it. My code has three functions namely for memory allocation for a 2D array, user data input and displaying stored data. While 1x1 to 4x4 matrix works fine, 5x5 and above matrix results in

    Segmentation fault (core dumped)

Why is it so? What am I doing wrong ?
The following is my code-

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

int ** allocateMemory(int, int);
void createMatrix(int **, int, int);
void displayMatrix(int **, int, int);

int main()
{
  int sizeA, sizeB;

  printf("\nMatrix type(a x b): ");
  scanf("%d %d", &sizeA, &sizeB);
  printf("You entered: %d x %d\n", sizeA, sizeB);
  int ** arrayA;

  arrayA = allocateMemory(sizeA, sizeB);
  printf("\nMATRIX A\n");
  createMatrix(arrayA, sizeA, sizeB);
  displayMatrix(arrayA, sizeA, sizeB);

  getchar();
  free(arrayA);
  printf("\n");
  return 0;
}

/*-----------------------------------------*/
/* FUNCTION TO ALLOCATE MEMORY TO AN ARRAY */
/*-----------------------------------------*/

int ** allocateMemory(int r, int c)          //r - rows, c - columns
{
  int ** ptr;
  ptr = (int **) malloc(r*sizeof(int));
  for(int i = 0; i < r; i++){
    ptr[i] = (int *) malloc(c*sizeof(int));
  }
  return ptr;
}

/*-----------------------------*/
/* FUNCTION TO CREATE A MATRIX */
/*-----------------------------*/

void createMatrix(int ** array, int r, int c)
{
  printf("\nEnter matrix values: \n");
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      scanf("%d", &array[i][j]);
    }
  }
  printf("Array Created.");
  printf("\n");
}

/*----------------------------*/
/* FUNCTION TO DISPLAY MATRIX */
/*----------------------------*/

void displayMatrix(int ** array, int r, int c)
{
  printf("\n");
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      printf("%5d  ", *(*(array + i) + j));
    }
    printf("\n");
  }
}

Body:
In allocateMemory() you have

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

That line is wrong, because you want t allocate memory for an array of pointers, so it shoud be

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

or

ptr = malloc(r*sizeof *ptr);

If sizeof(int) < sizeof(int *) (as it is in general on 64bit platforms) you don't allocate enough memory which invokes Undefined Behaviour. And "Undefined" means that anything might happen, including that the codes seems to run flawlessly (at least for certain values of r and c in your case)

Off topic:

you might to want to read about why you should not cast the result of malloc()


问:
How to switch screens from a dynamically created button in kivy recycleview

Problem

I have a screen (OrderScreen) that populates with buttons if there is data to be processed. I would like the user to click one of the buttons to be brought to another screen (MenuScreen) to process the data. While my intention is to populate the next screen with data from the button, I am currently just trying to get the ScreenManager to change to the next screen after a button press. I added a pass_data() method to the OrderButton and tried to trigger the screen manager there but self.manager.current and root.manager.current were throwing exceptions. Any help would be greatly appreciated.

recycleview_test.py

```<code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.recycleview import RecycleView
from kivy.uix.screenmanager import ScreenManager, Screen
from random import randint

class MenuScreen(Screen):
    def quit(self):
        App.get_running_app.stop()
        Window.close()

class OrderScreen(Screen):
    pass

class OrderButton(Button):
    def __init__(self, **kwargs):
        super(OrderButton, self).__init__(**kwargs)

    def pass_data(self):
        print("button pushed")

class OrderScroll(RecycleView):
    def __init__(self, **kwargs):
        super(OrderScroll, self).__init__(**kwargs)
        self.data = [{'text': str(f"Make {randint(10, 25)} items from package #{randint(1,4)}")} for x in range(12)]

class WindowManager(ScreenManager):
    pass

class RecycleApp(App):
    def build(self):
        return WindowManager()

if __name__ == "__main__":
    RecycleApp().run()
</code>```

recycle.kv

```<code>#:import Factory kivy.factory.Factory
#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
#:import App kivy.app.App

<OrderScroll>:
    viewclass: 'OrderButton'
    manager: None
    RecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        padding: 20
        spacing: 10

<OrderButton>:
    manager: None
    font_size: 32
    bold: True
    on_release:
        root.pass_data()

<WindowManager>:
    id: screen_manager
    OrderScreen:
        id: order_screen
        name: "OrderScreen"
        manager: screen_manager
    MenuScreen:
        id: menu_screen
        name: 'MenuScreen'
        manager: screen_manager

<OrderScreen>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Data Buttons"
            font_size: 64
            size_hint_y: None
            # pos_hint: {"x":0, "y":1}
            height: 200
        OrderScroll:

<MenuScreen>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Made it"
            font_size: 64
        FloatLayout:
            Button:
                text: 'Keep going'
                font_size: 48
                size_hint: .8,.5
                pos_hint: {"center_x": .5, "center_y": .1}
        FloatLayout:
            Button:
                text: 'Quit'
                size_hint: .15,.3
                pos_hint: {"center_x": .5, "center_y": .5}
                on_release:
                    root.quit()

</code>```

答:
Try to create an object of screen manager:

```<code>class RecycleApp(App):
    def build(self):
        self.sm = WindowManager()
        return self.sm
</code>```

And then access it by:

```<code>App.get_running_app().sm.current = 'MenuScreen' # in Python
app.sm.current = 'MenuScreen' # in kv
</code>```

Body:
Problem

I have a screen (OrderScreen) that populates with buttons if there is data to be processed. I would like the user to click one of the buttons to be brought to another screen (MenuScreen) to process the data. While my intention is to populate the next screen with data from the button, I am currently just trying to get the ScreenManager to change to the next screen after a button press. I added a pass_data() method to the OrderButton and tried to trigger the screen manager there but self.manager.current and root.manager.current were throwing exceptions. Any help would be greatly appreciated.

recycleview_test.py

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.recycleview import RecycleView
from kivy.uix.screenmanager import ScreenManager, Screen
from random import randint

class MenuScreen(Screen):
    def quit(self):
        App.get_running_app.stop()
        Window.close()

class OrderScreen(Screen):
    pass

class OrderButton(Button):
    def __init__(self, **kwargs):
        super(OrderButton, self).__init__(**kwargs)

    def pass_data(self):
        print("button pushed")

class OrderScroll(RecycleView):
    def __init__(self, **kwargs):
        super(OrderScroll, self).__init__(**kwargs)
        self.data = [{'text': str(f"Make {randint(10, 25)} items from package #{randint(1,4)}")} for x in range(12)]

class WindowManager(ScreenManager):
    pass

class RecycleApp(App):
    def build(self):
        return WindowManager()

if __name__ == "__main__":
    RecycleApp().run()

recycle.kv

#:import Factory kivy.factory.Factory
#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
#:import App kivy.app.App

<OrderScroll>:
    viewclass: 'OrderButton'
    manager: None
    RecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        padding: 20
        spacing: 10

<OrderButton>:
    manager: None
    font_size: 32
    bold: True
    on_release:
        root.pass_data()

<WindowManager>:
    id: screen_manager
    OrderScreen:
        id: order_screen
        name: "OrderScreen"
        manager: screen_manager
    MenuScreen:
        id: menu_screen
        name: 'MenuScreen'
        manager: screen_manager

<OrderScreen>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Data Buttons"
            font_size: 64
            size_hint_y: None
            # pos_hint: {"x":0, "y":1}
            height: 200
        OrderScroll:

<MenuScreen>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Made it"
            font_size: 64
        FloatLayout:
            Button:
                text: 'Keep going'
                font_size: 48
                size_hint: .8,.5
                pos_hint: {"center_x": .5, "center_y": .1}
        FloatLayout:
            Button:
                text: 'Quit'
                size_hint: .15,.3
                pos_hint: {"center_x": .5, "center_y": .5}
                on_release:
                    root.quit()

Body:
Try to create an object of screen manager:

class RecycleApp(App):
    def build(self):
        self.sm = WindowManager()
        return self.sm

And then access it by:

App.get_running_app().sm.current = 'MenuScreen' # in Python
app.sm.current = 'MenuScreen' # in kv


问:
Setting min-width of mat-select-panel leaves a visible animation in Angular 2+
I am trying to re-position a mat-select-panel, to be below the corresponding dropdown form-field. Using some of the code provided in here, I have been able to do that. The problem is, that upon clicking, you can see the panel change size. This behaviour is visible in the stackblitz provided in the same question and accepted answer. So far I haven't been able to find a solution.
Currently my .mat-select-panel in styles.css looks like this: </p>

```<code>.mat-select-panel {
  position: absolute;
  top: 94px;
  left: 28px;
  min-width: calc(100% + 24px) !important;
  border-radius: 0px !important;
  border-top-style: none;
}
</code>```

答:
There is jump animation added to <mat-select> by angular
  material, that's the reason it looks like width is increasing.

Simple solution is to disable animation, but I could not find a solution to disable animation on specific element/component

As said/discussed here and here

To disable animation on single elements or material components

```<code>//TS
isDisabled = true;

//HTML
<div [@.disabled]="isDisabled">
 <div [@childAnimation]="exp"></div>
</div>

<mat-form-field appearance="outline">
 <mat-select [@.disabled]="isDisabled" placeholder="Favorite food" disableOptionCentering>
  <mat-option *ngFor="let food of foods" [value]="food.value">
   {{food.viewValue}}
  </mat-option>
 </mat-select>
</mat-form-field>
</code>```

But unfortunately that doesn't work for <mat-select>

To disable animation for component

```<code>export class YourComponent {
 @HostBinding('@.disabled')
 public animationsDisabled = true;
}
</code>```

This doesn't work either.

What works is ?

Disabling animation for material cdk overlay (Include all material components) from component

```<code>import { Component, Renderer2 } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
...
overlayContainerElement: HTMLElement
constructor( private overlayContainer:OverlayContainer, private renderer:Renderer2) {
    this.overlayContainerElement = this.overlayContainer.getContainerElement();
    //To disable pass true as third argument
    this.renderer.setProperty( this.overlayContainerElement, "@.disabled", true );
}
</code>```

Note: The above code disables animation for whole application, if you want to disable animation for your specific component, simply add the above code in your component and add below code to re-enable animation.

```<code>ngOnDestroy() {
 this.renderer.setProperty( this.overlayContainerElement, "@.disabled", false );
}
</code>```

To disable animation for whole application

You can add the above code in main component (i.e., app.component.ts) or

Replace BrowserAnimationsModule with NoopAnimationsModule in app.module.ts

```<code>import { NoopAnimationsModule } from '@angular/platform-browser/animations';
...
@NgModule({
  imports:      [ NoopAnimationsModule ],
  declarations: [ ... ],
  bootstrap:    [ ... ]
})
</code>```

Working example (Animation disabled for component).

Body:
I am trying to re-position a mat-select-panel, to be below the corresponding dropdown form-field. Using some of the code provided in here, I have been able to do that. The problem is, that upon clicking, you can see the panel change size. This behaviour is visible in the stackblitz provided in the same question and accepted answer. So far I haven't been able to find a solution.
Currently my .mat-select-panel in styles.css looks like this:

.mat-select-panel {
  position: absolute;
  top: 94px;
  left: 28px;
  min-width: calc(100% + 24px) !important;
  border-radius: 0px !important;
  border-top-style: none;
}

Body:
There is jump animation added to <mat-select> by angular
  material, that's the reason it looks like width is increasing.

Simple solution is to disable animation, but I could not find a solution to disable animation on specific element/component

As said/discussed here and here

To disable animation on single elements or material components

//TS
isDisabled = true;

//HTML
<div [@.disabled]="isDisabled">
 <div [@childAnimation]="exp"></div>
</div>

<mat-form-field appearance="outline">
 <mat-select [@.disabled]="isDisabled" placeholder="Favorite food" disableOptionCentering>
  <mat-option *ngFor="let food of foods" [value]="food.value">
   {{food.viewValue}}
  </mat-option>
 </mat-select>
</mat-form-field>

But unfortunately that doesn't work for <mat-select>

To disable animation for component

export class YourComponent {
 @HostBinding('@.disabled')
 public animationsDisabled = true;
}

This doesn't work either.

What works is ?

Disabling animation for material cdk overlay (Include all material components) from component

import { Component, Renderer2 } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
...
overlayContainerElement: HTMLElement
constructor( private overlayContainer:OverlayContainer, private renderer:Renderer2) {
    this.overlayContainerElement = this.overlayContainer.getContainerElement();
    //To disable pass true as third argument
    this.renderer.setProperty( this.overlayContainerElement, "@.disabled", true );
}

Note: The above code disables animation for whole application, if you want to disable animation for your specific component, simply add the above code in your component and add below code to re-enable animation.

ngOnDestroy() {
 this.renderer.setProperty( this.overlayContainerElement, "@.disabled", false );
}

To disable animation for whole application

You can add the above code in main component (i.e., app.component.ts) or

Replace BrowserAnimationsModule with NoopAnimationsModule in app.module.ts

import { NoopAnimationsModule } from '@angular/platform-browser/animations';
...
@NgModule({
  imports:      [ NoopAnimationsModule ],
  declarations: [ ... ],
  bootstrap:    [ ... ]
})

Working example (Animation disabled for component).


问:
Does windows have same maximum path lengths (name of directory entry) for different filesystems it mounts?
I have to know if a specific vulnerablity in TCL 8.4 affects Windows platform

The vulnerability is: http://www.securityfocus.com/bid/15259/info
As per the link:

Operating systems with no difference in the maximum path lengths among differing file systems are not affected by this issue

I am using TCL on windows and want to know if this vulnerablity affects TCL on windows and how ?

Further, how can a person exploit this vulnerability on Windows ?

Thanks

答:
That article does not mention any vulnerability of systems hosted on Windows to this at all; the standard recommended size of buffer to be  allocated there is sufficiently long to hold any legal filename. This is specifically true for Tcl (Tk does not do directory scanning except via Tcl's interfaces).

Exploiting the vulnerability on Windows is going to be hard (and impossible with Tcl, which is very careful with buffer management). If you're on another platform, you are recommended to switch to a later patchlevel of Tcl; the current version is 8.4.19. (Actually, you're recommended to switch to the 8.5 series – currently 8.5.9 – as 8.4 as basically been EOLed; there will be maybe one more roll-up release on that branch but bugfixes are now only committed to 8.4 for critical things like demonstrated security issues or build-chain problems.)

Note that, since Tcl has never allocated buffers for holding a whole path directly anyway, it's not clear how this sort of thing could cause an exploit in the first place. The article does state that there is no instance of this issue in the wild.

ContentLicense: CC BY-SA 3.0


问:
Oracle PL/SQL get current timestamp number 19
Is there a way in Oralce PL/SQL to get the current timestamp as a NUMBER ?

Something like '1582185277302'

答:
If you subtract a fixed timestamp from systimestamp you get an interval:

```<code>select systimestamp - timestamp '1970-01-01 00:00:00 UTC' as diff
from dual;

DIFF
----------------------
+18312 10:05:29.674905
</code>```

You can then extract and manipulate the elements of that to get the epoch time, using an inline view or CTE to avoid repeating the interval generation:

```<code>with t (diff) as (
  select systimestamp - timestamp '1970-01-01 00:00:00 UTC'
  from dual
)
select trunc(1000 * (
    extract (day from diff) * 24 * 60 *60
      + extract (hour from diff) * 60 * 60
      + extract (minute from diff) * 60
      + extract (second from diff)
  )) as epoch
from t;

              EPOCH
-------------------
      1582193129829
</code>```

Adding all the extracts together gives you the total number of seconds, including fractions; multiplying by 1000 gives you milliseconds but will still have fractions (depending on the precision your platform supports); truncating that gives you just milliseconds.

This takes the time zone into account (epoch times are supposed to count from UTC); but doesn't allow for leap seconds.

As a further demo, using a fixed time in an arbitrary time zone to get the result in your question:

```<code>with t (diff) as (
  select timestamp '2020-02-20 02:54:37.302789 America/New_York' - timestamp '1970-01-01 00:00:00 UTC'
  from dual
)
select trunc(1000 * (
    extract (day from diff) * 24 * 60 *60
      + extract (hour from diff) * 60 * 60
      + extract (minute from diff) * 60
      + extract (second from diff)
  )) as epoch
from t;

              EPOCH
-------------------
      1582185277302
</code>```

Body:
If you subtract a fixed timestamp from systimestamp you get an interval:

select systimestamp - timestamp '1970-01-01 00:00:00 UTC' as diff
from dual;

DIFF
----------------------
+18312 10:05:29.674905

You can then extract and manipulate the elements of that to get the epoch time, using an inline view or CTE to avoid repeating the interval generation:

with t (diff) as (
  select systimestamp - timestamp '1970-01-01 00:00:00 UTC'
  from dual
)
select trunc(1000 * (
    extract (day from diff) * 24 * 60 *60
      + extract (hour from diff) * 60 * 60
      + extract (minute from diff) * 60
      + extract (second from diff)
  )) as epoch
from t;

              EPOCH
-------------------
      1582193129829

Adding all the extracts together gives you the total number of seconds, including fractions; multiplying by 1000 gives you milliseconds but will still have fractions (depending on the precision your platform supports); truncating that gives you just milliseconds.

This takes the time zone into account (epoch times are supposed to count from UTC); but doesn't allow for leap seconds.

As a further demo, using a fixed time in an arbitrary time zone to get the result in your question:

with t (diff) as (
  select timestamp '2020-02-20 02:54:37.302789 America/New_York' - timestamp '1970-01-01 00:00:00 UTC'
  from dual
)
select trunc(1000 * (
    extract (day from diff) * 24 * 60 *60
      + extract (hour from diff) * 60 * 60
      + extract (minute from diff) * 60
      + extract (second from diff)
  )) as epoch
from t;

              EPOCH
-------------------
      1582185277302


问:
JAXB ~ Dynamically parse multiple namespaces
I am trying to create an unmarshaller that will work for the following XML files:

```<code><?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd
  xml:lang="en">
  [...]
</REQ-IF>
</code>```

```<code><?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:configuration="http://eclipse.org/rmf/pror/toolextensions/1.0"
  xmlns:id="http://pror.org/presentation/id"
  xmlns:xhtml="http://www.w3.org/1999/xhtml">
  [...]
</REQ-IF>
</code>```

```<code><?xml version="1.0" encoding="UTF-8"?>
  <REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:doors="http://www.ibm.com/rdm/doors/REQIF/xmlns/1.0"
  xmlns:reqif="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:reqif-common="http://www.prostep.org/reqif"
  xmlns:reqif-xhtml="http://www.w3.org/1999/xhtml"
  xmlns:rm="http://www.ibm.com/rm"
  xmlns:rm-reqif="http://www.ibm.com/rm/reqif"
  xmlns:xhtml="http://www.w3.org/1999/xhtml"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  [...]
</REQ-IF>
</code>```

All those files are structurally the same and are based of the same top-level namespace, but also contain a variety of variable sub-level namespaces and other "things" (which by my understanding should be attributes, but are not), which need to be saved in the system.

Thus far, I have managed to get to the point where this much is saved:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd">
  [...]
</REQ-IF>
</code>```

however, my intended result would look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd
  xml:lang="en">
  [...]
</REQ-IF>
</code>```

So the top-level namespace is saved, but the sub-level namespaces and other "things" are lost in the import/export process. This is bad.

How can I save those other sub-namespaces and other "things", considering that they are dynamically generated?

Basically, what I want to say is "save all these extra attributes in any way you like while parsing the XML, and once you export the XML again, re-write them exactly as they were".

答:
Unfortunately it seems that JAXB alone is not capable of manage all the namespace prefixes dynamically and you need to combine it with another parsing mechanism.

I would try to implement something like this (only rough implementation, details below):

```<code>public class MyXmlHandler {

    XMLInputFactory xif = XMLInputFactory.newInstance();

    XMLOutputFactory xof = XMLOutputFactory.newInstance();

    XMLEventFactory xef = XMLEventFactory.newInstance();

    /**
     * Retrieve XMLEvent for root element
     */
    public StartElement getStartElement(String source) throws XMLStreamException {
        XMLEvent event;
        XMLEventReader reader = xif.createXMLEventReader(new StringReader(source));
        while (reader.hasNext()) {
            event = reader.nextEvent();
            if (event.isStartElement()) {
                return event.asStartElement();
            }
            // alternativery you can retrieve here also QNames for first level child elements
            // and return all this data in some synthetic wrapper class
        }
        return null; // alternatively throw an exception
    }

    /**
     * Write root element, than some content from JAXB elements, than end element
     */
    public void write(
        Marshaller marshaller,
        Writer writer,
        StartElement root,
        List<JAXBElement> elements
    ) throws JAXBException, XMLStreamException {
        XMLEventWriter xew = xof.createXMLEventWriter(writer);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        xew.add(root);
        for(JAXBElement element : elements) {
            marshaller.marshal(element, xew);
        }
        xew.add(xef.createEndElement(root.getName(), root.getNamespaces()));
        xew.close();
    }

}
</code>```

And use it like this:

```<code>// create JAXB context and unmarshaller
JAXBContext ctx = JAXBContext.newInstance(RootClass.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();

// unmarshall XML
JAXBElement<RootClass> element = unmarshaller.unmarshal(source, RootClass.class);
RootClass rootValue = element.getValue();

// extract root element data from XML
StartElement root = handler.getStartElement(data);

// perform some business logic

// create marshaller
Marshaller marshaller = ctx.createMarshaller();

// create list of JAXBElements for root children
List<JAXBElement> elements = new ArrayList<>();
QName qname = ... // construct qualified name or retrieve it from saved structure
// very schematic, names of the child elements depend on your implementation
elements.add(new JAXBElement(qname , rootValue.getChild().getClass(), rootValue.getChild()));
handler.write(marshaller, writer, root, elements);
</code>```

When preserving root element data, you can save also QNames for its children in some wrapper class. So far I see the REQ-IF structure contains header, core content and tool extensions. You could save QNames for all of them and then use them for constructing JAXB elements during marshalling process.

Body:
I am trying to create an unmarshaller that will work for the following XML files:

<?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd
  xml:lang="en">
  [...]
</REQ-IF>

<?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:configuration="http://eclipse.org/rmf/pror/toolextensions/1.0"
  xmlns:id="http://pror.org/presentation/id"
  xmlns:xhtml="http://www.w3.org/1999/xhtml">
  [...]
</REQ-IF>

<?xml version="1.0" encoding="UTF-8"?>
  <REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:doors="http://www.ibm.com/rdm/doors/REQIF/xmlns/1.0"
  xmlns:reqif="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:reqif-common="http://www.prostep.org/reqif"
  xmlns:reqif-xhtml="http://www.w3.org/1999/xhtml"
  xmlns:rm="http://www.ibm.com/rm"
  xmlns:rm-reqif="http://www.ibm.com/rm/reqif"
  xmlns:xhtml="http://www.w3.org/1999/xhtml"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  [...]
</REQ-IF>

All those files are structurally the same and are based of the same top-level namespace, but also contain a variety of variable sub-level namespaces and other "things" (which by my understanding should be attributes, but are not), which need to be saved in the system.

Thus far, I have managed to get to the point where this much is saved:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd">
  [...]
</REQ-IF>

however, my intended result would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd
  xml:lang="en">
  [...]
</REQ-IF>

So the top-level namespace is saved, but the sub-level namespaces and other "things" are lost in the import/export process. This is bad.

How can I save those other sub-namespaces and other "things", considering that they are dynamically generated?

Basically, what I want to say is "save all these extra attributes in any way you like while parsing the XML, and once you export the XML again, re-write them exactly as they were".

Body:
Unfortunately it seems that JAXB alone is not capable of manage all the namespace prefixes dynamically and you need to combine it with another parsing mechanism.

I would try to implement something like this (only rough implementation, details below):

public class MyXmlHandler {

    XMLInputFactory xif = XMLInputFactory.newInstance();

    XMLOutputFactory xof = XMLOutputFactory.newInstance();

    XMLEventFactory xef = XMLEventFactory.newInstance();

    /**
     * Retrieve XMLEvent for root element
     */
    public StartElement getStartElement(String source) throws XMLStreamException {
        XMLEvent event;
        XMLEventReader reader = xif.createXMLEventReader(new StringReader(source));
        while (reader.hasNext()) {
            event = reader.nextEvent();
            if (event.isStartElement()) {
                return event.asStartElement();
            }
            // alternativery you can retrieve here also QNames for first level child elements
            // and return all this data in some synthetic wrapper class
        }
        return null; // alternatively throw an exception
    }

    /**
     * Write root element, than some content from JAXB elements, than end element
     */
    public void write(
        Marshaller marshaller,
        Writer writer,
        StartElement root,
        List<JAXBElement> elements
    ) throws JAXBException, XMLStreamException {
        XMLEventWriter xew = xof.createXMLEventWriter(writer);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        xew.add(root);
        for(JAXBElement element : elements) {
            marshaller.marshal(element, xew);
        }
        xew.add(xef.createEndElement(root.getName(), root.getNamespaces()));
        xew.close();
    }

}

And use it like this:

// create JAXB context and unmarshaller
JAXBContext ctx = JAXBContext.newInstance(RootClass.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();

// unmarshall XML
JAXBElement<RootClass> element = unmarshaller.unmarshal(source, RootClass.class);
RootClass rootValue = element.getValue();

// extract root element data from XML
StartElement root = handler.getStartElement(data);

// perform some business logic

// create marshaller
Marshaller marshaller = ctx.createMarshaller();

// create list of JAXBElements for root children
List<JAXBElement> elements = new ArrayList<>();
QName qname = ... // construct qualified name or retrieve it from saved structure
// very schematic, names of the child elements depend on your implementation
elements.add(new JAXBElement(qname , rootValue.getChild().getClass(), rootValue.getChild()));
handler.write(marshaller, writer, root, elements);

When preserving root element data, you can save also QNames for its children in some wrapper class. So far I see the REQ-IF structure contains header, core content and tool extensions. You could save QNames for all of them and then use them for constructing JAXB elements during marshalling process.


问:
How to set variables in a loop with oracle?
I have a loop and a variable v_rownum and I want to set value for it:

```<code>        FOR donvi_rows IN v_donvi
        LOOP
            DECLARE
               v_rownum number;
            SELECT r
            INTO v_rownum
            FROM
            (SELECT ROWNUM AS r, k.Id
            FROM don_vi k
            WHERE k.ParentId = 1 )
            WHERE Id = donvi_rows.Id;

        END LOOP;
</code>```

But it throw a exception:

```<code>PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:

   begin function pragma procedure subtype type <an identifier>
   <a double-quoted delimited-identifier> current cursor delete
   exists prior
The symbol "begin" was substituted for "SELECT" to continue.
</code>```

I'm currently studying Oracle. I don't know much about it. Please help me to resolve my problem.

答:
Try this</p>

```<code>    FOR donvi_rows IN v_donvi
    LOOP
        DECLARE
           v_rownum number;
        BEGIN
           SELECT r
           INTO v_rownum
           FROM
           (SELECT ROWNUM AS r, k.Id
           FROM don_vi k
           WHERE k.ParentId = 1 )
           WHERE Id = donvi_rows.Id;
        END;
    END LOOP;
</code>```

Body:
I have a loop and a variable v_rownum and I want to set value for it:

        FOR donvi_rows IN v_donvi
        LOOP
            DECLARE
               v_rownum number;
            SELECT r
            INTO v_rownum
            FROM
            (SELECT ROWNUM AS r, k.Id
            FROM don_vi k
            WHERE k.ParentId = 1 )
            WHERE Id = donvi_rows.Id;

        END LOOP;

But it throw a exception:

PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:

   begin function pragma procedure subtype type <an identifier>
    current cursor delete
   exists prior
The symbol "begin" was substituted for "SELECT" to continue.

I'm currently studying Oracle. I don't know much about it. Please help me to resolve my problem.

Body:
Try this

    FOR donvi_rows IN v_donvi
    LOOP
        DECLARE
           v_rownum number;
        BEGIN
           SELECT r
           INTO v_rownum
           FROM
           (SELECT ROWNUM AS r, k.Id
           FROM don_vi k
           WHERE k.ParentId = 1 )
           WHERE Id = donvi_rows.Id;
        END;
    END LOOP;


问:
How to implement a triggerless .NET Core Console App as a continuous Azure WebJob?
All the code samples I've seen so far for Azure WebJobs rely on some kind of trigger (e.g. TimerTrigger or QueueTrigger).
I am looking specifically at WebJobs SDK 3.x, by the way.

So. For a triggerless WebJob (Windows Service-alike one), am I expected to use NoAutomaticTrigger and find a way to kickoff my "main" code manually?

Or should I resort to implementing and registering a class that implements the IHostedService interface?
So far that's the approach I'm taking but it feels more of a hack than a recommended way.
I have not even tried to deploy this code and only ran it on my local machine, so I am afraid that the publishing process will confirm my code is not suitable for Azure WebJobs in its current form.

EntryPoint.cs

This is how the application is being bootstrap when the process is starting.

using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AbcCorp.Jobs
{
    public static class Program
    {
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false)
                .Build();

            var hostBuilder = new HostBuilder()
                .ConfigureWebJobs(builder => { builder.AddAzureStorageCoreServices(); })
                .ConfigureServices(serviceCollection =>
                {
                    ConfigureServices(serviceCollection, config);
                    serviceCollection.AddHostedService<ConsoleApplication>();
                });

            using (var host = hostBuilder.Build())
                await host.RunAsync();
        }

        private static IServiceCollection ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddTransient<ConsoleApplication>();
            // ... more DI registrations
            return services;
        }
    }
}
```

<p><strong>ConsoleApplication.cs</strong></p>

<p>This would normally be implemented as a function with a trigger.
The thing is, I want this code to only run once on the process startup.
It will start listening on the service bus events using the regular <code>Microsoft.Azure.ServiceBus</code> SDK package.</p>

<pre class="lang-cs prettyprint-override"><code>using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using AbcCorp.Internal.Microsoft.Azure.ServiceBus;
using AbcCorp.Api.Messaging;

namespace AbcCorp.Jobs
{
    public sealed class ConsoleApplication: IHostedService
    {
        private readonly IReceiver<SubmissionNotification> _messageReceiver;
        private readonly MessageHandler _messageHandler;

        public ConsoleApplication(IReceiver<SubmissionNotification> messageReceiver, MessageHandler messageHandler)
        {
            _messageReceiver = messageReceiver;
            _messageHandler = messageHandler;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.StartListening(_messageHandler.HandleMessage, _messageHandler.HandleException);
            return Task.Delay(Timeout.Infinite);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.Dispose();
            return Task.CompletedTask;
        }
    }
}
</code>```

答:
So you want a console application to run in a WebJob and listen to messages. You don't really care about WebJob magic like triggers, it's just a place to run your console app. I've done the exact same thing before.

I found the IHostedService abstraction to be very helpful, but I didn't like their SDK. I found it bloated and hard to use. I didn't want to take a large dependency in order use a large array of special magic Azure stuff, when all I wanted to do was run a console application in a WebJob for now, and maybe move it elsewhere later.

So I ended just deleting that dependency, stealing the Shutdown code from the SDK and writing my own Service Host. The result is on my Github Repo azure-webjob-host. Feel free to use it or raid it for ideas. I don't know, maybe if I did it again I'd have another attempt at getting the SDK to work, but I present this is a bit of an alternative to the SDK.

Basically I wrote an IServiceHost not too different from yours (except that StartAsync exited when stuff started instead of just hanging). Then I wrote my own service host, which is basically just a loop:

```<code>await _service.StartAsync(cancellationToken);
while (!token.IsCancellationRequested){await Task.Delay(1000);}
await _service.StopAsync(default);
</code>```

Then I stole the WebJobsShutdownWatcher code from their repo.

Then I created an IServiceHost that started my message handler. (I was using Rabbit, which has nothing to do with triggers or azure stuff)

```<code>public class MessagingService : IHostedService, IDisposable
{
    public MessagingService(ConnectionSettings connectionSettings,
        AppSubscriberSettings subscriberSettings,
        MessageHandlerTypeMapping[] messageHandlerTypeMappings,
        ILogger<MessagingService> logger)
    {
        ....
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        await Task.WhenAll(subscribers.Value.Select(s => s.StartSubscriptionAsync()));
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        ...
    }

    public void Dispose()
    {
        ...
    }
}
</code>```

Then I put that all together into something like this:

```<code>IHostedService myService = new MyService();

using (var host = new ServiceHostBuilder().HostService(myService))
{
    await host.RunAsync(default);
}
</code>```

Body:
All the code samples I've seen so far for Azure WebJobs rely on some kind of trigger (e.g. TimerTrigger or QueueTrigger).
I am looking specifically at WebJobs SDK 3.x, by the way.

So. For a triggerless WebJob (Windows Service-alike one), am I expected to use NoAutomaticTrigger and find a way to kickoff my "main" code manually?

Or should I resort to implementing and registering a class that implements the IHostedService interface?
So far that's the approach I'm taking but it feels more of a hack than a recommended way.
I have not even tried to deploy this code and only ran it on my local machine, so I am afraid that the publishing process will confirm my code is not suitable for Azure WebJobs in its current form.

EntryPoint.cs

This is how the application is being bootstrap when the process is starting.

using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AbcCorp.Jobs
{
    public static class Program
    {
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false)
                .Build();

            var hostBuilder = new HostBuilder()
                .ConfigureWebJobs(builder => { builder.AddAzureStorageCoreServices(); })
                .ConfigureServices(serviceCollection =>
                {
                    ConfigureServices(serviceCollection, config);
                    serviceCollection.AddHostedService<ConsoleApplication>();
                });

            using (var host = hostBuilder.Build())
                await host.RunAsync();
        }

        private static IServiceCollection ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddTransient<ConsoleApplication>();
            // ... more DI registrations
            return services;
        }
    }
}

ConsoleApplication.cs

This would normally be implemented as a function with a trigger.
The thing is, I want this code to only run once on the process startup.
It will start listening on the service bus events using the regular Microsoft.Azure.ServiceBus SDK package.

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using AbcCorp.Internal.Microsoft.Azure.ServiceBus;
using AbcCorp.Api.Messaging;

namespace AbcCorp.Jobs
{
    public sealed class ConsoleApplication: IHostedService
    {
        private readonly IReceiver<SubmissionNotification> _messageReceiver;
        private readonly MessageHandler _messageHandler;

        public ConsoleApplication(IReceiver<SubmissionNotification> messageReceiver, MessageHandler messageHandler)
        {
            _messageReceiver = messageReceiver;
            _messageHandler = messageHandler;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.StartListening(_messageHandler.HandleMessage, _messageHandler.HandleException);
            return Task.Delay(Timeout.Infinite);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.Dispose();
            return Task.CompletedTask;
        }
    }
}

Body:
So you want a console application to run in a WebJob and listen to messages. You don't really care about WebJob magic like triggers, it's just a place to run your console app. I've done the exact same thing before.

I found the IHostedService abstraction to be very helpful, but I didn't like their SDK. I found it bloated and hard to use. I didn't want to take a large dependency in order use a large array of special magic Azure stuff, when all I wanted to do was run a console application in a WebJob for now, and maybe move it elsewhere later.

So I ended just deleting that dependency, stealing the Shutdown code from the SDK and writing my own Service Host. The result is on my Github Repo azure-webjob-host. Feel free to use it or raid it for ideas. I don't know, maybe if I did it again I'd have another attempt at getting the SDK to work, but I present this is a bit of an alternative to the SDK.

Basically I wrote an IServiceHost not too different from yours (except that StartAsync exited when stuff started instead of just hanging). Then I wrote my own service host, which is basically just a loop:

await _service.StartAsync(cancellationToken);
while (!token.IsCancellationRequested){await Task.Delay(1000);}
await _service.StopAsync(default);

Then I stole the WebJobsShutdownWatcher code from their repo.

Then I created an IServiceHost that started my message handler. (I was using Rabbit, which has nothing to do with triggers or azure stuff)

public class MessagingService : IHostedService, IDisposable
{
    public MessagingService(ConnectionSettings connectionSettings,
        AppSubscriberSettings subscriberSettings,
        MessageHandlerTypeMapping[] messageHandlerTypeMappings,
        ILogger<MessagingService> logger)
    {
        ....
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        await Task.WhenAll(subscribers.Value.Select(s => s.StartSubscriptionAsync()));
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        ...
    }

    public void Dispose()
    {
        ...
    }
}

Then I put that all together into something like this:

IHostedService myService = new MyService();

using (var host = new ServiceHostBuilder().HostService(myService))
{
    await host.RunAsync(default);
}


问:
How i can getDatabaseName in Phinx?
I am using Phinx to migrate.
https://github.com/cakephp/phinx

Now i want to use the name of my database in some special query in Migration file, the database name is specified depending on the enviroment in the phinx-config file.

```<code>    return [
    'paths' => [
        'migrations' => './database/migrations',
        'seeds' => './database/seeds',
    ],
    'environments' => [
        'default_migration_table' => 'phinxlog',
        'default_database' => 'development',
        'development' => [
            'adapter' => 'mysql',
            'host' => ,
            'name' => ,
            'user' => ,
            'pass' => ,
            'port' => 3306,
            'charset' => 'utf8',
        ],
    ],
];
</code>```

I have found in the scope of the project some line

```<code>$output->writeln('<info>using database</info> ' . $envOptions['name']);
</code>```

based in the vendor\robmorgan\phinx\src\Phinx\Console\Command\Migrate.php

If i start the command there is an message witch calls the cli the correct database.
How i can use this $envOptions in my migrations file?

I am missing something like getConfig().

答:
You can access environment config params like $this->getAdapter()->getOption('<paramKey>'); inside your migration:

```<code><?php

use Phinx\Migration\AbstractMigration;

/**
 * Class InnoDB
 */
class SomeMigration extends AbstractMigration
{
    /**
     * Up
     */
    public function change()
    {
        //returns the field "name" from environment config
        $dbName = $this->getAdapter()->getOption('name');
    }
}
</code>```

Title: How i can getDatabaseName in Phinx?

Body:
I am using Phinx to migrate.
https://github.com/cakephp/phinx

Now i want to use the name of my database in some special query in Migration file, the database name is specified depending on the enviroment in the phinx-config file.

    return [
    'paths' => [
        'migrations' => './database/migrations',
        'seeds' => './database/seeds',
    ],
    'environments' => [
        'default_migration_table' => 'phinxlog',
        'default_database' => 'development',
        'development' => [
            'adapter' => 'mysql',
            'host' => ,
            'name' => ,
            'user' => ,
            'pass' => ,
            'port' => 3306,
            'charset' => 'utf8',
        ],
    ],
];

I have found in the scope of the project some line

$output->writeln('<info>using database</info> ' . $envOptions['name']);

based in the vendor\robmorgan\phinx\src\Phinx\Console\Command\Migrate.php

If i start the command there is an message witch calls the cli the correct database.
How i can use this $envOptions in my migrations file?

I am missing something like getConfig().

Body:
You can access environment config params like $this->getAdapter()->getOption('<paramKey>'); inside your migration:

<?php

use Phinx\Migration\AbstractMigration;

/**
 * Class InnoDB
 */
class SomeMigration extends AbstractMigration
{
    /**
     * Up
     */
    public function change()
    {
        //returns the field "name" from environment config
        $dbName = $this->getAdapter()->getOption('name');
    }
}


问:
How can I animate my less from "display: block" to "display: none"?
I have a less file that hide and display an element like the following:

```<code>.cmp-accordion__panel {
      &--hidden {
      display: none;
   }

   &--expanded {
     display: block;
     -webkit-animation: slide-down 0.5s ease-out;
     -moz-animation: slide-down 0.5s ease-out;
  }
}

@-webkit-keyframes slide-down {
  0% {
    opacity: 0;
    -webkit-transform: translateY(-5%);
 }
100% {
  opacity: 1;
  -webkit-transform: translateY(0);
   }
}

@-moz-keyframes slide-down {
0% {
  opacity: 0;
  -moz-transform: translateY(-5%);
  }
  100% {
   opacity: 1;
  -moz-transform: translateY(0);
   }
}
</code>```

In my JavaScript, I toggle the class name of the element between "cmp-accordion__panel--hidden" and "cmp-accordion__panel--expanded" if the event is triggered. I use keyframe and opacity to animate the transition from "display:none" to "display:block".

However, when I go from "display:block" to "display:none" to hide the element, the effect happens INSTANTLY. What should I add to animate the hiding?

答:
As already said, is not possible animate or transition from display:block; to display: none; but this could be simulated in another way and is not necessary to use CSS animations, simply CSS transitions (in addition, is not necessary anymore to use vendor-prefixes to declare transitions or animations).

Please, look at this working example:

HTML (I inserted a fake content to create an element with a relative big height)

```<code><div class="cmp-accordion__panel--expanded">
  b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b
</div>
</code>```

LESS

```<code>[class*="cmp-accordion__panel"] {
  border:solid 1px red;
  overflow:hidden;
  transition:opacity 0.3s ease-out, max-height 0.8s ease-out;
}

.cmp-accordion__panel {
   &--hidden {
      max-height:0;
      opacity:0;
   }

   &--expanded {
     opacity:1;
     max-height:1000px;
  }
}
</code>```

Please note that, thanks to attribute partial value selector I added also some rules that apply to both *--hidden and *--expanded classes (I personally prefer a general class and an addition of a second one in some cases, instead of switching between two, but I did not want to change too much your approach).

The key rule is switching between two values of max-height property, from a 0 value to another "enough big" one. If you effectively know final height of the element you can simply use also height property, but in case of dynamic content, max-height did the trick.

Please note also the presence of overflow:hidden; applied to both classes, to simulate height changes.

Finally, animation effect relies only on a CSS transition applied to opacity and max-height properties, with different timings to enhance effect.

Body:
I have a less file that hide and display an element like the following:

.cmp-accordion__panel {
      &--hidden {
      display: none;
   }

   &--expanded {
     display: block;
     -webkit-animation: slide-down 0.5s ease-out;
     -moz-animation: slide-down 0.5s ease-out;
  }
}

@-webkit-keyframes slide-down {
  0% {
    opacity: 0;
    -webkit-transform: translateY(-5%);
 }
100% {
  opacity: 1;
  -webkit-transform: translateY(0);
   }
}

@-moz-keyframes slide-down {
0% {
  opacity: 0;
  -moz-transform: translateY(-5%);
  }
  100% {
   opacity: 1;
  -moz-transform: translateY(0);
   }
}

In my JavaScript, I toggle the class name of the element between "cmp-accordion__panel--hidden" and "cmp-accordion__panel--expanded" if the event is triggered. I use keyframe and opacity to animate the transition from "display:none" to "display:block".

However, when I go from "display:block" to "display:none" to hide the element, the effect happens INSTANTLY. What should I add to animate the hiding?

Body:
As already said, is not possible animate or transition from display:block; to display: none; but this could be simulated in another way and is not necessary to use CSS animations, simply CSS transitions (in addition, is not necessary anymore to use vendor-prefixes to declare transitions or animations).

Please, look at this working example:

HTML (I inserted a fake content to create an element with a relative big height)

<div class="cmp-accordion__panel--expanded">
  b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b
</div>

LESS

[class*="cmp-accordion__panel"] {
  border:solid 1px red;
  overflow:hidden;
  transition:opacity 0.3s ease-out, max-height 0.8s ease-out;
}

.cmp-accordion__panel {
   &--hidden {
      max-height:0;
      opacity:0;
   }

   &--expanded {
     opacity:1;
     max-height:1000px;
  }
}

Please note that, thanks to attribute partial value selector I added also some rules that apply to both *--hidden and *--expanded classes (I personally prefer a general class and an addition of a second one in some cases, instead of switching between two, but I did not want to change too much your approach).

The key rule is switching between two values of max-height property, from a 0 value to another "enough big" one. If you effectively know final height of the element you can simply use also height property, but in case of dynamic content, max-height did the trick.

Please note also the presence of overflow:hidden; applied to both classes, to simulate height changes.

Finally, animation effect relies only on a CSS transition applied to opacity and max-height properties, with different timings to enhance effect.


问:
Bootstrap Navbar Dropdown Menu Items Right
As you see in the picture below, when I click on the bell icon, a dropdown menu appears at the bottom-right of the icon. I want this dropdown menu to appear at bottom-left instead of bottom-right. What should I do?

      ...

```

答:
I Chaned it by add dir="rtl"

```<code><div class="dropdown-menu " dir="rtl" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item " href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <a class="dropdown-item" href="#">Something else here</a>
</div>
</code>```

Body:
I Chaned it by add dir="rtl"

<div class="dropdown-menu " dir="rtl" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item " href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <a class="dropdown-item" href="#">Something else here</a>
</div>


问:
Simultaneous operation of groupby and resample on pandas dataframe?
My pandas dataframe consists of a categorical column JOB_TITLE, a numeric column BASE_SALARY and a datetime index JOIN_DATE. I'd like to perform an aggregation over the groups of the categorical and downsampled datetimes as follows:

```<code># Resampled at frequency of start data of every 5 years
mean_agg = (df
          .groupby('JOB_TITLE')
          .resample('5AS')['BASE_SALARY']
          .mean())
</code>```

Unfortunately, as the groupby operation is occurring before the resample, the resample operation is performed independently for each JOB_TITLE group. This results in following Series:

```<code>| JOB_TITLE         | JOIN_DATE  |       |
|-------------------|------------|-------|
| Data Scientist    | 2004-01-01 | 60000 |
|                   | 2009-01-01 | 75000 |
|                   | 2014-01-01 | 90000 |
|                   |            |       |
| Software Engineer | 2001-01-01 | 70000 |
|                   | 2006-01-01 | 85000 |
|                   | 2011-01-01 | 90000 |
|                   | 2016-01-01 | 85000 |
</code>```

As you can see the indexes at JOIN_DATE level for Data Scientist group and Software Engineer are not aligned. This creates a problem when you apply unstack for level JOB_TITLE as follows:

```<code>mean_agg.unstack('JOB_TITLE')
</code>```

This results in the following dataframe:

```<code>| JOB_TITLE  | Data Scientist | Software Engineer |
|------------|----------------|-------------------|
| JOIN_DATE  |                |                   |
| 2001-01-01 | NaN            | 70000             |
| 2004-01-01 | 60000          | NaN               |
| 2006-01-01 | NaN            | 85000             |
| 2009-01-01 | 75000          | NaN               |
| 2011-01-01 | NaN            | 70000             |
| 2014-01-01 | 90000          | NaN               |
| 2016-01-01 | NaN            | 85000             |
</code>```

How can I avoid this sequential operation of groupby and resample and instead perform a simultaneous operation? Thanks!

答:
You can either use .reset_index() </p>

```<code>day = pd.Grouper(freq='D')
df.set_index('JOIN_DATE').groupby(['JOB_TITLE', day]).BASE_SALARY.mean()
</code>```

<p>...or use the key argument in pd.Grouper</p>

```<code>day = pd.Grouper(key='JOIN_DATE', freq='D')
df.groupby(['JOB_TITLE', day]).BASE_SALARY.mean()
</code>```

Body:
My pandas dataframe consists of a categorical column JOB_TITLE, a numeric column BASE_SALARY and a datetime index JOIN_DATE. I'd like to perform an aggregation over the groups of the categorical and downsampled datetimes as follows:

# Resampled at frequency of start data of every 5 years
mean_agg = (df
          .groupby('JOB_TITLE')
          .resample('5AS')['BASE_SALARY']
          .mean())

Unfortunately, as the groupby operation is occurring before the resample, the resample operation is performed independently for each JOB_TITLE group. This results in following Series:

| JOB_TITLE         | JOIN_DATE  |       |
|-------------------|------------|-------|
| Data Scientist    | 2004-01-01 | 60000 |
|                   | 2009-01-01 | 75000 |
|                   | 2014-01-01 | 90000 |
|                   |            |       |
| Software Engineer | 2001-01-01 | 70000 |
|                   | 2006-01-01 | 85000 |
|                   | 2011-01-01 | 90000 |
|                   | 2016-01-01 | 85000 |

As you can see the indexes at JOIN_DATE level for Data Scientist group and Software Engineer are not aligned. This creates a problem when you apply unstack for level JOB_TITLE as follows:

mean_agg.unstack('JOB_TITLE')

This results in the following dataframe:

| JOB_TITLE  | Data Scientist | Software Engineer |
|------------|----------------|-------------------|
| JOIN_DATE  |                |                   |
| 2001-01-01 | NaN            | 70000             |
| 2004-01-01 | 60000          | NaN               |
| 2006-01-01 | NaN            | 85000             |
| 2009-01-01 | 75000          | NaN               |
| 2011-01-01 | NaN            | 70000             |
| 2014-01-01 | 90000          | NaN               |
| 2016-01-01 | NaN            | 85000             |

How can I avoid this sequential operation of groupby and resample and instead perform a simultaneous operation? Thanks!

Body:
You can either use .reset_index()

day = pd.Grouper(freq='D')
df.set_index('JOIN_DATE').groupby(['JOB_TITLE', day]).BASE_SALARY.mean()

...or use the key argument in pd.Grouper

day = pd.Grouper(key='JOIN_DATE', freq='D')
df.groupby(['JOB_TITLE', day]).BASE_SALARY.mean()


问:
Explain surprising number of timers and finding their origin
I have a CPU leak somewhere and am trying to find out the origin (the RAM increases a bit too but not as fast).

I have collected some data through dotnet-counters and found out that the number of timers in the given process keeps increasing. For instance, when 46 % of the CPU was used, it was reporting around 450 timers (see following data). Note that this count only increases, slowly but surely like my CPU usage. And also note that it's pretty much at a time where it was idle, not having customers online.

This leads to 2 questions:

1) Is it normal? Should I continue on this track? I find it odd to have this many timers.

2) In my own code, I never user the Timer class, I use the Stopwatch class once but that's it.

So what would be the best way to find the class/library that uses those timers?

答:
1) There was indeed something fishy and it is definitely not normal.

I had a class spawning hundreds of threads and keeping them alive to listen to incoming calls.

Long story short, that many timers is not something normal.

2) The Timer was coming from somewhere deep in a library. I couldn't find an easy way to find them.

Best option is to use dotnet-trace collect. https://www.speedscope.app/ helped me a lot and it is possible to generate de traces for speedscope directly from dotnet-trace.


问:
Memoization of a recursive function in Javascript
I have this recursive function that takes in an array of deck cards and finds the index of the certain card:

```<code>const getCardIndex = (deck, fullCardName) => fullCardName === deck[0] ? 52 - deck.length : getCardIndex(deck.splice(1), fullCardName)

const deck = 'Ace of Hearts, Ace of Diamonds, Ace of Clubs, Ace of Spades, Two of Hearts, Two of Diamonds, Two of Clubs, Two of Spades, Three of Hearts, Three of Diamonds, Three of Clubs, Three of Spades, Four of Hearts, Four of Diamonds, Four of Clubs, Four of Spades, Five of Hearts, Five of Diamonds, Five of Clubs, Five of Spades, Six of Hearts, Six of Diamonds, Six of Clubs, Six of Spades, Seven of Hearts, Seven of Diamonds, Seven of Clubs, Seven of Spades, Eight of Hearts, Eight of Diamonds, Eight of Clubs, Eight of Spades, Nine of Hearts, Nine of Diamonds, Nine of Clubs, Nine of Spades, Ten of Hearts, Ten of Diamonds, Ten of Clubs, Ten of Spades, Jack of Hearts, Jack of Diamonds, Jack of Clubs, Jack of Spades, Queen of Hearts, Queen of Diamonds, Queen of Clubs, Queen of Spades, King of Hearts, King of Diamonds, King of Clubs, King of Spades'.split(', ')

const result = getCardIndex(deck, 'King of Spades')

console.log(result)
</code>```

Is there any way it can be sped-up, i.e. using memoization?

答:
For a solution that identifies the solutions in advance (O(52) = O(1)) and then can look up solutions in a single operation, ditch the recursive function, turn the deck into an object, whose keys are card names and values are card indicies, and then just look up the card property on the object:

const deck = 'Ace of Hearts, Ace of Diamonds, Ace of Clubs, Ace of Spades, Two of Hearts, Two of Diamonds, Two of Clubs, Two of Spades, Three of Hearts, Three of Diamonds, Three of Clubs, Three of Spades, Four of Hearts, Four of Diamonds, Four of Clubs, Four of Spades, Five of Hearts, Five of Diamonds, Five of Clubs, Five of Spades, Six of Hearts, Six of Diamonds, Six of Clubs, Six of Spades, Seven of Hearts, Seven of Diamonds, Seven of Clubs, Seven of Spades, Eight of Hearts, Eight of Diamonds, Eight of Clubs, Eight of Spades, Nine of Hearts, Nine of Diamonds, Nine of Clubs, Nine of Spades, Ten of Hearts, Ten of Diamonds, Ten of Clubs, Ten of Spades, Jack of Hearts, Jack of Diamonds, Jack of Clubs, Jack of Spades, Queen of Hearts, Queen of Diamonds, Queen of Clubs, Queen of Spades, King of Hearts, King of Diamonds, King of Clubs, King of Spades'.split(', ')
const deckObj = Object.fromEntries(deck.map((str, i) => [str, i]));

console.log(deckObj['King of Spades'])
console.log(deckObj['Ace of Diamonds'])
console.log(deckObj['Queen of Diamonds'])```

Body:
I have this recursive function that takes in an array of deck cards and finds the index of the certain card:

const getCardIndex = (deck, fullCardName) => fullCardName === deck[0] ? 52 - deck.length : getCardIndex(deck.splice(1), fullCardName)

const deck = 'Ace of Hearts, Ace of Diamonds, Ace of Clubs, Ace of Spades, Two of Hearts, Two of Diamonds, Two of Clubs, Two of Spades, Three of Hearts, Three of Diamonds, Three of Clubs, Three of Spades, Four of Hearts, Four of Diamonds, Four of Clubs, Four of Spades, Five of Hearts, Five of Diamonds, Five of Clubs, Five of Spades, Six of Hearts, Six of Diamonds, Six of Clubs, Six of Spades, Seven of Hearts, Seven of Diamonds, Seven of Clubs, Seven of Spades, Eight of Hearts, Eight of Diamonds, Eight of Clubs, Eight of Spades, Nine of Hearts, Nine of Diamonds, Nine of Clubs, Nine of Spades, Ten of Hearts, Ten of Diamonds, Ten of Clubs, Ten of Spades, Jack of Hearts, Jack of Diamonds, Jack of Clubs, Jack of Spades, Queen of Hearts, Queen of Diamonds, Queen of Clubs, Queen of Spades, King of Hearts, King of Diamonds, King of Clubs, King of Spades'.split(', ')

const result = getCardIndex(deck, 'King of Spades')

console.log(result)

Is there any way it can be sped-up, i.e. using memoization?


问:
bash: print a dynamic variable using dynamic name
In a for, I have the following:

```<code>COUNT="1"
GEOZONE[1]="EU"
declare -A CLIENTS_"${GEOZONE[$COUNT]}"="client1 client2"
</code>```

At this point, if I would like to print ${CLIENTS_EU} it works, but how to print that by using the GEOZONE array?

I got bad substitution while trying to:

```<code>~ $ echo ${CLIENTS_${GEOZONE[$COUNT]}}
bash: ${CLIENTS_${GEOZONE[$COUNT]}}: bad substitution
</code>```

And I got EU while trying to:

```<code>~ $ echo $CLIENTS_${GEOZONE[$COUNT]}
EU
</code>```

I would like to get client1 client2

Thanks

答:
You need to create a separate variable that will hold composite variable name:

```<code># ccomposte variable name
var=CLIENTS_"${GEOZONE[$COUNT]}"

# assign value
declare $var="client1 client2"

# print it
echo "${!var}"
</code>```

```<code>client1 client2
</code>```

Body:
In a for, I have the following:

COUNT="1"
GEOZONE[1]="EU"
declare -A CLIENTS_"${GEOZONE[$COUNT]}"="client1 client2"

At this point, if I would like to print ${CLIENTS_EU} it works, but how to print that by using the GEOZONE array?

I got bad substitution while trying to:

~ $ echo ${CLIENTS_${GEOZONE[$COUNT]}}
bash: ${CLIENTS_${GEOZONE[$COUNT]}}: bad substitution

And I got EU while trying to:

~ $ echo $CLIENTS_${GEOZONE[$COUNT]}
EU

I would like to get client1 client2

Thanks

Body:
You need to create a separate variable that will hold composite variable name:

# ccomposte variable name
var=CLIENTS_"${GEOZONE[$COUNT]}"

# assign value
declare $var="client1 client2"

# print it
echo "${!var}"

client1 client2


问:
Xpath: Get Text After Element With Containing Text
I am looking for a way to get text which is not inside an HTML element:

```<code><div class="col-sm-4">
  <strong>Handelnde Personen:</strong><br><br>
  <strong>Geschäftsführer</strong><br>
  Mr John Doe<br>
  Privatperson<br>
  .....<br>
  <br>
</code>```

I want to get "Mr John Doe".

The only way I see is looking for a strong element which contains "Geschäftsführer" and then look for the following text.

My idea so far:

//strong[contains(text(), 'Gesch')]/br/../text()

... I simply can't make it work.

Also, is there a "wildcard" for strings? That I could use

```<code>*esch*ftsf*hr*
</code>```

for "Geschäftsführer"?

I highly appreciate your help, thanks!

答:
Try

```<code>//strong[starts-with(., 'Gesch')]/following-sibling::text()[1]
</code>```

As for wildcard matching, with XPath 2.0 you use regular expressions:

```<code>//strong[matches(., '.*esch.*ftsf.*hr.*')]
</code>```

With XPath 3.0 you could also use the Unicode collation algorithm

```<code>//strong[compare(., 'Geschäftsführer',
  'http://www.w3.org/2013/collation/UCA?strength=primary') = 0]
</code>```

(strength=primary ignores case and accents)

But to get anything more advanced than XPath 1.0 in the browser, you would need to deploy Saxon-JS.

Another option with 1.0 is to use translate() to remove case and umlauts:

```<code>//strong[translate(., 'ABCD..XYZÄÖÜäöüß', 'abcd..xyzaouaous') = 'geschaftsfuhrer']
</code>```

Note, in all these examples I have used "." rather than "text()" to get the string value of an element - this is recommended practice.

Body:
I am looking for a way to get text which is not inside an HTML element:

  Handelnde Personen:

  Geschäftsführer

  Mr John Doe

  Privatperson

  .....

I want to get "Mr John Doe".

The only way I see is looking for a strong element which contains "Geschäftsführer" and then look for the following text.

My idea so far:

//strong[contains(text(), 'Gesch')]/br/../text()

... I simply can't make it work.

Also, is there a "wildcard" for strings? That I could use

*esch*ftsf*hr*

for "Geschäftsführer"?

I highly appreciate your help, thanks!

Body:
Try

//strong[starts-with(., 'Gesch')]/following-sibling::text()[1]

As for wildcard matching, with XPath 2.0 you use regular expressions:

//strong[matches(., '.*esch.*ftsf.*hr.*')]

With XPath 3.0 you could also use the Unicode collation algorithm

//strong[compare(., 'Geschäftsführer',
  'http://www.w3.org/2013/collation/UCA?strength=primary') = 0]

(strength=primary ignores case and accents)

But to get anything more advanced than XPath 1.0 in the browser, you would need to deploy Saxon-JS.

Another option with 1.0 is to use translate() to remove case and umlauts:

//strong[translate(., 'ABCD..XYZÄÖÜäöüß', 'abcd..xyzaouaous') = 'geschaftsfuhrer']

Note, in all these examples I have used "." rather than "text()" to get the string value of an element - this is recommended practice.


问:
Is there a command to check if Git Bash is opened in Administrator mode?
Let's say you opened a Git Bash console and used it for a time but you forgot if you opened it as Administrator or not.

Is there a way to check this in the current console, without closing and opening it again?

答:
My PS1 environmental variable looks like this:

```<code>\[\033]0;$TITLEPREFIX:$PWD\007\]\n\[\033[32m\]\u@\h \[\033[35m\]$MSYSTEM \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n$
</code>```

So off the back of the answer from @daveloyall. I've put this into my .bash_profile

```<code>if [[ $(sfc 2>&1 | tr -d '\0') =~ SCANNOW ]]; then
    export TITLEPREFIX='ADMIN'
fi
</code>```

This then prefixes the window title with ADMIN if you've opened git-bash as administrator.

Body:
My PS1 environmental variable looks like this:

\[\033]0;$TITLEPREFIX:$PWD\007\]\n\[\033[32m\]\u@\h \[\033[35m\]$MSYSTEM \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n$

So off the back of the answer from @daveloyall. I've put this into my .bash_profile

if [[ $(sfc 2>&1 | tr -d '\0') =~ SCANNOW ]]; then
    export TITLEPREFIX='ADMIN'
fi

This then prefixes the window title with ADMIN if you've opened git-bash as administrator.


问:
Android: Clear old activity instance from history stack
I have the following simple scenario:

One Activity called ListCarsActivity.kt where list of cars are displayed. When the user click on the FloatingActionButton, it opens another activity called AddCarActivity.kt

When the user click on the Add Car button, I start a new intent to go to the initial activity ListCarsActivity.kt where the added car is now displayed.

Problem: From now, when I click on the Back button, the ListCarsActivity is displayed a second time.

How to clear the old entry of ListCarsActivity from the History stack?

答:
You should run AddCarActivity with startActivityForResult method, and then you have to set result with setResult method in AddCarActivity which returns you to ListCarsActivity without starting it again

Official documentation:
https://developer.android.com/training/basics/intents/result

https://developer.android.com/reference/android/app/Activity#setResult(int,%20android.content.Intent)