问:
Visual Studio 2015 NodeJS/Typescript overwriting node startup file
I keep getting the following error:

```<code>Error Code: TS5055
Cannot write file C:/project/dir/server.js' because it would overwrite input file.
Project: TypeScript/JavaScript Virtual Projects
</code>```

I even tried changing my entry filename to nodeserver.js and after a while I get the same error:

```<code>Error Code: TS5055
Cannot write file C:/project/dir/nodeserver.js' because it would overwrite input file.
Project: TypeScript/JavaScript Virtual Projects
</code>```

How can I find out what component is trying to overwrite it?

I did notice the file has the BuildAction set to Compile and 'Publish' to true. Could this be the cause? What is the implication of turning off Compile for a .js file? Will I not get any error checking?

Config Files

My tsconfig.json

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "isolatedModules": false,
    "jsx": "react"
  },
  "exclude": [
    "node_modules",
    "public",
    "server.js",
    "Scripts/typings/main",
    "Scripts/typings/main.d.ts"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./src/**/*.tsx"
  ]
}
</code>```

My package.json

```<code>{
  "name": "contract-vs-paye-calc-type-script",
  "version": "0.0.0",
  "description": "ContractVsPayeCalcTypeScript",
  "scripts": {
    "start": "node nodeserver.js",
    "lint": "eslint src"
  },
  "main": "/src/App.js",
  "author": {
    "name": "MC",
    "email": "admin@admin.com"
  },
  "dependencies": {
    "babel-core": "^6.7.7",
    "babel-loader": "^6.2.4",
    "express": "3.4.4",
    "jade": "*",
    "react": "^15.0.1",
    "react-dom": "^15.0.1",
    "react-hot-loader": "^1.3.0",
    "stylus": "*",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1"
  },
  "module": {
    "loaders": [
      {
        "test": "/\\.ts(x?)$/",
        "loader": "babel-loader!ts-loader"
      }
    ]
  }
}
</code>```

答:
It seems that typescript compiler tries to transpile everything, including files that are already javascript. The solution is to add a new field outDir, to the compilerOptions, so it looks like this:

```<code>{
    ...
    "compilerOptions": {
        ...
        "outDir": "generated"
    }
    ...
}
</code>```

Body:
I keep getting the following error:

Error Code: TS5055
Cannot write file C:/project/dir/server.js' because it would overwrite input file.
Project: TypeScript/JavaScript Virtual Projects

I even tried changing my entry filename to nodeserver.js and after a while I get the same error:

Error Code: TS5055
Cannot write file C:/project/dir/nodeserver.js' because it would overwrite input file.
Project: TypeScript/JavaScript Virtual Projects

How can I find out what component is trying to overwrite it?

I did notice the file has the BuildAction set to Compile and 'Publish' to true. Could this be the cause? What is the implication of turning off Compile for a .js file? Will I not get any error checking?

Config Files

My tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "isolatedModules": false,
    "jsx": "react"
  },
  "exclude": [
    "node_modules",
    "public",
    "server.js",
    "Scripts/typings/main",
    "Scripts/typings/main.d.ts"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./src/**/*.tsx"
  ]
}

My package.json

{
  "name": "contract-vs-paye-calc-type-script",
  "version": "0.0.0",
  "description": "ContractVsPayeCalcTypeScript",
  "scripts": {
    "start": "node nodeserver.js",
    "lint": "eslint src"
  },
  "main": "/src/App.js",
  "author": {
    "name": "MC",
    "email": "admin@admin.com"
  },
  "dependencies": {
    "babel-core": "^6.7.7",
    "babel-loader": "^6.2.4",
    "express": "3.4.4",
    "jade": "*",
    "react": "^15.0.1",
    "react-dom": "^15.0.1",
    "react-hot-loader": "^1.3.0",
    "stylus": "*",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1"
  },
  "module": {
    "loaders": [
      {
        "test": "/\\.ts(x?)$/",
        "loader": "babel-loader!ts-loader"
      }
    ]
  }
}

Body:
It seems that typescript compiler tries to transpile everything, including files that are already javascript. The solution is to add a new field outDir, to the compilerOptions, so it looks like this:

{
    ...
    "compilerOptions": {
        ...
        "outDir": "generated"
    }
    ...
}


来源: stackexchange

问:
Stop fadeToggle() from building up
When I hover over what I want fading in and out too many times, then it keeps repeating itself. Even when I stop hovering it. How can I stop this?</p>

```<code>$(".featured").hover(function(){
    $(this).find("h3").fadeToggle(800);
   });
</code>```

答:
You need to call .stop()

```<code>$(this).find("h3").stop(true, true).fadeToggle(800);
</code>```

Parameters indicate: clearQueue, jumpToEnd

This will almost immediately stop the current animation. To have a more smooth stopping, you should call .stop(true, false)

Another way I can think of is to check whether the element is animated or not:

```<code>$(".featured").hover(function(){
    var $h3 = $(this).find('h3');

    if(!$h3.is(':animated') )
        $h3.fadeToggle(800);
});
</code>```

Reference: .stop(), :animated selector

ContentLicense: CC BY-SA 2.5

Title: Stop fadeToggle() from building up

Body:
When I hover over what I want fading in and out too many times, then it keeps repeating itself. Even when I stop hovering it. How can I stop this?

$(".featured").hover(function(){
    $(this).find("h3").fadeToggle(800);
   });

Body:
You need to call .stop()

$(this).find("h3").stop(true, true).fadeToggle(800);

Parameters indicate: clearQueue, jumpToEnd

This will almost immediately stop the current animation. To have a more smooth stopping, you should call .stop(true, false)

Another way I can think of is to check whether the element is animated or not:

$(".featured").hover(function(){
    var $h3 = $(this).find('h3');

    if(!$h3.is(':animated') )
        $h3.fadeToggle(800);
});

Reference: .stop(), :animated selector


问:
Zoom with animation in current location when map loads in IOS
I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.

My code is this:

```<code>-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
</code>```

Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.

I have also tested it in real device but it does not show my location.

The maps looks like that when loads:

ViewController class code:

```<code>@property BOOL updateUserLocation;
@property(strong,nonatomic) CLLocation *userLocation;

@property (nonatomic, retain) MKPolyline *routeLine;

@property (nonatomic, retain) MKPolylineView *routeLineView;

@property (nonatomic,retain) NSString *latitude;

@property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
 [[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;

locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}
</code>```

答:
You can call this method and zoom on map</p>

```<code> CLLocationCoordinate2D zoomLocation;
    zoomLocation.latitude = ; // your latitude value
        zoomLocation.longitude=  // your longitude value
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.18; // change as per your zoom level
    span.longitudeDelta=0.18;
    region.span=span;
    region.center= zoomLocation;
    [mapview setRegion:region animated:TRUE];
    [mapview regionThatFits:region];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have used map in my view controller but when the maps loads it shows me view of the whole country. I want to show my current location view when maps loads, for that I have used didUpdateUserLocation method and set delegate for it.

My code is this:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   [self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}

Now when my map loads it animate and zoom but in wrong location. It is taking me to any location in sea when map loads , but my current location is different.

I have also tested it in real device but it does not show my location.

The maps looks like that when loads:

ViewController class code:

@property BOOL updateUserLocation;
@property(strong,nonatomic) CLLocation *userLocation;

@property (nonatomic, retain) MKPolyline *routeLine;

@property (nonatomic, retain) MKPolylineView *routeLineView;

@property (nonatomic,retain) NSString *latitude;

@property (nonatomic,retain) NSString *longitude;
- (void)viewDidLoad {
[super viewDidLoad];
 [[self navigationController] setNavigationBarHidden:YES animated:YES];
_AlertView.hidden=YES;
_distanceView.hidden=YES;
self.mapView.zoomEnabled=YES;

locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

[self.mapView setShowsUserLocation:YES];
[self.mapView setDelegate:self];

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[self.mapView setRegion:MKCoordinateRegionMake(_userLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)) animated:YES];
}

Body:
You can call this method and zoom on map

 CLLocationCoordinate2D zoomLocation;
    zoomLocation.latitude = ; // your latitude value
        zoomLocation.longitude=  // your longitude value
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.18; // change as per your zoom level
    span.longitudeDelta=0.18;
    region.span=span;
    region.center= zoomLocation;
    [mapview setRegion:region animated:TRUE];
    [mapview regionThatFits:region];


问:
how to handle empty JSON responses?
```<code>[]
</code>```

this is the JSON response i'm getting when calling a webservice. i need to print nothing to show if the response is empty.

```<code>$http({
        method:'POST',
        url: 'http://xxxxxx',
        headers: {
           Content-Type: 'application/json',
           Accept: 'application/json'
        },
        data: JSON.stringify(x)
}).then(function (response) {
        $scope.details=response.data;
        if($scope.invoiceDetails == null){
           console.log("nothing to show");
        }
    });
</code>```

This is the code i'm using now. But it is not working. Someone please give me some suggestions.

答:
You can use something like this</p>

```<code>if (response.data.length === 0)
{
    console.log("nothing to show");
}
</code>```

Title: how to handle empty JSON responses?

Body:
[]

this is the JSON response i'm getting when calling a webservice. i need to print nothing to show if the response is empty.

$http({
        method:'POST',
        url: 'http://xxxxxx',
        headers: {
           Content-Type: 'application/json',
           Accept: 'application/json'
        },
        data: JSON.stringify(x)
}).then(function (response) {
        $scope.details=response.data;
        if($scope.invoiceDetails == null){
           console.log("nothing to show");
        }
    });

This is the code i'm using now. But it is not working. Someone please give me some suggestions.

Body:
You can use something like this

if (response.data.length === 0)
{
    console.log("nothing to show");
}


问:
Measuring code coverage java using protractor e2e test
There are a two projects one of them is written java is a backend code one of them is angular typescript frontend codes. i wrote e2e tests in the frontend project. now i want to measuring backend code coverage using this e2e test please help</p>

答:
Code Coverage is a measurement of how many lines/blocks/arcs of your code are executed while the automated tests are running.

Search online code coverage tools that can help you, protractor is just end to end testing tool, you need another tool for code coverage.


问:
Load Kendo Grid in Kendo Window
I want to open Kendo Grid in Kendo Window. My Kendo window code is like this.

```<code>   $("#Dialog").kendoWindow({
            title: "Add",
            modal: true
        });

        var dialog = $("#Dialog").data("kendoWindow");
        dialog.center().open();
</code>```

I want to open kendo grid in window. I am not passing any values to the window.
When Opening the window, I want to read data from database and populate the grid. How can I do this ? Can I use Partial View for the Grid and Load in Kendo Window ?

答:
Create an Empty Div where you can render your grid. Have the visibility hidden

```<code><div id="Dialog" style="display:none;">
</div>
</code>```

Create a Kendo Window and unhide the div whenever you want.

```<code>document.getElementById("Dialog").style.display = "block";
$("#Dialog").kendoWindow({
    visible: false,
    modal: true,
    actions: ["Minimize", "Close"],
    title: "Select an Enterprise",
    width: "400px",
    visible: false
});
var _dialog = $("#Dialog").data("kendoWindow");
_dialog.center().open();
</code>```

Make an Ajax call to the controller and render the output in the earlier mentioned Div

```<code>$.ajax({
 url: RootUrl + 'Controller/ActionMethod',
 type: 'POST',
 contentType: 'application/json;',
 data: JSON.stringify({ Property: Value }),
 async: false,
 success: function (data) {
    document.getElementById("Dialog").innerHTML = data;
}
});
</code>```

In the Controller, return a partial View that would contain your grid

```<code>public ActionResult ActionMethod()
{
   return PartialView("PartialViewName");
}
</code>```

Title: Load Kendo Grid in Kendo Window

Body:
I want to open Kendo Grid in Kendo Window. My Kendo window code is like this.

   $("#Dialog").kendoWindow({
            title: "Add",
            modal: true
        });

        var dialog = $("#Dialog").data("kendoWindow");
        dialog.center().open();

I want to open kendo grid in window. I am not passing any values to the window.
When Opening the window, I want to read data from database and populate the grid. How can I do this ? Can I use Partial View for the Grid and Load in Kendo Window ?

Body:
Create an Empty Div where you can render your grid. Have the visibility hidden

<div id="Dialog" style="display:none;">
</div>

Create a Kendo Window and unhide the div whenever you want.

document.getElementById("Dialog").style.display = "block";
$("#Dialog").kendoWindow({
    visible: false,
    modal: true,
    actions: ["Minimize", "Close"],
    title: "Select an Enterprise",
    width: "400px",
    visible: false
});
var _dialog = $("#Dialog").data("kendoWindow");
_dialog.center().open();

Make an Ajax call to the controller and render the output in the earlier mentioned Div

$.ajax({
 url: RootUrl + 'Controller/ActionMethod',
 type: 'POST',
 contentType: 'application/json;',
 data: JSON.stringify({ Property: Value }),
 async: false,
 success: function (data) {
    document.getElementById("Dialog").innerHTML = data;
}
});

In the Controller, return a partial View that would contain your grid

public ActionResult ActionMethod()
{
   return PartialView("PartialViewName");
}


答:
You are checking some other variable in your if condition.</p>

```<code>  $http({ method:'POST',
                url: 'http://xxxxxx',
                headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
                },
                data: JSON.stringify(x)
                 }).then(function (response) {

     $scope.details=response.data;

    if(!$scope.details){
    console.log("nothing to show");
    }

    OR
    //if your details is an array
    if(!$scope.details || $scope.details.length <= 0){
    console.log("nothing to show");
    }

    //You can also check for empty objects like this
    if(angular.equals({}, $scope.items)){
    console.log("nothing to show");
    }
</code>```

Title: how to handle empty JSON responses?

Body:
You are checking some other variable in your if condition.

  $http({ method:'POST',
                url: 'http://xxxxxx',
                headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
                },
                data: JSON.stringify(x)
                 }).then(function (response) {

     $scope.details=response.data;

    if(!$scope.details){
    console.log("nothing to show");
    }

    OR
    //if your details is an array
    if(!$scope.details || $scope.details.length <= 0){
    console.log("nothing to show");
    }

    //You can also check for empty objects like this
    if(angular.equals({}, $scope.items)){
    console.log("nothing to show");
    }


问:
Check the count of column value is equal to one based on condition in sql server
I have two tables

Student

```<code>StudentId    |  StudentName
----------   |  --------------
1            |  John
2            |  Susan
3            |  Andy
4            |  Joe
</code>```

Department

```<code>StudentId    |    DepartmentId
----------   |    ------------
1            |    123
1            |    234
2            |    123
2            |    456
3            |    123
4            |    456
</code>```

Each student can be in multiple departments but I have to find those students which are only in one department like student 3 and 4

Any help?

答:
Try this,</p>

```<code>SELECT st.StudentId, St.StudentName
FROM student st
     JOIN Department dep ON dep.StudentId = st.StudentId
GROUP BY st.StudentId
HAVING COUNT(dep.DepartmentId) = 1;
</code>```

Body:
I have two tables

Student

StudentId    |  StudentName
----------   |  --------------
1            |  John
2            |  Susan
3            |  Andy
4            |  Joe

Department

StudentId    |    DepartmentId
----------   |    ------------
1            |    123
1            |    234
2            |    123
2            |    456
3            |    123
4            |    456

Each student can be in multiple departments but I have to find those students which are only in one department like student 3 and 4

Any help?

Body:
Try this,

SELECT st.StudentId, St.StudentName
FROM student st
     JOIN Department dep ON dep.StudentId = st.StudentId
GROUP BY st.StudentId
HAVING COUNT(dep.DepartmentId) = 1;


问:
Retrieve Number of JMS Message retry
I am using JMS Queue, and MDB which listen to it.
I have a retry mechanism, so when exception is being thrown a rollback to the transaction will occur and the operation will re-executed/

I would like to achieve the Message_retry_number, each time "onMessage" being executed, so I can write the current execution retry number.
I heard I can retrieve it through the Header of the message object, but couldn't find anything in the properties or in the net.

anyone has any clue?

Thanks,
ray.

答: The only standard way to do this is be having a look at the JMSXDeliveryCount property. However you should be aware that the JMS specification states that JMS defined properties (those starting with JMSX) are optional - so it depends on your specific provider whether this property is supported, and set in every case.</p>

Title: Retrieve Number of JMS Message retry


问:
Display content from DIV
I have the two text button Main Folder & Second Folder using the  tag inside the div element.

```<code><div class="zf-folder">
   <!-- another div elements -->
      <a href="#mainTab" aria-controls="mainTab" role="tab" data-toggle="tab">Main Folder</a>
   <!-- another div elements -->
</div>
</code>```

Unfortunately, I have to click the text to move tabs, can't use the button (div) column to display the content.

How can I display tab content not only from text, but can from clicking on div element.

Please help me, I give a lot of code on JSFiddle.

Thanks in advance

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._tabFolder {
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: rgba(255, 255, 255, 0.2)
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._sideFolder {
  background-color: none;
  height: 90%;
  left: 0;
  position: absolute;
  top: 2px;
  width: 5px
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -437px -21px;
  height: 24px;
  position: relative;
  width: 24px
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

._icon-col {
  height: 16px;
  left: 4px;
  position: absolute;
  top: 4px;
  width: 16px
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

              Main Folder

              Second Folder

Main Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button th:id="${off.id}" class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

Second Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

```

答:
You can add a span inside your link:

```<code><a href="#mainTab" aria-controls="mainTab" role="tab" data-toggle="tab">
   Main Folder
      <span class="hyperspan"></span>
</a>
</code>```

And CSS:

```<code>.hyperspan
{
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}
</code>```

Title: Display content from DIV

Body:
I have the two text button Main Folder & Second Folder using the  tag inside the div element.

      Main Folder

Unfortunately, I have to click the text to move tabs, can't use the button (div) column to display the content.

How can I display tab content not only from text, but can from clicking on div element.

Please help me, I give a lot of code on JSFiddle.

Thanks in advance

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});

._tabFolder {
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: rgba(255, 255, 255, 0.2)
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._sideFolder {
  background-color: none;
  height: 90%;
  left: 0;
  position: absolute;
  top: 2px;
  width: 5px
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -437px -21px;
  height: 24px;
  position: relative;
  width: 24px
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

._icon-col {
  height: 16px;
  left: 4px;
  position: absolute;
  top: 4px;
  width: 16px
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

              Main Folder

              Second Folder

Main Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button th:id="${off.id}" class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

Second Folder

            Name
            Start Date
            End Date
            Leave Type
            Remarks
            Status
            Operation

            ...
            ...
            ...
            ...
            ...
            ...

              <input hidden="hidden" name="offId" th:value="${off.id}" />
              <button th:id="${off.id}" class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

Body:
You can add a span inside your link:

<a href="#mainTab" aria-controls="mainTab" role="tab" data-toggle="tab">
   Main Folder
      <span class="hyperspan"></span>
</a>

And CSS:

.hyperspan
{
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}


问:
Overriding C++ STL allocator function to wrap it as threadsafe
My legacy C++ codebase is failing in a multithreaded execution scenario when two threads are concurrently tries to allocate memory for STL vector. The stacktrace of two threads are given below.

```<code>-----------------  lwp# 4 / thread# 4  --------------------
 00136e10 allocate__t24__default_alloc_template2b0i0Ui (4, 4, 0, 0, 0, 0) + a4
 0015ee80 allocate__t12simple_alloc2ZP12ReconInitRecZt24__default_alloc_template2b0i0Ui (1, 0, 0, 0
, 0, 0) + 20
 0015da24 _M_allocate__t18_Vector_alloc_base3ZP12ReconInitRecZt9allocator1ZP12ReconInitRecb1Ui (86f
204, 1, 0, 0, 0, 0) + 10
 0014f438 _M_insert_aux__t6vector2ZP12ReconInitRecZt9allocator1ZP12ReconInitRecPP12ReconInitRecRCP1
2ReconInitRec (86f204, 0, fbe7fd04, 0, 0, 0) + cc
 0015f0a8 push_back__t6vector2ZP12ReconInitRecZt9allocator1ZP12ReconInitRecRCP12ReconInitRec (86f20
4, fbe7fd04, 0, 0, 0, 0) + 5c
 0015dbc0 push_back__t26ReconListOfRecFromMMapFile1ZP12ReconInitRecRCP12ReconInitRec (86f1f0, fbe7f
d04, 0, 0, fc551200, ff120400) + 28
 0017ca48 preprocess__8ReconCmpRCt26ReconListOfRecFromMMapFile1ZP12ReconInitRecb (86f160, 975100, 0
, b4, b4, 1) + 268
<<other stacktrace details truncated>>
. . . .
 ff1494f0 _lwp_start (0, 0, 0, 0, 0, 0)
-----------------  lwp# 5 / thread# 5  --------------------
 ff14d1e4 _lwp_kill (6, 0, ff1b5010, ff12c928, ffffffff, 6) + 8
 ff0c1bac abort    (1f2b24, 1, 264ae4, ee930, ff1b34d8, 0) + 110
 001f2ca8 corehandler__7CdrSigsi (a, 0, fbaff4a8, 1, fedb2c40, cb4) + 184
 ff14961c __sighndlr (a, 0, fbaff4a8, 1f2b24, 0, 1) + c
 ff13dce8 call_user_handler (a, 0, 4, 0, fc551a00, fbaff4a8) + 3b8
 ff13ded0 sigacthandler (a, 0, fbaff4a8, 0, 0, 0) + 60
 --- called from signal handler with signal 10 (SIGBUS) ---
 00136e10 allocate__t24__default_alloc_template2b0i0Ui (8, 8, fbaffa38, 2d, 0, 0) + a4
 00126300 allocate__t12simple_alloc2Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc
_template2b0i0Zt24__default_alloc_template2b0i0Ui (2, 4, ffffffff, fbaffa38, 2d, 80808080) + 20
 00126338 _M_allocate__t18_Vector_alloc_base3Zt12basic_string3ZcZt18string_char_traits1ZcZt24__defa
ult_alloc_template2b0i0Zt9allocator1Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc
_template2b0i0b1Ui (86f2a0, 2, 2d, fbaffa65, fbaffa65, 1) + 10
 00133768 _M_insert_aux__t6vector2Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_t
emplate2b0i0Zt9allocator1Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_template2b
0i0Pt12basic_string3ZcZt18string_char_traits1ZcZt24__defa (86f2a0, 8730b4, fbaffa20, fcbf4062, fbaf
fa65, 7fffffd2) + fc
 00157808 push_back__t6vector2Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_templ
ate2b0i0Zt9allocator1Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_template2b0i0R
Ct12basic_string3ZcZt18string_char_traits1ZcZt24__default (86f2a0, fbaffa20, 7ffffc00, fcbf4062, 1c
, 2d) + 5c
 002064b8 getFiles__7ListDirb (86f280, 0, 253800, 4, 1c00, 1d3c) + 12c
<<other stacktrace details truncated>>
. . . .
</code>```

From the stacktrace, it shows that concurrent call to allocate__t24__default_alloc_template2b0i0Ui i.e. __default_alloc_template<false, 0>::allocate(unsigned int) is failing as this is not thread-safe.
This allocate function is being called by the function

```<code>simple_alloc<X, __default_alloc_template<false, 0> >::allocate(unsi
gned int)
</code>```

that in turn is called by

```<code>_Vector_alloc_base<X, allocator<X>, true>::_M_allocate
(unsigned int)
</code>```

I would like to override one of these three functions, fpr overriding C++ STL allocator function to wrap it as threadsafe protected under mutual exclusion guarantee.
Please advise.

答:
You should synchronize your access to the containers instead of making the containers thread safe! It will end up in a nightmare if you try to reinvent the wheel. There is not only the insert and remove operations, but also element copy and shifting and also the concurrent operation on the stored elements.

In fact, I believe your design is broken and the container allocators only show that your application has design flaws.

BTW: Maybe you can use already implemented thread safe containers, instead of reinventing the wheel:

http://libcds.sourceforge.net/

http://www.boost.org/doc/libs/1_55_0/doc/html/lockfree.html

Remark: I never used them and can not say anything about robustness or other quality issues.

Body:
My legacy C++ codebase is failing in a multithreaded execution scenario when two threads are concurrently tries to allocate memory for STL vector. The stacktrace of two threads are given below.

-----------------  lwp# 4 / thread# 4  --------------------
 00136e10 allocate__t24__default_alloc_template2b0i0Ui (4, 4, 0, 0, 0, 0) + a4
 0015ee80 allocate__t12simple_alloc2ZP12ReconInitRecZt24__default_alloc_template2b0i0Ui (1, 0, 0, 0
, 0, 0) + 20
 0015da24 _M_allocate__t18_Vector_alloc_base3ZP12ReconInitRecZt9allocator1ZP12ReconInitRecb1Ui (86f
204, 1, 0, 0, 0, 0) + 10
 0014f438 _M_insert_aux__t6vector2ZP12ReconInitRecZt9allocator1ZP12ReconInitRecPP12ReconInitRecRCP1
2ReconInitRec (86f204, 0, fbe7fd04, 0, 0, 0) + cc
 0015f0a8 push_back__t6vector2ZP12ReconInitRecZt9allocator1ZP12ReconInitRecRCP12ReconInitRec (86f20
4, fbe7fd04, 0, 0, 0, 0) + 5c
 0015dbc0 push_back__t26ReconListOfRecFromMMapFile1ZP12ReconInitRecRCP12ReconInitRec (86f1f0, fbe7f
d04, 0, 0, fc551200, ff120400) + 28
 0017ca48 preprocess__8ReconCmpRCt26ReconListOfRecFromMMapFile1ZP12ReconInitRecb (86f160, 975100, 0
, b4, b4, 1) + 268
<<other stacktrace details truncated>>
. . . .
 ff1494f0 _lwp_start (0, 0, 0, 0, 0, 0)
-----------------  lwp# 5 / thread# 5  --------------------
 ff14d1e4 _lwp_kill (6, 0, ff1b5010, ff12c928, ffffffff, 6) + 8
 ff0c1bac abort    (1f2b24, 1, 264ae4, ee930, ff1b34d8, 0) + 110
 001f2ca8 corehandler__7CdrSigsi (a, 0, fbaff4a8, 1, fedb2c40, cb4) + 184
 ff14961c __sighndlr (a, 0, fbaff4a8, 1f2b24, 0, 1) + c
 ff13dce8 call_user_handler (a, 0, 4, 0, fc551a00, fbaff4a8) + 3b8
 ff13ded0 sigacthandler (a, 0, fbaff4a8, 0, 0, 0) + 60
 --- called from signal handler with signal 10 (SIGBUS) ---
 00136e10 allocate__t24__default_alloc_template2b0i0Ui (8, 8, fbaffa38, 2d, 0, 0) + a4
 00126300 allocate__t12simple_alloc2Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc
_template2b0i0Zt24__default_alloc_template2b0i0Ui (2, 4, ffffffff, fbaffa38, 2d, 80808080) + 20
 00126338 _M_allocate__t18_Vector_alloc_base3Zt12basic_string3ZcZt18string_char_traits1ZcZt24__defa
ult_alloc_template2b0i0Zt9allocator1Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc
_template2b0i0b1Ui (86f2a0, 2, 2d, fbaffa65, fbaffa65, 1) + 10
 00133768 _M_insert_aux__t6vector2Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_t
emplate2b0i0Zt9allocator1Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_template2b
0i0Pt12basic_string3ZcZt18string_char_traits1ZcZt24__defa (86f2a0, 8730b4, fbaffa20, fcbf4062, fbaf
fa65, 7fffffd2) + fc
 00157808 push_back__t6vector2Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_templ
ate2b0i0Zt9allocator1Zt12basic_string3ZcZt18string_char_traits1ZcZt24__default_alloc_template2b0i0R
Ct12basic_string3ZcZt18string_char_traits1ZcZt24__default (86f2a0, fbaffa20, 7ffffc00, fcbf4062, 1c
, 2d) + 5c
 002064b8 getFiles__7ListDirb (86f280, 0, 253800, 4, 1c00, 1d3c) + 12c
<<other stacktrace details truncated>>
. . . .

From the stacktrace, it shows that concurrent call to allocate__t24__default_alloc_template2b0i0Ui i.e. __default_alloc_template<false, 0>::allocate(unsigned int) is failing as this is not thread-safe.
This allocate function is being called by the function

simple_alloc<X, __default_alloc_template<false, 0> >::allocate(unsi
gned int)

that in turn is called by

_Vector_alloc_base<X, allocator<X>, true>::_M_allocate
(unsigned int)

I would like to override one of these three functions, fpr overriding C++ STL allocator function to wrap it as threadsafe protected under mutual exclusion guarantee.
Please advise.


问:
Using Qt libraries on VS
I am trying to build a C++ project on VS. The project was developed using NetBeans in a Linux machine and now I am using Visual Studio 2017 on Windows.

It wasn't developed using Qt Creatos so the libraries has been added manually with sentences like:

```<code>#include <QtCore>
#include <QCoreApplication>
#include <QObject>
#include <QStringList>
#include <QMap>
...
</code>```

This is what I did so far:

Downloaded the last Qt release

Unpacked everything in C:\Qt

In VS properties > VC++ Directories > Include directories - I added C:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include and C:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore

In VS properties > VC++ Directories > Library directories - I added C:\Qt\Qt5.9.2\5.9.2\msvc2017_64\lib

However, when I try to #include <QtCore> it seems like VS expects something more:
https://imgur.com/a/ruSbi

but it doesn't compile.

```<code>Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0020   identifier "QEvent" is undefined        c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractanimation.h 121
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractstate.h 73
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractstate.h 74
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractstate.h 76
Error (active)  E1455   member function declared with 'override' does not override a base class member      c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstracttransition.h    105
Error (active)  E1455   member function declared with 'override' does not override a base class member  c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qanimationgroup.h    70
Error (active)  E1455   member function declared with 'override' does not override a base class member  c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qcoreapplication.h   190
Error (active)  E0020   identifier "qint8" is undefined c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qdatastream.h    147
Error (active)  E0020   identifier "qint8" is undefined c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qdatastream.h    163
Error (active)  E0260   explicit type is missing ('int' assumed)    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0801   "qint8" is not a class or function template name in the current scope   c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0065   expected a ';'  c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0020   identifier "qint8" is undefined c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qeventloop.h 79
Error (active)  E1455   member function declared with 'override' does not override a base class member
...
</code>```

So, I guess I'm missing something. I am new with VS, so I would appreciate any help.

Thank you

答:
QtCore is both a directory and an include file:

```<code>Directory: <Qt_Install_Path>/include/QtCore
File:      <Qt_Install_Path>/include/QtCore/QtCore
</code>```

Also you need to run the Qt moc on every header that contains the Q_OBJECT macro. The moc will generate extra C++ files, which you need to compile. It is fairly straightforward when using tools like qmake or cmake. For VS you might wan to use Qt Visual Studio Add-in.

Title: Using Qt libraries on VS

Body:
I am trying to build a C++ project on VS. The project was developed using NetBeans in a Linux machine and now I am using Visual Studio 2017 on Windows.

It wasn't developed using Qt Creatos so the libraries has been added manually with sentences like:

#include <QtCore>
#include <QCoreApplication>
#include <QObject>
#include <QStringList>
#include <QMap>
...

This is what I did so far:

Downloaded the last Qt release

Unpacked everything in C:\Qt

In VS properties > VC++ Directories > Include directories - I added C:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include and C:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore

In VS properties > VC++ Directories > Library directories - I added C:\Qt\Qt5.9.2\5.9.2\msvc2017_64\lib

However, when I try to #include <QtCore> it seems like VS expects something more:
https://imgur.com/a/ruSbi

but it doesn't compile.

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0020   identifier "QEvent" is undefined        c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractanimation.h 121
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractstate.h 73
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractstate.h 74
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstractstate.h 76
Error (active)  E1455   member function declared with 'override' does not override a base class member      c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qabstracttransition.h    105
Error (active)  E1455   member function declared with 'override' does not override a base class member  c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qanimationgroup.h    70
Error (active)  E1455   member function declared with 'override' does not override a base class member  c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qcoreapplication.h   190
Error (active)  E0020   identifier "qint8" is undefined c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qdatastream.h    147
Error (active)  E0020   identifier "qint8" is undefined c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qdatastream.h    163
Error (active)  E0260   explicit type is missing ('int' assumed)    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0801   "qint8" is not a class or function template name in the current scope   c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0065   expected a ';'  c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0020   identifier "qint8" is undefined c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qendian.h    236
Error (active)  E0020   identifier "QEvent" is undefined    c:\Qt\Qt5.9.2\5.9.2\msvc2017_64\include\QtCore\qeventloop.h 79
Error (active)  E1455   member function declared with 'override' does not override a base class member
...

So, I guess I'm missing something. I am new with VS, so I would appreciate any help.

Thank you

Body:
QtCore is both a directory and an include file:

Directory: <Qt_Install_Path>/include/QtCore
File:      <Qt_Install_Path>/include/QtCore/QtCore

Also you need to run the Qt moc on every header that contains the Q_OBJECT macro. The moc will generate extra C++ files, which you need to compile. It is fairly straightforward when using tools like qmake or cmake. For VS you might wan to use Qt Visual Studio Add-in.


问:
Stored procedure
```<code>  String path= "Translator.txt";
       String file=" LOAD DATA LOCAL INFILE '" + path +
                            "' INTO TABLE Translator " +
                            " FIELDS TERMINATED BY \',\' ENCLOSED BY \'\"'" +
                            " LINES TERMINATED BY \'\\n\'";
</code>```

Is the following code above, a stored procedure?

答:
Store procedure is like which inputs some values and return data back , Or some insert , update , delete operations done by it. So yes there will be a query for store procedure. </p>

<p>This is a simple string statement. </p>

Title: Stored procedure

Body:
  String path= "Translator.txt";
       String file=" LOAD DATA LOCAL INFILE '" + path +
                            "' INTO TABLE Translator " +
                            " FIELDS TERMINATED BY \',\' ENCLOSED BY \'\"'" +
                            " LINES TERMINATED BY \'\\n\'";

Is the following code above, a stored procedure?

Body:
Store procedure is like which inputs some values and return data back , Or some insert , update , delete operations done by it. So yes there will be a query for store procedure.

This is a simple string statement.


问:
Android: Coloring part of a string using TextView.setText()?
I am looking to change the text of a TextView view via the .setText("") method while also coloring a part of the text (or making it bold, italic, transparent, etc.)and not the rest. For example:

```<code>title.setText("Your big island <b>ADVENTURE!</b>";
</code>```

I know the above code is incorrect but it helps illustrate what I would like to achieve. How would I do this?

答:
```<code>public static void setColorForPath(Spannable spannable, String[] paths, int color) {
    for (int i = 0; i < paths.length; i++) {
        int indexOfPath = spannable.toString().indexOf(paths[i]);
        if (indexOfPath == -1) {
            continue;
        }
        spannable.setSpan(new ForegroundColorSpan(color), indexOfPath,
                indexOfPath + paths[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
</code>```

Using

```<code>Spannable spannable = new SpannableString("Your big island ADVENTURE");
Utils.setColorForPath(spannable, new String[] { "big", "ADVENTURE" }, Color.BLUE);

textView.setText(spannable);
</code>```

Body:
I am looking to change the text of a TextView view via the .setText("") method while also coloring a part of the text (or making it bold, italic, transparent, etc.)and not the rest. For example:

title.setText("Your big island ADVENTURE!";

I know the above code is incorrect but it helps illustrate what I would like to achieve. How would I do this?

Body:
public static void setColorForPath(Spannable spannable, String[] paths, int color) {
    for (int i = 0; i < paths.length; i++) {
        int indexOfPath = spannable.toString().indexOf(paths[i]);
        if (indexOfPath == -1) {
            continue;
        }
        spannable.setSpan(new ForegroundColorSpan(color), indexOfPath,
                indexOfPath + paths[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

Using

Spannable spannable = new SpannableString("Your big island ADVENTURE");
Utils.setColorForPath(spannable, new String[] { "big", "ADVENTURE" }, Color.BLUE);

textView.setText(spannable);

ContentLicense: CC BY-SA 4.0


问:
java - find all combinations of given numbers in a given array size and store into matrix
I am looking a way to create a matrix[][] in public static void main (String[] args), the purpose of the matrix[][]
is store  data[] in static void combinationUtil(), the original class permutation is output like

1 2 3 4

1 2 3 5

1 2 4 5

1 3 4 5

2 3 4 5

what I need to to is create the matrix[][] output is the same like class permutation, it is just like

```<code>public static void main (String[] args) {

    matrix[][]=data[] ;

    for(int i=0,i<5;i++){

        for(int j=0,j<5;j++){

            System.out.print(matrix[i][j]);

        }
        System.out.println();
    }
</code>```

the original class:

```<code>class permutation {

    static void combinationUtil(int arr[], int data[], int start, int end,int index, int r)
    {
        if (index == r)
        {
            for (int j=0; j<r; j++)
            {
                System.out.print(data[j]+" ");
            }
            System.out.println("");
            return;
        }

        for (int i=start; i<=end && end-i+1 >= r-index; i++)
        {
            data[index] = arr[i];
            combinationUtil(arr, data, i+1, end, index+1, r);
        }
    }

    public static void main (String[] args) {
        int arr[] = {1, 2, 3, 4, 5};
        int r = 4;
        int n = arr.length;
        int data[]=new int[r];
        int start=0,end=n-1,index=0;
        combinationUtil(arr, data, start, end, index, r);
    }
}
</code>```

答:
Using this code you can find the possible combinations for any known input array and sequence length. Its not that basic to understand but it is the only real solution that is non-recursive as far as i know. Hope this helps. :)  </p>

```<code>public static void main(String[] args) {

     int[] input = {1, 2, 3, 4, 5};    // input array
     int k = 4;                             // sequence length

     List<int[]> subsets = new ArrayList<>();

     int[] s = new int[k];                  // here we'll keep indices
                                            // pointing to elements in input array

     if (k <= input.length) {
         // first index sequence: 0, 1, 2, ...
         for (int i = 0; (s[i] = i) < k - 1; i++);
         subsets.add(getSubset(input, s));
         for(;;) {
             int i;
             // find position of item that can be incremented
             for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
             if (i < 0) {
                 break;
             }
             s[i]++;                    // increment this item
             for (++i; i < k; i++) {    // fill up remaining items
                 s[i] = s[i - 1] + 1;
             }
             subsets.add(getSubset(input, s));
         }
     }
        System.out.println(Arrays.deepToString(subsets.toArray()));

}

    // generate actual subset by index sequence
   static int[] getSubset(int[] input, int[] subset) {
        int[] result = new int[subset.length];
        for (int i = 0; i < subset.length; i++)
            result[i] = input[subset[i]];
        return result;
    }

  }

  Outputs:
  [1, 2, 3, 4]
  [1, 2, 3, 5]
  [1, 2, 4, 5]
  [1, 3, 4, 5]
  [2, 3, 4, 5]
</code>```

Body:
I am looking a way to create a matrix[][] in public static void main (String[] args), the purpose of the matrix[][]
is store  data[] in static void combinationUtil(), the original class permutation is output like

1 2 3 4

1 2 3 5

1 2 4 5

1 3 4 5

2 3 4 5

what I need to to is create the matrix[][] output is the same like class permutation, it is just like

public static void main (String[] args) {

    matrix[][]=data[] ;

    for(int i=0,i<5;i++){

        for(int j=0,j<5;j++){

            System.out.print(matrix[i][j]);

        }
        System.out.println();
    }

the original class:

class permutation {

    static void combinationUtil(int arr[], int data[], int start, int end,int index, int r)
    {
        if (index == r)
        {
            for (int j=0; j<r; j++)
            {
                System.out.print(data[j]+" ");
            }
            System.out.println("");
            return;
        }

        for (int i=start; i<=end && end-i+1 >= r-index; i++)
        {
            data[index] = arr[i];
            combinationUtil(arr, data, i+1, end, index+1, r);
        }
    }

    public static void main (String[] args) {
        int arr[] = {1, 2, 3, 4, 5};
        int r = 4;
        int n = arr.length;
        int data[]=new int[r];
        int start=0,end=n-1,index=0;
        combinationUtil(arr, data, start, end, index, r);
    }
}

Body:
Using this code you can find the possible combinations for any known input array and sequence length. Its not that basic to understand but it is the only real solution that is non-recursive as far as i know. Hope this helps. :)

public static void main(String[] args) {

     int[] input = {1, 2, 3, 4, 5};    // input array
     int k = 4;                             // sequence length

     List<int[]> subsets = new ArrayList<>();

     int[] s = new int[k];                  // here we'll keep indices
                                            // pointing to elements in input array

     if (k <= input.length) {
         // first index sequence: 0, 1, 2, ...
         for (int i = 0; (s[i] = i) < k - 1; i++);
         subsets.add(getSubset(input, s));
         for(;;) {
             int i;
             // find position of item that can be incremented
             for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
             if (i < 0) {
                 break;
             }
             s[i]++;                    // increment this item
             for (++i; i < k; i++) {    // fill up remaining items
                 s[i] = s[i - 1] + 1;
             }
             subsets.add(getSubset(input, s));
         }
     }
        System.out.println(Arrays.deepToString(subsets.toArray()));

}

    // generate actual subset by index sequence
   static int[] getSubset(int[] input, int[] subset) {
        int[] result = new int[subset.length];
        for (int i = 0; i < subset.length; i++)
            result[i] = input[subset[i]];
        return result;
    }

  }

  Outputs:
  [1, 2, 3, 4]
  [1, 2, 3, 5]
  [1, 2, 4, 5]
  [1, 3, 4, 5]
  [2, 3, 4, 5]


问:
Generic return type in scala with akka marshalling
I've got the following rather simple code:

```<code>case class InverterResponse(body: InverterBody) extends SolarResponse
case class InverterBody(data: InverterData)
case class InverterData(dayEnergy: DayEnergy)
case class DayEnergy(unit: String, values: Values)
case class Values(value: Int)

case class MeterResponse(body: MeterBody) extends SolarResponse
case class MeterBody(data: MeterData)
case class MeterData(powerRealSum: BigDecimal, powerRealPhase1: BigDecimal, powerRealPhase2: BigDecimal, powerRealPhase3: BigDecimal)

class SolarWebConnector extends JsonSupport {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

  val httpClient = Http().outgoingConnection(host = "192.168.178.22", port = 80)

  def getInverterRealtimeData(): InverterData = {
    val inverterRealtimeURLPath = s"""/solar_api/v1/GetInverterRealtimeData.cgi?scope=System"""
    val flowGet: Future[InverterResponse] = sendRequest[InverterResponse](inverterRealtimeURLPath)
    val start = System.currentTimeMillis()
    val result = Await.result(flowGet, 5 seconds)
    val end = System.currentTimeMillis()
    println(s"Result in ${end - start} millis: $result")
    result.body.data
  }

  private def sendRequest[T](inverterRealtimeURLPath: String) : Future[T] = {
    val flowGet: Future[T] =
      Source.single(
        HttpRequest(
          method = HttpMethods.GET,
          uri = Uri(inverterRealtimeURLPath))
      )
        .via(httpClient)
        .mapAsync(1)(response => Unmarshal(response.entity).to[T])
        .runWith(Sink.head)
    flowGet
  }

  def getMeterRealtimeData(): String = {
    "test"
  }
}
</code>```

JsonSupport contains the json format definitions to marshall incoming json towards the response case classes. This works just fine as long as I'm not trying to define a generic version for the sendRequest method which can either return an InverterResponse or a MeterResponse type. It compiles fine, but am getting:

```<code>Error:(54, 63) Play 2 Compiler:
 /Users/tbecker/workspaces/home-integrator/app/services/SolarWebConnector.scala:54:63: could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.ResponseEntity,T]
         .mapAsync(1)(response => Unmarshal(response.entity).to[T])
                                                               ^
</code>```

Haven't used scala really for about 2 years...so my knowledge might be rusted a fair bit...

答:
Found the answer myself by digging around in the sources and documentation.

https://doc.akka.io/docs/akka-http/current/scala/http/common/unmarshalling.html

https://github.com/akka/akka-http/blob/v10.0.3/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/Unmarshal.scala

Umarshall needs an implicit Unmarshaller. Providing it in the method signature like so solves the problem:

private def sendRequest[T](inverterRealtimeURLPath: String)(implicit m: Unmarshaller[ResponseEntity, T]) : Future[T] = {

Body:
I've got the following rather simple code:

case class InverterResponse(body: InverterBody) extends SolarResponse
case class InverterBody(data: InverterData)
case class InverterData(dayEnergy: DayEnergy)
case class DayEnergy(unit: String, values: Values)
case class Values(value: Int)

case class MeterResponse(body: MeterBody) extends SolarResponse
case class MeterBody(data: MeterData)
case class MeterData(powerRealSum: BigDecimal, powerRealPhase1: BigDecimal, powerRealPhase2: BigDecimal, powerRealPhase3: BigDecimal)

class SolarWebConnector extends JsonSupport {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

  val httpClient = Http().outgoingConnection(host = "192.168.178.22", port = 80)

  def getInverterRealtimeData(): InverterData = {
    val inverterRealtimeURLPath = s"""/solar_api/v1/GetInverterRealtimeData.cgi?scope=System"""
    val flowGet: Future[InverterResponse] = sendRequest[InverterResponse](inverterRealtimeURLPath)
    val start = System.currentTimeMillis()
    val result = Await.result(flowGet, 5 seconds)
    val end = System.currentTimeMillis()
    println(s"Result in ${end - start} millis: $result")
    result.body.data
  }

  private def sendRequest[T](inverterRealtimeURLPath: String) : Future[T] = {
    val flowGet: Future[T] =
      Source.single(
        HttpRequest(
          method = HttpMethods.GET,
          uri = Uri(inverterRealtimeURLPath))
      )
        .via(httpClient)
        .mapAsync(1)(response => Unmarshal(response.entity).to[T])
        .runWith(Sink.head)
    flowGet
  }

  def getMeterRealtimeData(): String = {
    "test"
  }
}

JsonSupport contains the json format definitions to marshall incoming json towards the response case classes. This works just fine as long as I'm not trying to define a generic version for the sendRequest method which can either return an InverterResponse or a MeterResponse type. It compiles fine, but am getting:

Error:(54, 63) Play 2 Compiler:
 /Users/tbecker/workspaces/home-integrator/app/services/SolarWebConnector.scala:54:63: could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.ResponseEntity,T]
         .mapAsync(1)(response => Unmarshal(response.entity).to[T])
                                                               ^

Haven't used scala really for about 2 years...so my knowledge might be rusted a fair bit...


问:
Storing a list of unicode strings in a csv file python 2
I created a function(parse_html(param)) that returns a list like below,

```<code>list = [u'John', u'Muchia', u'Prozessoptimierung Fahrwiderst\xe4nde']
</code>```

if I return print list[2], and in my function, it gives me Prozessoptimierung Fahrwiderstände which is perfect, but it appears differently when in a list

The problem lies when I return the whole list return list I want to avoid the 'u'. I want to store a list of strings and the Unicode characters like ä ö and ü should also appear.

fname[x] is the source of the HTML file where x is the file number which is incremented from 0 to count(file_number)

```<code>list=[]
newlist=[]
list = parse_html(fname[7])
for row in list:
  drow = row.encode('utf-8')
  newlist.append(drow)
print newlist
</code>```

The goal is to save the returned list to a CSV file. Everytime a new file(fname) is selected, the list is created and should add the new list to the csv file previously created.

I am doing something really wrong and I can realize that and my head hurts. Please help.

update:

```<code>for x in range(0,count):
    list = parse_html(fname[x])
    with open('output.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(list)
</code>```

error:

```<code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 132: ordinal not in range(1
28)
</code>```

Answer:

```<code>wr.writerow([c.encode('utf-8') for c in list]) # instead `wr.writerow(list)
</code>```

答: The u prefix merely indicates that the string is in Unicode format. There's nothing wrong with your code, and it will behave correctly (as if it didn't have the u) in code. It's only output in the print function to let you know it's a Unicode string.

Body:
I created a function(parse_html(param)) that returns a list like below,

list = [u'John', u'Muchia', u'Prozessoptimierung Fahrwiderst\xe4nde']

if I return print list[2], and in my function, it gives me Prozessoptimierung Fahrwiderstände which is perfect, but it appears differently when in a list

The problem lies when I return the whole list return list I want to avoid the 'u'. I want to store a list of strings and the Unicode characters like ä ö and ü should also appear.

fname[x] is the source of the HTML file where x is the file number which is incremented from 0 to count(file_number)

list=[]
newlist=[]
list = parse_html(fname[7])
for row in list:
  drow = row.encode('utf-8')
  newlist.append(drow)
print newlist

The goal is to save the returned list to a CSV file. Everytime a new file(fname) is selected, the list is created and should add the new list to the csv file previously created.

I am doing something really wrong and I can realize that and my head hurts. Please help.

update:

for x in range(0,count):
    list = parse_html(fname[x])
    with open('output.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(list)

error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 132: ordinal not in range(1
28)

Answer:

wr.writerow([c.encode('utf-8') for c in list]) # instead `wr.writerow(list)


问:
Azure CosmosDB Query on Sub Elements
I have such documents

```<code>   [
    {
      "id": "1",
      "name": "My Product 1",
      "variants": [
        {
          "id": 2179,
          "code": "A",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 1200,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 500,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    },
    {
      "id": "2",
      "name": "My Product 2",
      "variants": [
        {
          "id": 2180,
          "code": "B",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 1300,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 200,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    },
    {
      "id": "3",
      "name": "My Product 3",
      "variants": [
        {
          "id": 2181,
          "code": "C",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2000,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 999,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    }
  ]
</code>```

I want now to find all products where one of the variants has the Height >= 1200 and Weight >= 500

In this example this should be My Product 1 and My Product 3. My Product 2 doesn't match as the Weight Property is below the criteria.

How can I do this. Is there a way. The data structure can be changed but only if really needed.

答:
I follow your document and created 3 sample documents as below in my cosmos db :

```<code>[
  {
    "id": "1",
    "name": "My Product 1",
    "variants": [
      {
        "id": 2179,
        "code": "A",
        "attributes": {
          "att_set_1": {
            "en": {
              "name": "Attribute Set 1",
              "data": [
                {
                  "id": 919,
                  "title": "Height",
                  "label": "height_mm",
                  "v": 2330,
                  "unit": "mm"
                },
                {
                  "id": 921,
                  "title": "Weight",
                  "label": "weight",
                  "v": 2931,
                  "unit": "kg"
                },
                {
                  "id": 923,
                  "title": "Other",
                  "label": "blah",
                  "v": 200,
                  "unit": "mm"
                }
              ]
            }
          }
        }
      }
    ]
  },
  {
    "id": "2",
    "name": "My Product 2",
    "variants": [
      {
        "id": 2180,
        "code": "B",
        "attributes": {
          "att_set_1": {
            "en": {
              "name": "Attribute Set 1",
              "data": [
                {
                  "id": 919,
                  "title": "Height",
                  "label": "height_mm",
                  "v": 100,
                  "unit": "mm"
                },
                {
                  "id": 921,
                  "title": "Weight",
                  "label": "weight",
                  "v": 200,
                  "unit": "kg"
                },
                {
                  "id": 923,
                  "title": "Other",
                  "label": "blah",
                  "v": 200,
                  "unit": "mm"
                }
              ]
            }
          }
        }
      }
    ]
  },
  {
    "id": "3",
    "name": "My Product 3",
    "variants": [
      {
        "id": 2181,
        "code": "C",
        "attributes": {
          "att_set_1": {
            "en": {
              "name": "Attribute Set 1",
              "data": [
                {
                  "id": 919,
                  "title": "Height",
                  "label": "height_mm",
                  "v": 2000,
                  "unit": "mm"
                },
                {
                  "id": 921,
                  "title": "Weight",
                  "label": "weight",
                  "v": 999,
                  "unit": "kg"
                },
                {
                  "id": 923,
                  "title": "Other",
                  "label": "blah",
                  "v": 200,
                  "unit": "mm"
                }
              ]
            }
          }
        }
      }
    ]
  }
]
</code>```

Then I use the SQL ：

SELECT all FROM all join a in all.variants join b in
  a.attributes.att_set_1.en.data where (b.title = 'Height' and b.v >=
  2000) or  (b.title = 'Weight' and b.v >= 1000)

Result data:

```<code>[
  {
    "all": {
      "id": "1",
      "name": "My Product 1",
      "variants": [
        {
          "id": 2179,
          "code": "A",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2330,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 2931,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  {
    "all": {
      "id": "1",
      "name": "My Product 1",
      "variants": [
        {
          "id": 2179,
          "code": "A",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2330,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 2931,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
  },
  {
    "all": {
      "id": "3",
      "name": "My Product 3",
      "variants": [
        {
          "id": 2181,
          "code": "C",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2000,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 999,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
]
</code>```

Please notice that the value column is a keyword and cannot be used in a document. So, in my documents I remove it with v.

Update Answer:

After a few attempts, it seems impossible to directly query the results you want from the the Cosmos DB via the SQL statement.

However , Cosmos DB provides us with Stored Procedure when we face complex queries. If you do not know much about stored procedure, you can read this article.

Please refer to the stored procedure I created as below :

```<code>function sample() {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM c',
        function (err, feed, options) {
            if (err) throw err;

            var returnArray = [];

            if (!feed || !feed.length){
                getContext().getResponse().setBody('no docs found');
            } else{
                for(var i=0;i<feed.length;i++){
                    var foundHeight = false, foundWeight=false;
                    var dataArray = feed[i].variants[0].attributes.att_set_1.en.data;
                    for(var j=0;j<dataArray.length;j++){
                      var f = dataArray[j];
                      if((f.title=='Height'&&f.v>=2000){
                        foundHeight = true;
                      } else if(f.title=='Weight'&&f.v>=1000)){
                        foundWeight = true;
                      }
                    }
                    if(foundHeight && foundWeight)
                       returnArray.push(feed[i]);
                }
            }
            getContext().getResponse().setBody(JSON.stringify(returnArray));
        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
</code>```

Output result :

```<code>[
    {
        "id": "1",
        "name": "My Product 1",
        "variants": [
            {
                "id": 2179,
                "code": "A",
                "attributes": {
                    "att_set_1": {
                        "en": {
                            "name": "Attribute Set 1",
                            "data": [
                                {
                                    "id": 919,
                                    "title": "Height",
                                    "label": "height_mm",
                                    "v": 2330,
                                    "unit": "mm"
                                },
                                {
                                    "id": 921,
                                    "title": "Weight",
                                    "label": "weight",
                                    "v": 2931,
                                    "unit": "kg"
                                },
                                {
                                    "id": 923,
                                    "title": "Other",
                                    "label": "blah",
                                    "v": 200,
                                    "unit": "mm"
                                }
                            ]
                        }
                    }
                }
            }
        ]
    },
    {
        "id": "3",
        "name": "My Product 3",
        "variants": [
            {
                "id": 2181,
                "code": "C",
                "attributes": {
                    "att_set_1": {
                        "en": {
                            "name": "Attribute Set 1",
                            "data": [
                                {
                                    "id": 919,
                                    "title": "Height",
                                    "label": "height_mm",
                                    "v": 2000,
                                    "unit": "mm"
                                },
                                {
                                    "id": 921,
                                    "title": "Weight",
                                    "label": "weight",
                                    "v": 999,
                                    "unit": "kg"
                                },
                                {
                                    "id": 923,
                                    "title": "Other",
                                    "label": "blah",
                                    "v": 200,
                                    "unit": "mm"
                                }
                            ]
                        }
                    }
                }
            }
        ]
    }
]
</code>```

This result should be what you want. You can create it on portal or in your code. Any concern ,please let me know.

Hope it helps you.

Title: Azure CosmosDB Query on Sub Elements

Body:
I have such documents

   [
    {
      "id": "1",
      "name": "My Product 1",
      "variants": [
        {
          "id": 2179,
          "code": "A",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 1200,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 500,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    },
    {
      "id": "2",
      "name": "My Product 2",
      "variants": [
        {
          "id": 2180,
          "code": "B",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 1300,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 200,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    },
    {
      "id": "3",
      "name": "My Product 3",
      "variants": [
        {
          "id": 2181,
          "code": "C",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2000,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 999,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    }
  ]

I want now to find all products where one of the variants has the Height >= 1200 and Weight >= 500

In this example this should be My Product 1 and My Product 3. My Product 2 doesn't match as the Weight Property is below the criteria.

How can I do this. Is there a way. The data structure can be changed but only if really needed.

Body:
I follow your document and created 3 sample documents as below in my cosmos db :

[
  {
    "id": "1",
    "name": "My Product 1",
    "variants": [
      {
        "id": 2179,
        "code": "A",
        "attributes": {
          "att_set_1": {
            "en": {
              "name": "Attribute Set 1",
              "data": [
                {
                  "id": 919,
                  "title": "Height",
                  "label": "height_mm",
                  "v": 2330,
                  "unit": "mm"
                },
                {
                  "id": 921,
                  "title": "Weight",
                  "label": "weight",
                  "v": 2931,
                  "unit": "kg"
                },
                {
                  "id": 923,
                  "title": "Other",
                  "label": "blah",
                  "v": 200,
                  "unit": "mm"
                }
              ]
            }
          }
        }
      }
    ]
  },
  {
    "id": "2",
    "name": "My Product 2",
    "variants": [
      {
        "id": 2180,
        "code": "B",
        "attributes": {
          "att_set_1": {
            "en": {
              "name": "Attribute Set 1",
              "data": [
                {
                  "id": 919,
                  "title": "Height",
                  "label": "height_mm",
                  "v": 100,
                  "unit": "mm"
                },
                {
                  "id": 921,
                  "title": "Weight",
                  "label": "weight",
                  "v": 200,
                  "unit": "kg"
                },
                {
                  "id": 923,
                  "title": "Other",
                  "label": "blah",
                  "v": 200,
                  "unit": "mm"
                }
              ]
            }
          }
        }
      }
    ]
  },
  {
    "id": "3",
    "name": "My Product 3",
    "variants": [
      {
        "id": 2181,
        "code": "C",
        "attributes": {
          "att_set_1": {
            "en": {
              "name": "Attribute Set 1",
              "data": [
                {
                  "id": 919,
                  "title": "Height",
                  "label": "height_mm",
                  "v": 2000,
                  "unit": "mm"
                },
                {
                  "id": 921,
                  "title": "Weight",
                  "label": "weight",
                  "v": 999,
                  "unit": "kg"
                },
                {
                  "id": 923,
                  "title": "Other",
                  "label": "blah",
                  "v": 200,
                  "unit": "mm"
                }
              ]
            }
          }
        }
      }
    ]
  }
]

Then I use the SQL ：

SELECT all FROM all join a in all.variants join b in
  a.attributes.att_set_1.en.data where (b.title = 'Height' and b.v >=
  2000) or  (b.title = 'Weight' and b.v >= 1000)

Result data:

[
  {
    "all": {
      "id": "1",
      "name": "My Product 1",
      "variants": [
        {
          "id": 2179,
          "code": "A",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2330,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 2931,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  {
    "all": {
      "id": "1",
      "name": "My Product 1",
      "variants": [
        {
          "id": 2179,
          "code": "A",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2330,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 2931,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
  },
  {
    "all": {
      "id": "3",
      "name": "My Product 3",
      "variants": [
        {
          "id": 2181,
          "code": "C",
          "attributes": {
            "att_set_1": {
              "en": {
                "name": "Attribute Set 1",
                "data": [
                  {
                    "id": 919,
                    "title": "Height",
                    "label": "height_mm",
                    "v": 2000,
                    "unit": "mm"
                  },
                  {
                    "id": 921,
                    "title": "Weight",
                    "label": "weight",
                    "v": 999,
                    "unit": "kg"
                  },
                  {
                    "id": 923,
                    "title": "Other",
                    "label": "blah",
                    "v": 200,
                    "unit": "mm"
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
]

Please notice that the value column is a keyword and cannot be used in a document. So, in my documents I remove it with v.

Update Answer:

After a few attempts, it seems impossible to directly query the results you want from the the Cosmos DB via the SQL statement.

However , Cosmos DB provides us with Stored Procedure when we face complex queries. If you do not know much about stored procedure, you can read this article.

Please refer to the stored procedure I created as below :

function sample() {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM c',
        function (err, feed, options) {
            if (err) throw err;

            var returnArray = [];

            if (!feed || !feed.length){
                getContext().getResponse().setBody('no docs found');
            } else{
                for(var i=0;i<feed.length;i++){
                    var foundHeight = false, foundWeight=false;
                    var dataArray = feed[i].variants[0].attributes.att_set_1.en.data;
                    for(var j=0;j<dataArray.length;j++){
                      var f = dataArray[j];
                      if((f.title=='Height'&&f.v>=2000){
                        foundHeight = true;
                      } else if(f.title=='Weight'&&f.v>=1000)){
                        foundWeight = true;
                      }
                    }
                    if(foundHeight && foundWeight)
                       returnArray.push(feed[i]);
                }
            }
            getContext().getResponse().setBody(JSON.stringify(returnArray));
        });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

Output result :

[
    {
        "id": "1",
        "name": "My Product 1",
        "variants": [
            {
                "id": 2179,
                "code": "A",
                "attributes": {
                    "att_set_1": {
                        "en": {
                            "name": "Attribute Set 1",
                            "data": [
                                {
                                    "id": 919,
                                    "title": "Height",
                                    "label": "height_mm",
                                    "v": 2330,
                                    "unit": "mm"
                                },
                                {
                                    "id": 921,
                                    "title": "Weight",
                                    "label": "weight",
                                    "v": 2931,
                                    "unit": "kg"
                                },
                                {
                                    "id": 923,
                                    "title": "Other",
                                    "label": "blah",
                                    "v": 200,
                                    "unit": "mm"
                                }
                            ]
                        }
                    }
                }
            }
        ]
    },
    {
        "id": "3",
        "name": "My Product 3",
        "variants": [
            {
                "id": 2181,
                "code": "C",
                "attributes": {
                    "att_set_1": {
                        "en": {
                            "name": "Attribute Set 1",
                            "data": [
                                {
                                    "id": 919,
                                    "title": "Height",
                                    "label": "height_mm",
                                    "v": 2000,
                                    "unit": "mm"
                                },
                                {
                                    "id": 921,
                                    "title": "Weight",
                                    "label": "weight",
                                    "v": 999,
                                    "unit": "kg"
                                },
                                {
                                    "id": 923,
                                    "title": "Other",
                                    "label": "blah",
                                    "v": 200,
                                    "unit": "mm"
                                }
                            ]
                        }
                    }
                }
            }
        ]
    }
]

This result should be what you want. You can create it on portal or in your code. Any concern ,please let me know.

Hope it helps you.


问:
Variable has incomplete type 'struct sockaddr_in'
I try to use the

```<code> struct sockaddr_in sin;
</code>```

but if I use this I get

```<code>Variable has incomplete type 'struct sockaddr_in'
</code>```

and

```<code>Forward declaration of 'struct sockaddr_in'
</code>```

as Error.
I get error when I use Xcode4. In Xcode3.2 it works.
Does someone know how to solve this error??
My imports are

```<code>#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#include <netdb.h>
#import <SystemConfiguration/SCNetworkReachability.h>
</code>```

答:
Try to use #import rather #include.
#import ensures you never have a recursive include problem.

Tried and succeeded the same in Xcode 9.0.1, obj C. iOS 11

```<code>-SN
</code>```

Body:
I try to use the

 struct sockaddr_in sin;

but if I use this I get

Variable has incomplete type 'struct sockaddr_in'

and

Forward declaration of 'struct sockaddr_in'

as Error.
I get error when I use Xcode4. In Xcode3.2 it works.
Does someone know how to solve this error??
My imports are

#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#include <netdb.h>
#import <SystemConfiguration/SCNetworkReachability.h>

Body:
Try to use #import rather #include.
#import ensures you never have a recursive include problem.

Tried and succeeded the same in Xcode 9.0.1, obj C. iOS 11

-SN


问:
How to animate centered square to the top
I have a UIView in a portrait-only app.

The view is centered vertically and horizontally with AutoLayout ("manually" using storyboards).

The width equals the (main)view.width * 0.9

The height is the same size of the width (it is a square).

I want to tap a button inside this UIView and animate it only vertically until it reaches the top border of the screen (eg. height*0.9, 10 pts, whatever is possible).

When I click again, I want to reposition back the view to its original position (centered as it was when I first tapped).

During the transition the square should not be tappable.

After reading many posts I could not understand what's the best way to do this (I red mainly developers saying old techniques using centerX should be avoided and lamentations about some versions of the SO behaving in strange ways).

I suppose I should find a way to get the current "position" of the constraints and to assign a constraint the "final" position, but I was not able to do it.

Any help is appreciated

答:
While you can use Autolayout to animate - to take the constraint constraining the centerY and set its constant to a value that would move to the top (e.g., constant = -(UIScreen.main.bounds.height / 2)), I would recommend using view's transform property.

So to move the view to the top you can use:

```<code>let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
UIView.animate(withDuration: 0.2) {
    box.transform = CGAffineTransform.identity
         .translatedBy(x: 0, y: -(viewHalfHeight - (boxHalfHeight + topMargin)))
}
</code>```

You are moving box.center related to the view.center - so if you want to move the box to the top, you have to move its center by half a view's height (because the view's centerY is exactly height / 2 far from the view's top). That is not enough though, because then only a bottom half of the box is visible (now the box.centerY == view.top). Therefore you have to move it back by the box.bounds.height / 2 (in my code boxHalfHeight) - to make the top half visible. And to that boxHalfHeight you add topMargin so that there is some margin to the top.

Then, to move the box back to original position:

```<code>UIView.animate(withDuration: 0.2) {
    box.transform = CGAffineTransform.identity
}
</code>```

EDIT

If you really want to go with autolayout, you have to have a reference to the centerY constraint, so for example if it is created this way:

```<code>let boxCenterYConstraint = self.box.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
boxCenterYConstraint.isActive = true
</code>```

Then you can try this:

```<code>// calculating the translation is the same
let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
let diff = -(viewHalfHeight - (boxHalfHeight + topMargin))

boxCenterYConstraint.constant = diff
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
    self.view.layoutIfNeeded()
}
</code>```

And animation back:

```<code>boxCenterYConstraint.constant = 0
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
    self.view.layoutIfNeeded()
}
</code>```

Body:
While you can use Autolayout to animate - to take the constraint constraining the centerY and set its constant to a value that would move to the top (e.g., constant = -(UIScreen.main.bounds.height / 2)), I would recommend using view's transform property.

So to move the view to the top you can use:

let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
UIView.animate(withDuration: 0.2) {
    box.transform = CGAffineTransform.identity
         .translatedBy(x: 0, y: -(viewHalfHeight - (boxHalfHeight + topMargin)))
}

You are moving box.center related to the view.center - so if you want to move the box to the top, you have to move its center by half a view's height (because the view's centerY is exactly height / 2 far from the view's top). That is not enough though, because then only a bottom half of the box is visible (now the box.centerY == view.top). Therefore you have to move it back by the box.bounds.height / 2 (in my code boxHalfHeight) - to make the top half visible. And to that boxHalfHeight you add topMargin so that there is some margin to the top.

Then, to move the box back to original position:

UIView.animate(withDuration: 0.2) {
    box.transform = CGAffineTransform.identity
}

EDIT

If you really want to go with autolayout, you have to have a reference to the centerY constraint, so for example if it is created this way:

let boxCenterYConstraint = self.box.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
boxCenterYConstraint.isActive = true

Then you can try this:

// calculating the translation is the same
let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
let diff = -(viewHalfHeight - (boxHalfHeight + topMargin))

boxCenterYConstraint.constant = diff
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
    self.view.layoutIfNeeded()
}

And animation back:

boxCenterYConstraint.constant = 0
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
    self.view.layoutIfNeeded()
}


答:
Use GROUP BY and HAVING

```<code>SELECT s.StudentId,s.StudentName
FROM Department d
JOIN Student s ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)=1
</code>```

And if you also want to show students which not in Department table

```<code>SELECT s.StudentId,s.StudentName
FROM Department d
RIGHT JOIN Student s ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)<=1
</code>```

Variant with LEFT JOIN

```<code>SELECT s.StudentId,s.StudentName
FROM Student s
LEFT JOIN Department d ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)<=1
</code>```

Title: Check the count of column value is equal to one based on condition in sql server

Body:
I have two tables

Student

StudentId    |  StudentName
----------   |  --------------
1            |  John
2            |  Susan
3            |  Andy
4            |  Joe

Department

StudentId    |    DepartmentId
----------   |    ------------
1            |    123
1            |    234
2            |    123
2            |    456
3            |    123
4            |    456

Each student can be in multiple departments but I have to find those students which are only in one department like student 3 and 4

Any help?

Body:
Use GROUP BY and HAVING

SELECT s.StudentId,s.StudentName
FROM Department d
JOIN Student s ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)=1

And if you also want to show students which not in Department table

SELECT s.StudentId,s.StudentName
FROM Department d
RIGHT JOIN Student s ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)<=1

Variant with LEFT JOIN

SELECT s.StudentId,s.StudentName
FROM Student s
LEFT JOIN Department d ON s.StudentId=d.StudentId
GROUP BY s.StudentId,s.StudentName
HAVING COUNT(d.DepartmentId)<=1