问:
creating new Javascript objects in angular4/typescript sending json receving json
This is going to be a long post but I need to be clear in my understanding of communicating between my server and client.

say I have a variable called  cityList:City[] = []; , and it is designed to contain a list of cities.

```<code>The model for `City` is:

    export class City{
  public name: string;

  constructor(name:string){
    this.name = name;
  }
}
</code>```

I have a api call that is designed to return a list of cities. This service has my generic getService injected into it (getservice below):

```<code>getService(url) {
    var value: any[] = [];
    this.http.get(url)
      .map(
        (response: Response) => {
          const data = response.json()
            .subscribe(
              (mappedData: any[]) => value = mappedData,
              (error) => console.log(error)
            )
              }
      );
    return value;
</code>```

The service that will act on the data:

```<code>import {Injectable, OnInit} from '@angular/core';
import 'rxjs/Rx';

import {City, Neighborhood, Cuisine, Privacy, VenueType, Amenities } from
import {ServerComService} from "./serverComService";
import {cityListUrl, venueFilterDataOptionsUrl} from 'app/backendUrls';

@Injectable()
export class DynamicFormDataService implements OnInit {

  constructor(private serverComService: ServerComService){}

  cityList: City[]= [];
  neighborhood = [];
  cuisine = [];
  privacy = [];
  venueType = [];
  amenities = [];

  cityGet(){

    if(this.cityList.length > 0 ){
      return this.cityList;
    }
    this.cityList = this.serverComService.getService(cityListUrl)
    return this.cityList;
  }

 ngOnInit(){
    this.cityGet();
}
</code>```

}

there are some typos in the imports but lets ignore them this is me just working on understanding first.

when I want to use the data in the cityList array is it just iterating through and calling that array positions city.name value?

what about if I wanted to add to the city list array?

I would have to call the city constructor,
so perhaps a function that takes form data as its arguments, then

```<code>c = new City('Pound Town');
cityList.push(c);
</code>```

then a service which called the push or put http method depending on if I am updating or creating a new.

The main and total question is then, is there anything I am missing in this process that skips transforming
Json into Javascript objects

or javascript objects to Json?

Or am I correct in my overall execution? Does setting the type of variables take the strings of json and transform them into the proper types for the objects to be used in my client code?

答:
There are a few issues with your code:

(1) You cannot return the value if it is being fetched in an asynchronous operation (such as an http request).

You'll need to return a promise to the value instead of the value itself.

Something like:

```<code>getService(url) {
    this.http.get(url).then(response => {
        // transform response and return it
    }).catch(e => console.log(e));
}
</code>```

(2) Since getService is async, cityGet also can't return value, so maybe something like:

```<code>cityGet() {
    if(this.cityList.length > 0 ){
        return Promise.resolve(this.cityList);
    }

    return this.serverComService.getService(cityListUrl).then(response => {
        this.cityList = response;
    });
}
</code>```

(3) In getService you receive a js object representing the json response, if you want to have instances of City then you need to create an instance of it per item in your result:

```<code>getService(url) {
    this.http.get(url).then(response => {
        return response.map(city => Object.assign(new City(), city));
    }).catch(e => console.log(e));
}
</code>```

Body:
This is going to be a long post but I need to be clear in my understanding of communicating between my server and client.

say I have a variable called  cityList:City[] = []; , and it is designed to contain a list of cities.

The model for `City` is:

    export class City{
  public name: string;

  constructor(name:string){
    this.name = name;
  }
}

I have a api call that is designed to return a list of cities. This service has my generic getService injected into it (getservice below):

getService(url) {
    var value: any[] = [];
    this.http.get(url)
      .map(
        (response: Response) => {
          const data = response.json()
            .subscribe(
              (mappedData: any[]) => value = mappedData,
              (error) => console.log(error)
            )
              }
      );
    return value;

The service that will act on the data:

import {Injectable, OnInit} from '@angular/core';
import 'rxjs/Rx';

import {City, Neighborhood, Cuisine, Privacy, VenueType, Amenities } from
import {ServerComService} from "./serverComService";
import {cityListUrl, venueFilterDataOptionsUrl} from 'app/backendUrls';

@Injectable()
export class DynamicFormDataService implements OnInit {

  constructor(private serverComService: ServerComService){}

  cityList: City[]= [];
  neighborhood = [];
  cuisine = [];
  privacy = [];
  venueType = [];
  amenities = [];

  cityGet(){

    if(this.cityList.length > 0 ){
      return this.cityList;
    }
    this.cityList = this.serverComService.getService(cityListUrl)
    return this.cityList;
  }

 ngOnInit(){
    this.cityGet();
}

}

there are some typos in the imports but lets ignore them this is me just working on understanding first.

when I want to use the data in the cityList array is it just iterating through and calling that array positions city.name value?

what about if I wanted to add to the city list array?

I would have to call the city constructor,
so perhaps a function that takes form data as its arguments, then

c = new City('Pound Town');
cityList.push(c);

then a service which called the push or put http method depending on if I am updating or creating a new.

The main and total question is then, is there anything I am missing in this process that skips transforming
Json into Javascript objects

or javascript objects to Json?

Or am I correct in my overall execution? Does setting the type of variables take the strings of json and transform them into the proper types for the objects to be used in my client code?

Body:
There are a few issues with your code:

(1) You cannot return the value if it is being fetched in an asynchronous operation (such as an http request).

You'll need to return a promise to the value instead of the value itself.

Something like:

getService(url) {
    this.http.get(url).then(response => {
        // transform response and return it
    }).catch(e => console.log(e));
}

(2) Since getService is async, cityGet also can't return value, so maybe something like:

cityGet() {
    if(this.cityList.length > 0 ){
        return Promise.resolve(this.cityList);
    }

    return this.serverComService.getService(cityListUrl).then(response => {
        this.cityList = response;
    });
}

(3) In getService you receive a js object representing the json response, if you want to have instances of City then you need to create an instance of it per item in your result:

getService(url) {
    this.http.get(url).then(response => {
        return response.map(city => Object.assign(new City(), city));
    }).catch(e => console.log(e));
}


来源: stackexchange

问:
AJAX, Image from file to an array
I would like to place all images contained in an image folder, and pass them all into an array. Have went through a few similar questions on stackoverflow, and I've become a bit stumped at this point.</p>

```<code>var folder = "images/";

$.ajax({
    url: folder,
    success:function(data){
        function(i,val){
            if( val.match(/\.(jpe?g|png|gif)$/) ){
                var arr = [folder + val + ","];
                console.log('contents of array' + arr);
            }
        }
    }
})
</code>```

答:
First in you program function(i, val) has error

it should be data.forEach(function(i,val))

and from server get the response as list of files inside images/. then your can iterate through them using your code.
like hostname/images/ request should give response as

```<code>['img1.jpg','img2.png'] as json
</code>```

or

you can convert all the images in server as base64 and send it back as array of string.

ContentLicense: CC BY-SA 3.0

Title: AJAX, Image from file to an array

Body:
I would like to place all images contained in an image folder, and pass them all into an array. Have went through a few similar questions on stackoverflow, and I've become a bit stumped at this point.

var folder = "images/";

$.ajax({
    url: folder,
    success:function(data){
        function(i,val){
            if( val.match(/\.(jpe?g|png|gif)$/) ){
                var arr = [folder + val + ","];
                console.log('contents of array' + arr);
            }
        }
    }
})

Body:
First in you program function(i, val) has error

it should be data.forEach(function(i,val))

and from server get the response as list of files inside images/. then your can iterate through them using your code.
like hostname/images/ request should give response as

['img1.jpg','img2.png'] as json

or

you can convert all the images in server as base64 and send it back as array of string.


问:
How can I remove bitnami banner on WordPress site?
I installed WordPress using Bitnami and now I have the Bitnami banner in the lower right corner of the page on that WordPress site. How can I remove it?</p>

答:
The easiest way to remove that weird logo of bitnami from your precious website is below:

That logo of bitnami is hosted on your own website/server so you need to remove that image from your website. The link of that logo would be in below manner just replace your website domain with "yourwebsite.com" and paste it to search bar of your browser and you will see that logo there.

http://yourwebsite.com/bitnami/images/xcorner-logo.png.pagespeed.ic.6TukXqDtLV.png

Now go to your wordpress site and go to media -> Gallery then find that logo image name there or search via search option and then delete it permanently from your wordpress site.

ContentLicense: CC BY-SA 4.0


问:
selecting a span inside a table cell
I thought this would be straightforward

$("#info-table tbody tr").each(function(){
  $(this).find(".label").addClass("black");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.black{
    font-weight:bold;
}</code>```

            THIS ONE
             hello label
            else
            here

            THIS ONE
             hello label
            else
            here

```

what am I doing wrong here?

答:
You need to change #info-table selector to .info-table. Because info-table is a class not id.
See Below Code.

$(".info-table tbody tr").each(function(){
    $(this).find(".label").addClass("black");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.black{
    font-weight:bold;
}</code>```

                THIS ONE
                 hello label
                else
                here

                THIS ONE
                 hello label
                else
                here

```

Title: selecting a span inside a table cell

Body:
I thought this would be straightforward

$("#info-table tbody tr").each(function(){
  $(this).find(".label").addClass("black");
});

.black{
    font-weight:bold;
}

            THIS ONE
             hello label
            else
            here

            THIS ONE
             hello label
            else
            here

what am I doing wrong here?

Body:
You need to change #info-table selector to .info-table. Because info-table is a class not id.
See Below Code.

$(".info-table tbody tr").each(function(){
    $(this).find(".label").addClass("black");
});

.black{
    font-weight:bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="info-table">
        <tbody>
            <tr>
                <td>THIS ONE</td>
                <td><span class='label'> hello label</span></td>
                <td>else</td>
                <td>here</td>
            </tr>
            <tr>
                <td>THIS ONE</td>
                <td><span class='label'> hello label</span></td>
                <td>else</td>
                <td>here</td>
            </tr>
        </tbody>
    </table>


问:
Pass the Count(*) to variable via T-SQL
How can I pass the Count(*) to the @FoundFields variable ? Please note that there are 2 records that satisfy this criteria in the OECompany table but thou output for @FoundFields is null :-(</p>

```<code>--******************

declare @sql nvarchar(4000)
DECLARE @MyTable nvarchar(50);
DECLARE @SecondaryTargetField nvarchar(100)
DECLARE @FoundFields int

set @sql = N'
select
 @FoundFields=(count(*))
from
 sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
where
 c.name LIKE @SecondaryTargetField
 and t.name= @MyTable'

SET @MyTable='OECompany'
SET @SecondaryTargetField='%PRODUCTGROUP%'

PRINT @sql

EXEC sp_executesql @sql, N' @FoundFields int OUTPUT, @SecondaryTargetField VARCHAR(100), @MyTable nvarchar(50)',
@FoundFields, @SecondaryTargetField, @MyTable

PRINT @FoundFields
</code>```

答:
Add OUTPUT keyword to the field you want to return from query.</p>

```<code>    EXEC sp_executesql @sql, N' @FoundFields int OUTPUT, @SecondaryTargetField VARCHAR(100), @MyTable nvarchar(50)',
@FoundFields OUTPUT,
@SecondaryTargetField,
@MyTable
</code>```

Title: Pass the Count(*) to variable via T-SQL

Body:
How can I pass the Count(*) to the @FoundFields variable ? Please note that there are 2 records that satisfy this criteria in the OECompany table but thou output for @FoundFields is null :-(

--******************

declare @sql nvarchar(4000)
DECLARE @MyTable nvarchar(50);
DECLARE @SecondaryTargetField nvarchar(100)
DECLARE @FoundFields int

set @sql = N'
select
 @FoundFields=(count(*))
from
 sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
where
 c.name LIKE @SecondaryTargetField
 and t.name= @MyTable'

SET @MyTable='OECompany'
SET @SecondaryTargetField='%PRODUCTGROUP%'

PRINT @sql

EXEC sp_executesql @sql, N' @FoundFields int OUTPUT, @SecondaryTargetField VARCHAR(100), @MyTable nvarchar(50)',
@FoundFields, @SecondaryTargetField, @MyTable

PRINT @FoundFields

Body:
Add OUTPUT keyword to the field you want to return from query.

    EXEC sp_executesql @sql, N' @FoundFields int OUTPUT, @SecondaryTargetField VARCHAR(100), @MyTable nvarchar(50)',
@FoundFields OUTPUT,
@SecondaryTargetField,
@MyTable


问:
displaying upload preview and stopping auto upload with dropzone react
Right now when the user presses the upload button and picks a file it automatically uploads the file but I don't want to do an automatic upload instead, I want to display the files first to the user that they have selected and then upload. I need help with this please help. This is all done in react.</p>

```<code>const TITLE = 'Resources'

class ResourceStep extends React.Component {

 onDrop(files) {
var file = files[0];

axios.get('/awsUrl', {
  headers: {
    filename: file.name,
    filetype: file.type
  }
})
.then(function (result) {
  var signedUrl = result.data;

  var options = {
    headers: {
      'Content-Type': file.type
    }
  };

  return axios.put(signedUrl, file, options);
})
.then(function (result) {
  console.log(result);
})
.catch(function (err) {
  console.log(err);
});
}

render() {
let dropzoneRef;
    return (
    <div>
     <Paper style={style} zDepth={3}>
       <div style={{textAlign:'center'}}>
         <label> Upload ID : <RaisedButton style={{marginLeft: '20px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
        <br/>
        <br/>
        <br/>
        <label> Upload Picture : <RaisedButton style={{marginLeft: '30px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
        <br/>
        <br/>
        <br/>
        <label> Upload Logo : <RaisedButton style={{marginLeft: '45px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
      </div>
      <Dropzone ref={(node) => { dropzoneRef = node; }} onDrop={ (files) => this.onDrop(files) } style={{display:'none'}}/>
    </Paper>
  </div>
);
}
}

const mapStateToProps = (state) => {
 return {
 initialValues: state.application.Resources
 };
 };

 ResourceStep = reduxForm({

   form: 'ResourceStep'
 })(ResourceStep)

 export default {
   Cmp: ResourceStep = connect(mapStateToProps)(ResourceStep),
  TITLE
 };
</code>```

答:
Just use preview property on the file and set that to img src.

```<code>class ResourceStep extends React.Component {
    constructor() {
        super();

        this.state = {
            file: {},
        };
    }
    onDrop = (files) => {
        var file = files[0];

        this.setState({ file });
    }
    submitFile = () => {
        axios.get('/awsUrl', {
          headers: {
            filename: this.state.file.name,
            filetype: this.state.file.type
          }
        })
        .then(function (result) {
          var signedUrl = result.data;

          var options = {
            headers: {
              'Content-Type': this.state.file.type
            }
          };

          return axios.put(signedUrl, this.state.file, options);
        })
        .then(function (result) {
          console.log(result);
        })
        .catch(function (err) {
          console.log(err);
        });
    }
    render() {
        let dropzoneRef;
            return (
            <div>
             <Paper style={style} zDepth={3}>
               <div style={{textAlign:'center'}}>
                 <label> Upload ID : <RaisedButton style={{marginLeft: '20px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
                <br/>
                <br/>
                <br/>
                <label> Upload Picture : <RaisedButton style={{marginLeft: '30px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
                <img src={this.state.file.preview} />
                <br/>
                <br/>
                <br/>
                <label> Upload Logo : <RaisedButton style={{marginLeft: '45px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
              </div>
              <button type="button" onClick={this.submitFile} />
              <Dropzone ref={(node) => { dropzoneRef = node; }} onDrop={ (files) => this.onDrop(files) } style={{display:'none'}}/>
            </Paper>
          </div>
        );
    }
}
</code>```

Body:
Right now when the user presses the upload button and picks a file it automatically uploads the file but I don't want to do an automatic upload instead, I want to display the files first to the user that they have selected and then upload. I need help with this please help. This is all done in react.

const TITLE = 'Resources'

class ResourceStep extends React.Component {

 onDrop(files) {
var file = files[0];

axios.get('/awsUrl', {
  headers: {
    filename: file.name,
    filetype: file.type
  }
})
.then(function (result) {
  var signedUrl = result.data;

  var options = {
    headers: {
      'Content-Type': file.type
    }
  };

  return axios.put(signedUrl, file, options);
})
.then(function (result) {
  console.log(result);
})
.catch(function (err) {
  console.log(err);
});
}

render() {
let dropzoneRef;
    return (

     <Paper style={style} zDepth={3}>

          Upload ID : <RaisedButton style={{marginLeft: '20px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/>

         Upload Picture : <RaisedButton style={{marginLeft: '30px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/>

         Upload Logo : <RaisedButton style={{marginLeft: '45px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/>

      <Dropzone ref={(node) => { dropzoneRef = node; }} onDrop={ (files) => this.onDrop(files) } style={{display:'none'}}/>
    </Paper>

);
}
}

const mapStateToProps = (state) => {
 return {
 initialValues: state.application.Resources
 };
 };

 ResourceStep = reduxForm({

   form: 'ResourceStep'
 })(ResourceStep)

 export default {
   Cmp: ResourceStep = connect(mapStateToProps)(ResourceStep),
  TITLE
 };

Body:
Just use preview property on the file and set that to img src.

class ResourceStep extends React.Component {
    constructor() {
        super();

        this.state = {
            file: {},
        };
    }
    onDrop = (files) => {
        var file = files[0];

        this.setState({ file });
    }
    submitFile = () => {
        axios.get('/awsUrl', {
          headers: {
            filename: this.state.file.name,
            filetype: this.state.file.type
          }
        })
        .then(function (result) {
          var signedUrl = result.data;

          var options = {
            headers: {
              'Content-Type': this.state.file.type
            }
          };

          return axios.put(signedUrl, this.state.file, options);
        })
        .then(function (result) {
          console.log(result);
        })
        .catch(function (err) {
          console.log(err);
        });
    }
    render() {
        let dropzoneRef;
            return (
            <div>
             <Paper style={style} zDepth={3}>
               <div style={{textAlign:'center'}}>
                 <label> Upload ID : <RaisedButton style={{marginLeft: '20px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
                <br/>
                <br/>
                <br/>
                <label> Upload Picture : <RaisedButton style={{marginLeft: '30px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
                <img src={this.state.file.preview} />
                <br/>
                <br/>
                <br/>
                <label> Upload Logo : <RaisedButton style={{marginLeft: '45px'}}label="Upload" primary={true} onClick={() => { dropzoneRef.open() }}/></label>
              </div>
              <button type="button" onClick={this.submitFile} />
              <Dropzone ref={(node) => { dropzoneRef = node; }} onDrop={ (files) => this.onDrop(files) } style={{display:'none'}}/>
            </Paper>
          </div>
        );
    }
}


问:
Multipeer Connectivity: Invalid service type
I am trying to use the Multipeer Connectivity framework but I am getting a crash while trying to instantiate MCNearbyServiceBrowser with a serviceType called "stc-classroom-vik".

Here is the code:

```<code>private func setUpSession() {
    self.session = MCSession(peer: self.peerId);
    self.session!.delegate = self;

    self.browser = MCNearbyServiceBrowser(peer: self.peerId, serviceType: "stc-classroom-vik");
    self.browser!.delegate =  self;

    self.advertiser = MCNearbyServiceAdvertiser(peer: self.peerId, discoveryInfo: nil, serviceType: "stc-classroom-vik");
    self.advertiser!.delegate = self;
}
</code>```

and this is the crash/error I am getting:

2014-08-15 12:24:42.689 Xavier[614:254319] *** Terminating app due to uncaught exception     'NSInvalidArgumentException', reason: 'Invalid serviceType passed to MCNearbyServiceBrowser'
```

I would really appreciate any help.

答:
The above answers are correct in that a Bonjour service type may only have 15 characters.

However, there is not a "one hyphen" limit. The wording of the Bonjour specification is to describe the characters which are permitted in the serviceType.

"stc-class-vik" is a valid serviceType

Body:
I am trying to use the Multipeer Connectivity framework but I am getting a crash while trying to instantiate MCNearbyServiceBrowser with a serviceType called "stc-classroom-vik".

Here is the code:

private func setUpSession() {
    self.session = MCSession(peer: self.peerId);
    self.session!.delegate = self;

    self.browser = MCNearbyServiceBrowser(peer: self.peerId, serviceType: "stc-classroom-vik");
    self.browser!.delegate =  self;

    self.advertiser = MCNearbyServiceAdvertiser(peer: self.peerId, discoveryInfo: nil, serviceType: "stc-classroom-vik");
    self.advertiser!.delegate = self;
}

and this is the crash/error I am getting:

2014-08-15 12:24:42.689 Xavier[614:254319] *** Terminating app due to uncaught exception     'NSInvalidArgumentException', reason: 'Invalid serviceType passed to MCNearbyServiceBrowser'

I would really appreciate any help.


问:
PHP output hex string "as is"
I am having a weird problem and have hit a road block.

Background:

I am working with MSSQL database.

The table that I am querying has a "TIMESTAMP" field.

Problem:

When I try to output the data retrieved from this column, I get weird output.

For example, suppose I have the following data saved in the field:
0x000000000ADDAB2F

PHP will output it as:
������

Perhaps it is happening because PHP is trying to convert this string to a number or something.

What I want to do is output the string "AS IS" (i.e I dont want PHP to process it at all, just output the raw data).

I am unable to find a solution that will stop PHP from processing this data.

I am using mssql_* functions to query the data.

What I have tried

As I dont even have a clue of why is it happening at all, I tried to implement whatever I could find on the Google. So far I have tried to convert the number back to its original form.

So I have used utf8_decode, mb_encode_numericentity, mb_decode_numericentity, base_convert, unpack and dechex

None of them do what I am trying to do.

If you are going to suggest converting the TIMESTAMP value to NVARCHAR or something in the SQL Query itself, then please note that this is not possible.

Because I am creating a simple generic query form, where a user will type MSSQL queries in a textarea and will get the results returned in the browser.

So he can type SELECT * FROM table and he should get all columns in the output.

So it is not possible to fix the problem in the query itself, I have to do it in PHP itself.

Any help?

答:
If you want to print/show any hex value from a variable, You can use the code below:</p>

```<code>$hex_value=0x000000000ADDAB2F;
echo sprintf("0x%'016X", $hex_value);
</code>```

Title: PHP output hex string "as is"

Body:
If you want to print/show any hex value from a variable, You can use the code below:

$hex_value=0x000000000ADDAB2F;
echo sprintf("0x%'016X", $hex_value);


问:
C# Mysql Update last row in table
I am trying  to update the last row inside a Mysql table. This is what I've been trying so far, but the problem is that it updates every row and not only the last one.

```<code> query = "UPDATE Callbacks SET UniqueID = ?UID WHERE UniqueID = (SELECT UniqueID Callbacks ORDER BY UniqueID LIMIT 1);";
                using (MySqlCommand cmd = new MySqlCommand(query, cn))
                {
                    cmd.Parameters.Add(new MySqlParameter("?UID", UID));
                    cmd.ExecuteScalar();
                }
</code>```

Any ideas?

答:
You have to use he order by in an descending order</p>

```<code>UPDATE Callbacks SET UniqueID = ?UID WHERE UniqueID = (SELECT UniqueID Callbacks ORDER BY UniqueID DESC LIMIT 1);
</code>```

Title: C# Mysql Update last row in table

Body:
I am trying  to update the last row inside a Mysql table. This is what I've been trying so far, but the problem is that it updates every row and not only the last one.

 query = "UPDATE Callbacks SET UniqueID = ?UID WHERE UniqueID = (SELECT UniqueID Callbacks ORDER BY UniqueID LIMIT 1);";
                using (MySqlCommand cmd = new MySqlCommand(query, cn))
                {
                    cmd.Parameters.Add(new MySqlParameter("?UID", UID));
                    cmd.ExecuteScalar();
                }

Any ideas?

Body:
You have to use he order by in an descending order

UPDATE Callbacks SET UniqueID = ?UID WHERE UniqueID = (SELECT UniqueID Callbacks ORDER BY UniqueID DESC LIMIT 1);


问:
How to sort a javascript array numerically twice
I have an array of bible verses that i'm trying to order according to the natural order of verses.

The array looks like this:

```<code>let array = ["1.2","1.3","1.19","2.25","1.0"]
</code>```

What i'm expecting as end result is:

```<code>1.0, 1.2, 1.3, 1.19, 2.25
</code>```

Any pointers welcome, I haven't quite managed to come up with the perfect sort function that sorts the first digit before sorting everything else on the opposite end of the decimal.

My current approach that needs to be improved I believe is:

```<code>x.sort(function(a,b){

let y = a.split(".")[1]
let x = b.split(".")[1]

return a-b && y - x;
})
</code>```

答:
let array = ["1.2","1.3","1.19","2.25","1.0"];

// split the number into the integer part and decimal part
splits = array.map(x => ({
  val: x,
  int: Number(x.split(".")[0]),
  dec: Number(x.split(".")[1])
  }));

splits.sort(function(a, b) {
    // compare the integer part first, if equal, compare decimal part
    return (a.int === b.int)?(a.dec - b.dec):(a.int - b.int);
    });

sorted = splits.map(x => x.val);
console.log(sorted);```
</div>
</div>
</p>

<p>Another option to sort array in place:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let array = ["1.2","1.3","1.19","2.25","1.0"];

array.sort(function(a, b) {

  a_split = a.split(".").map(Number);
  b_split = b.split(".").map(Number);

  return (a_split[0] === b_split[0])?(a_split[1] - b_split[1]):(a_split[0] - b_split[0]);
})

console.log(array);</code>```

Body:
I have an array of bible verses that i'm trying to order according to the natural order of verses.

The array looks like this:

let array = ["1.2","1.3","1.19","2.25","1.0"]

What i'm expecting as end result is:

1.0, 1.2, 1.3, 1.19, 2.25

Any pointers welcome, I haven't quite managed to come up with the perfect sort function that sorts the first digit before sorting everything else on the opposite end of the decimal.

My current approach that needs to be improved I believe is:

x.sort(function(a,b){

let y = a.split(".")[1]
let x = b.split(".")[1]

return a-b && y - x;
})

Body:
let array = ["1.2","1.3","1.19","2.25","1.0"];

// split the number into the integer part and decimal part
splits = array.map(x => ({
  val: x,
  int: Number(x.split(".")[0]),
  dec: Number(x.split(".")[1])
  }));

splits.sort(function(a, b) {
    // compare the integer part first, if equal, compare decimal part
    return (a.int === b.int)?(a.dec - b.dec):(a.int - b.int);
    });

sorted = splits.map(x => x.val);
console.log(sorted);

Another option to sort array in place:

let array = ["1.2","1.3","1.19","2.25","1.0"];

array.sort(function(a, b) {

  a_split = a.split(".").map(Number);
  b_split = b.split(".").map(Number);

  return (a_split[0] === b_split[0])?(a_split[1] - b_split[1]):(a_split[0] - b_split[0]);
})

console.log(array);


问:
How to load a component from a variable name in Vue.js?
I want to load a component from a dynamic variable name in my vue.js application.

I have the following component registered:

```<code><template id="goal">
  <h1>Goal:{{data.text}}</h1>
</template>
</code>```

Instead of loading it like this

```<code><goal></goal>
</code>```

I want to load from a variable name, something like this:

```<code><{{mytemplate.type}}></{{mytemplate.type}}>
</code>```

Where, of course, mytemplate.type would be, in this case equal to "goal"

答:
Use a dynamic component like this:

<component :is="myTemplate.type"></component>
```

Body:
I want to load a component from a dynamic variable name in my vue.js application.

I have the following component registered:

<template id="goal">

Goal:{{data.text}}

</template>

Instead of loading it like this

<goal></goal>

I want to load from a variable name, something like this:

<{{mytemplate.type}}></{{mytemplate.type}}>

Where, of course, mytemplate.type would be, in this case equal to "goal"


问:
Cannot access https on codeigniter
The following is my base_url of config.php in my project.

```<code>$config['base_url'] = 'https://www.mywebsite.com/';
</code>```

But my website always go to http://www.mywebsite.com unless the user implicitly write https in browser url.

What is the problem?

Why codeigniter goes to url that define in config.php ?

答:
you need to use HOOKS as it is simpler than .htaccess.
first change base url in ***

application/config/config.php

```<code>$config['base_url'] = 'https://www.mywebsite.com';
</code>```

Inside

application/config/hooks.php

write this code as:

```<code>$hook['post_controller_constructor'][] = array(
                                'function' => 'redirect_ssl',
                                'filename' => 'ssl.php',
                                'filepath' => 'hooks'
                                );
</code>```

Now make a file name as ssl.php inside

application/hooks/

and paste the below code

```<code><?php
function redirect_ssl() {
    $CI =& get_instance();
    $class = $CI->router->fetch_class();
    $exclude =  array('');  // add more controller name to exclude ssl.
    if(!in_array($class,$exclude)) {
      // redirecting to ssl.
      $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
      if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
    }
    else {
      // redirecting with no ssl.
      $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
      if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
    }
}
?>
</code>```

Now it should work like charm as I have used the same method and found as the easiest one

Title: Cannot access https on codeigniter

Body:
The following is my base_url of config.php in my project.

$config['base_url'] = 'https://www.mywebsite.com/';

But my website always go to http://www.mywebsite.com unless the user implicitly write https in browser url.

What is the problem?

Why codeigniter goes to url that define in config.php ?

Body:
you need to use HOOKS as it is simpler than .htaccess.
first change base url in ***

application/config/config.php

$config['base_url'] = 'https://www.mywebsite.com';

Inside

application/config/hooks.php

write this code as:

$hook['post_controller_constructor'][] = array(
                                'function' => 'redirect_ssl',
                                'filename' => 'ssl.php',
                                'filepath' => 'hooks'
                                );

Now make a file name as ssl.php inside

application/hooks/

and paste the below code

<?php
function redirect_ssl() {
    $CI =& get_instance();
    $class = $CI->router->fetch_class();
    $exclude =  array('');  // add more controller name to exclude ssl.
    if(!in_array($class,$exclude)) {
      // redirecting to ssl.
      $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
      if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
    }
    else {
      // redirecting with no ssl.
      $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
      if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
    }
}
?>

Now it should work like charm as I have used the same method and found as the easiest one


问:
Read file with various white spaces in R
I want to read this file into R

https://earthquake.usgs.gov/data/centennial/centennial_Y2K.CAT
I copy & pasted the text on the website into Sublime and saved it as a .csv

```<code>quakes <- read.table(file = "./anss/centinnel.csv",
                     stringsAsFactors = FALSE,
                     sep = "",
                     header = FALSE)
</code>```

the sep = "" in read.table() should handle multiple whitespaces automatically... However, I get

Row 1 does not have 27 elements.

Whats going wrong?

答:
This is a fixed-width file. Each column spans a specific number of characters. You can't assume that white space is a reliable separator, because it appears that missing data is simply left blank (a big stretch of white space). For example, row 4 has several values that are simply blank in rows 1-3.

You can use read.fwf to read this file correctly. You have to specify the width of each column, in characters. The following is my (quick) best guess at the column widths, but you will want to verify these yourself:

```<code>new.df <- read.fwf(
    'https://earthquake.usgs.gov/data/centennial/centennial_Y2K.CAT',
    widths = c(5, 8, 4, 3, 3, 4, 3, 5, 10, 8, 6, 4, 4, 4, 3, 7, 3, 3, 4, 6, 3, 4, 6, 3, 4, 6, 3, 5, 4, 3, 4, 3)
)
</code>```

Body:
I want to read this file into R

https://earthquake.usgs.gov/data/centennial/centennial_Y2K.CAT
I copy & pasted the text on the website into Sublime and saved it as a .csv

quakes <- read.table(file = "./anss/centinnel.csv",
                     stringsAsFactors = FALSE,
                     sep = "",
                     header = FALSE)

the sep = "" in read.table() should handle multiple whitespaces automatically... However, I get

Row 1 does not have 27 elements.

Whats going wrong?

Body:
This is a fixed-width file. Each column spans a specific number of characters. You can't assume that white space is a reliable separator, because it appears that missing data is simply left blank (a big stretch of white space). For example, row 4 has several values that are simply blank in rows 1-3.

You can use read.fwf to read this file correctly. You have to specify the width of each column, in characters. The following is my (quick) best guess at the column widths, but you will want to verify these yourself:

new.df <- read.fwf(
    'https://earthquake.usgs.gov/data/centennial/centennial_Y2K.CAT',
    widths = c(5, 8, 4, 3, 3, 4, 3, 5, 10, 8, 6, 4, 4, 4, 3, 7, 3, 3, 4, 6, 3, 4, 6, 3, 4, 6, 3, 5, 4, 3, 4, 3)
)


问:
Is function prototype compulsory in C++?
By this I mean that even though I define the function before the function call,is it required to have a function prototype?
I tried a program with definition b4 call,it worked.but in C++ by Herbert schildt it says C++ requires full function prototyping.so am confused.
So,does C++ really require full function prototyping?</p>

答: A function definition is also a function declaration (i.e. a prototype). So if you define the function before you call it everything will be hunkydory. And I would strongly recommend not attempting to learn C++ from the works of Herb Schildt.


问:
Pull an IP from the landing page and compare to known users
I am trying to create a working sql query that will give an accurate FLAG for a known or unknown IP address in our database upon hitting our landing page. I use this

```<code>// get the IP of the user on this landing page
$ip_address=$_SERVER['REMOTE_ADDR'];
echo $ip_address. ' ip address<br/>';

// see if we know this user..
$search_first="SELECT COUNT(DISTINCT(ip_address)) FROM `qb_sessions` WHERE `ip_address` = '$ip_address' ";
$has_ips = mysql_query($search_first);
$has_ip = mysql_num_rows($has_ips);
echo $has_ip. ' has IP<br/>'; // should show count in table
</code>```

Using this snippet does not provide the result that I need.  If the table is empty, (no match to this IP), I still get a '1' as the echo of $has_ip. I really need '0' if there is no match, and anything '&gt 1' if this IP has been recorded in qb_sessions table before. The purpose of this snippet is to identify a new, non-registered hit on this landing page and later to redirect them to another page, like join a newsletter, get a discount coupon, etc.

I have tried various combinations of the sql to no avail, including escaping the (') $ip_address quotes.

Thank you in advance for any help.

答:
Should be binding your parameters via PDO.

Here is an alternative way, here I simply check if any results have been returned.

```<code>$stmt = $conn->prepare("SELECT * FROM qb_sessions WHERE ip_address=:ip_address");
$stmt->bindParam(':ip_address', $ip_address);
$ip_address = "73.85.207.17"; // example ip
$stmt->execute();
$result = $stmt->fetchAll();
echo (count($result) > 0) ? 'IP found' : 'IP NOT found';
</code>```

Body:
I am trying to create a working sql query that will give an accurate FLAG for a known or unknown IP address in our database upon hitting our landing page. I use this

// get the IP of the user on this landing page
$ip_address=$_SERVER['REMOTE_ADDR'];
echo $ip_address. ' ip address
';

// see if we know this user..
$search_first="SELECT COUNT(DISTINCT(ip_address)) FROM `qb_sessions` WHERE `ip_address` = '$ip_address' ";
$has_ips = mysql_query($search_first);
$has_ip = mysql_num_rows($has_ips);
echo $has_ip. ' has IP
'; // should show count in table

Using this snippet does not provide the result that I need.  If the table is empty, (no match to this IP), I still get a '1' as the echo of $has_ip. I really need '0' if there is no match, and anything '&gt 1' if this IP has been recorded in qb_sessions table before. The purpose of this snippet is to identify a new, non-registered hit on this landing page and later to redirect them to another page, like join a newsletter, get a discount coupon, etc.

I have tried various combinations of the sql to no avail, including escaping the (') $ip_address quotes.

Thank you in advance for any help.

Body:
Should be binding your parameters via PDO.

Here is an alternative way, here I simply check if any results have been returned.

$stmt = $conn->prepare("SELECT * FROM qb_sessions WHERE ip_address=:ip_address");
$stmt->bindParam(':ip_address', $ip_address);
$ip_address = "73.85.207.17"; // example ip
$stmt->execute();
$result = $stmt->fetchAll();
echo (count($result) > 0) ? 'IP found' : 'IP NOT found';


问:
Determine a "tangential quadrilateral" from 4 points in OpenCv
what I'm trying to do is getting a tangential quadrilateral from 4 points using OpenCv.

I'm tried an approach where I just take the center of the four points and adding a circle. But this is not always true. Further its very hard to determine the radius of the circle.

Shortly: A tangential quadrilateral is a circle which lies completely within a square. e.g.:

Source: https://commons.wikimedia.org/wiki/File:Tangentenviereck.svg CC BY-SA 4.0

Is there a way in OpenCv for this?

答:
If you have 4 points A,B, C, D you definitely already have quadrilateral (four-side polygon).

It is not guaranteed that this tangential  is tangential - it is true only if sums of opposite side lengths are equal.

If you really have vertices of tangential tangential - find length of sides a,b,c,d and diagonals p,q and get incircle radius as

```<code>r = Sqrt(4*p^2*q^2-(a^2-b^2+c^2-d^2)^2)) / (2*(a+b+c+d))
</code>```

There is a lot of formulas for incircle center at wiki page, but I'd use trigonometric approach - get bisector vector of A angle as sum of normalized AB and AD vectors, normalize it, multiply by length |AM|=r/tg(A/2) and add resulting vector to A.

Note that OpenCV is library for image processing, not for geometric calculations.

Body:
If you have 4 points A,B, C, D you definitely already have quadrilateral (four-side polygon).

It is not guaranteed that this tangential  is tangential - it is true only if sums of opposite side lengths are equal.

If you really have vertices of tangential tangential - find length of sides a,b,c,d and diagonals p,q and get incircle radius as

r = Sqrt(4*p^2*q^2-(a^2-b^2+c^2-d^2)^2)) / (2*(a+b+c+d))

There is a lot of formulas for incircle center at wiki page, but I'd use trigonometric approach - get bisector vector of A angle as sum of normalized AB and AD vectors, normalize it, multiply by length |AM|=r/tg(A/2) and add resulting vector to A.

Note that OpenCV is library for image processing, not for geometric calculations.


问:
Testing a custom Django template filter
I have a custom template filter I created under project/app/templatetags.

I want to add some regression tests for some bugs I just found. How would I go about doing so?

答:
The easiest way to test a template filter is to test it as a regular function.

@register.filter decorator doesn't harm the underlying function, you can import the filter and use just it like if it is not decorated. This approach is useful for testing filter logic.

If you want to write more integration-style test then you should create a django Template instance and check if the output is correct (as shown in Gabriel's answer).

ContentLicense: CC BY-SA 2.5

Title: Testing a custom Django template filter


问:
Permission error every time I build in visual studio 2015
I have just started learning to program using Unreal and I am following a tutorial for Unreal Engine on Udemy and recently I've been running into a problem where every time I write code wrong and I build the project , even though there are no lines indicating errors , I get this message

>

```<code> 1>------ Build started: Project: BuildingEscape, Configuration: Development_Editor x64 ------
1>  Compiling game modules for hot reload
1>  Performing 2 actions (2 in parallel)
1>  [2/2] Link UE4Editor-BuildingEscape-2523.lib
1>  [1/2] Link UE4Editor-BuildingEscape-7173.dll
1>     Creating library D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.lib and object D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.exp
1>     Creating library D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.suppressed.lib and object D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.suppressed.exp
1>ERROR : UBT error : Failed to produce item: D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-2523.lib
1>  Total build time: 3.07 seconds (Local executor: 0.00 seconds)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.MakeFile.Targets(41,5): error MSB3075: The command ""D:\Unreal Engine\Engine\UE_4.15\Engine\Build\BatchFiles\Build.bat" BuildingEscapeEditor Win64 Development "D:\Unreal Projects\03_BuildingEscape\BuildingEscape\BuildingEscape.uproject" -waitmutex" exited with code 5. Please verify that you have sufficient rights to run this command.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

and even though I delete the code that I wrote and hit build again I get the same error...
I am using windows 10.

答: Before you go too far down the rabbit hole, check to be sure your operating system doesn't simply have a lock on one of your intermediate files. If you delete the entire contents of D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\ before rebuilding, that will ensure that you're not simply looking at a locked or corrupt intermediate. This isn't guaranteed to be the issue, but bad intermediates can cause otherwise inexplicable build errors, so clearing them can at least narrow down the range of possible causes you'll need to investigate. Of course make sure your editor isn't running, or running as a stuck process, while you're trying to rebuild.</p>

Body:
I have just started learning to program using Unreal and I am following a tutorial for Unreal Engine on Udemy and recently I've been running into a problem where every time I write code wrong and I build the project , even though there are no lines indicating errors , I get this message

>

 1>------ Build started: Project: BuildingEscape, Configuration: Development_Editor x64 ------
1>  Compiling game modules for hot reload
1>  Performing 2 actions (2 in parallel)
1>  [2/2] Link UE4Editor-BuildingEscape-2523.lib
1>  [1/2] Link UE4Editor-BuildingEscape-7173.dll
1>     Creating library D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.lib and object D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.exp
1>     Creating library D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.suppressed.lib and object D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-7173.suppressed.exp
1>ERROR : UBT error : Failed to produce item: D:\Unreal Projects\03_BuildingEscape\BuildingEscape\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-BuildingEscape-2523.lib
1>  Total build time: 3.07 seconds (Local executor: 0.00 seconds)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.MakeFile.Targets(41,5): error MSB3075: The command ""D:\Unreal Engine\Engine\UE_4.15\Engine\Build\BatchFiles\Build.bat" BuildingEscapeEditor Win64 Development "D:\Unreal Projects\03_BuildingEscape\BuildingEscape\BuildingEscape.uproject" -waitmutex" exited with code 5. Please verify that you have sufficient rights to run this command.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

and even though I delete the code that I wrote and hit build again I get the same error...
I am using windows 10.


答:
By this I mean that even though I define the function before the function call,is it required to have a function prototype?

No, it doesn't mean that.

So,does C++ really require full function prototyping?

Yes it does. The compiler needs to see at least the declaration of a function before it can be used:

```<code>void foo(int i);
</code>```

Alternatively you can provide a full (inlined) definition

```<code>inline void foo(int i) {
   // do something
}
</code>```

Title: Is function prototype compulsory in C++?

Body:
By this I mean that even though I define the function before the function call,is it required to have a function prototype?
I tried a program with definition b4 call,it worked.but in C++ by Herbert schildt it says C++ requires full function prototyping.so am confused.
So,does C++ really require full function prototyping?

Body:
By this I mean that even though I define the function before the function call,is it required to have a function prototype?

No, it doesn't mean that.

So,does C++ really require full function prototyping?

Yes it does. The compiler needs to see at least the declaration of a function before it can be used:

void foo(int i);

Alternatively you can provide a full (inlined) definition

inline void foo(int i) {
   // do something
}


问:
GetLowestPricedOffersForSKU failed processing arguments
I have a slight issue when trying to call GetLowestPricedOffersForSKU, I get the response :

Failed processing arguments of org.jboss.resteasy.spi.metadata

I can call other functions in the Product Api and they work fine, just get the above error on this function.

I have looked round the net for the answer but can't find anything that is related to this, does anybody have any idea why I'm getting this ?

By the way it all works fine in the MWS Scratchpad !

答:
MWS needs the POST data passed as form params instead of as a query string for some operations. Otherwise, it pukes a Failed processing arguments of org.jboss.resteasy.spi.metadata style 400 Bad Request error for some operations such as this one (GetMyFeesEstimate is another that suffers from this).

For instance, if you did the following POST request in Guzzle 6 then you'd likely get the error:

```<code>$response = $client->request('POST', 'https://mws.amazonservices.com/Products/2011-10-01/?AWSAccessKeyId=YOURAWSACCESSKEY&Action=GetLowestPricedOffersForASIN&SellerId=YOURSELLERID&MWSAuthToken=amzn.mws.fghsffg-4t44e-hfgh-dfgd-zgsdbfe5erg&SignatureVersion=2&Timestamp=2017-07-09T15%3A45%3A18%2B00%3A00&Version=2011-10-01&Signature=bCasdxXmYDCasdaXBhsdgse4pQ6hEbevML%2FJvzdgdsfdy2o%3D&SignatureMethod=HmacSHA256&MarketplaceId=ATVPDKIKX0DER&ASIN=B007EZK19E');
</code>```

To fix this you'd submit it as form data as in this Guzzle 6 example:

```<code>$response = $client->request('POST', 'https://mws.amazonservices.com/Products/2011-10-01', [
    'form_params' => [
        'AWSAccessKeyId' => 'YOURAWSACCESSKEY',
        'Action' => 'GetLowestPricedOffersForASIN',
        'SellerId' => 'YOURSELLERID',
        'MWSAuthToken' => 'amzn.mws.fghsffg-4t44e-hfgh-dfgd-zgsdbfe5erg',
        'SignatureVersion' => 2,
        'Timestamp' => '2017-07-09T15%3A45%3A18%2B00%3A00',
        'Version' => '2011-10-01',
        'Signature' => 'bCasdxXmYDCasdaXBhsdgse4pQ6hEbevML%2FJvzdgdsfdy2o%3D',
        'SignatureMethod' => 'HmacSHA256',
        'MarketplaceId' => 'ATVPDKIKX0DER',
        'ASIN' => 'B007EZK19E',
    ]
]);
</code>```

Body:
MWS needs the POST data passed as form params instead of as a query string for some operations. Otherwise, it pukes a Failed processing arguments of org.jboss.resteasy.spi.metadata style 400 Bad Request error for some operations such as this one (GetMyFeesEstimate is another that suffers from this).

For instance, if you did the following POST request in Guzzle 6 then you'd likely get the error:

$response = $client->request('POST', 'https://mws.amazonservices.com/Products/2011-10-01/?AWSAccessKeyId=YOURAWSACCESSKEY&Action=GetLowestPricedOffersForASIN&SellerId=YOURSELLERID&MWSAuthToken=amzn.mws.fghsffg-4t44e-hfgh-dfgd-zgsdbfe5erg&SignatureVersion=2&Timestamp=2017-07-09T15%3A45%3A18%2B00%3A00&Version=2011-10-01&Signature=bCasdxXmYDCasdaXBhsdgse4pQ6hEbevML%2FJvzdgdsfdy2o%3D&SignatureMethod=HmacSHA256&MarketplaceId=ATVPDKIKX0DER&ASIN=B007EZK19E');

To fix this you'd submit it as form data as in this Guzzle 6 example:

$response = $client->request('POST', 'https://mws.amazonservices.com/Products/2011-10-01', [
    'form_params' => [
        'AWSAccessKeyId' => 'YOURAWSACCESSKEY',
        'Action' => 'GetLowestPricedOffersForASIN',
        'SellerId' => 'YOURSELLERID',
        'MWSAuthToken' => 'amzn.mws.fghsffg-4t44e-hfgh-dfgd-zgsdbfe5erg',
        'SignatureVersion' => 2,
        'Timestamp' => '2017-07-09T15%3A45%3A18%2B00%3A00',
        'Version' => '2011-10-01',
        'Signature' => 'bCasdxXmYDCasdaXBhsdgse4pQ6hEbevML%2FJvzdgdsfdy2o%3D',
        'SignatureMethod' => 'HmacSHA256',
        'MarketplaceId' => 'ATVPDKIKX0DER',
        'ASIN' => 'B007EZK19E',
    ]
]);


问:
IDE for C application development that you admire most
I am looking for a good Integrated development environment for developing applictaions in C language for both windows and linux.

IDE should have:

good interface,

easy file management,

auto filling and

any advanced options.

Tell me which IDE you most admire for these tasks

For general PC application development

For embedded application development in C

If you think it is more specific question then you may also take it as a general case.
Thanks in advance.

答: For both purposes I'd suggest Eclipse.</p>

OwnerDisplayName: Manoj Doubts

Body: For both purposes I'd suggest Eclipse.


问:
Opencart getProductOptions in cart.php
I make a dynamic change of option names for each product.
The problem is that I'm writing the table change. Oc_product_option

By going to system / library / cart.php > public function getProducts() { } there is only loaded there product_option_value.
I want to load this code in system / library / cart.php > public function getProducts() { }

And then call it in the catalog / controller / common> cart.php

```<code>$data['options'] = array();

    foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) {
        $product_option_value_data = array();

        foreach ($option['product_option_value'] as $option_value) {
            if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
                if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                    $price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']);
                } else {
                    $price = false;
                }

                $product_option_value_data[] = array(
                    'product_option_value_id' => $option_value['product_option_value_id'],
                    'option_value_id'         => $option_value['option_value_id'],
                    'name'                    => $option_value['name'],
                    'ob_info'                    => $option_value['ob_info'],
                    'image'                   => $this->model_tool_image->onesize($option_value['image'], 100, 100),
                    'price'                   => $price,
                    'price_prefix'            => $option_value['price_prefix']
                );
            }
        }

        $data['options'][] = array(
            'product_option_id'    => $option['product_option_id'],
            'product_option_value' => $product_option_value_data,
            'option_id'            => $option['option_id'],
            'name'                 => $option['name'],
            'type'                 => $option['type'],
            'value'                => $option['value'],
            'required'             => $option['required']
        );
    }
</code>```

Table img: http://imgur.com/a/A9Ibw

I want to do this because when I add a product it does not stay with the changed name and it takes the name of the option so dynamicname does not detect it.

答:
Please make changes in catalog/model/catalog/product.php as following

public function getProductOptions($product_id) {
        $product_option_data = array();

```<code>    $product_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_id = '" . (int)$product_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.sort_order");

    foreach ($product_option_query->rows as $product_option) {
        $product_option_value_data = array();

        $product_option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_id = '" . (int)$product_id . "' AND pov.product_option_id = '" . (int)$product_option['product_option_id'] . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY ov.sort_order");

        foreach ($product_option_value_query->rows as $product_option_value) {
            $product_option_value_data[] = array(
                'product_option_value_id' => $product_option_value['product_option_value_id'],
                'option_value_id'         => $product_option_value['option_value_id'],
                'name'                    => $product_option_value['name'],
                'image'                   => $product_option_value['image'],
                'quantity'                => $product_option_value['quantity'],
                'subtract'                => $product_option_value['subtract'],
                'price'                   => $product_option_value['price'],
                'price_prefix'            => $product_option_value['price_prefix'],
                'weight'                  => $product_option_value['weight'],
                'weight_prefix'           => $product_option_value['weight_prefix']
            );
        }

        $product_option_data[] = array(
            'product_option_id'    => $product_option['product_option_id'],
            'product_option_value' => $product_option_value_data,
            'option_id'            => $product_option['option_id'],
            'name'                 => $product_option['name'],
            'dynamicname'          => $product_option['dynamicname'],
            'type'                 => $product_option['type'],
            'value'                => $product_option['value'],
            'required'             => $product_option['required']
        );
    }

    return $product_option_data;
}
</code>```

after that you can get the dynamicname in controller as following

$data['options'] = array();

```<code>foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) {
    $product_option_value_data = array();

    foreach ($option['product_option_value'] as $option_value) {
        if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
            if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                $price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']);
            } else {
                $price = false;
            }

            $product_option_value_data[] = array(
                'product_option_value_id' => $option_value['product_option_value_id'],
                'option_value_id'         => $option_value['option_value_id'],
                'name'                    => $option_value['name'],
                'ob_info'                    => $option_value['ob_info'],
                'image'                   => $this->model_tool_image->onesize($option_value['image'], 100, 100),
                'price'                   => $price,
                'price_prefix'            => $option_value['price_prefix']
            );
        }
    }

    $data['options'][] = array(
        'product_option_id'    => $option['product_option_id'],
        'product_option_value' => $product_option_value_data,
        'option_id'            => $option['option_id'],
        'name'                 => $option['name'],
        'dynamicname'          => $option['dynamicname'],
        'type'                 => $option['type'],
        'value'                => $option['value'],
        'required'             => $option['required']
    );
}
</code>```

Title: Opencart getProductOptions in cart.php

Body:
I make a dynamic change of option names for each product.
The problem is that I'm writing the table change. Oc_product_option

By going to system / library / cart.php > public function getProducts() { } there is only loaded there product_option_value.
I want to load this code in system / library / cart.php > public function getProducts() { }

And then call it in the catalog / controller / common> cart.php

$data['options'] = array();

    foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) {
        $product_option_value_data = array();

        foreach ($option['product_option_value'] as $option_value) {
            if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
                if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                    $price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']);
                } else {
                    $price = false;
                }

                $product_option_value_data[] = array(
                    'product_option_value_id' => $option_value['product_option_value_id'],
                    'option_value_id'         => $option_value['option_value_id'],
                    'name'                    => $option_value['name'],
                    'ob_info'                    => $option_value['ob_info'],
                    'image'                   => $this->model_tool_image->onesize($option_value['image'], 100, 100),
                    'price'                   => $price,
                    'price_prefix'            => $option_value['price_prefix']
                );
            }
        }

        $data['options'][] = array(
            'product_option_id'    => $option['product_option_id'],
            'product_option_value' => $product_option_value_data,
            'option_id'            => $option['option_id'],
            'name'                 => $option['name'],
            'type'                 => $option['type'],
            'value'                => $option['value'],
            'required'             => $option['required']
        );
    }

Table img: http://imgur.com/a/A9Ibw

I want to do this because when I add a product it does not stay with the changed name and it takes the name of the option so dynamicname does not detect it.

Body:
Please make changes in catalog/model/catalog/product.php as following

public function getProductOptions($product_id) {
        $product_option_data = array();

    $product_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_id = '" . (int)$product_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.sort_order");

    foreach ($product_option_query->rows as $product_option) {
        $product_option_value_data = array();

        $product_option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_id = '" . (int)$product_id . "' AND pov.product_option_id = '" . (int)$product_option['product_option_id'] . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY ov.sort_order");

        foreach ($product_option_value_query->rows as $product_option_value) {
            $product_option_value_data[] = array(
                'product_option_value_id' => $product_option_value['product_option_value_id'],
                'option_value_id'         => $product_option_value['option_value_id'],
                'name'                    => $product_option_value['name'],
                'image'                   => $product_option_value['image'],
                'quantity'                => $product_option_value['quantity'],
                'subtract'                => $product_option_value['subtract'],
                'price'                   => $product_option_value['price'],
                'price_prefix'            => $product_option_value['price_prefix'],
                'weight'                  => $product_option_value['weight'],
                'weight_prefix'           => $product_option_value['weight_prefix']
            );
        }

        $product_option_data[] = array(
            'product_option_id'    => $product_option['product_option_id'],
            'product_option_value' => $product_option_value_data,
            'option_id'            => $product_option['option_id'],
            'name'                 => $product_option['name'],
            'dynamicname'          => $product_option['dynamicname'],
            'type'                 => $product_option['type'],
            'value'                => $product_option['value'],
            'required'             => $product_option['required']
        );
    }

    return $product_option_data;
}

after that you can get the dynamicname in controller as following

$data['options'] = array();

foreach ($this->model_catalog_product->getProductOptions($this->request->get['product_id']) as $option) {
    $product_option_value_data = array();

    foreach ($option['product_option_value'] as $option_value) {
        if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
            if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                $price = $this->currency->format($this->tax->calculate($option_value['price'], $product_info['tax_class_id'], $this->config->get('config_tax') ? 'P' : false), $this->session->data['currency']);
            } else {
                $price = false;
            }

            $product_option_value_data[] = array(
                'product_option_value_id' => $option_value['product_option_value_id'],
                'option_value_id'         => $option_value['option_value_id'],
                'name'                    => $option_value['name'],
                'ob_info'                    => $option_value['ob_info'],
                'image'                   => $this->model_tool_image->onesize($option_value['image'], 100, 100),
                'price'                   => $price,
                'price_prefix'            => $option_value['price_prefix']
            );
        }
    }

    $data['options'][] = array(
        'product_option_id'    => $option['product_option_id'],
        'product_option_value' => $product_option_value_data,
        'option_id'            => $option['option_id'],
        'name'                 => $option['name'],
        'dynamicname'          => $option['dynamicname'],
        'type'                 => $option['type'],
        'value'                => $option['value'],
        'required'             => $option['required']
    );
}


问:
Javascript counter on key input instead of button?
So I have this counter that increments 'positive' and 'negative' values, it's working fine. Now I also want to assign keyboard key to increment the values, 'f' for negative and 'j' for positive. How do I do this?
I have been fiddling with onkeypress/onkeyup but it is still confusing.

```<code><html>
<head>
<script type="text/javascript">

function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;

if (new_qty < 0) {
    new_qty = 0;
}

document.getElementById('qty').value = new_qty;
return new_qty;
}

function modify_qtyn(val) {
var qtyn = document.getElementById('qtyn').value;
var new_qtyn = parseInt(qtyn,10) + val;

if (new_qtyn < 0) {
    new_qtyn = 0;
}

document.getElementById('qtyn').value = new_qtyn;
return new_qtyn;
}

</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="box">
    <label for="Positive"><abbr title="Positive">Qty</abbr></label>
    <label for="Negative"><abbr title="Negative">Qtyn</abbr></label>
    <input id="qtyn" value="0" />
    <input id="qty" value="0" />
    <button id="down" onclick="modify_qtyn(1)">MINUS</button>
    <button id="up" onclick="modify_qty(1)">PLUS</button>

</div>

</body>
</html>
</code>```

I found the solution by adding this:

```<code>function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};
</code>```

答:
method 1: addEventListener to body-

```<code>document.addEventListener('keypress', function(e){
  console.log(e.which)
  if(e.which==70){ // 102
     modify_qtyn(1);
   }else if(e.which == 74){ // 106
     modify_qtyn(-1);
   }
});
</code>```

method 2: input type to number to use arrow key

```<code><input id="qtyn" value="0" type="number"/>
</code>```

Body:
So I have this counter that increments 'positive' and 'negative' values, it's working fine. Now I also want to assign keyboard key to increment the values, 'f' for negative and 'j' for positive. How do I do this?
I have been fiddling with onkeypress/onkeyup but it is still confusing.

<link rel="stylesheet" type="text/css" href="style.css">

    Qty
    Qtyn
    <input id="qtyn" value="0" />
    <input id="qty" value="0" />
    <button id="down" onclick="modify_qtyn(1)">MINUS</button>
    <button id="up" onclick="modify_qty(1)">PLUS</button>

I found the solution by adding this:

function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};

Body:
method 1: addEventListener to body-

document.addEventListener('keypress', function(e){
  console.log(e.which)
  if(e.which==70){ // 102
     modify_qtyn(1);
   }else if(e.which == 74){ // 106
     modify_qtyn(-1);
   }
});

method 2: input type to number to use arrow key

<input id="qtyn" value="0" type="number"/>


问:
Copying result from pgAdmin to a spreadsheet
I am copying every result of Query (application pgAdmin) into Google Docs Sheet.

I am wonder if it is possible to set Postgres to output tabs instead of semicolon ; to separate values in columns - I would like to simply copy and paste from Postgres to Google Docs sheet.

If it is not possible, is there any way to write a macro in Google Docs sheet?

I would like to ask one more question - how can I divide two values which I get by using select command (and how to demand from Postgres SQL to store values as for example double)?

答:
In PGAdmin 4, you can achieve this by executing your sql query and then press F8 and it will export the query results.

Step 1:

Step 2: Now select the query result and click download query result in CSV format as shown below:

Step 3: Verify the query result

You are done.


问:
Incorrect usage of UNION and ORDER BY
I want to select 12 posts from posts table. If there is no 12 of them, I need to select the missing from parchive table.

```<code>$stmt = $db->query("SELECT * FROM posts where status='public' and user='public' order by inde asc limit 12 offset " . $offset);
$count1 = $stmt->rowCount();
if ($count1 < 12){
    $diff = 12 - $count1;
    $stmt = $db->query("SELECT * FROM posts where status='public' and user='public' order by inde asc limit 12 offset " . $offset .
    " union select * from parchive where status='public' order by date desc limit " . $diff);
}
</code>```

Error:

General error: 1221 Incorrect usage of UNION and ORDER BY in...

Any help?

答:
if you need  limited  and order select for union add  a couple of ()  around the select out the union </p>

```<code>  $stmt = $db->query("(SELECT *
              FROM posts
              where status='public' and user='public'
              order by inde asc limit 12 offset " . $offset .
          ")  union  ( select *
          from parchive where status='public' order by date desc limit " . $diff .")");
</code>```

<p>in this way the the UNION work on result set and not on the direct select  </p>

Title: Incorrect usage of UNION and ORDER BY

Body:
I want to select 12 posts from posts table. If there is no 12 of them, I need to select the missing from parchive table.

$stmt = $db->query("SELECT * FROM posts where status='public' and user='public' order by inde asc limit 12 offset " . $offset);
$count1 = $stmt->rowCount();
if ($count1 < 12){
    $diff = 12 - $count1;
    $stmt = $db->query("SELECT * FROM posts where status='public' and user='public' order by inde asc limit 12 offset " . $offset .
    " union select * from parchive where status='public' order by date desc limit " . $diff);
}

Error:

General error: 1221 Incorrect usage of UNION and ORDER BY in...

Any help?

Body:
if you need  limited  and order select for union add  a couple of ()  around the select out the union

  $stmt = $db->query("(SELECT *
              FROM posts
              where status='public' and user='public'
              order by inde asc limit 12 offset " . $offset .
          ")  union  ( select *
          from parchive where status='public' order by date desc limit " . $diff .")");

in this way the the UNION work on result set and not on the direct select


问:
Partition by table using Partitioned Views ( union all multiple tables ) in redshift
Is there a build in function for this in Redshift? Interleaved keys sort of mitigate this somehow.
If there can be mix of Sort by Compound then Interleaved then this would be ideal.

Is there a disadvantage of using Partitioned view. Example what I mean as below.

https://sqlsunday.com/2014/08/31/partitioned-views/

However instead of using date, I want to partition by other field type. e.g. Product Type or Country.

so the view will be

Select '1' as Prod_type, 'USA' as Country , *
from fact_Sales_1_USA
union all
Select '2' as Prod_type, 'UK' as Country , *
from fact_Sales_2_UK

This way it will prevent query from reading the whole table and just limit to the particular Product Type and Region.

Also is there function to select multiple tables with similar name.

So instead of the view above
It will be just, but this requires the partitioned column to be included in the table.

Select * from fact_*

One of disadvantage is our course the update of data slightly more complex?

Will it slow down a query where I don't use the field above?

答:
There is no built in function for partitioned views in Redshift. Its developers believe that sort and dist key model and encoding allows to handle most of performance issues. Particular solution is heavily dependent on nature of your data and typical queries that you do.

In a specific example that you mentioned, having multiple tables based on product type/country and sorted by some other column won't prevent query planner from scanning all tables if product type/country are not in the sort key. AFAIK Redshift is agnostic about values distribution of columns that are don't participate in the sort/dist keys, so it will scan each table that participates in the union even if the values needed are just in one table by design. If you're going to filter frequently by product type AND country, create a compound sort key (product_type,country,timestamp). This way Redshift will scan only blocks of data that satisfy the search condition. If you're going to filter frequently by product type OR country, create an interleaved sort key on the same columns. Interleaved key is better here because if you filter table with compound sort key mentioned above by country (second column) the key won't be used.

If this doesn't alleviate the problem it means your data is so big that your company can afford building an application on top of Redshift that will handle this logic outside SQL (keep different product type / country in separate tables and generate dynamic SQL that queries these specific tables based on the filter value).

As for the function to select from tables with a similar name, there is no such. In Postgres you could query system tables, generate SQL based on the query results and run it right away but Redshift doesn't support dynamic SQL. The solution is above (right sort keys or application on top of Redshift).


问:
how often optimize table query called
Actually i queried optimize table query for one table. then i didn't do any operation on that table. then again i'm querying optimize table query at the end of every month. but the data in the table may be changed once in four or 8 months. is it create any problem in performance of the mysql query?</p>

答: Did your read the manual about OPTIMIZE? And do you have a problem you want to solve using OPTIMIZE? If not, don't use this statement at all.

Title: how often optimize table query called


问:
How to get columns' name from a table in sqlite3 database using python3?
I already have read some answers on this. But all of them are giving me the same error.

Here are the solutions I read:

Link 1

Link 2

```<code>import sqlite3 as sql

#connect to database
connection = sql.connect("database.db")

#make a cursor which will move in the database
cursor = connection.cursor()

#execute the different command
def execute(cursor, command):
    return cursor.execute(command)

#print the result
def print_result(result):
    for var in result:
        print(var)
# select columns' name from table

command = """select distinct emplyee from emplyee.information_schema.columns"""

result = execute(cursor, command)
print_result(result)
</code>```

The table name is emplyee.

Error is:
Traceback (most recent call last):

File "database.py", line 47, in

```<code>result = execute(cursor, command)
</code>```

File "database.py", line 11, in execute

```<code>return cursor.execute(command)
</code>```

sqlite3.OperationalError: near ".": syntax error

答:
SQLite doesn't support the information_schema, so you need to do something like this:</p>

```<code>def table_columns(db, table_name)
    curs = db.cursor()
    sql = "select * from %s where 1=0;" % table_name
    curs.execute(sql)
    return [d[0] for d in curs.description]
</code>```

Body:
I already have read some answers on this. But all of them are giving me the same error.

Here are the solutions I read:

Link 1

Link 2

import sqlite3 as sql

#connect to database
connection = sql.connect("database.db")

#make a cursor which will move in the database
cursor = connection.cursor()

#execute the different command
def execute(cursor, command):
    return cursor.execute(command)

#print the result
def print_result(result):
    for var in result:
        print(var)
# select columns' name from table

command = """select distinct emplyee from emplyee.information_schema.columns"""

result = execute(cursor, command)
print_result(result)

The table name is emplyee.

Error is:
Traceback (most recent call last):

File "database.py", line 47, in

result = execute(cursor, command)

File "database.py", line 11, in execute

return cursor.execute(command)

sqlite3.OperationalError: near ".": syntax error

Body:
SQLite doesn't support the information_schema, so you need to do something like this:

def table_columns(db, table_name)
    curs = db.cursor()
    sql = "select * from %s where 1=0;" % table_name
    curs.execute(sql)
    return [d[0] for d in curs.description]


问:
How to center a sublayer on another layer?
I drew something on a CAShapeLayer(). Now I want to put it on anther layer.

```<code>let layer = CAShapeLayer() // This is the layer I drew something on
let imageView = UIImageView() //  The imageView I want to put the layer on
imageView.layer.addSublayer(layer)
</code>```

So how to align the center of the layer with the center of the image view?
Thanks.

答:
```<code>layer.frame = imageView.bounds
</code>```

It's OK.

To center a sublayer on anther layer, you could also check the anchorPointZ.

The anchor point for the layer’s position along the z axis.

The default value is to align the center of the layer to the center of the image view

If you need the layer of UIImageView resizes with its view .You need create a custom view class, and override layoutSublayersOfLayer

```<code>class CenterImageView: UIImageView {

    override func layoutSublayersOfLayer(layer: CALayer!) {
         super.layoutSublayersOfLayer(layer)
         layer.frame = self.bounds
    }
 }
</code>```

Body:
I drew something on a CAShapeLayer(). Now I want to put it on anther layer.

let layer = CAShapeLayer() // This is the layer I drew something on
let imageView = UIImageView() //  The imageView I want to put the layer on
imageView.layer.addSublayer(layer)

So how to align the center of the layer with the center of the image view?
Thanks.

Body:
layer.frame = imageView.bounds

It's OK.

To center a sublayer on anther layer, you could also check the anchorPointZ.

The anchor point for the layer’s position along the z axis.

The default value is to align the center of the layer to the center of the image view

If you need the layer of UIImageView resizes with its view .You need create a custom view class, and override layoutSublayersOfLayer

class CenterImageView: UIImageView {

    override func layoutSublayersOfLayer(layer: CALayer!) {
         super.layoutSublayersOfLayer(layer)
         layer.frame = self.bounds
    }
 }


问:
Selenium - How to click on a-tag
I am new to python, webscraping and selenium- so my question might be very basic. I was following a lot of advice to similar questions here, but that did not help with my problem

The url I am opening with selenium contains a button "sign in". The corresponding html line looks like this:

```<code><a class="o-buttons o-buttons--big" role="button" href="https://accounts.ft.com/login?location=https%3A%2F%2Fftalphaville.ft.com%2F2012%2F07%2F27%2F1098471%2Fwhat-is-the-ecb-going-to-do-next%2F" data-trackable="sign-in">or sign in</a>
</code>```

and the x-path is

```<code>html/body/section/div/div/div[1]/div/a[2]
</code>```

Among others, I was trying to use

```<code>button = driver.find_element_by_xpath("//a/u[data-trackable='sign-in')]")
button.click()
</code>```

but it did not work- can anybody help me out?

答:
Your xpath is not correct:

button = driver.find_element_by_xpath("//a[@data-trackable='sign-in']")
button.click()

Title: Selenium - How to click on a-tag

Body:
I am new to python, webscraping and selenium- so my question might be very basic. I was following a lot of advice to similar questions here, but that did not help with my problem

The url I am opening with selenium contains a button "sign in". The corresponding html line looks like this:

or sign in

and the x-path is

html/body/section/div/div/div[1]/div/a[2]

Among others, I was trying to use

button = driver.find_element_by_xpath("//a/u[data-trackable='sign-in')]")
button.click()

but it did not work- can anybody help me out?


问:
C# Mysql Update last row in table
I am trying  to update the last row inside a Mysql table. This is what I've been trying so far, but the problem is that it updates every row and not only the last one.

```<code> query = "UPDATE Callbacks SET UniqueID = ?UID WHERE UniqueID = (SELECT UniqueID Callbacks ORDER BY UniqueID LIMIT 1);";
                using (MySqlCommand cmd = new MySqlCommand(query, cn))
                {
                    cmd.Parameters.Add(new MySqlParameter("?UID", UID));
                    cmd.ExecuteScalar();
                }
</code>```

Any ideas?

答:
```<code>UPDATE Callbacks SET UniqueID = ?UID ORDER BY UniqueID DESC LIMIT 1
</code>```

In MySQL 4.0 and later, you can use UPDATE with ORDER BY and LIMIT in the same statement. This should give you the result you are looking for. Note: I changed the ORDER BY to be descending (an assumption on my part for what you might be looking to do).

Title: C# Mysql Update last row in table

Body:
I am trying  to update the last row inside a Mysql table. This is what I've been trying so far, but the problem is that it updates every row and not only the last one.

 query = "UPDATE Callbacks SET UniqueID = ?UID WHERE UniqueID = (SELECT UniqueID Callbacks ORDER BY UniqueID LIMIT 1);";
                using (MySqlCommand cmd = new MySqlCommand(query, cn))
                {
                    cmd.Parameters.Add(new MySqlParameter("?UID", UID));
                    cmd.ExecuteScalar();
                }

Any ideas?

Body:
UPDATE Callbacks SET UniqueID = ?UID ORDER BY UniqueID DESC LIMIT 1

In MySQL 4.0 and later, you can use UPDATE with ORDER BY and LIMIT in the same statement. This should give you the result you are looking for. Note: I changed the ORDER BY to be descending (an assumption on my part for what you might be looking to do).


问:
How can I perform multiplication without the '*' operator?
I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it's like this

```<code>      (x << 3) - x;
</code>```

Now I know about basic bit manipulation operations, but I can't get how do you multiply a number by any other odd number without using the * operator? Is there a general algorithm for this?

答:
To multiply of two numbers without * operator:

```<code>int mul(int a,int b) {
    int result = 0;
    if(b > 0) {
        for(int i=1;i<=b;i++){
            result += a;
        }
    }
    return result;
}
</code>```

Body:
I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it's like this

      (x << 3) - x;

Now I know about basic bit manipulation operations, but I can't get how do you multiply a number by any other odd number without using the * operator? Is there a general algorithm for this?

Body:
To multiply of two numbers without * operator:

int mul(int a,int b) {
    int result = 0;
    if(b > 0) {
        for(int i=1;i<=b;i++){
            result += a;
        }
    }
    return result;
}


问:
Parse TXT file to Batch file
I am wanting to set a variable one line at a time from a text file, run a particular command using this variable, then loop back, grab the second line, process the command, and so on until the file ends.

The batch file works well and asks for user input, then processes using the input as the variable with no problems at all. The script gets the computer name first, then copies the install files to the local machine the uses WMIC to install the MSI:

```<code>@echo off
SET /P computer=Enter Computer Name
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
</code>```

The text file will look something like this:

```<code>PC-01
PC-02
PC-27
Odd-PC
</code>```

However, when I try to introduce a "for" loop, so that I can process a hundred or more machines one at a time, nothing happens. Even if I have only one line in the file I cannot get it to work. This is what I have tried:

```<code>@echo off
For /F %%i in (c:\test.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
)
</code>```

For the record I have tried the variables with %%computer%% and !computer! with no success.

I have also tried the following also with or without the /p in the "SET" command:

```<code>@echo off
SET /P computer=<"c:\test.txt"
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
</code>```

I would appreciate any suggestions or input.

答:
After formatting your input file and saving it in ANSI format, this is the final code that works:

```<code>@echo off
setlocal enabledelayedexpansion
For /F %%i in (c:\computers.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\msifolder\*.*" "\\!computer!\c$\temp\msifolder\*.*" /E /C /H /R /Y
WMIC /Node:"!computer!" product call install true,"","c:\temp\msi_to_install.msi"
RD /S /Q "\\!computer!\c$\temp\msifolder\"
)
</code>```

In my final rendition of the script, I am copying the folder the MSI file is located in locally, installing the MSI, then deleting the folder after completion. If the MSI is already installed you will get this error:

```<code>instance of __PARAMETERS
{
ReturnValue = 1603
</code>```

For a successful install you will get a ReturnValue = 0

@magoo provided a lot of direction in troubleshooting, thank you, and the file format was the final piece of the puzzle.

Title: Parse TXT file to Batch file

Body:
I am wanting to set a variable one line at a time from a text file, run a particular command using this variable, then loop back, grab the second line, process the command, and so on until the file ends.

The batch file works well and asks for user input, then processes using the input as the variable with no problems at all. The script gets the computer name first, then copies the install files to the local machine the uses WMIC to install the MSI:

@echo off
SET /P computer=Enter Computer Name
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"

The text file will look something like this:

PC-01
PC-02
PC-27
Odd-PC

However, when I try to introduce a "for" loop, so that I can process a hundred or more machines one at a time, nothing happens. Even if I have only one line in the file I cannot get it to work. This is what I have tried:

@echo off
For /F %%i in (c:\test.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
)

For the record I have tried the variables with %%computer%% and !computer! with no success.

I have also tried the following also with or without the /p in the "SET" command:

@echo off
SET /P computer=<"c:\test.txt"
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"

I would appreciate any suggestions or input.

Body:
After formatting your input file and saving it in ANSI format, this is the final code that works:

@echo off
setlocal enabledelayedexpansion
For /F %%i in (c:\computers.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\msifolder\*.*" "\\!computer!\c$\temp\msifolder\*.*" /E /C /H /R /Y
WMIC /Node:"!computer!" product call install true,"","c:\temp\msi_to_install.msi"
RD /S /Q "\\!computer!\c$\temp\msifolder\"
)

In my final rendition of the script, I am copying the folder the MSI file is located in locally, installing the MSI, then deleting the folder after completion. If the MSI is already installed you will get this error:

instance of __PARAMETERS
{
ReturnValue = 1603

For a successful install you will get a ReturnValue = 0

@magoo provided a lot of direction in troubleshooting, thank you, and the file format was the final piece of the puzzle.


问:
Derived class initialization with parameter of another derived class
I am new in Abstract classes so please excuse any ignorant mistakes

The exercise is given from my school, so the main.cpp file is to be used, almost as it is

I am trying to create a simple calculator in Eclipse using C++11

There exists a simple Abstract class with two virtual methods.

The two derived classes are simply the "Result" and the "Const" classes.
This is the header file of the Abstract class called

Expression.h

```<code>class Expression
{
public:
    Expression();
    virtual ~Expression();
   //methods
};
</code>```

Following is the source file of Expression

Expression.cpp

```<code>#include "expression.h"
#include <iostream>

Expression::Expression(){}
Expression::~Expression(){}
</code>```

Then I have created two classes called Const and Result

Const.h

```<code>#include <iostream>
#include "expression.h"

class  Const : public Expression
{
public:
    Const(int value);
    //inherited methods
private:
    int value;
};
</code>```

and the source file

Const.cpp

```<code>#include "expression.h"
#include "Const.h"

Const::Const(int x)
{
    value=x;
};

//inherited methods
</code>```

Result.h

```<code>#include <iostream>
#include "expression.h"
#include "Const.h"

class  Result : public Expression
{
public:
    Result(Const& c);
    //inherited methods
private:
    double value;
};
</code>```

Result.cpp

```<code>#include "expression.h"
#include "Result.h"
Result::Result(Const& c)
{
    value=c.point;
};
//inherited methods
</code>```

So what i need is to understand

main.cpp

```<code>#include <iostream>
#include "expression.h"
#include "const.h"
#include "result.h"
void testResult()
{
    Result  res (new Const(4));
    //Here an inherited method will be used to print the contents of object res
}
int main()
{
    testResult();
    return 0;
}
</code>```

The problem i can't solve is the line

```<code>Result res (new Const(4));
</code>```

The error i get is

Conversion from 'Const* to non-scalar type 'Result' requested

The thing is that what is described in this line should be used as it is, and i can't seem to find exactly what it is.

EDIT

The question as asked firstly was apparently misleading due to my fault, tried to fix the question so as to describe exactly my problem

答:
One issue is that

```<code>double point= value;
</code>```

doesn't initialize your member, but a new unused local variable.

just do

```<code>point = value;
</code>```

Body:
I am new in Abstract classes so please excuse any ignorant mistakes

The exercise is given from my school, so the main.cpp file is to be used, almost as it is

I am trying to create a simple calculator in Eclipse using C++11

There exists a simple Abstract class with two virtual methods.

The two derived classes are simply the "Result" and the "Const" classes.
This is the header file of the Abstract class called

Expression.h

class Expression
{
public:
    Expression();
    virtual ~Expression();
   //methods
};

Following is the source file of Expression

Expression.cpp

#include "expression.h"
#include <iostream>

Expression::Expression(){}
Expression::~Expression(){}

Then I have created two classes called Const and Result

Const.h

#include <iostream>
#include "expression.h"

class  Const : public Expression
{
public:
    Const(int value);
    //inherited methods
private:
    int value;
};

and the source file

Const.cpp

#include "expression.h"
#include "Const.h"

Const::Const(int x)
{
    value=x;
};

//inherited methods

Result.h

#include <iostream>
#include "expression.h"
#include "Const.h"

class  Result : public Expression
{
public:
    Result(Const& c);
    //inherited methods
private:
    double value;
};

Result.cpp

#include "expression.h"
#include "Result.h"
Result::Result(Const& c)
{
    value=c.point;
};
//inherited methods

So what i need is to understand

main.cpp

#include <iostream>
#include "expression.h"
#include "const.h"
#include "result.h"
void testResult()
{
    Result  res (new Const(4));
    //Here an inherited method will be used to print the contents of object res
}
int main()
{
    testResult();
    return 0;
}

The problem i can't solve is the line

Result res (new Const(4));

The error i get is

Conversion from 'Const* to non-scalar type 'Result' requested

The thing is that what is described in this line should be used as it is, and i can't seem to find exactly what it is.

EDIT

The question as asked firstly was apparently misleading due to my fault, tried to fix the question so as to describe exactly my problem

Body:
One issue is that

double point= value;

doesn't initialize your member, but a new unused local variable.

just do

point = value;