答:
```<code>UPDATE products SET price = (CEIL(price*1.20)-0.01)/1.20 WHERE product_id = 123
</code>```

Title: VAT changes - how to change VAT and then round price up

Body:
With the UK VAT rate due to change in the New Year, several clients will need to update their sites to the new VAT rate. As prices are all stored in a MySQL table (excluding VAT), changing the actual VAT rate is a simple flag in the backend of most sites, but this leaves 'ugly' prices £10.87, rather than £10.99.

I'd like to run a query against the prices to alter the prices so that all of the new prices (when the new VAT rate is added) are 'nice' prices rather than ugly ones.

For instance:

Current Price (ex VAT): £8.50

Current Price (VAT @ 17.5%): £9.99

New Price (VAT @ 20%): £10.20

Desired Price (VAT @ 20%): £10.99


来源: stackexchange

问:
Filtering array of dictionaries in Swift
I have An Array With Dictionaries example :

```<code>(
        {
        Email = "kate-bell@mac.com";
        Name = "Kate Bell";
        Number = "(555) 564-8583";
    },
        {
        Email = "d-higgins@mac.com";
        Name = "Daniel Higgins";
        Number = "555-478-7672";
    }
)
</code>```

And i want to filter this dictionary according to Key "Name"

```<code> func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    let predicate = NSPredicate(format:"Name == %@", searchText)
    let filteredArray = (arrContact as NSMutableArray).filteredArrayUsingPredicate(predicate)
    print(filteredArray)
    if(filteredArray.count == 0){
                searchActive = false;
            } else {
                searchActive = true;
            }
            tblData.reloadData()
 }
</code>```

I am always getting empty array in result from above swift code. Please help me to resolve this issue. Thanks

答:
where "name" is the key name</p>

```<code>  var namePredicate = NSPredicate(format: "Name like %@",  String(searchText));
        let searchPredicate = NSPredicate(format: "Name CONTAINS[C] %@", searchText)
        arrrDict = self.arrrDict.filter { searchPredicate.evaluate(with: $0) };
       you will get the result in dictionary specialy made to get contats from the phone book
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have An Array With Dictionaries example :

(
        {
        Email = "kate-bell@mac.com";
        Name = "Kate Bell";
        Number = "(555) 564-8583";
    },
        {
        Email = "d-higgins@mac.com";
        Name = "Daniel Higgins";
        Number = "555-478-7672";
    }
)

And i want to filter this dictionary according to Key "Name"

 func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    let predicate = NSPredicate(format:"Name == %@", searchText)
    let filteredArray = (arrContact as NSMutableArray).filteredArrayUsingPredicate(predicate)
    print(filteredArray)
    if(filteredArray.count == 0){
                searchActive = false;
            } else {
                searchActive = true;
            }
            tblData.reloadData()
 }

I am always getting empty array in result from above swift code. Please help me to resolve this issue. Thanks

Body:
where "name" is the key name

  var namePredicate = NSPredicate(format: "Name like %@",  String(searchText));
        let searchPredicate = NSPredicate(format: "Name CONTAINS[C] %@", searchText)
        arrrDict = self.arrrDict.filter { searchPredicate.evaluate(with: $0) };
       you will get the result in dictionary specialy made to get contats from the phone book


问:
Can I tell if a users Google password is SHA1 or SHA512?
I want to tell if a Google account's password is stored as SHA1 or SHA512. Is there an easy way to do that?

I'm asking because I have a "google-api-php-client" (according to composer.json its branch dev-master: 1.1.x-dev). I would like to know whether this is storing SHA1 or SHA512 passwords on Google? When I greped the code base for 'SHA' all I see is the '/src/Google/IO/cacerts.pem' that specifies a fingerprint for the cert. I went through the code and it looks like it's building using Google Directory API to PUT a setPassword().

https://travis-ci.org/google/google-api-php-client

答:
No. You have no way to know that.
You can know whether it is a plain password or a hashed password by looking at the password strenght assessment at the admin control panel, though.</p>


问:
How to concatenate variable name AngularJS?
Concatenate variable name in HTML code like:

app.controller code

```<code>  $scope.name ='abc';
  $scope.abc123 = response.data;
</code>```

HTML code

```<code>   <h1>{{name}}</h1>
   <h1>{{{{name}}123}}</h1> <!-- here i need value of abc123 -->
</code>```

答:
```<code> $scope.name ='abc';
  $scope.abc123 = response.data;
</code>```

You are not creating variable with dynamic name; hence it should be accessed as below

```<code><h1>{{name}}</h1>
 <h1>{{abc123}}</h1> //as $scope.abc123 is defined in controller
</code>```

Body:
Concatenate variable name in HTML code like:

app.controller code

  $scope.name ='abc';
  $scope.abc123 = response.data;

HTML code

{{name}}

{{{{name}}123}}

Body:
 $scope.name ='abc';
  $scope.abc123 = response.data;

You are not creating variable with dynamic name; hence it should be accessed as below

<h1>{{name}}</h1>
 <h1>{{abc123}}</h1> //as $scope.abc123 is defined in controller


问:
Check connectivity between Kamailio and Database
How I can check connectivity between Kamailio and database server on Kamailio?
When Kamailio has connection problems to the database due to network or something else, I want to create some logic to handle these cases. I was looking for a similar functionality, but have not found.</p>

答:
You can eventually do a simple query from configuration file using sql_query(...) from sqlops and if it fails, very likely there is something wrong with the database server. For example:</p>

```<code>if(!sql_query("SELECT NOW()")) { ... }
</code>```

Body:
You can eventually do a simple query from configuration file using sql_query(...) from sqlops and if it fails, very likely there is something wrong with the database server. For example:

if(!sql_query("SELECT NOW()")) { ... }


问:
want to add to buttons on top of every view in iPhone
I want to add two buttons of width 133 px and 150 px each and 28 px in height on top of every view in my iPhone app. Only the view below this button bar will change, but when navigation occurs (push pop operation), I want this bar also to slide with the remaining view.
basically, i want a bar containing 2 buttons to be present in ever screen of the app. Please help me. Thanks</p>

答:
We'll start by laying out a view containing buttons. In Xcode, create a new View-based iPhone application, and call it "GradientButtons" (or whatever you want). Double-click the GradientButtonsViewController.xib resource to open it in Interface Builder.

Drag a UIButton control from the library onto the view. Set its properties like this:

```<code>* Change the type to "Custom"
* Set the title to "Gray"
* Change the text color to white
* Change the background color to gray
</code>```

ContentLicense: CC BY-SA 2.5

Body:
We'll start by laying out a view containing buttons. In Xcode, create a new View-based iPhone application, and call it "GradientButtons" (or whatever you want). Double-click the GradientButtonsViewController.xib resource to open it in Interface Builder.

Drag a UIButton control from the library onto the view. Set its properties like this:

* Change the type to "Custom"
* Set the title to "Gray"
* Change the text color to white
* Change the background color to gray


问:
How to call element.onload inside AJAX sucess function?
I am uploading a image using AJAX in php codeignitor and on  upload return a JSON response containing path of uploaded image, then i insert that path into a img tag for preview

Now what i want to do is get the height and width of rendered img tag after updating its path, but the problem is i am getting a 0 always so please somebody help me out here

here is my JS

function uploadAd(){
    // console.log($('#uploadedPDF').prop('files'));
    var file_data = $('#uploadedAdFile').prop('files')[0];
    var form_data = new FormData();
    form_data.append('uploadedAdFile', file_data);
    // alert(form_data);
    $.ajax({

      url: BASE_URL+'home/uploadAdFile', // point to server-side PHP script
      dataType: 'json',  // what to expect back from the PHP script, if anything
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'post',
      async: false,
      success: function(data){
          console.log(data);
          if(data.status == -1){
            // If file extension Validation failed
            $('#uploadedAdFileMsg').html(data.msg);
            $('#uploadedAdFileMsg').removeClass('hidden');
            $('#uploadedAdFilePreview').addClass('hidden');
          }
          else{
            // If file extension Validation passed
            $('#uploadedAdFilePreview').attr('src', data.path); // Render file in img tag

            $('#uploadedAdFileMsg').addClass('hidden');
            $('#uploadedAdFilePreview').removeClass('hidden');

            console.log(document.getElementById('uploadedAdFilePreview').naturalWidth);
            // console.log()
          }
      },
      complete: function(){
        console.log('Complte '+document.getElementById('uploadedAdFilePreview').naturalWidth);
      }
    }).done(function(){
      console.log('Done '+document.getElementById('uploadedAdFilePreview').naturalWidth);
    });
  }
  $(document).ajaxComplete(function(){
    console.log('AJAX '+document.getElementById('uploadedAdFilePreview').naturalWidth);
  })
```

as you can see I inserted get height code in various places but no luck

PS: I used clientHeight, height, naturalHeight as well but still got 0

so what I concluded is the height function is called before the img tag rendered its content hence it shows a 0

so can I include a onload type of function inside a AJAX success function ??

thanks

答:
I Solved it :D ,

actually i was using onload on a Jquery returned object which is wrong , it should be used on document.getElement , so then i put a

element.onload = function(){ getHeight(); }

inside my success function os AJAX, and it worked :)

ContentLicense: CC BY-SA 4.0

Body:
I am uploading a image using AJAX in php codeignitor and on  upload return a JSON response containing path of uploaded image, then i insert that path into a img tag for preview

Now what i want to do is get the height and width of rendered img tag after updating its path, but the problem is i am getting a 0 always so please somebody help me out here

here is my JS

function uploadAd(){
    // console.log($('#uploadedPDF').prop('files'));
    var file_data = $('#uploadedAdFile').prop('files')[0];
    var form_data = new FormData();
    form_data.append('uploadedAdFile', file_data);
    // alert(form_data);
    $.ajax({

      url: BASE_URL+'home/uploadAdFile', // point to server-side PHP script
      dataType: 'json',  // what to expect back from the PHP script, if anything
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'post',
      async: false,
      success: function(data){
          console.log(data);
          if(data.status == -1){
            // If file extension Validation failed
            $('#uploadedAdFileMsg').html(data.msg);
            $('#uploadedAdFileMsg').removeClass('hidden');
            $('#uploadedAdFilePreview').addClass('hidden');
          }
          else{
            // If file extension Validation passed
            $('#uploadedAdFilePreview').attr('src', data.path); // Render file in img tag

            $('#uploadedAdFileMsg').addClass('hidden');
            $('#uploadedAdFilePreview').removeClass('hidden');

            console.log(document.getElementById('uploadedAdFilePreview').naturalWidth);
            // console.log()
          }
      },
      complete: function(){
        console.log('Complte '+document.getElementById('uploadedAdFilePreview').naturalWidth);
      }
    }).done(function(){
      console.log('Done '+document.getElementById('uploadedAdFilePreview').naturalWidth);
    });
  }
  $(document).ajaxComplete(function(){
    console.log('AJAX '+document.getElementById('uploadedAdFilePreview').naturalWidth);
  })

as you can see I inserted get height code in various places but no luck

PS: I used clientHeight, height, naturalHeight as well but still got 0

so what I concluded is the height function is called before the img tag rendered its content hence it shows a 0

so can I include a onload type of function inside a AJAX success function ??

thanks


问:
C# correct and efficient conversion of double to decimal
What is the most efficient (and strictly correct) way to convert from a double to a decimal rounded to n places of precision?

I am using decimal.Round((decimal)d, n, MidpointRounding.AwayFromZero) but it occurs to me that I am rounding twice here- once duing the cast (decimal)d and once via Round().

Is there a way to directly round a double to a decimal to n places?  I suppose I can round trip it via strings but that seems ugly and expensive.

5/12/2017: i added an issue to corefx github here https://github.com/dotnet/corefx/issues/19706

答:
What I don't understand is why do you want to round the double value when you convert it to decimal, since decimal has a lot more precision than double. The rounding simply does not have sense.

You can simply cast the double to decimal:

```<code>double doubleValue = 12.23;
decimal decimalValue = (decimal) doubleValue;
</code>```

or as suggested by the others:

```<code>decimalValue = Convert.ToDecimal(doubleValue);
</code>```

And if you are really concerned about performance (and I am not very sure this is the case) you should rethink about using decimal instead of double, as it is neither very fast, nor very memory efficient. Double is precise enough for many applications and you should really think if you need that additional precision offered by decimal type.

Body:
What I don't understand is why do you want to round the double value when you convert it to decimal, since decimal has a lot more precision than double. The rounding simply does not have sense.

You can simply cast the double to decimal:

double doubleValue = 12.23;
decimal decimalValue = (decimal) doubleValue;

or as suggested by the others:

decimalValue = Convert.ToDecimal(doubleValue);

And if you are really concerned about performance (and I am not very sure this is the case) you should rethink about using decimal instead of double, as it is neither very fast, nor very memory efficient. Double is precise enough for many applications and you should really think if you need that additional precision offered by decimal type.


问:
Unable to import angular datepicker into my App
I am trying to import the angular-ui-bootstrap datepicker into my app but I am not sure how to do so.

I am using ES6 and this is what I have got in place:

map/src/app.js

```<code>import angular from 'angular';
import timeCtrl from './time.controller';
import timeComp from '../../../components/angular-components/time.component.js';
import mapComp from '../../../components/angular-components/map.component.js';
import mapHeaderComp from '../../../components/angular-components/map-header.component.js';
import mapViewstate from '../../../components/angular-components/map-viewstate.component.js';

export default angular.module('mymap', [])
  .component('ppmapHeader', mapHeaderComp)
  .component('ppmapViewstate', mapViewstate)
  .component('pptime', timeComp)
  .component('ppmap', mapComp)
  .controller('app', timeCtrl)
</code>```

components/angular-components/map.component.js

```<code>  export default {
    bindings: {
      ctrl: "<"
    },
    template: `
    <div>
      <div style="position: relative; height: 750px">
          <pp-map-viewstate
             viewstate="$ctrl.ctrl.viewstate"
             on-viewstate-change="$ctrl.ctrl.onViewstateChange(type, args)">
          </pp-map-viewstate>
      </div>
    </div>
    `
   }
</code>```

components/angular-components/map-viewstate.component.js'

```<code>    function viewStateCtrl () {
      const self = this

        self.$onInit = () => {
          const viewstate = self.viewstate

          self.zoom = viewstate.zoom
          self.duration = viewstate.duration

          self.onDurationChange = (duration, zoom) => {
            self.onViewstateChange({
             type: "duration",
             args: {
              duration,
              zoom
             }
            });
          }
        }

     }

 export default {
   bindings: {
     viewstate: "<",
     onViewstateChange: "&"
   },
   controller: viewStateCtrl,
   template: `
     <pp-map-header
       zoom="$ctrl.zoom"
       duration="$ctrl.duration"
       on-duration-change="$ctrl.onDurationChange(duration, zoom)">
     </pp-map-header>
   `
 }
</code>```

components/angular-components/map-header.component.js

```<code>function headerCtrl () {
  const self = this;

self.$onInit = () => {
  self.datePicker = {
    opened: false
  };

  self.targetDate = null;
  self.dateOptions = {
    showWeeks: 'false',
    formatYear: 'yyyy',
    startingDay: 1,
    altInputFormats : ['d!/M!/yyyy','dd/MM/yyyy']
  };

  self.openDatePicker = function() {
    self.datePicker.opened = true;
  };

  self.formats = ['dd, MMMM yyyy'];
  self.format = self.formats[0];

  self.uiConfig = {
    calendar:{
      firstDay: 1,
      timeFormat: 'HH:mm',
      dateFormat: 'ddmm',
      displayEventEnd: true
    }
   };

  self.changeDuration = () => {
    self.onDurationChange({
      duration: self.duration,
      zoom: self.zoom
    })
  }
}
}

export default {
  bindings: {
   duration: "<",
   zoom: "<",
   onDurationChange: "&"
  },
  controller: headerCtrl,
  template: `
  <div class="pp-header-container">
    <div class="pp-sch-header-item-input-label"><span class="pp-sch-label">Date</span></div>
    <input class="map-header pp-sch-header-item"
         type="text"
         uib-datepicker-popup="{{$ctrl.format}}"
         ng-model="$ctrl.targetDate"
         ng-click="$ctrl.openDatePicker()"
         is-open="$ctrl.datePicker.opened"
         datepicker-options="$ctrl.dateOptions"
         show-button-bar="false"
         ng-required="false"
         close-text="Close" alt-input-formats="altInputFormats"
         ng-change="$ctrl.gotoDate()" readonly />
    <div class="pp-sch-header-item-input-label"><span class="pp-sch-label">Zoom</span></div>
    <div class="map-header pp-sch-header-item">
      <select ng-model="$ctrl.zoom" ng-change="$ctrl.changeDuration()">
          <option value="0">1</option>
          <option value="1">2</option>
      </select>
    </div>
    <div class="pp-sch-header-item-input-label"><span class="pp-sch-label">Duration</span></div>
    <div class="map-header pp-sch-header-item">
    <select class="pp-sch-filter-container-col-1"  ng-model="$ctrl.duration" ng-change="$ctrl.changeDuration()">
      <option value="0">Day</option>
      <option value="1">1 week</option>
    </select>
  </div>
  </div>
  `
}
</code>```

In the above code I would like to get the datepicker working or at list showing a calendar. So how do I get that to work?
menu bar

I have installed bootstrap through node:

node modules

答:
You need to import ui-bootstrap with template version (ui-bootstrap-tpls-2.5.0.min.js) from your node_modules/dist folder.

Then you can inject it in your app module

```<code>angular.module('mymap', [ui.bootstrap])
</code>```

You can get the full installation details on their website.

Body:
I am trying to import the angular-ui-bootstrap datepicker into my app but I am not sure how to do so.

I am using ES6 and this is what I have got in place:

map/src/app.js

import angular from 'angular';
import timeCtrl from './time.controller';
import timeComp from '../../../components/angular-components/time.component.js';
import mapComp from '../../../components/angular-components/map.component.js';
import mapHeaderComp from '../../../components/angular-components/map-header.component.js';
import mapViewstate from '../../../components/angular-components/map-viewstate.component.js';

export default angular.module('mymap', [])
  .component('ppmapHeader', mapHeaderComp)
  .component('ppmapViewstate', mapViewstate)
  .component('pptime', timeComp)
  .component('ppmap', mapComp)
  .controller('app', timeCtrl)

components/angular-components/map.component.js

  export default {
    bindings: {
      ctrl: "<"
    },
    template: `

          <pp-map-viewstate
             viewstate="$ctrl.ctrl.viewstate"
             on-viewstate-change="$ctrl.ctrl.onViewstateChange(type, args)">
          </pp-map-viewstate>

    `
   }

components/angular-components/map-viewstate.component.js'

    function viewStateCtrl () {
      const self = this

        self.$onInit = () => {
          const viewstate = self.viewstate

          self.zoom = viewstate.zoom
          self.duration = viewstate.duration

          self.onDurationChange = (duration, zoom) => {
            self.onViewstateChange({
             type: "duration",
             args: {
              duration,
              zoom
             }
            });
          }
        }

     }

 export default {
   bindings: {
     viewstate: "<",
     onViewstateChange: "&"
   },
   controller: viewStateCtrl,
   template: `
     <pp-map-header
       zoom="$ctrl.zoom"
       duration="$ctrl.duration"
       on-duration-change="$ctrl.onDurationChange(duration, zoom)">
     </pp-map-header>
   `
 }

components/angular-components/map-header.component.js

function headerCtrl () {
  const self = this;

self.$onInit = () => {
  self.datePicker = {
    opened: false
  };

  self.targetDate = null;
  self.dateOptions = {
    showWeeks: 'false',
    formatYear: 'yyyy',
    startingDay: 1,
    altInputFormats : ['d!/M!/yyyy','dd/MM/yyyy']
  };

  self.openDatePicker = function() {
    self.datePicker.opened = true;
  };

  self.formats = ['dd, MMMM yyyy'];
  self.format = self.formats[0];

  self.uiConfig = {
    calendar:{
      firstDay: 1,
      timeFormat: 'HH:mm',
      dateFormat: 'ddmm',
      displayEventEnd: true
    }
   };

  self.changeDuration = () => {
    self.onDurationChange({
      duration: self.duration,
      zoom: self.zoom
    })
  }
}
}

export default {
  bindings: {
   duration: "<",
   zoom: "<",
   onDurationChange: "&"
  },
  controller: headerCtrl,
  template: `

Date

    <input class="map-header pp-sch-header-item"
         type="text"
         uib-datepicker-popup="{{$ctrl.format}}"
         ng-model="$ctrl.targetDate"
         ng-click="$ctrl.openDatePicker()"
         is-open="$ctrl.datePicker.opened"
         datepicker-options="$ctrl.dateOptions"
         show-button-bar="false"
         ng-required="false"
         close-text="Close" alt-input-formats="altInputFormats"
         ng-change="$ctrl.gotoDate()" readonly />

Zoom

      <select ng-model="$ctrl.zoom" ng-change="$ctrl.changeDuration()">
          <option value="0">1</option>
          <option value="1">2</option>
      </select>

Duration

    <select class="pp-sch-filter-container-col-1"  ng-model="$ctrl.duration" ng-change="$ctrl.changeDuration()">
      <option value="0">Day</option>
      <option value="1">1 week</option>
    </select>

  `
}

In the above code I would like to get the datepicker working or at list showing a calendar. So how do I get that to work?
menu bar

I have installed bootstrap through node:

node modules

Body:
You need to import ui-bootstrap with template version (ui-bootstrap-tpls-2.5.0.min.js) from your node_modules/dist folder.

Then you can inject it in your app module

angular.module('mymap', [ui.bootstrap])

You can get the full installation details on their website.


问:
AspectJ expression gives formal unbound in pointcut error
I have within aspectJ the expression:

```<code>@Pointcut("within(com.param.cpms.dao.impl.ProjectMetaDaoImpl)")
public void daoExceptionHandle() {

}
</code>```

At Spring 3.0 startup, I am getting the following error :

```<code>nested exception is java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut
</code>```

答: I got this error because of wrong import of class. I should have imported import org.aspectj.lang.JoinPoint class   , but instead imported some other Joinpoint class from a different package. </p>

Body:
I have within aspectJ the expression:

@Pointcut("within(com.param.cpms.dao.impl.ProjectMetaDaoImpl)")
public void daoExceptionHandle() {

}

At Spring 3.0 startup, I am getting the following error :

nested exception is java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut


问:
How to fill the primeng
 with FirebaseObservableList?
I´m trying to fill my datatable () with my firebase database content. But I don´t know how to use the *ngFor like I used in a normal table.
The normal way is done:

```<code><tr *ngFor="let docu of documentos | async">
  <td>{{docu.nombre}}</td>
  <td>{{docu.tipoDocumento}}</td>
  <td  >{{docu.usuario}}</td>
  <td  >{{docu.grupo}}</td>
  <td width="20%"><a class="btn btn-success" target="_blank" href="{{docu.enlaceDescarga}}">Ver</a></td>
</tr>
</code>```

It fills perfectly.
But now I want to use PrimeNG

```<code><p-dataTable [value]="" *ngFor='let docu of documentos | async'>
<p-column field={{docu.nombre}} header="Nombre"></p-column>
<p-column field="year" header="Tipo"></p-column>
<p-column field="brand" header="Permiso de usuario"></p-column>
<p-column field="color" header="Permiso de grupo"></p-column>
<p-column field="color" header="Enlace"></p-column></p-dataTable>
</code>```

My problen is [value], I don´t know how to fill an array with a FirebaseObservableList.
I retrieve the the list with this:

```<code>documentos: FirebaseListObservable<any> = af.database.list('/Documentos');
</code>```

af is my AngularFire on constructor.

Some ideas?

答:
Try to use the below code:PrimeFace table the value contains the list of values so the prime face will take care of looping </p>

```<code><p-dataTable [value]="documentos|async">
<p-column field="nombre" header="Nombre"></p-column>
<p-column field="year" header="Tipo"></p-column>
<p-column field="brand" header="Permiso de usuario"></p-column>
<p-column field="color" header="Permiso de grupo"></p-column>
<p-column field="color" header="Enlace"></p-column></p-dataTable>
</code>```

Title: How to fill the primeng <p-datatable> with FirebaseObservableList?

Body:
I´m trying to fill my datatable () with my firebase database content. But I don´t know how to use the *ngFor like I used in a normal table.
The normal way is done:

  {{docu.nombre}}
  {{docu.tipoDocumento}}
  {{docu.usuario}}
  {{docu.grupo}}
  Ver

It fills perfectly.
But now I want to use PrimeNG

My problen is [value], I don´t know how to fill an array with a FirebaseObservableList.
I retrieve the the list with this:

documentos: FirebaseListObservable<any> = af.database.list('/Documentos');

af is my AngularFire on constructor.

Some ideas?

Body:
Try to use the below code:PrimeFace table the value contains the list of values so the prime face will take care of looping

<p-dataTable [value]="documentos|async">
<p-column field="nombre" header="Nombre"></p-column>
<p-column field="year" header="Tipo"></p-column>
<p-column field="brand" header="Permiso de usuario"></p-column>
<p-column field="color" header="Permiso de grupo"></p-column>
<p-column field="color" header="Enlace"></p-column></p-dataTable>


问:
Modelling a heat pump in oemof (solph)
How can I model a heat pump in the oemof. I think it is necessary to create three buses (low temperature reservoir, electricity, high temperature). But the LinearTransformer class does not allow more than one input. Is there another way to do it?

I would like to set an oemof tag but I am not allowed to do so.

答:
It depends on which oemof version you use. If you use oemof < v0.1.2 you have to model it with just two buses. You can calculate the COP in advance using the temperature of the reservoir and the average temperature of the heat bus. You can pass it as a list, numpy.array, pandas.Series etc..

```<code>from oemof import solph
cop = [2.5, 2.3, 2.5]  # length = number of time steps
solph.LinearTransformer(
    label="pp_gas",
    inputs={electricity_bus: solph.Flow()},
    outputs={heat_bus: solph.Flow(nominal_value=maximum_output)},
    conversion_factors={electricity_bus: cop})
</code>```

With oemof >= v0.1.2 you can use two or three buses. But think hard if gain an extra value by using a third bus.

```<code>from oemof import solph
b_el = solph.Bus(label='electricity')
b_th_low = solph.Bus(label='low_temp_heat')
b_th_high = solph.Bus(label='high_temp_heat')

cop = 3  # coefficient of performance of the heat pump

solph.LinearN1Transformer(
    label='heat_pump',
    inputs={bus_elec: Flow(), bus_low_temp_heat: Flow()},
    outputs={bus_th_high: Flow()},
    conversion_factors={bus_elec: cop,
                        b_th_low: cop/(cop-1)})
</code>```

Title: Modelling a heat pump in oemof (solph)

Body:
It depends on which oemof version you use. If you use oemof < v0.1.2 you have to model it with just two buses. You can calculate the COP in advance using the temperature of the reservoir and the average temperature of the heat bus. You can pass it as a list, numpy.array, pandas.Series etc..

from oemof import solph
cop = [2.5, 2.3, 2.5]  # length = number of time steps
solph.LinearTransformer(
    label="pp_gas",
    inputs={electricity_bus: solph.Flow()},
    outputs={heat_bus: solph.Flow(nominal_value=maximum_output)},
    conversion_factors={electricity_bus: cop})

With oemof >= v0.1.2 you can use two or three buses. But think hard if gain an extra value by using a third bus.

from oemof import solph
b_el = solph.Bus(label='electricity')
b_th_low = solph.Bus(label='low_temp_heat')
b_th_high = solph.Bus(label='high_temp_heat')

cop = 3  # coefficient of performance of the heat pump

solph.LinearN1Transformer(
    label='heat_pump',
    inputs={bus_elec: Flow(), bus_low_temp_heat: Flow()},
    outputs={bus_th_high: Flow()},
    conversion_factors={bus_elec: cop,
                        b_th_low: cop/(cop-1)})


问:
Parsing YAML with Scala
I have a simple YAML file, which is a map of maps:

```<code>top_level_1:
  entry_1: value_1
  entry_2: value_2
top_level_2:
  entry_3: value_3
  entry_4: value_4
</code>```

How can I parse it to map of maps in Scala?

```<code>Map("top_level_1" -> Map("entry_1" -> "value_1",
                         "entry_2" -> "value_2"),
    "top_level_2" -> Map("entry_3" -> "value_3",
                         "entry_4" -> "value_4"))
</code>```

答:
You most likely want to use a yaml parser that converts it into scala classes.
Look into using jackson with scala module and yaml dataformat module.</p>

```<code>val mapper = new ObjectMapper(new YAMLFactory()) with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)

final case class YamlData(something: SomeYamlData, map: Map[String, String])
final case class SomeYamlData(field: String)
val myYamlData = mapper.readValue[YamlData](yaml)
</code>```

Title: Parsing YAML with Scala

Body:
I have a simple YAML file, which is a map of maps:

top_level_1:
  entry_1: value_1
  entry_2: value_2
top_level_2:
  entry_3: value_3
  entry_4: value_4

How can I parse it to map of maps in Scala?

Map("top_level_1" -> Map("entry_1" -> "value_1",
                         "entry_2" -> "value_2"),
    "top_level_2" -> Map("entry_3" -> "value_3",
                         "entry_4" -> "value_4"))

Body:
You most likely want to use a yaml parser that converts it into scala classes.
Look into using jackson with scala module and yaml dataformat module.

val mapper = new ObjectMapper(new YAMLFactory()) with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)

final case class YamlData(something: SomeYamlData, map: Map[String, String])
final case class SomeYamlData(field: String)
val myYamlData = mapper.readValue[YamlData](yaml)


问:
How to defferentiate several running java Jar in windows
I have a Windows server which run several java .jar running in the background.
For example programABC.jar, programDEF.jar, and so on.
They were triggered trough the Windows task scheduler.

I can see through DOS command line tasklist or Windows "Task Manager" there are a couple of java.exe currently running, I can also tell their Process ID. But I don't know which instance belong to which jar program. How to identify these processes?

As a comparison in linux if we have the Process ID we can just cat /proc/YOURPID/maps that will give a clue what is the program name, run from where, etc.

Thanks in advance

答: In Task Manager processes tab click View|Select Columns. Scroll down the list then select "Command Line" then OK. You should see the command line of the process which should include the .jar file used.</p>


问:
How do I strip all javascript out of an HTML document using PHP?
In my email program I use Tidy to clean up the HTML before I send out the emails. A problem is beginning to persist that if I send a mail fetching the html from a url on the web there may exist some javascript in the document.

I want to clean up this html document even more by stripping out all javascript, embedded, referenced and in any form so that the mail exist only of html.

I want to use php's preg_replace() to strip out all javascript from a mail and I need some help with the best regex because it's not my strongest point i must confess.

答:
```<code>echo preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $var);
</code>```

As shown here.

Body:
echo preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $var);

As shown here.


问:
git push fails: `refusing to update checked out branch: refs/heads/master`
I want to store my local modifications to JBoss config in git. For this, I have set up the following structure:

```<code>lrwxrwxrwx  1 jboss jboss        19 Jan 24 11:53 current -> jboss-as-7.1.0.CR1b
drwxr-xr-x 11 jboss jboss      4096 Jan 24 12:13 jboss-as-7.1.0.CR1b
-rw-r--r--  1 jboss jboss 108211143 Jan 23 16:02 jboss-as-7.1.0.CR1b.tar.gz
drwxr-xr-x  6 jboss jboss      4096 Jan 24 11:36 local
</code>```

local is the git repository which shall be the "origin". The idea is that I want to be able to easily update my JBoss distribution once an update is available. I want to store all local modifications to the distributed JBoss package in git.

So, currently I do this:

```<code>jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git init
Initialized empty Git repository in /opt/jboss/jboss-as-7.1.0.CR1b/.git/
jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git remote add origin ../local/
jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git pull origin master
From ../local
 * branch            master     -> FETCH_HEAD
</code>```

So far so good, all my local modifications are there where I want them.

However, once I have local modifications and want to bush them back to the local repository, I get an error:

```<code>jboss@tpl0:~/jboss-as-7.1.0.CR1b$ vim standalone/configuration/standalone.xml
jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git commit -a -m "renamed database to project2_core,   to distinguish from other projects"
[master 3e54f34] renamed database to project2_core, to distinguish from other projects
Committer: jboss <jboss@tpl0.(none)>
 1 files changed, 1 insertions(+), 1 deletions(-)

jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git push origin master
Counting objects: 9, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (5/5), 447 bytes, done.
Total 5 (delta 3), reused 0 (delta 0)
Unpacking objects: 100% (5/5), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable t
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing int
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in som
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, se
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To ../local/
 ! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '../local/'
</code>```

What can I do about this? Any help is greatly appreciated!

EDIT

Here's what I did, which solved the problem:

```<code>cd ~/current
git init
vim .gitignore                   # set up a basic .gitignore file
git add .gitignore
git commit -a -m "initial commit"
cd ~/local
git clone ~/current
git branch -m master current     # rename master branch to 'current'
git branch repo
git checkout repo
</code>```

Now, the branch current in directory ~/local is always up-to-date, but it's not cheked out, so that i can push into it.

答: I know this is quite an old question, but if you go with git init --bare, watch out for 'GIT_DIR=.' which will be set for a bare repo hook if using hooks to checkout the repo after pushing.  Use 'export GIT_DIR=.git' in your hook routine to make it recognise the repo you are pulling into....</p>

Body:
I want to store my local modifications to JBoss config in git. For this, I have set up the following structure:

lrwxrwxrwx  1 jboss jboss        19 Jan 24 11:53 current -> jboss-as-7.1.0.CR1b
drwxr-xr-x 11 jboss jboss      4096 Jan 24 12:13 jboss-as-7.1.0.CR1b
-rw-r--r--  1 jboss jboss 108211143 Jan 23 16:02 jboss-as-7.1.0.CR1b.tar.gz
drwxr-xr-x  6 jboss jboss      4096 Jan 24 11:36 local

local is the git repository which shall be the "origin". The idea is that I want to be able to easily update my JBoss distribution once an update is available. I want to store all local modifications to the distributed JBoss package in git.

So, currently I do this:

jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git init
Initialized empty Git repository in /opt/jboss/jboss-as-7.1.0.CR1b/.git/
jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git remote add origin ../local/
jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git pull origin master
From ../local
 * branch            master     -> FETCH_HEAD

So far so good, all my local modifications are there where I want them.

However, once I have local modifications and want to bush them back to the local repository, I get an error:

jboss@tpl0:~/jboss-as-7.1.0.CR1b$ vim standalone/configuration/standalone.xml
jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git commit -a -m "renamed database to project2_core,   to distinguish from other projects"
[master 3e54f34] renamed database to project2_core, to distinguish from other projects
Committer: jboss <jboss@tpl0.(none)>
 1 files changed, 1 insertions(+), 1 deletions(-)

jboss@tpl0:~/jboss-as-7.1.0.CR1b$ git push origin master
Counting objects: 9, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (5/5), 447 bytes, done.
Total 5 (delta 3), reused 0 (delta 0)
Unpacking objects: 100% (5/5), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable t
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing int
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in som
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, se
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To ../local/
 ! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '../local/'

What can I do about this? Any help is greatly appreciated!

EDIT

Here's what I did, which solved the problem:

cd ~/current
git init
vim .gitignore                   # set up a basic .gitignore file
git add .gitignore
git commit -a -m "initial commit"
cd ~/local
git clone ~/current
git branch -m master current     # rename master branch to 'current'
git branch repo
git checkout repo

Now, the branch current in directory ~/local is always up-to-date, but it's not cheked out, so that i can push into it.


问:
Aurelia iterate over map where keys are strings
I'm having trouble getting Aurelia to iterate over a map where the keys are strings (UUIDs).

Here is an example of the data I'm getting from an API running somewhere else:

```<code>my_data = {
  "5EI22GER7NE2XLDCPXPT5I2ABE": {
    "my_property": "a value"
  },
  "XWBFODLN6FHGXN3TWF22RBDA7A": {
    "my_property": "another value"
  }
}
</code>```

And I'm trying to use something like this:

```<code><template>
<div class="my_class">
    <ul class="list-group">
        <li repeat.for="[key, value] of my_data" class="list-group-item">
                <span>${key} - ${value.my_property}</span>
        </li>
    </ul>
</div>
</template>
</code>```

But Aurelia is telling me that Value for 'my_data' is non-repeatable.

I've found various answer by googling, but they have not been clearly explained or incomplete. Either I'm googling wrong or a good SO question and answer is needed.

答:
The easiest method would be to convert this into an array yourself (in the ViewModel code)

Or you could use a ValueConverter inside repeat.for as described in this article Iterating Objects

The code...

```<code>// A ValueConverter for iterating an Object's properties inside of a repeat.for in Aurelia
export class ObjectKeysValueConverter {
    toView(obj) {
        // Create a temporary array to populate with object keys
        let temp = [];

        // A basic for..in loop to get object properties
        // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in
        for (let prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                temp.push(obj[prop]);
            }
        }

        return temp;
    }
}

/**
 * Usage
 * Shows how to use the custom ValueConverter to iterate an objects properties
 * aka its keys.
 *
 * <require from="ObjectKeys"></require>
 * <li repeat.for="prop of myVmObject | objectKeys">${prop}</li>
 */
</code>```

OR, you could use the Aurelia Repeat Strategies provided by an Aurelia Core Team member

You'd have to import the plugin into your app.
Then you'd use it using the pipe syntax in your repeat.for....like so....

```<code><div repeat.for="[key, value] of data | iterable">
    ${key} ${value.my_property}
</div>
</code>```

Body:
I'm having trouble getting Aurelia to iterate over a map where the keys are strings (UUIDs).

Here is an example of the data I'm getting from an API running somewhere else:

my_data = {
  "5EI22GER7NE2XLDCPXPT5I2ABE": {
    "my_property": "a value"
  },
  "XWBFODLN6FHGXN3TWF22RBDA7A": {
    "my_property": "another value"
  }
}

And I'm trying to use something like this:

<template>

                ${key} - ${value.my_property}

</template>

But Aurelia is telling me that Value for 'my_data' is non-repeatable.

I've found various answer by googling, but they have not been clearly explained or incomplete. Either I'm googling wrong or a good SO question and answer is needed.

Body:
The easiest method would be to convert this into an array yourself (in the ViewModel code)

Or you could use a ValueConverter inside repeat.for as described in this article Iterating Objects

The code...

// A ValueConverter for iterating an Object's properties inside of a repeat.for in Aurelia
export class ObjectKeysValueConverter {
    toView(obj) {
        // Create a temporary array to populate with object keys
        let temp = [];

        // A basic for..in loop to get object properties
        // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in
        for (let prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                temp.push(obj[prop]);
            }
        }

        return temp;
    }
}

/**
 * Usage
 * Shows how to use the custom ValueConverter to iterate an objects properties
 * aka its keys.
 *
 * <require from="ObjectKeys"></require>
 * <li repeat.for="prop of myVmObject | objectKeys">${prop}</li>
 */

OR, you could use the Aurelia Repeat Strategies provided by an Aurelia Core Team member

You'd have to import the plugin into your app.
Then you'd use it using the pipe syntax in your repeat.for....like so....

<div repeat.for="[key, value] of data | iterable">
    ${key} ${value.my_property}
</div>


问:
Remove 'is missing from working copy' alerts in Xcode
We are trying to remove the Zendesk support previously used in our app, however when we removed it, we ended up with around 200 alerts, saying "(file path) is missing from the working copy." Although this is not effecting our app from running, the alerts are annoying, we have tried updating Xcode but no luck.

Does anyone know how to remove these alerts?

答:
Xcode warns you that you have removed files from the working copy, which are checked in to your repository (git?).

Simply commit your changes to get rid of the warnings.


问:
How can i customize the button if it set a AcceptButton of the form?
I have implemented the custom button control with some additional options. And added my custom button into the form. When i set the Form.Acception is the added custom button, then I want to do some customization in the Button. I want to customize the button appearance in the Custom button class implementation, when it marked as AcceptButton of the Form.

Anyone suggest how can i know the button is marked as AcceptButton of the form in Button class?

答:
WRONG:

protected override void OnLoad(EventArgs e)
      {
          base.OnLoad(e);
          if (((Form)this.TopLevelControl).AcceptButton == this)
              ....
      }

UPD:

```<code>public class MyButton : Button
    {
        public override void NotifyDefault(bool value)
        {
            if (this.IsDefault != value)
            {
                this.IsDefault = value;
            }

            if (IsDefault)
            {
                this.BackColor = Color.Red;
            }
            else
            {
                this.BackColor = Color.Green;
            }
        }
    }
</code>```

Body:
WRONG:

protected override void OnLoad(EventArgs e)
      {
          base.OnLoad(e);
          if (((Form)this.TopLevelControl).AcceptButton == this)
              ....
      }

UPD:

public class MyButton : Button
    {
        public override void NotifyDefault(bool value)
        {
            if (this.IsDefault != value)
            {
                this.IsDefault = value;
            }

            if (IsDefault)
            {
                this.BackColor = Color.Red;
            }
            else
            {
                this.BackColor = Color.Green;
            }
        }
    }


问:
Read excel file from a stream
I need a way to read a Excel file from a stream. It doesn't seem to work with the ADO.NET way of doing things.

The scenario is that a user uploads a file through a FileUpload and i need to read some values from the file and import to a database.

For several reasons I can't save the file to disk, and there is no reason to do so either.

So, anyone know of a way to read a Excel file from a FileUpload stream?

答:
This can be done easily with EPPlus.</p>
```<code>//the excel sheet as byte array (as example from a FileUpload Control)
byte[] bin = FileUpload1.FileBytes;

//gen the byte array into the memorystream
using (MemoryStream ms = new MemoryStream(bin))
using (ExcelPackage package = new ExcelPackage(ms))
{
    //get the first sheet from the excel file
    ExcelWorksheet sheet = package.Workbook.Worksheets[1];

    //loop all rows in the sheet
    for (int i = sheet.Dimension.Start.Row; i <= sheet.Dimension.End.Row; i++)
    {
        //loop all columns in a row
        for (int j = sheet.Dimension.Start.Column; j <= sheet.Dimension.End.Column; j++)
        {
            //do something with the current cell value
            string currentCellValue = sheet.Cells[i, j].Value.ToString();
        }
    }
}
</code>```

OwnerDisplayName: Kristian

Title: Read excel file from a stream

Body:
This can be done easily with EPPlus.

//the excel sheet as byte array (as example from a FileUpload Control)
byte[] bin = FileUpload1.FileBytes;

//gen the byte array into the memorystream
using (MemoryStream ms = new MemoryStream(bin))
using (ExcelPackage package = new ExcelPackage(ms))
{
    //get the first sheet from the excel file
    ExcelWorksheet sheet = package.Workbook.Worksheets[1];

    //loop all rows in the sheet
    for (int i = sheet.Dimension.Start.Row; i <= sheet.Dimension.End.Row; i++)
    {
        //loop all columns in a row
        for (int j = sheet.Dimension.Start.Column; j <= sheet.Dimension.End.Column; j++)
        {
            //do something with the current cell value
            string currentCellValue = sheet.Cells[i, j].Value.ToString();
        }
    }
}


问:
Multiple OfType Linq?
I have a linq query that selects all textboxes in a placeholder and adds them to a list using a struct. I need to expand this functionality to also take the selectedvalue of a DropDownList I am pretty sure I am doing this wrong, because when I debug the method the lists count is 0.

My own guess is that declaring 2 OfType<>() is wrong, but I am pretty new to linq and I have no idea of how else to do it.

Any help would be awesome! Thanks in advance.

Here's what I have so far:

```<code>public struct content
{
    public string name;
    public string memberNo;
    public int points;
    public string carclass;
}

List<content> rows = new List<content>();

protected void LinkButton_Submit_Attendees_Click(object sender, EventArgs e)
{
List<content> rows = PlaceHolder_ForEntries.Controls.OfType<TextBox>().OfType<DropDownList>()
        .Select(txt => new
        {
            Txt = txt,
            Number = new String(txt.ID.SkipWhile(c => !Char.IsDigit(c)).ToArray())
        })
        .GroupBy(x => x.Number)
        .Select(g => new content
        {
            carclass = g.First(x => x.Txt.ID.StartsWith("DropDownlist_CarClass")).Txt.SelectedValue,
            name = g.First(x => x.Txt.ID.StartsWith("TextBox_Name")).Txt.Text,
            memberNo = g.First(x => x.Txt.ID.StartsWith("TextBox_MemberNo")).Txt.Text,
            points = int.Parse(g.First(x => x.Txt.ID.StartsWith("TextBox_Points")).Txt.Text)
        })
        .ToList();
}
</code>```

Here's the method that creates the controls.

```<code>protected void createcontrols()
{
    int count = 0;
    if (ViewState["count"] != null)
    {
        count = (int)ViewState["count"];
    }
    while (PlaceHolder_ForEntries.Controls.Count < count)
    {
        TextBox TextBox_Name = new TextBox();
        TextBox TextBox_MemberNo = new TextBox();
        TextBox TextBox_Points = new TextBox();
        DropDownList DropDownList_CarClass = new DropDownList();
        DropDownList_CarClass.Items.Add("Car1");
        ...
        DropDownList_CarClass.Items.Add("Car2");
        TextBox_Name.Attributes.Add("placeholder", "Navn");
        TextBox_Name.ID = "TextBox_Name" + PlaceHolder_ForEntries.Controls.Count.ToString();
        TextBox_Name.CssClass = "input-small";
        TextBox_MemberNo.Attributes.Add("placeholder", "Medlemsnr.");
        TextBox_MemberNo.ID = "TextBox_MemberNo" + PlaceHolder_ForEntries.Controls.Count.ToString();
        TextBox_MemberNo.CssClass = "input-small";
        TextBox_Points.Attributes.Add("placeholder", "Point");
        TextBox_Points.ID = "TextBox_Points" + PlaceHolder_ForEntries.Controls.Count.ToString();
        TextBox_Points.CssClass = "input-small";
        PlaceHolder_ForEntries.Controls.Add(TextBox_Name);
        PlaceHolder_ForEntries.Controls.Add(TextBox_MemberNo);
        PlaceHolder_ForEntries.Controls.Add(DropDownList_CarClass);
        PlaceHolder_ForEntries.Controls.Add(TextBox_Points);
        PlaceHolder_ForEntries.Controls.Add(new LiteralControl("<br />"));
    }
}
</code>```

答:
Took @Shimmys answer for an extension method:

```<code>/// <param name="wantedTypes">--- Sample: --- new Type[] { typeof(Label), typeof(Button) }</param>
public static IEnumerable OfTypes(this IEnumerable collection, Type[] wantedTypes)
{
    if (wantedTypes == null)
        return null;
    else
        return collection.Cast<object>().Where(element => wantedTypes.Contains(element.GetType()));
}
</code>```

Usage:

```<code>// List of 3 different controls
List<object> controls = new List<object>(new object[] { new Label(), new Button(), new TextBox() });

// Get all labels and buttons
var labelsAndButtons = controls.OfTypes(new Type[] { typeof(Label), typeof(Button) });
</code>```

Title: Multiple OfType Linq?

Body:
I have a linq query that selects all textboxes in a placeholder and adds them to a list using a struct. I need to expand this functionality to also take the selectedvalue of a DropDownList I am pretty sure I am doing this wrong, because when I debug the method the lists count is 0.

My own guess is that declaring 2 OfType<>() is wrong, but I am pretty new to linq and I have no idea of how else to do it.

Any help would be awesome! Thanks in advance.

Here's what I have so far:

public struct content
{
    public string name;
    public string memberNo;
    public int points;
    public string carclass;
}

List<content> rows = new List<content>();

protected void LinkButton_Submit_Attendees_Click(object sender, EventArgs e)
{
List<content> rows = PlaceHolder_ForEntries.Controls.OfType<TextBox>().OfType<DropDownList>()
        .Select(txt => new
        {
            Txt = txt,
            Number = new String(txt.ID.SkipWhile(c => !Char.IsDigit(c)).ToArray())
        })
        .GroupBy(x => x.Number)
        .Select(g => new content
        {
            carclass = g.First(x => x.Txt.ID.StartsWith("DropDownlist_CarClass")).Txt.SelectedValue,
            name = g.First(x => x.Txt.ID.StartsWith("TextBox_Name")).Txt.Text,
            memberNo = g.First(x => x.Txt.ID.StartsWith("TextBox_MemberNo")).Txt.Text,
            points = int.Parse(g.First(x => x.Txt.ID.StartsWith("TextBox_Points")).Txt.Text)
        })
        .ToList();
}

Here's the method that creates the controls.

protected void createcontrols()
{
    int count = 0;
    if (ViewState["count"] != null)
    {
        count = (int)ViewState["count"];
    }
    while (PlaceHolder_ForEntries.Controls.Count < count)
    {
        TextBox TextBox_Name = new TextBox();
        TextBox TextBox_MemberNo = new TextBox();
        TextBox TextBox_Points = new TextBox();
        DropDownList DropDownList_CarClass = new DropDownList();
        DropDownList_CarClass.Items.Add("Car1");
        ...
        DropDownList_CarClass.Items.Add("Car2");
        TextBox_Name.Attributes.Add("placeholder", "Navn");
        TextBox_Name.ID = "TextBox_Name" + PlaceHolder_ForEntries.Controls.Count.ToString();
        TextBox_Name.CssClass = "input-small";
        TextBox_MemberNo.Attributes.Add("placeholder", "Medlemsnr.");
        TextBox_MemberNo.ID = "TextBox_MemberNo" + PlaceHolder_ForEntries.Controls.Count.ToString();
        TextBox_MemberNo.CssClass = "input-small";
        TextBox_Points.Attributes.Add("placeholder", "Point");
        TextBox_Points.ID = "TextBox_Points" + PlaceHolder_ForEntries.Controls.Count.ToString();
        TextBox_Points.CssClass = "input-small";
        PlaceHolder_ForEntries.Controls.Add(TextBox_Name);
        PlaceHolder_ForEntries.Controls.Add(TextBox_MemberNo);
        PlaceHolder_ForEntries.Controls.Add(DropDownList_CarClass);
        PlaceHolder_ForEntries.Controls.Add(TextBox_Points);
        PlaceHolder_ForEntries.Controls.Add(new LiteralControl("
"));
    }
}

Body:
Took @Shimmys answer for an extension method:

/// <param name="wantedTypes">--- Sample: --- new Type[] { typeof(Label), typeof(Button) }</param>
public static IEnumerable OfTypes(this IEnumerable collection, Type[] wantedTypes)
{
    if (wantedTypes == null)
        return null;
    else
        return collection.Cast<object>().Where(element => wantedTypes.Contains(element.GetType()));
}

Usage:

// List of 3 different controls
List<object> controls = new List<object>(new object[] { new Label(), new Button(), new TextBox() });

// Get all labels and buttons
var labelsAndButtons = controls.OfTypes(new Type[] { typeof(Label), typeof(Button) });


问:
Insert a string at a specific index
How can I insert a string at a specific index of another string?

```<code> var txt1 = "foo baz"
</code>```

Suppose I want to insert "bar " after the "foo" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

答:
Given your current example you could achieve the result by either

```<code>var txt2 = txt1.split(' ').join(' bar ')
</code>```

or

```<code>var txt2 = txt1.replace(' ', ' bar ');
</code>```

but given that you can make such assumptions, you might as well skip directly to Gullen's example.

In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.

Title: Insert a string at a specific index

Body:
How can I insert a string at a specific index of another string?

 var txt1 = "foo baz"

Suppose I want to insert "bar " after the "foo" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

Body:
Given your current example you could achieve the result by either

var txt2 = txt1.split(' ').join(' bar ')

or

var txt2 = txt1.replace(' ', ' bar ');

but given that you can make such assumptions, you might as well skip directly to Gullen's example.

In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.


问:
how to keep the response.body() data of Retrofit onRespose() call in a singleton
I tried to store the data from response.body() during a network call using retrofit. But I couldn't access the data using a singleton object.

Here is my singleton class code:

```<code>public class FishCategory {
    private SparseArray<String> sparseArray = new SparseArray<>(3);
    private static FishCategory singleton;

    public static FishCategory getSingleton() {
        if (singleton == null) {
            singleton = new FishCategory();
        }
        return singleton;
    }

    public SparseArray<String> getSparse() {
        ApiService service = ApiClient.getClient().create(ApiService.class);
        Call<CategoryResp> call = service.categoryAPI();
        call.enqueue(new Callback<CategoryResp>() {
            @Override
            public void onResponse(Call<CategoryResp> call, Response<CategoryResp> response) {

                CategoryResp categoryResp = response.body();
                for (int i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
                    sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
                }
            }

            @Override
            public void onFailure(Call<CategoryResp> call, Throwable t) {

            }
        });
        return sparseArray;
    }
}
</code>```

Now if I use this singleton object in a different class, it returns null.
PLEASE HELP....

答:
```<code>public SparseArray<String> getSparse() {
        ApiService service = ApiClient.getClient().create(ApiService.class);
        Call<CategoryResp> call = service.categoryAPI();
        call.enqueue(new Callback<CategoryResp>() {
            @Override
            public void onResponse(Call<CategoryResp> call, Response<CategoryResp> response) {

                CategoryResp categoryResp = response.body();
                for (int i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
                    sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
                }
            }

            @Override
            public void onFailure(Call<CategoryResp> call, Throwable t) {

            }
        });
        return sparseArray;
    }
</code>```

You are not creating non blocking coding in this case .Using enqueue you are shifting it to a separate thread while your code is still being executed which would obviously not wait for your code to execute.So your sparseArray is null.
Please use below for blocking nature and do note that below would be working on Main UI thread which would throw exception.

```<code>TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
List<Task>> tasks = call.execute().body();
</code>```

Read below for understanding synchronous and asynchronous nature .
https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests

```<code>    public SparseArray<String> getSparse() {
            ApiService service = ApiClient.getClient().create(ApiService.class);
            Call<CategoryResp> call = service.categoryAPI();
            call.execute().body();
            for( i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
                        sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
            }
            return sparseArray;
        }
</code>```

Body:
I tried to store the data from response.body() during a network call using retrofit. But I couldn't access the data using a singleton object.

Here is my singleton class code:

public class FishCategory {
    private SparseArray<String> sparseArray = new SparseArray<>(3);
    private static FishCategory singleton;

    public static FishCategory getSingleton() {
        if (singleton == null) {
            singleton = new FishCategory();
        }
        return singleton;
    }

    public SparseArray<String> getSparse() {
        ApiService service = ApiClient.getClient().create(ApiService.class);
        Call<CategoryResp> call = service.categoryAPI();
        call.enqueue(new Callback<CategoryResp>() {
            @Override
            public void onResponse(Call<CategoryResp> call, Response<CategoryResp> response) {

                CategoryResp categoryResp = response.body();
                for (int i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
                    sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
                }
            }

            @Override
            public void onFailure(Call<CategoryResp> call, Throwable t) {

            }
        });
        return sparseArray;
    }
}

Now if I use this singleton object in a different class, it returns null.
PLEASE HELP....

Body:
public SparseArray<String> getSparse() {
        ApiService service = ApiClient.getClient().create(ApiService.class);
        Call<CategoryResp> call = service.categoryAPI();
        call.enqueue(new Callback<CategoryResp>() {
            @Override
            public void onResponse(Call<CategoryResp> call, Response<CategoryResp> response) {

                CategoryResp categoryResp = response.body();
                for (int i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
                    sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
                }
            }

            @Override
            public void onFailure(Call<CategoryResp> call, Throwable t) {

            }
        });
        return sparseArray;
    }

You are not creating non blocking coding in this case .Using enqueue you are shifting it to a separate thread while your code is still being executed which would obviously not wait for your code to execute.So your sparseArray is null.
Please use below for blocking nature and do note that below would be working on Main UI thread which would throw exception.

TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
List<Task>> tasks = call.execute().body();

Read below for understanding synchronous and asynchronous nature .
https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests

    public SparseArray<String> getSparse() {
            ApiService service = ApiClient.getClient().create(ApiService.class);
            Call<CategoryResp> call = service.categoryAPI();
            call.execute().body();
            for( i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
                        sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
            }
            return sparseArray;
        }


答:
This error normally occurs when you haven't committed. Simply try committing current changes!

If that does not remove the error try the following:

Try cleaning the project.

If that does not work do the following:

Go to Build phases.

Link Binary with libraries.

Select your framework that you want to remove and press minus button down there.

Failing that, try deleting derived data by doing Shift+Alt+Command+K

Title: Remove 'is missing from working copy' alerts in Xcode

Body:
We are trying to remove the Zendesk support previously used in our app, however when we removed it, we ended up with around 200 alerts, saying "(file path) is missing from the working copy." Although this is not effecting our app from running, the alerts are annoying, we have tried updating Xcode but no luck.

Does anyone know how to remove these alerts?


问:
Parsing a file in backward and forward direction
I have a very long file with a periodical structure (the three dots resembles numbers of lines not necessarily equal, and n is just an index):

```<code>...
string bar text1 (n-2)
...
string bar text1 (n-1)
...
string bar text1 (n)
...
STRING FOO
elements1
elements1
...
string bar text2 (n-2)
...
string bar text2 (n-1)
...
string bar text2 (n)
...
STRING FOO
elements2
elements2
...
</code>```

I am trying to make a bash script to parse this file, and print to another file the following information: find all the appearances of STRING FOO and print to the new file the elements (which can be two, for example) plus the string bar n. In order to achieve that, I have tried the following commands:

```<code>grep -A 2 "STRING FOO"  input_file.txt   >> output_file.txt
grep -B 200 "STRING FOO" input_file.txt | tac | sed -n '/'string bar n'/ { p ; q }' >> output_file.txt
</code>```

Expected output:

```<code>STRING FOO
elements1
elements1
string bar text1
STRING FOO
elements2
elements2
string bar text2
</code>```

Where the number 200 is just a "guess" of how many lines I need to go back. Those commands, besides inefficient, are not working properly. I would really appreciate someone else's help.

答:
```<code>$ sed -n '/string bar/h;/STRING FOO/{N;N;x;H;g;p}' in.txt
</code>```

Output:

```<code>STRING FOO
elements1
elements1
string bar text1 (n)
STRING FOO
elements2
elements2
string bar text2 (n)
</code>```

sed flag -n mean "do not print output by default. Printing can be done by command p.

/string bar/h - when found string "string bar", hold(command h) it in hold buffer.

/STRING FOO/{ .. } - when found string "STRING FOO" execute commands inside brackets.

N;N - append next (command N) two line to current one (i.e. "STRING FOO" + two lines "elements").

x - exchange hold and pattern buffer. Now in hold buffer 3 lines with "STRING FOO" and two with "elements".
And in current pattern buffer "string bar".

H - append current lines to hold buffer.

g - get strings from hold buffer to current pattern space.

p - print lines from current pattern space.

Body:
I have a very long file with a periodical structure (the three dots resembles numbers of lines not necessarily equal, and n is just an index):

...
string bar text1 (n-2)
...
string bar text1 (n-1)
...
string bar text1 (n)
...
STRING FOO
elements1
elements1
...
string bar text2 (n-2)
...
string bar text2 (n-1)
...
string bar text2 (n)
...
STRING FOO
elements2
elements2
...

I am trying to make a bash script to parse this file, and print to another file the following information: find all the appearances of STRING FOO and print to the new file the elements (which can be two, for example) plus the string bar n. In order to achieve that, I have tried the following commands:

grep -A 2 "STRING FOO"  input_file.txt   >> output_file.txt
grep -B 200 "STRING FOO" input_file.txt | tac | sed -n '/'string bar n'/ { p ; q }' >> output_file.txt

Expected output:

STRING FOO
elements1
elements1
string bar text1
STRING FOO
elements2
elements2
string bar text2

Where the number 200 is just a "guess" of how many lines I need to go back. Those commands, besides inefficient, are not working properly. I would really appreciate someone else's help.

Body:
$ sed -n '/string bar/h;/STRING FOO/{N;N;x;H;g;p}' in.txt

Output:

STRING FOO
elements1
elements1
string bar text1 (n)
STRING FOO
elements2
elements2
string bar text2 (n)

sed flag -n mean "do not print output by default. Printing can be done by command p.

/string bar/h - when found string "string bar", hold(command h) it in hold buffer.

/STRING FOO/{ .. } - when found string "STRING FOO" execute commands inside brackets.

N;N - append next (command N) two line to current one (i.e. "STRING FOO" + two lines "elements").

x - exchange hold and pattern buffer. Now in hold buffer 3 lines with "STRING FOO" and two with "elements".
And in current pattern buffer "string bar".

H - append current lines to hold buffer.

g - get strings from hold buffer to current pattern space.

p - print lines from current pattern space.


问:
How could I encode a long number using uppercase letters and numbers to make it shorter to type?
Is there a way I could encode a long number (e.g. 12349874529768521) as lower-case letters AND numbers for the purposes of reducing its length?  The idea is that a user might have a long number on a piece of paper.

It seems to me that if there are more symbols available, that the resulting number could be made shorter. So I'm looking for something like hexadecimal but using the larger symbol space of A-Z instead of just A-F.

This would be in C# (if it matters)

答:
Here's a similar approach to the others, using a Base-N conversion:

```<code>using System;
using System.Text;

namespace ConsoleApp3
{
    class Program
    {
        static void Main()
        {
            long n = 12349874529768521;

            string baseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#";

            var encoded = AsBaseN(n, baseChars.ToCharArray());
            Console.WriteLine(encoded); // Prints "9HXNyK2uh"

            long decoded = AsLong(encoded, baseChars.ToCharArray());
            Console.WriteLine(decoded); // Prints "12349874529768521"
        }

        public static string AsBaseN(long value, char[] baseChars)
        {
            var result = new StringBuilder();
            int targetBase = baseChars.Length;

            do
            {
                result.Append(baseChars[value % targetBase]);
                value /= targetBase;
            }
            while (value > 0);

            return result.ToString();
        }

        public static long AsLong(string number, char[] baseChars)
        {
            long result = 0;
            int numberBase = baseChars.Length;
            long multiplier = 1;

            foreach (char c in number)
            {
                result += multiplier * Array.IndexOf(baseChars, c);
                multiplier *= numberBase;
            }

            return result;
        }
    }
}
</code>```

If you want a different set of allowable characters, just change baseChars as appropriate. For example, if you just want 0-9 and A-Z:

```<code>string baseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
</code>```

This gives a result of T3OPA1YNLD3 (base 36) instead of 9HXNyK2uh (base 64).

Body:
Here's a similar approach to the others, using a Base-N conversion:

using System;
using System.Text;

namespace ConsoleApp3
{
    class Program
    {
        static void Main()
        {
            long n = 12349874529768521;

            string baseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#";

            var encoded = AsBaseN(n, baseChars.ToCharArray());
            Console.WriteLine(encoded); // Prints "9HXNyK2uh"

            long decoded = AsLong(encoded, baseChars.ToCharArray());
            Console.WriteLine(decoded); // Prints "12349874529768521"
        }

        public static string AsBaseN(long value, char[] baseChars)
        {
            var result = new StringBuilder();
            int targetBase = baseChars.Length;

            do
            {
                result.Append(baseChars[value % targetBase]);
                value /= targetBase;
            }
            while (value > 0);

            return result.ToString();
        }

        public static long AsLong(string number, char[] baseChars)
        {
            long result = 0;
            int numberBase = baseChars.Length;
            long multiplier = 1;

            foreach (char c in number)
            {
                result += multiplier * Array.IndexOf(baseChars, c);
                multiplier *= numberBase;
            }

            return result;
        }
    }
}

If you want a different set of allowable characters, just change baseChars as appropriate. For example, if you just want 0-9 and A-Z:

string baseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

This gives a result of T3OPA1YNLD3 (base 36) instead of 9HXNyK2uh (base 64).


问:
Delete Row Using PHP Postgres
could someone help on below code? I have table data on that can allow user to click button to delete the row. I got error said " Undefined index: tenant_id " , Undefined variable: row.  Below are delete.php and pg-t-payment-view.php script : </p>

```<code>            <?php
            $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
            $id = $_POST['tenant_id'];

            $sql2 ="DELETE FROM payment_ref_tenancy WHERE tenant_name = '$id'";

            $result = pg_query($sql2);
            $cmdtuples = pg_affected_rows($result);
            echo $cmdtuples . " record affected.\n";
            if (!$result) {
                $errormessage = pg_last_error();
                echo "Error with query: " . $errormessage;
                exit();
            }
            pg_close();

            header('location:pg-t-payment-view.php');

            ?>
</code>```

<p>-------------pg-t-payment-view.php script</p>

```<code>          <div class="box-body table-responsive no-padding">
             <?php
            $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
            $sql2 ="select tenant_id,to_char(last_update_time, 'MM-dd-yyyy HH24:MI') as last_update_time , tenant_name, tenant_cost_category, invoice_no,tenant_agreed_cost,
            to_char(submission_date, 'MM-dd-yyyy') as submission_date,to_char(cpr_submission_to_finance, 'MM-dd-yyyy') as cpr_submission_to_finance,io,cheque_no
            FROM payment_ref_tenancy order by insert_datetime desc limit 10";

            $result = pg_query($db,$sql2);
            if (!$result) {
                $errormessage = pg_last_error();
                echo "Error with query: " . $errormessage;
                exit();
            }
            pg_close();

                echo "<table class='table table-hover table-striped'>";
                echo "<th align='center' >Date</th>";
                echo "<th align='center' >Payee</th>";
                echo "<th align='center' >Category</th>";
                echo "<th align='center' >Cost (RM)</th>";
                echo "<th align='center' >Invoice No</th>";
                echo "<th align='center' >Payment Submission Date</th>";
                echo "<th align='center'>CPR Submission to Finance</th>";
                echo "<th align='center'>IO</th>";
                echo "<th align='center'>Cheque No</th>";
                echo "<th align='center' div style ='color:#ff0000'>Action</th>";
                echo "<th align='center'></th>";
                echo "<th align='center'></th>";

                while($row=pg_fetch_assoc($result))
                { $id = $row['tenant_id'];

                echo "<tr>";
                echo "<td>" . $row['last_update_time'] . "</td>";
                echo "<td>" . $row['tenant_name'] . "</td>";
                echo "<td>" . $row['tenant_cost_category'] . "</td>";
                echo "<td>" . $row['tenant_agreed_cost'] . "</td>";
                echo "<td>" . $row['invoice_no'] . "</td>";
                echo "<td>" . $row['submission_date'] . "</td>";
                echo "<td>" . $row['cpr_submission_to_finance'] . "</td>";
                echo "<td>" . $row['io'] . "</td>";
                echo "<td>" . $row['cheque_no'] . "</td>";

                echo  "<td><a href='pg-t-payment-edit.php'>Edit</a></td>";

                echo  "<td><a href='delete.php?id=$id'><input type='hidden' name='id' value=$id>Delete</a></td>";
                echo "</tr>";}
                echo "</table>";
</code>```

<p>?>
                </p>

答:
Try to move pg_close(); in pg-t-payment-view.php somewhere after you have already worked with data fetched from database.
So basically after this loop executes: while($row=pg_fetch_assoc($result))

Change name of argument you pass in your delete button to reflect column name or change in delete.php how you get said ID.

```<code>          <div class="box-body table-responsive no-padding">
         <?php
        $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
        $sql2 ="select tenant_id,to_char(last_update_time, 'MM-dd-yyyy HH24:MI') as last_update_time , tenant_name, tenant_cost_category, invoice_no,tenant_agreed_cost,
        to_char(submission_date, 'MM-dd-yyyy') as submission_date,to_char(cpr_submission_to_finance, 'MM-dd-yyyy') as cpr_submission_to_finance,io,cheque_no
        FROM payment_ref_tenancy order by insert_datetime desc limit 10";

        $result = pg_query($db,$sql2);
        if (!$result) {
            $errormessage = pg_last_error();
            echo "Error with query: " . $errormessage;
            pg_close();
            exit();
        }

            echo "<table class='table table-hover table-striped'>";
            echo "<th align='center' >Date</th>";
            echo "<th align='center' >Payee</th>";
            echo "<th align='center' >Category</th>";
            echo "<th align='center' >Cost (RM)</th>";
            echo "<th align='center' >Invoice No</th>";
            echo "<th align='center' >Payment Submission Date</th>";
            echo "<th align='center'>CPR Submission to Finance</th>";
            echo "<th align='center'>IO</th>";
            echo "<th align='center'>Cheque No</th>";
            echo "<th align='center' div style ='color:#ff0000'>Action</th>";
            echo "<th align='center'></th>";
            echo "<th align='center'></th>";

            while($row=pg_fetch_assoc($result))
            { $id = $row['tenant_id'];

            echo "<tr>";
            echo "<td>" . $row['last_update_time'] . "</td>";
            echo "<td>" . $row['tenant_name'] . "</td>";
            echo "<td>" . $row['tenant_cost_category'] . "</td>";
            echo "<td>" . $row['tenant_agreed_cost'] . "</td>";
            echo "<td>" . $row['invoice_no'] . "</td>";
            echo "<td>" . $row['submission_date'] . "</td>";
            echo "<td>" . $row['cpr_submission_to_finance'] . "</td>";
            echo "<td>" . $row['io'] . "</td>";
            echo "<td>" . $row['cheque_no'] . "</td>";

            echo  "<td><a href='pg-t-payment-edit.php'>Edit</a></td>";

            echo  "<td><a href='delete.php?tenant_id=$id'><input type='hidden' name='id' value=$id>Delete</a></td>";
            echo "</tr>";}
            pg_close();
            echo "</table>";
?>
</code>```

Change in your delete.php how you get and use ID. If your tenant_id is integer, you can omit quotes from DELETE query.

```<code>        <?php
        $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
        $id = $_GET['tenant_id'];

        $sql2 ="DELETE FROM payment_ref_tenancy WHERE tenant_id = '$id'";

        $result = pg_query($sql2);
        $cmdtuples = pg_affected_rows($result);
        echo $cmdtuples . " record affected.\n";
        if (!$result) {
            $errormessage = pg_last_error();
            echo "Error with query: " . $errormessage;
            exit();
        }
        pg_close();

        header('location:pg-t-payment-view.php');

        ?>
</code>```

Just so you know, this code can be SQL Injected, this is security issue if untrusted people will use it.

Title: Delete Row Using PHP Postgres

Body:
could someone help on below code? I have table data on that can allow user to click button to delete the row. I got error said " Undefined index: tenant_id " , Undefined variable: row.  Below are delete.php and pg-t-payment-view.php script :

            <?php
            $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
            $id = $_POST['tenant_id'];

            $sql2 ="DELETE FROM payment_ref_tenancy WHERE tenant_name = '$id'";

            $result = pg_query($sql2);
            $cmdtuples = pg_affected_rows($result);
            echo $cmdtuples . " record affected.\n";
            if (!$result) {
                $errormessage = pg_last_error();
                echo "Error with query: " . $errormessage;
                exit();
            }
            pg_close();

            header('location:pg-t-payment-view.php');

            ?>

-------------pg-t-payment-view.php script

             <?php
            $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
            $sql2 ="select tenant_id,to_char(last_update_time, 'MM-dd-yyyy HH24:MI') as last_update_time , tenant_name, tenant_cost_category, invoice_no,tenant_agreed_cost,
            to_char(submission_date, 'MM-dd-yyyy') as submission_date,to_char(cpr_submission_to_finance, 'MM-dd-yyyy') as cpr_submission_to_finance,io,cheque_no
            FROM payment_ref_tenancy order by insert_datetime desc limit 10";

            $result = pg_query($db,$sql2);
            if (!$result) {
                $errormessage = pg_last_error();
                echo "Error with query: " . $errormessage;
                exit();
            }
            pg_close();

                echo "
";
                echo "Date	";
                echo "Payee	";
                echo "Category	";
                echo "Cost (RM)	";
                echo "Invoice No	";
                echo "Payment Submission Date	";
                echo "CPR Submission to Finance	";
                echo "IO	";
                echo "Cheque No	";
                echo "Action	";
                echo "	";
                echo "	";

                while($row=pg_fetch_assoc($result))
                { $id = $row['tenant_id'];

                echo "
";
                echo "" . $row['last_update_time'] . "	";
                echo "" . $row['tenant_name'] . "	";
                echo "" . $row['tenant_cost_category'] . "	";
                echo "" . $row['tenant_agreed_cost'] . "	";
                echo "" . $row['invoice_no'] . "	";
                echo "" . $row['submission_date'] . "	";
                echo "" . $row['cpr_submission_to_finance'] . "	";
                echo "" . $row['io'] . "	";
                echo "" . $row['cheque_no'] . "	";

                echo  "Edit	";

                echo  "<input type='hidden' name='id' value=$id>Delete	";
                echo "
";}
                echo "
";

?>

Body:
Try to move pg_close(); in pg-t-payment-view.php somewhere after you have already worked with data fetched from database.
So basically after this loop executes: while($row=pg_fetch_assoc($result))

Change name of argument you pass in your delete button to reflect column name or change in delete.php how you get said ID.

          <div class="box-body table-responsive no-padding">
         <?php
        $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
        $sql2 ="select tenant_id,to_char(last_update_time, 'MM-dd-yyyy HH24:MI') as last_update_time , tenant_name, tenant_cost_category, invoice_no,tenant_agreed_cost,
        to_char(submission_date, 'MM-dd-yyyy') as submission_date,to_char(cpr_submission_to_finance, 'MM-dd-yyyy') as cpr_submission_to_finance,io,cheque_no
        FROM payment_ref_tenancy order by insert_datetime desc limit 10";

        $result = pg_query($db,$sql2);
        if (!$result) {
            $errormessage = pg_last_error();
            echo "Error with query: " . $errormessage;
            pg_close();
            exit();
        }

            echo "<table class='table table-hover table-striped'>";
            echo "<th align='center' >Date</th>";
            echo "<th align='center' >Payee</th>";
            echo "<th align='center' >Category</th>";
            echo "<th align='center' >Cost (RM)</th>";
            echo "<th align='center' >Invoice No</th>";
            echo "<th align='center' >Payment Submission Date</th>";
            echo "<th align='center'>CPR Submission to Finance</th>";
            echo "<th align='center'>IO</th>";
            echo "<th align='center'>Cheque No</th>";
            echo "<th align='center' div style ='color:#ff0000'>Action</th>";
            echo "<th align='center'></th>";
            echo "<th align='center'></th>";

            while($row=pg_fetch_assoc($result))
            { $id = $row['tenant_id'];

            echo "<tr>";
            echo "<td>" . $row['last_update_time'] . "</td>";
            echo "<td>" . $row['tenant_name'] . "</td>";
            echo "<td>" . $row['tenant_cost_category'] . "</td>";
            echo "<td>" . $row['tenant_agreed_cost'] . "</td>";
            echo "<td>" . $row['invoice_no'] . "</td>";
            echo "<td>" . $row['submission_date'] . "</td>";
            echo "<td>" . $row['cpr_submission_to_finance'] . "</td>";
            echo "<td>" . $row['io'] . "</td>";
            echo "<td>" . $row['cheque_no'] . "</td>";

            echo  "<td><a href='pg-t-payment-edit.php'>Edit</a></td>";

            echo  "<td><a href='delete.php?tenant_id=$id'><input type='hidden' name='id' value=$id>Delete</a></td>";
            echo "</tr>";}
            pg_close();
            echo "</table>";
?>

Change in your delete.php how you get and use ID. If your tenant_id is integer, you can omit quotes from DELETE query.

        <?php
        $db = pg_connect("host=10.0.32.204 port=5432 dbname=postgres user=postgres password=postgres");
        $id = $_GET['tenant_id'];

        $sql2 ="DELETE FROM payment_ref_tenancy WHERE tenant_id = '$id'";

        $result = pg_query($sql2);
        $cmdtuples = pg_affected_rows($result);
        echo $cmdtuples . " record affected.\n";
        if (!$result) {
            $errormessage = pg_last_error();
            echo "Error with query: " . $errormessage;
            exit();
        }
        pg_close();

        header('location:pg-t-payment-view.php');

        ?>

Just so you know, this code can be SQL Injected, this is security issue if untrusted people will use it.


答:
In your project setting -> build setting -> search path.

Check there if your SDK path are there then remove it from framework search path or Header search path.


问:
Can't get ray picking to work in my 3D scene when the camera moves
I have my own 3D engine implementation around OpenGL (C++) and it has worked fine for everything these last years.

But today I stumbled upon a problem. I have this scene with spheres (planets around a sun, orbit rings and things like that, very very simple) and I want to ray pick them with the mouse.

As long as the camera/view matrix is identity, picking works. When the camera is rotated and then moved, the picking goes completely haywire. I have been searching for a solution for a while now so now I'm asking you guys.

This is the code (summarized for this question):

```<code>mat4f mProj = createPerspective(PI / 4.0f, float(res.x) / float(res.y), 0.1f, 100.0f);
mat4f mCamera = createTranslation(-1.5f, 3, -34.0f) * createRotationZ(20.0f * PI / 180.0f) * createRotationX(20.0f * PI / 180.0f);
... render scene, using shaders that transform vertices with gl_Position = mProj * mCamera * aPosition;

mat4f mUnproject = (mProj * mCamera).getInverse();
vec2f mouseClip(2.0f * float(coord.x) / float(res.x) - 1.0f, 1.0f - 2.0f * float(coord.y) / float(res.y));
vec3f rayOrigin = (mUnproject * vec4f(mouseClip, 0, 1)).xyz();
vec3f rayDir = (mUnproject * vec4f(mouseClip, -1, 1)).xyz();

// In a loop over all planets:
    mat4f mObject = createRotationY(planet.angle) * createTranslation(planet.distance, 0, 0);
    vec3f planetPos = mObject.transformCoord(vec3f(0, 0, 0));
    float R = planet.distance;

    float a = rayDir.dot(rayDir);
    float b = 2 * rayDir.x * (rayOrigin.x - planetPos.x) + 2 * rayDir.y * (rayOrigin.y - planetPos.y) + 2 * rayDir.z * (rayOrigin.z - planetPos.z);
    float c = planetPos.dot(planetPos) + rayOrigin.dot(rayOrigin) -2 * planetPos.dot(rayOrigin) - R * R;
    float d = b * b - 4 * a * c;
    if (d >= 0)
        HIT!
</code>```

So when I use identity for mCamera, everything works fine, even when I use only rotation for mCamera, it works fine. It is when I start using the translation that it goes completely wrong.
Anyone knows where I am going wrong?

答:
BDL's answer was spot on and put me back in the right direction. Indeed, when transforming coordinates myself, I forgot to do the perspective-divide. After writing so much shader code where the gpu does this for you, you forget about these things.

It is logical that this only gave issues when the camera moved and not when it was at (0, 0, 0) as then, the translation part of the transformation matrices stayed 0 and the w-factor of the coordinates were unaffected.

I immediately wrote transformCoord and transformNormal implementations in my matrix classes to prevent this error from happening again.

Also, the ray origin and direction were incorrect, although I don't really understand why yet. I now take the origin from my camera matrix (inverted of course) and calculate the direction the same way but now subtract the camera position from it to make it a direction vector. I normalize it, although I don't think it is really necessary in this case, but normalizing it will make its numbers look more readable when debugging anyway.

This works:

```<code>vec2f mouseClip(2.0f * float(coord.x) / float(res.x) - 1.0f, 1.0f - 2.0f * float(coord.y) / float(res.y));

mat4f mUnproject = (mProj * mCamera).getInverse();
mat4f mInvCamera = mCamera.getInverse();
vec3f rayOrigin(mInvCamera.m[12], mInvCamera.m[13], mInvCamera.m[14]);
vec3f rayDir = (mUnproject.transformCoord(vec3f(mouseClip, 1)) - rayOrigin).normalized();

... per planet
    vec3f planetPos = mObject.transformCoord(vec3f(0, 0, 0));
    float a = rayDir.dot(rayDir);
  float b = 2 * rayDir.x * (rayOrigin.x - planetPos.x) + 2 * rayDir.y * (rayOrigin.y - planetPos.y) + 2 * rayDir.z * (rayOrigin.z - planetPos.z);
  float c = planetPos.dot(planetPos) + rayOrigin.dot(rayOrigin) -2 * planetPos.dot(rayOrigin) - 0.4f * 0.4f;
  float d = b * b - 4 * a * c;
  if (d >= 0)
    ... HIT!
</code>```

Body:
I have my own 3D engine implementation around OpenGL (C++) and it has worked fine for everything these last years.

But today I stumbled upon a problem. I have this scene with spheres (planets around a sun, orbit rings and things like that, very very simple) and I want to ray pick them with the mouse.

As long as the camera/view matrix is identity, picking works. When the camera is rotated and then moved, the picking goes completely haywire. I have been searching for a solution for a while now so now I'm asking you guys.

This is the code (summarized for this question):

mat4f mProj = createPerspective(PI / 4.0f, float(res.x) / float(res.y), 0.1f, 100.0f);
mat4f mCamera = createTranslation(-1.5f, 3, -34.0f) * createRotationZ(20.0f * PI / 180.0f) * createRotationX(20.0f * PI / 180.0f);
... render scene, using shaders that transform vertices with gl_Position = mProj * mCamera * aPosition;

mat4f mUnproject = (mProj * mCamera).getInverse();
vec2f mouseClip(2.0f * float(coord.x) / float(res.x) - 1.0f, 1.0f - 2.0f * float(coord.y) / float(res.y));
vec3f rayOrigin = (mUnproject * vec4f(mouseClip, 0, 1)).xyz();
vec3f rayDir = (mUnproject * vec4f(mouseClip, -1, 1)).xyz();

// In a loop over all planets:
    mat4f mObject = createRotationY(planet.angle) * createTranslation(planet.distance, 0, 0);
    vec3f planetPos = mObject.transformCoord(vec3f(0, 0, 0));
    float R = planet.distance;

    float a = rayDir.dot(rayDir);
    float b = 2 * rayDir.x * (rayOrigin.x - planetPos.x) + 2 * rayDir.y * (rayOrigin.y - planetPos.y) + 2 * rayDir.z * (rayOrigin.z - planetPos.z);
    float c = planetPos.dot(planetPos) + rayOrigin.dot(rayOrigin) -2 * planetPos.dot(rayOrigin) - R * R;
    float d = b * b - 4 * a * c;
    if (d >= 0)
        HIT!

So when I use identity for mCamera, everything works fine, even when I use only rotation for mCamera, it works fine. It is when I start using the translation that it goes completely wrong.
Anyone knows where I am going wrong?

Body:
BDL's answer was spot on and put me back in the right direction. Indeed, when transforming coordinates myself, I forgot to do the perspective-divide. After writing so much shader code where the gpu does this for you, you forget about these things.

It is logical that this only gave issues when the camera moved and not when it was at (0, 0, 0) as then, the translation part of the transformation matrices stayed 0 and the w-factor of the coordinates were unaffected.

I immediately wrote transformCoord and transformNormal implementations in my matrix classes to prevent this error from happening again.

Also, the ray origin and direction were incorrect, although I don't really understand why yet. I now take the origin from my camera matrix (inverted of course) and calculate the direction the same way but now subtract the camera position from it to make it a direction vector. I normalize it, although I don't think it is really necessary in this case, but normalizing it will make its numbers look more readable when debugging anyway.

This works:

vec2f mouseClip(2.0f * float(coord.x) / float(res.x) - 1.0f, 1.0f - 2.0f * float(coord.y) / float(res.y));

mat4f mUnproject = (mProj * mCamera).getInverse();
mat4f mInvCamera = mCamera.getInverse();
vec3f rayOrigin(mInvCamera.m[12], mInvCamera.m[13], mInvCamera.m[14]);
vec3f rayDir = (mUnproject.transformCoord(vec3f(mouseClip, 1)) - rayOrigin).normalized();

... per planet
    vec3f planetPos = mObject.transformCoord(vec3f(0, 0, 0));
    float a = rayDir.dot(rayDir);
  float b = 2 * rayDir.x * (rayOrigin.x - planetPos.x) + 2 * rayDir.y * (rayOrigin.y - planetPos.y) + 2 * rayDir.z * (rayOrigin.z - planetPos.z);
  float c = planetPos.dot(planetPos) + rayOrigin.dot(rayOrigin) -2 * planetPos.dot(rayOrigin) - 0.4f * 0.4f;
  float d = b * b - 4 * a * c;
  if (d >= 0)
    ... HIT!