问:
How to sum count variable in PHP
i want to sum for some data which come from function foreach in PHP, but i found error while run it, here my simple code :

```<code>        <?php
            $no=1;
            foreach($data_tersimpan->result_array() as $dp)
            {
            ?>
            <?php
            $total = 0;
            $total += count($dp['id_plan']);
            echo $total;
        ?>
         <?php
                $no++;
            }
         ?>
</code>```

from my code above, i print $total, then data shown like this :

```<code>1   1   1   1   1
</code>```

I want to get summary 5 if i print $total
is there any suggestion to make summary in php scrypt(not in sql query)?

THanks

答:
your code have some problem first you add total and every time assign total 0 so total not update and no need more php tag and also counter value

```<code><?php
$total = 0; // first assign total 0
foreach ($data_tersimpan->result_array() as $dp) {
    $total += count($dp['id_plan']); // every time update total  = total + your value;
}
echo $total; // this is final total
?>
</code>```

when loop complete then final output is total value, if no data found then final total will be 0.

Title: How to sum count variable in PHP

Body:
i want to sum for some data which come from function foreach in PHP, but i found error while run it, here my simple code :

        <?php
            $no=1;
            foreach($data_tersimpan->result_array() as $dp)
            {
            ?>
            <?php
            $total = 0;
            $total += count($dp['id_plan']);
            echo $total;
        ?>
         <?php
                $no++;
            }
         ?>

from my code above, i print $total, then data shown like this :

1   1   1   1   1

I want to get summary 5 if i print $total
is there any suggestion to make summary in php scrypt(not in sql query)?

THanks

Body:
your code have some problem first you add total and every time assign total 0 so total not update and no need more php tag and also counter value

<?php
$total = 0; // first assign total 0
foreach ($data_tersimpan->result_array() as $dp) {
    $total += count($dp['id_plan']); // every time update total  = total + your value;
}
echo $total; // this is final total
?>

when loop complete then final output is total value, if no data found then final total will be 0.


来源: stackexchange

问:
Linq with optional WHERE options
I have a .Net function that accepts 3 parameters, all optional. Something like this:

```<code>public List<MyObject> Search(string colour, string size, string name)
{
     var result = (from c in MyTable where .... select c).ToList();
}
</code>```

My question is, what is the best way to do the where part. Would the best be to create dynamic linq? What's the best pattern, within linq, to have optional where parameters?

So, in SQL, something like this:

```<code>SELECT *
FROM MyTable
WHERE (@colour <> '' AND colour = @colour)
  AND (@size <> '' AND size = @size)
  AND (@name <> '' AND name = @name)
</code>```

But I am hoping there a neater, more acceptable pattern for doing this within linq.

答:
Chain Where clauses with checking for null

var result = context.MyTable
    .Where(t => color == null || color == t.Color)
    .Where(t => size == null || size == t.Size)
    .Where(t => name == null || name == t.Name)
    .ToList();
```
<p>Alternative approach would be to add conditions only when you need them</p>
```var query = context.MyTable;

if (color != null) query = query.Where(t => t.Color == color);
if (size != null) query = query.Where(t => t.Size == size);
if (name != null) query = query.Where(t => t.Name == name);

var result = query.ToList();
```

ContentLicense: CC BY-SA 3.0

Title: Linq with optional WHERE options

Body:
I have a .Net function that accepts 3 parameters, all optional. Something like this:

public List<MyObject> Search(string colour, string size, string name)
{
     var result = (from c in MyTable where .... select c).ToList();
}

My question is, what is the best way to do the where part. Would the best be to create dynamic linq? What's the best pattern, within linq, to have optional where parameters?

So, in SQL, something like this:

SELECT *
FROM MyTable
WHERE (@colour <> '' AND colour = @colour)
  AND (@size <> '' AND size = @size)
  AND (@name <> '' AND name = @name)

But I am hoping there a neater, more acceptable pattern for doing this within linq.

Body:
Chain Where clauses with checking for null

var result = context.MyTable
    .Where(t => color == null || color == t.Color)
    .Where(t => size == null || size == t.Size)
    .Where(t => name == null || name == t.Name)
    .ToList();

Alternative approach would be to add conditions only when you need them

var query = context.MyTable;

if (color != null) query = query.Where(t => t.Color == color);
if (size != null) query = query.Where(t => t.Size == size);
if (name != null) query = query.Where(t => t.Name == name);

var result = query.ToList();

ContentLicense: CC BY-SA 4.0


问:
Dynamics CRM mobile client, how to add shortcut on an entity in left navigation pane
I am using dynamics 365 mobile app for IOS. I need to add the Email and Phone call entities shortcut into the main left navigation pane. Right now, I do not have any idea on how to add this.

Does anybody help me to add these shortcuts?

答:
You have to edit the sitemap to customize navigation.

You can use Sitemap editor to edit the sitemap.

Open the Solution that you would like to use to contain the sitemap.

Under Components. Select Client Extensions > Add Existing > Select “Site Map”

Once it’s added to the solution, click on the Edit

It will then open up the Dynamics 365 Sitemap Editor.

Make changes, click Save and then Publish.

Dynamics 365 for phones and tablets uses the same sitemap data to provide navigation options as the web application except that it is optimized for presentation in the mobile apps.

Technet reference


问:
Word wrap in verbatim environments
I noticed that LaTeX's verbatim environment doesn't do word wrapping. How do I get it to word wrap verbatim text?

答:
Essentially you can’t.

But the listings package, whose actual purpose is to format source code, does support word wrapping. So maybe you can use the listings environment instead.

ContentLicense: CC BY-SA 2.5

Title: Word wrap in verbatim environments


问:
Best approach for creating http request service?
I created one service for handling all http request. It is working perfectly. But I want to know is there any fault in my approach and also want to know other good approaches like observable?

request.service.js

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { MessageService } from './message.service';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};

interface IRequestOption {
    url: string;
    cxfgroup: string;
    endpoint: string;
    data: object;
}

interface IRequestBody {
    option: IRequestOption;
    log: string;
    error: string;
}

class HTTP {

    private messageService: MessageService;

    constructor(http, messageService, url: string, body: object, log: string, error: string) {
        this.callHTTP(http, url, body, log, error);
        this.messageService = messageService;
    }

    callHTTP(http, url, body, log, error) {
        return http.post(url, body, httpOptions).toPromise()
            .then(this.extractData)
            .catch(this.handleErrorPromise);
    }

    private extractData(res: Response) {
        // let body = res.json();
        // return body['data'] || {};
        return res || {};
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

class RequestFactory {
    private baseURL = 'https://app.domain.com/cxf/';
    /**
     * CXF ENPOINTS
     */
    private endpoints: any = {
        "auth": {
            "getcustomerkeys": "auth/getcustomerkeys"
        }
    };

    call(http, messageService, options: IRequestOption, log: string, error: string) {
        let url: string = options.url ? options.url : this.baseURL;
        if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
            url += this.endpoints[options.cxfgroup][options.endpoint];
        }

        return new HTTP(http, messageService, url, options.data, log, error);
    }
}

@Injectable()
export class RequestService {

    constructor(private http: HttpClient, private messageService: MessageService) { }

    post(request: IRequestBody) {
        let requestFactory = new RequestFactory();
        requestFactory.call(this.http, this.messageService, request.option, request.log, request.error);
    }

}
</code>```

I'm calling this "post" method using the following code. Here I want
  to set a promise once the request complete i want to show some
  message.

```<code>this.requestService.post({
  option: {
    url: '',
     cxfgroup: 'auth',
      endpoint: 'getcustomerkeys',
       data: {
         userid: 'user@domain.com'
       }
  },
  log: 'login initiated!',
  error: 'customerKeyError'
});
</code>```

答:
HTTP Service

Here is an observable based approach we're using in our projects:

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService {
  constructor(private http: HttpClient) {}

  /**
   * Invoke function should be able to handle any HTTP request based on the @params
   */
  invoke(params): Observable<any> {
    if (params) {
      const method = params.method.toLowerCase();
      const { url, path, body, headers, query } = params;

      const requestURL = `${url}/${path}`;

      let request;
      let requestParams = new HttpParams();
      let requestHeaders = new HttpHeaders();

      /**
       * DEFAULT HEADERS
       */
      requestHeaders = requestHeaders.set('Content-Type', 'application/json');

      /**
       * CUSTOM HEADERS
       */
      if (headers) {
        for (const key in headers) {
          if (headers.hasOwnProperty(key)) {
            requestHeaders = requestHeaders.append(key, headers[key]);
          }
        }
      }

      /**
       * CUSTOM REQUEST QUERY (?key=value)
       */
      if (query) {
        for (const key in query) {
          if (query.hasOwnProperty(key)) {
            requestParams = requestParams.append(key, query[key]);
          }
        }
      }

      const requestOptions = {
        headers: requestHeaders,
        params: requestParams,
      };

      /**
       * HANDLE GET, POST etc. REQUESTS
       */
      if (method === 'get') {
        request = this.http[method](requestURL, requestOptions);
      } else if (method === 'post' || method === 'put') {
        request = this.http[method](
          requestURL,
          JSON.stringify(body),
          requestOptions,
        );
      } else if (method === 'delete') {
        request = this.http.request(method, requestURL, {
          ...requestOptions,
          body: JSON.stringify(body),
        });
      } else {
        console.error('Unknown request method.');
      }

      /**
       * RETURN API REQUEST
       */
      return request;
    }
  }
}
</code>```

Usage example in services

Which is very simple to use in your service, so it's gonna look like this:

```<code>constructor(private http: HttpService) {}

makeRequest() {
  return this.http.invoke({
    method: 'POST', // method like POST, GET etc.
    url: 'http://blabla', // base URL
    path: 'makeReq', // API endpoint
    body: ..., // body for POST or PUT requests
    headers: {headerName: 'HeaderValue'} // headers you need to add to your request
    query: {query: 'queryValue'} // URL query to be added (eg. ?query=queryValue)
  });
}
</code>```

Please note that body, headers and query are optional.

Usage example in components

And finally, you need to subscribe to an Observable in your components to make the request:

```<code>this.yourServiceName.makeRequest().subscribe(
  success => {
    // handle success
  },
  error => {
    // handle error
  }
);
</code>```

Error Handling

To handle errors we can use HttpInterceptor so it's gonna look something like this:

```<code>import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse,
  HTTP_INTERCEPTORS,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    return next.handle(req).catch(errorReponse => {
      let error: string;
      if (errorReponse instanceof HttpErrorResponse) {
        error = errorReponse.error;
        const { status, statusText, message } = errorReponse;
        const errMsg = `HTTP ERROR: ${status} - ${statusText}\n${message}\n\nBACKEND RESPONSE: `;
        console.error(errMsg, error);
      } else {
        error = null;
      }
      return _throw(error);
    });
  }
}

export const ErrorHttpInterceptor = {
  provide: HTTP_INTERCEPTORS,
  useClass: ErrorInterceptor,
  multi: true,
};
</code>```

HttpInterceptor will apply some middleware functionality to all HTTP calls made with HttpClient provider. Please note it won't work with Http provider as it's deprecated in the latest releases. And don't forget to include the interceptor in @NgModule:

```<code>@NgModule({
  providers: [ErrorHttpInterceptor]
})
</code>```

A similar approach can be used to inject Authorization token etc.

Body:
I created one service for handling all http request. It is working perfectly. But I want to know is there any fault in my approach and also want to know other good approaches like observable?

request.service.js

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { MessageService } from './message.service';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};

interface IRequestOption {
    url: string;
    cxfgroup: string;
    endpoint: string;
    data: object;
}

interface IRequestBody {
    option: IRequestOption;
    log: string;
    error: string;
}

class HTTP {

    private messageService: MessageService;

    constructor(http, messageService, url: string, body: object, log: string, error: string) {
        this.callHTTP(http, url, body, log, error);
        this.messageService = messageService;
    }

    callHTTP(http, url, body, log, error) {
        return http.post(url, body, httpOptions).toPromise()
            .then(this.extractData)
            .catch(this.handleErrorPromise);
    }

    private extractData(res: Response) {
        // let body = res.json();
        // return body['data'] || {};
        return res || {};
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

class RequestFactory {
    private baseURL = 'https://app.domain.com/cxf/';
    /**
     * CXF ENPOINTS
     */
    private endpoints: any = {
        "auth": {
            "getcustomerkeys": "auth/getcustomerkeys"
        }
    };

    call(http, messageService, options: IRequestOption, log: string, error: string) {
        let url: string = options.url ? options.url : this.baseURL;
        if (this.endpoints.hasOwnProperty(options['cxfgroup'])) {
            url += this.endpoints[options.cxfgroup][options.endpoint];
        }

        return new HTTP(http, messageService, url, options.data, log, error);
    }
}

@Injectable()
export class RequestService {

    constructor(private http: HttpClient, private messageService: MessageService) { }

    post(request: IRequestBody) {
        let requestFactory = new RequestFactory();
        requestFactory.call(this.http, this.messageService, request.option, request.log, request.error);
    }

}

I'm calling this "post" method using the following code. Here I want
  to set a promise once the request complete i want to show some
  message.

this.requestService.post({
  option: {
    url: '',
     cxfgroup: 'auth',
      endpoint: 'getcustomerkeys',
       data: {
         userid: 'user@domain.com'
       }
  },
  log: 'login initiated!',
  error: 'customerKeyError'
});

Body:
HTTP Service

Here is an observable based approach we're using in our projects:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService {
  constructor(private http: HttpClient) {}

  /**
   * Invoke function should be able to handle any HTTP request based on the @params
   */
  invoke(params): Observable<any> {
    if (params) {
      const method = params.method.toLowerCase();
      const { url, path, body, headers, query } = params;

      const requestURL = `${url}/${path}`;

      let request;
      let requestParams = new HttpParams();
      let requestHeaders = new HttpHeaders();

      /**
       * DEFAULT HEADERS
       */
      requestHeaders = requestHeaders.set('Content-Type', 'application/json');

      /**
       * CUSTOM HEADERS
       */
      if (headers) {
        for (const key in headers) {
          if (headers.hasOwnProperty(key)) {
            requestHeaders = requestHeaders.append(key, headers[key]);
          }
        }
      }

      /**
       * CUSTOM REQUEST QUERY (?key=value)
       */
      if (query) {
        for (const key in query) {
          if (query.hasOwnProperty(key)) {
            requestParams = requestParams.append(key, query[key]);
          }
        }
      }

      const requestOptions = {
        headers: requestHeaders,
        params: requestParams,
      };

      /**
       * HANDLE GET, POST etc. REQUESTS
       */
      if (method === 'get') {
        request = this.http[method](requestURL, requestOptions);
      } else if (method === 'post' || method === 'put') {
        request = this.http[method](
          requestURL,
          JSON.stringify(body),
          requestOptions,
        );
      } else if (method === 'delete') {
        request = this.http.request(method, requestURL, {
          ...requestOptions,
          body: JSON.stringify(body),
        });
      } else {
        console.error('Unknown request method.');
      }

      /**
       * RETURN API REQUEST
       */
      return request;
    }
  }
}

Usage example in services

Which is very simple to use in your service, so it's gonna look like this:

constructor(private http: HttpService) {}

makeRequest() {
  return this.http.invoke({
    method: 'POST', // method like POST, GET etc.
    url: 'http://blabla', // base URL
    path: 'makeReq', // API endpoint
    body: ..., // body for POST or PUT requests
    headers: {headerName: 'HeaderValue'} // headers you need to add to your request
    query: {query: 'queryValue'} // URL query to be added (eg. ?query=queryValue)
  });
}

Please note that body, headers and query are optional.

Usage example in components

And finally, you need to subscribe to an Observable in your components to make the request:

this.yourServiceName.makeRequest().subscribe(
  success => {
    // handle success
  },
  error => {
    // handle error
  }
);

Error Handling

To handle errors we can use HttpInterceptor so it's gonna look something like this:

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse,
  HTTP_INTERCEPTORS,
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    return next.handle(req).catch(errorReponse => {
      let error: string;
      if (errorReponse instanceof HttpErrorResponse) {
        error = errorReponse.error;
        const { status, statusText, message } = errorReponse;
        const errMsg = `HTTP ERROR: ${status} - ${statusText}\n${message}\n\nBACKEND RESPONSE: `;
        console.error(errMsg, error);
      } else {
        error = null;
      }
      return _throw(error);
    });
  }
}

export const ErrorHttpInterceptor = {
  provide: HTTP_INTERCEPTORS,
  useClass: ErrorInterceptor,
  multi: true,
};

HttpInterceptor will apply some middleware functionality to all HTTP calls made with HttpClient provider. Please note it won't work with Http provider as it's deprecated in the latest releases. And don't forget to include the interceptor in @NgModule:

@NgModule({
  providers: [ErrorHttpInterceptor]
})

A similar approach can be used to inject Authorization token etc.


答:
```<code><?php
    $no=1;
    $total = 0;
    foreach($data_tersimpan->result_array() as $dp) {
        $total += count($dp['id_plan']);
        $no++;
    }
    echo $total;
?>
</code>```

Title: How to sum count variable in PHP


问:
Paramiko parse raise Exception when Using SSH keyfile with Fabric
I'm newbie using ssh_key in fabric. After I follow the instruction in Using an SSH keyfile with Fabric, in my code:

```<code>import os

from fabric.api import *

env.hosts = ['host.name.com']
env.use_ssh_config = True
env.user = "root"
env.key_filename = '/root/.ssh/config'

def local_uname():
local('uname -a')
</code>```

In file config, there is my id_rsa.pub key. I get an error like this:

```<code>File "paramiko/paramiko/config.py", line 68, in parse raise Exception("Unparsable line {}".format(line))
Exception: Unparsable line
</code>```

Can anyone help me, please?

答:
You would set a config file like

```<code>env.ssh_config_path = '/root/.ssh/config'
</code>```

or an SSH key like

```<code>env.key_filename = '/root/.ssh/id_rsa'
</code>```

But setting a config file to be used as your SSH key makes no sense.

Body:
I'm newbie using ssh_key in fabric. After I follow the instruction in Using an SSH keyfile with Fabric, in my code:

import os

from fabric.api import *

env.hosts = ['host.name.com']
env.use_ssh_config = True
env.user = "root"
env.key_filename = '/root/.ssh/config'

def local_uname():
local('uname -a')

In file config, there is my id_rsa.pub key. I get an error like this:

File "paramiko/paramiko/config.py", line 68, in parse raise Exception("Unparsable line {}".format(line))
Exception: Unparsable line

Can anyone help me, please?

Body:
You would set a config file like

env.ssh_config_path = '/root/.ssh/config'

or an SSH key like

env.key_filename = '/root/.ssh/id_rsa'

But setting a config file to be used as your SSH key makes no sense.


问:
In which specific cases are the two used - matplotlib.pyplot.imshow() and matplotlib.pyplot.show()?
I went through the documentation of both but the documentation does not specify for a specific use case for both. I have also found that sometimes the imshow() property on its own displays the figures but sometimes the show() property needs to be used to display the figure. In the documentation , the imshow() property mentions about displaying the image on the axes but the word "axes" is missing from the show() property. What does the word axes more specifically refer to?

imshow() documentation

show() documentation

答:
well as you can see in the doc, imshow displays an image while show displays a figure.

Imshow's arguments are array_type objects, such as a jpeg picture (which can be of shape n x m x 3 for coloured, or n x m for black and white.

When you run a script that calls methods as .plot(), or hist(), you need to call .show() to display them.

To display your image, you call imshow().

Hope it helps.


问:
Get the value from an Array
I have some code I need help with:

```<code>var bob = [10,30,50,20,8];

// Call the function

foo(bob);

var foo = function(bob){

 var max = 0,
 min = 0,
 average = 0,
 sum = 0;

 max = Math.max.apply( null, bob); // Get the max value.
 min = Math.min.apply( null, bob); // Get the min value.

 for( var i = 0; i < bob.length; i++ ){
  sum += bob[ i ];
 }

 average = sum / l;

 var resultArr = [];

 resultArr[0] = average;
 resultArr[1] = min;
 resultArr[2] = max;

 return resultArr;
}

document.getElementById('max').innerHTML = "Max value: "; // i want to print the max value here.
</code>```

This function returns an array with max, min and average values. How can I choose which value to print in different divs?

答:
```<code>document.getElementById('max').innerHTML = resultArr[2];
</code>```

Or

```<code><div id="max">
    <script>document.write(resultArr[2]);</script>
</div>
</code>```

Or (JQuery)

```<code>$('#max').val(resultArr[2]);
</code>```

Title: Get the value from an Array

Body:
I have some code I need help with:

var bob = [10,30,50,20,8];

// Call the function

foo(bob);

var foo = function(bob){

 var max = 0,
 min = 0,
 average = 0,
 sum = 0;

 max = Math.max.apply( null, bob); // Get the max value.
 min = Math.min.apply( null, bob); // Get the min value.

 for( var i = 0; i < bob.length; i++ ){
  sum += bob[ i ];
 }

 average = sum / l;

 var resultArr = [];

 resultArr[0] = average;
 resultArr[1] = min;
 resultArr[2] = max;

 return resultArr;
}

document.getElementById('max').innerHTML = "Max value: "; // i want to print the max value here.

This function returns an array with max, min and average values. How can I choose which value to print in different divs?

Body:
document.getElementById('max').innerHTML = resultArr[2];

Or

<div id="max">
    <script>document.write(resultArr[2]);</script>
</div>

Or (JQuery)

$('#max').val(resultArr[2]);


问:
How can I increase the timeout for the temporary EC2 credentials?
I am using IAM roles to access S3 from my EC2 instance calling the following end point.

curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access.

The response I get -

{
  "Code" : "Success",
  "LastUpdated" : "2017-12-07T06:29:59Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "AASDJCJNSDPLB5FZA",

"SecretAccessKey" : "/vKFYv4AFlarEspnSNSKD87SDNSDFx3EsJv",

"Token" : "FQoDYXdzEIj//////////wEaDBUN1g6SxPkVQ46UjyKcA0l0q7jpEphFkq1OR3TD3Zm180bKKfkUqYeG6Xr/537olhJWKT2GGdkl/kDXIg3WxxBBOafy+yl4jgn0XTrTT2DWOX+ETPLvjZ4vpfrMNfVP0kwZiWbOuk4GcruixVdiuuDM6cce3WxZprFMLIe5WI0jVkpdA/MQQkqVsIsVcsVMa5LdhUsgdLQ3Yo+82BXVMpccjo+jeYqKEvm3h9rk9XmVRlPxn0wHzHgyiUgIl9O3U6/Ocp+hai+L8JzH5EH8O9ystJvf/rPQyZi0tVmsadasdasdydZr4NPtGYiTEye0dWHOhNvUNg8ZzQ9iBSZzUH8YxgtuOsM8C4LESNubVUxj4d9D49Krzs+oc2lFzLvQaEsSosn+V2mLlGq/AtPHwvyVQvlEOD7Uo27+j0QU=",

"Expiration" : "2017-12-07T12:39:23Z"

============================

I want to increase the expiration time "2017-12-07T12:39:23Z" of the temporary credentials. Can someone please help?

答:
It is not possible to increase the duration the credentials obtained by instance profile and the instance/EC2 will rotate the credentials automatically.

Also, you don't have to curl the metadata url to get the credentials. AWS CLI and SDK can be used to get the credentials from the metadata itself.


问:
How can I insert multiple dynamically checkbox value in insert?
when i insert this form all field is inserted but the problem is multiple checkbox value is not insert?

This is my HTML Code:

```<code><form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">

    <?php
        $j=3;

        for($i=0;$i< $j; $i++)
        {
            ?>
            First name :: <input name="firstname[]" type="text" value=""/><br>
            <input name="loop" type="hidden" value="<?php echo $j ?>"/>
            Last name :: <input name="lastname[]" type="text" value="" /><br>
            Age :: <input name="age[]" type="text" value="" /><br>
            <input name="hobbey[]" type="checkbox" value="Cricket" />Cricket
            <input name="hobbey[]" type="checkbox" value="Football" />Football
            <input name="hobbey[]" type="checkbox" value="Tennis" />Tennis
            <br><br>
            <?php
        }
    ?>

    <input name="btnsubmit" type="submit" value="Submit" />
</form>

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

This is my PHP Code:

```<code>    $query = "insert into register (firstname,lastname,age,hobbey) values";

    for($i=0; $i<$_POST["loop"]; $i++)
    {
        $firstname=$_POST["firstname"][$i];
        $lastname=$_POST["lastname"][$i];
        $age=$_POST["age"][$i];

        $hobbey=$_POST["hobbey"][$i];

        $query .= "('$firstname','$lastname','$age','$hobbey')";
    }
</code>```

答:
Use a multi array on the name of the checkboxes

```<code><input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Cricket" />Cricket
<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Football" />Football
<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Tennis" />Tennis
</code>```

in php you do:

```<code> $hobbey=implode(';',$_POST["hobbey"][$i]);
</code>```

beware sql injection

Body:
when i insert this form all field is inserted but the problem is multiple checkbox value is not insert?

This is my HTML Code:

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">

    <?php
        $j=3;

        for($i=0;$i< $j; $i++)
        {
            ?>
            First name :: <input name="firstname[]" type="text" value=""/>

            <input name="loop" type="hidden" value="<?php echo $j ?>"/>
            Last name :: <input name="lastname[]" type="text" value="" />

            Age :: <input name="age[]" type="text" value="" />

            <input name="hobbey[]" type="checkbox" value="Cricket" />Cricket
            <input name="hobbey[]" type="checkbox" value="Football" />Football
            <input name="hobbey[]" type="checkbox" value="Tennis" />Tennis

            <?php
        }
    ?>

    <input name="btnsubmit" type="submit" value="Submit" />
</form>

This is my PHP Code:

    $query = "insert into register (firstname,lastname,age,hobbey) values";

    for($i=0; $i<$_POST["loop"]; $i++)
    {
        $firstname=$_POST["firstname"][$i];
        $lastname=$_POST["lastname"][$i];
        $age=$_POST["age"][$i];

        $hobbey=$_POST["hobbey"][$i];

        $query .= "('$firstname','$lastname','$age','$hobbey')";
    }

Body:
Use a multi array on the name of the checkboxes

<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Cricket" />Cricket
<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Football" />Football
<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Tennis" />Tennis

in php you do:

 $hobbey=implode(';',$_POST["hobbey"][$i]);

beware sql injection


问:
How should I choose an authentication library for CodeIgniter?
I see there are a few. Which ones are maintained and easy to use? What are their pros and cons? </p>

答:
Update (May 14, 2010):

It turns out, the russian developer Ilya Konyukhov picked up the gauntlet after reading this and created a new auth library for CI based on DX Auth, following the recommendations and requirements below.

And the resulting Tank Auth is looking like the answer to the OP's question. I'm going to go out on a limb here and call Tank Auth the best authentication library for CodeIgniter available today. It's a rock-solid library that has all the features you need and none of the bloat you don't:

Tank Auth

Pros

Full featured

Lean footprint (20 files) considering the feature set

Very good documentation

Simple and elegant database design (just 4 DB tables)

Most features are optional and easily configured

Language file support

reCAPTCHA supported

Hooks into CI's validation system

Activation emails

Login with email, username or both (configurable)

Unactivated accounts auto-expire

Simple yet effective error handling

Uses phpass for hashing (and also hashes autologin codes in the DB)

Does not use security questions

Separation of user and profile data is very nice

Very reasonable security model around failed login attempts (good protection against bots and DoS attacks)

(Minor) Cons

Lost password codes are not hashed in DB

Includes a native (poor) CAPTCHA, which is nice for those who don't want to depend on the (Google-owned) reCAPTCHA service, but it really isn't secure enough

Very sparse online documentation (minor issue here, since the code is nicely documented and intuitive)

Download Tank Auth here

Original answer:

I've implemented my own as well (currently about 80% done after a few weeks of work). I tried all of the others first; FreakAuth Light, DX Auth, Redux, SimpleLogin, SimpleLoginSecure, pc_user, Fresh Powered, and a few more. None of them were up to par, IMO, either they were lacking basic features, inherently INsecure, or too bloated for my taste.

Actually, I did a detailed roundup of all the authentication libraries for CodeIgniter when I was testing them out (just after New Year's). FWIW, I'll share it with you:

DX Auth

Pros

Very full featured

Medium footprint (25+ files), but manages to feel quite slim

Excellent documentation, although some is in slightly broken English

Language file support

reCAPTCHA supported

Hooks into CI's validation system

Activation emails

Unactivated accounts auto-expire

Suggests grc.com for salts (not bad for a PRNG)

Banning with stored 'reason' strings

Simple yet effective error handling

Cons

Only lets users 'reset' a lost password (rather than letting them pick a new one upon reactivation)

Homebrew pseudo-event model - good intention, but misses the mark

Two password fields in the user table, bad style

Uses two separate user tables (one for 'temp' users - ambiguous and redundant)

Uses potentially unsafe md5 hashing

Failed login attempts only stored by IP, not by username - unsafe!

Autologin key not hashed in the database - practically as unsafe as storing passwords in cleartext!

Role system is a complete mess: is_admin function with hard-coded role names, is_role a complete mess, check_uri_permissions is a mess, the whole permissions table is a bad idea (a URI can change and render pages unprotected; permissions should always be stored exactly where the sensitive logic is). Dealbreaker!

Includes a native (poor) CAPTCHA

reCAPTCHA function interface is messy

FreakAuth Light

Pros

Very full featured

Mostly quite well documented code

Separation of user and profile data is a nice touch

Hooks into CI's validation system

Activation emails

Language file support

Actively developed

Cons

Feels a bit bloated (50+ files)

And yet it lacks automatic cookie login (!)

Doesn't support logins with both username and email

Seems to have issues with UTF-8 characters

Requires a lot of autoloading (impeding performance)

Badly micromanaged config file

Terrible View-Controller separation, with lots of program logic in views and output hard-coded into controllers. Dealbreaker!

Poor HTML code in the included views

Includes substandard CAPTCHA

Commented debug echoes everywhere

Forces a specific folder structure

Forces a specific Ajax library (can be switched, but shouldn't be there in the first place)

No max limit on login attempts - VERY unsafe! Dealbreaker!

Hijacks form validation

Uses potentially unsafe md5 hashing

pc_user

Pros

Good feature set for its tiny footprint

Lightweight, no bloat (3 files)

Elegant automatic cookie login

Comes with optional test implementation (nice touch)

Cons

Uses the old CI database syntax (less safe)

Doesn't hook into CI's validation system

Kinda unintuitive status (role) system (indexes upside down - impractical)

Uses potentially unsafe sha1 hashing

Fresh Powered

Pros

Small footprint (6 files)

Cons

Lacks a lot of essential features. Dealbreaker!

Everything is hard-coded. Dealbreaker!

Redux / Ion Auth

According to the CodeIgniter wiki, Redux has been discontinued, but the Ion Auth fork is going strong: https://github.com/benedmunds/CodeIgniter-Ion-Auth

Ion Auth is a well featured library without it being overly heavy or under advanced. In most cases its feature set will more than cater for a project's requirements.

Pros

Lightweight and simple to integrate with CodeIgniter

Supports sending emails directly from the library

Well documented online and good active dev/user community

Simple to implement into a project

Cons

More complex DB schema than some others

Documentation lacks detail in some areas

SimpleLoginSecure

Pros

Tiny footprint (4 files)

Minimalistic, absolutely no bloat

Uses phpass for hashing (excellent)

Cons

Only login, logout, create and delete

Lacks a lot of essential features. Dealbreaker!

More of a starting point than a library

Don't get me wrong: I don't mean to disrespect any of the above libraries; I am very impressed with what their developers have accomplished and how far each of them have come, and I'm not above reusing some of their code to build my own. What I'm saying is, sometimes in these projects, the focus shifts from the essential 'need-to-haves' (such as hard security practices) over to softer 'nice-to-haves', and that's what I hope to remedy.

Therefore: back to basics.

Authentication for CodeIgniter done right

Here's my MINIMAL required list of features from an authentication library. It also happens to be a subset of my own library's feature list ;)

Tiny footprint with optional test implementation

Full documentation

No autoloading required. Just-in-time loading of libraries for performance

Language file support; no hard-coded strings

reCAPTCHA supported but optional

Recommended TRUE random salt generation (e.g. using random.org or random.irb.hr)

Optional add-ons to support 3rd party login (OpenID, Facebook Connect, Google Account, etc.)

Login using either username or email

Separation of user and profile data

Emails for activation and lost passwords

Automatic cookie login feature

Configurable phpass for hashing (properly salted of course!)

Hashing of passwords

Hashing of autologin codes

Hashing of lost password codes

Hooks into CI's validation system

NO security questions!

Enforced strong password policy server-side, with optional client-side (Javascript) validator

Enforced maximum number of failed login attempts with BEST PRACTICES countermeasures against both dictionary and DoS attacks!

All database access done through prepared (bound) statements!

Note: those last few points are not super-high-security overkill that you don't need for your web application. If an authentication library doesn't meet these security standards 100%, DO NOT USE IT!

Recent high-profile examples of irresponsible coders who left them out of their software: #17 is how Sarah Palin's AOL email was hacked during the Presidential campaign; a nasty combination of #18 and #19 were the culprit recently when the Twitter accounts of Britney Spears, Barack Obama, Fox News and others were hacked; and #20 alone is how Chinese hackers managed to steal 9 million items of personal information from more than 70.000 Korean web sites in one automated hack in 2008.

These attacks are not brain surgery. If you leave your back doors wide open, you shouldn't delude yourself into a false sense of security by bolting the front. Moreover, if you're serious enough about coding to choose a best-practices framework like CodeIgniter, you owe it to yourself to at least get the most basic security measures done right.

<rant>

Basically, here's how it is: I don't care if an auth library offers a bunch of features, advanced role management, PHP4 compatibility, pretty CAPTCHA fonts, country tables, complete admin panels, bells and whistles -- if the library actually makes my site less secure by not following best practices. It's an authentication package; it needs to do ONE thing right: Authentication. If it fails to do that, it's actually doing more harm than good.

</rant>

/Jens Roland

OwnerDisplayName: GavinR

LastEditorDisplayName: stesch

OwnerDisplayName: Jens Roland

LastEditorDisplayName: Jens Roland


问:
npm install running failed

Even though I use Administrator install gulp, it still failed.

What's wrong with it?

答:
Change the permission of the file and for more information about permission visit
https://docs.npmjs.com/getting-started/fixing-npm-permissions </p>

Title: npm install running failed


问:
Converting a char to uppercase in Java
How could I get the f and l variables converted to uppercase?

```<code>String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);

char f = first.charAt(0);
char l = last.charAt(0);

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

答:
I think you are trying to capitalize first and last character of each word in a sentence with space as delimiter.

Can be done through StringBuffer:

```<code>public static String toFirstLastCharUpperAll(String string){
    StringBuffer sb=new StringBuffer(string);
        for(int i=0;i<sb.length();i++)
            if(i==0 || sb.charAt(i-1)==' ' //for first character of string/each word
                || i==sb.length()-1 || sb.charAt(i+1)==' ') //for last character of string/each word
                sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
     return sb.toString();
}
</code>```

Title: Converting a char to uppercase in Java

Body:
How could I get the f and l variables converted to uppercase?

String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);

char f = first.charAt(0);
char l = last.charAt(0);

System.out.println(l);

Body:
I think you are trying to capitalize first and last character of each word in a sentence with space as delimiter.

Can be done through StringBuffer:

public static String toFirstLastCharUpperAll(String string){
    StringBuffer sb=new StringBuffer(string);
        for(int i=0;i<sb.length();i++)
            if(i==0 || sb.charAt(i-1)==' ' //for first character of string/each word
                || i==sb.length()-1 || sb.charAt(i+1)==' ') //for last character of string/each word
                sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
     return sb.toString();
}


问:
Errors when trying to call a method
I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.

```<code>staff[3].awardBonus(bonus);
</code>```

I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;

```<code>    import java.util.Scanner;
public class Tester
{
    public static void main (String args[])
    {
        Scanner scan = new Scanner(System.in);
        StaffMember[] staff = new StaffMember[4];
        String internName = "Susan 2";
        String empName = "Tyler O.";
        String hrName = "Becky R.";
        String execName = "Daniel H.";
        String address = "Brighton";
        String phone = "420 - 0000";
        String SSN = "12345789";
        double rate = 1000;

        staff [0] = new Intern(internName, address, phone);
        staff [1] = new Employee(empName, address, phone, SSN, rate);
        staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
        staff [3] = new Executive(execName, address, phone, SSN, rate);

        for (StaffMember staffPrint : staff)
        {
            System.out.println (staffPrint.toString() + "\n");
        }

        System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
        int input = scan.nextInt();
        if(input == 1)
        {
            double bonus = 0;
            System.out.println("Enter the bonus for your employee: ");
            bonus = scan.nextDouble();

        }
 }
</code>```

Here is the Executive class, Employee class and the StaffMember class

```<code>public class Executive extends Employee
{
    public Executive(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone, SSN, rate);
    }

    public double pay()
    {
        double money = super.pay();
        return money;
    }

    public String toString()
    {
        String employee = super.toString();
        return employee;
    }

    public void awardBonus(double execBonus)
    {
        rate += execBonus;
    }
}
</code>```

Employee

```<code>    public class Employee extends StaffMember
{
    String SSN;
    double rate;

    public Employee(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone);
        this.SSN = SSN;
        this.rate = rate;
    }

    public double pay()
    {
        return rate;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
        return employee;
    }
}
</code>```

StaffMember

```<code>public abstract class StaffMember
{
    String name;
    String address;
    String phone;

    public StaffMember(String name, String address, String phone)
    {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
        return employee;
    }

    public abstract double pay();
}
</code>```

答:
staff is a StaffMember array. When you reference any item from it (as you do it staff[3]), you get a StaffMember.

StaffMember does not have a method awardBonus().

Title: Errors when trying to call a method

Body:
I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.

staff[3].awardBonus(bonus);

I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;

    import java.util.Scanner;
public class Tester
{
    public static void main (String args[])
    {
        Scanner scan = new Scanner(System.in);
        StaffMember[] staff = new StaffMember[4];
        String internName = "Susan 2";
        String empName = "Tyler O.";
        String hrName = "Becky R.";
        String execName = "Daniel H.";
        String address = "Brighton";
        String phone = "420 - 0000";
        String SSN = "12345789";
        double rate = 1000;

        staff [0] = new Intern(internName, address, phone);
        staff [1] = new Employee(empName, address, phone, SSN, rate);
        staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
        staff [3] = new Executive(execName, address, phone, SSN, rate);

        for (StaffMember staffPrint : staff)
        {
            System.out.println (staffPrint.toString() + "\n");
        }

        System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
        int input = scan.nextInt();
        if(input == 1)
        {
            double bonus = 0;
            System.out.println("Enter the bonus for your employee: ");
            bonus = scan.nextDouble();

        }
 }

Here is the Executive class, Employee class and the StaffMember class

public class Executive extends Employee
{
    public Executive(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone, SSN, rate);
    }

    public double pay()
    {
        double money = super.pay();
        return money;
    }

    public String toString()
    {
        String employee = super.toString();
        return employee;
    }

    public void awardBonus(double execBonus)
    {
        rate += execBonus;
    }
}

Employee

    public class Employee extends StaffMember
{
    String SSN;
    double rate;

    public Employee(String name, String address, String phone, String SSN, double rate)
    {
        super(name, address, phone);
        this.SSN = SSN;
        this.rate = rate;
    }

    public double pay()
    {
        return rate;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
        return employee;
    }
}

StaffMember

public abstract class StaffMember
{
    String name;
    String address;
    String phone;

    public StaffMember(String name, String address, String phone)
    {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }

    public String toString()
    {
        String employee = "";
        employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
        return employee;
    }

    public abstract double pay();
}


问:
Delete local Git branches after deleting them on the remote repo
I want to have my local and remote repositories always in sync in terms of branches.

After a Pull Request review on GitHub, I merge and remove my branch there (remote).
How could I fetch this information in my local repository and get Git to remove my local version of the branch as well?

答:
I just do that to remove merged local branches:

```<code>git branch -d $(git branch --merged)
</code>```

and in case you want to remove inexistent trackings too:

```<code>git pull --prune
</code>```

Body:
I just do that to remove merged local branches:

git branch -d $(git branch --merged)

and in case you want to remove inexistent trackings too:

git pull --prune


问:
change window title with python on script start
I put together a simple script to encode movies, now while the script works just fine I am having difficulties on changing the window title on script start instead on when its terminated. since is kind of useless to mark each window after it finished. can I use subprocess to perform such task? so change the title while the script runs?

I am using this in a bash script to change the title:

```<code>PS1="\e]2;$1\a\[$1 \W]\$"
</code>```

答:
if you are running the sub process without invoking any new terminal , you can rename the windows with below code </p>

```<code># your subprocess code here
import sys
sys.stdout.write(b'\33]0;title you want\a')
</code>```

Body:
I put together a simple script to encode movies, now while the script works just fine I am having difficulties on changing the window title on script start instead on when its terminated. since is kind of useless to mark each window after it finished. can I use subprocess to perform such task? so change the title while the script runs?

I am using this in a bash script to change the title:

PS1="\e]2;$1\a\[$1 \W]\$"

Body:
if you are running the sub process without invoking any new terminal , you can rename the windows with below code

# your subprocess code here
import sys
sys.stdout.write(b'\33]0;title you want\a')


问:
ZF3: Read out url parameter in PhpRenderer
I want to upgrade from ZF2 to ZF3 right now and has the following problem with using URL parameter in my PhpRenderer.

In ZF2 I use the HelperPluginManager to get Application, then the MvcEvent and finally the routeMatch:

```<code>$routeMatch = $this
   ->getHelperPluginManager()
   ->getServiceLocator()
   ->get('Application')
   ->getMvcEvent()
   ->getRouteMatch();

$parameterAction = $routeMatch->getParam('action');
</code>```

In ZF3 there is a deprecation warning with using the getServiceLocator() (which makes sense, because it only returns the creationContext from the ServiceManager). I want to find a way not trigger the warning.

Configure the Application as a factory-using class (using \Zend\Mvc\Service\ApplicationFactory::class) also not works, because:

Zend\View\HelperPluginManager can only create instances of Zend\View\Helper\HelperInterface and/or callables.

Is there any way to get the Application context in my template (or better even the parameters of the URL)?

答:
For routeMatch, if you have a MvcEvent just use;

```<code>$event->getRouteMatch()
</code>```

If you have container;

```<code>$container->getApplication()->getMvcEvent()->getRouteMatch();
</code>```

If you want to access routeMatch in view there's no way except view helper like tasmaniski/zend-current-route

Body:
I want to upgrade from ZF2 to ZF3 right now and has the following problem with using URL parameter in my PhpRenderer.

In ZF2 I use the HelperPluginManager to get Application, then the MvcEvent and finally the routeMatch:

$routeMatch = $this
   ->getHelperPluginManager()
   ->getServiceLocator()
   ->get('Application')
   ->getMvcEvent()
   ->getRouteMatch();

$parameterAction = $routeMatch->getParam('action');

In ZF3 there is a deprecation warning with using the getServiceLocator() (which makes sense, because it only returns the creationContext from the ServiceManager). I want to find a way not trigger the warning.

Configure the Application as a factory-using class (using \Zend\Mvc\Service\ApplicationFactory::class) also not works, because:

Zend\View\HelperPluginManager can only create instances of Zend\View\Helper\HelperInterface and/or callables.

Is there any way to get the Application context in my template (or better even the parameters of the URL)?

Body:
For routeMatch, if you have a MvcEvent just use;

$event->getRouteMatch()

If you have container;

$container->getApplication()->getMvcEvent()->getRouteMatch();

If you want to access routeMatch in view there's no way except view helper like tasmaniski/zend-current-route


问:
Passing a variable result from one view controller to another non-view controller swift file
I am trying to make an iOS app that takes a username from a text field, turns it into a string and passes it to another file I have called HomeModel.swift. This file is NOT a ViewController but I need that variable name to add to a URL.

Currently, my app is set up with an initial view controller that has a text field for a username and a Login button. When I click the login button it takes the textfield entry and turns it into a string which I then use to turn into a label on the next ViewController. My issue is taking the username variable (that I used to turn into a label) and passing it to a non-ViewController swift file so I can do some "behind-the-scenes" stuff with it.

Any help would be greatly appreciated as I have spent hours trying to find an answer but came up short handed.

This is my initial ViewController

```<code>import UIKit

class Home: UIViewController, UITextFieldDelegate {

@IBOutlet var TextField: UITextField!
@IBOutlet var PasswordField: UITextField!
@IBOutlet var LoginBtn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.TextField.delegate = self
    self.PasswordField.delegate = self

    func checkField(sender: Any?) {
        if (TextField.text?.isEmpty)! || (PasswordField.text?.isEmpty)!
        {
            LoginBtn.isEnabled = false

        }
        else
        {
            LoginBtn.isEnabled = true
        }
    }
}

//Hide keyboard when touched outisde keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    PasswordField.resignFirstResponder()
    return (true)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController : ViewTwo = segue.destination as! ViewTwo

    DestViewController.PasswordText = PasswordField.text!
    DestViewController.LabelText = TextField.text!
}

}
</code>```

This is the HomeModel.swift file

```<code>import Foundation

protocol HomeModelProtocol: class {
func itemsDownloaded(items: NSArray)
}

class HomeModel: NSObject, URLSessionDataDelegate {

//properties

weak var delegate: HomeModelProtocol!

func viewDidLoad() {

}

func downloadItems() {

    let myusername = //Variable from initial controller here

    let urlPath = "http://urlhere.com/index.php?username="+myusername //this is where the list of users are

    let url: URL = URL(string: urlPath)!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
    let task = defaultSession.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("Failed to download data")
        }
        else {
            print("Contact List Data Downloaded")
            self.parseJSON(data!)
        }
    }
    task.resume()
}

func parseJSON(_ data:Data) {
    var jsonResult = NSArray()
    print (jsonResult)

    do {
        jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

    }
    catch let error as NSError {
        print(error)
    }

    var jsonElement = NSDictionary()
    let locations = NSMutableArray()

    for i in 0 ..< jsonResult.count
    {
        jsonElement = jsonResult[i] as! NSDictionary

        let location = LocationModel()

        //the following insures none of the JsonElement values are nil through optional binding
        if let name = jsonElement["name"] as? String,
            let phone = jsonElement["phone"] as? String
        {
            location.name = name
            location.phone = phone
        }

        locations.add(location)
    }

    DispatchQueue.main.async(execute: { () -> Void in

        self.delegate.itemsDownloaded(items: locations)

    })
}
}
</code>```

答:
Generally from what you are describing this is simply passing your object between view controllers you are having. Assume having:

```<code>class LoginData {
   var username: String?
}
</code>```

Now your first view controller seems to be your entry point so it is the one that creates it for instance on "next" button pressed. Then this object should be passed to the new view controller:

```<code>@IBAction onNextPressed() {
    let loginData = LoginData() // Create object
    loginData.username = self.textField.text // Set data to it

    let nextController = UIStoryboard(...) as! NextViewController // Generate new view controller
    nextController.loginData = loginData // Assign login data
    navigationController.push(... nextController ...) // Show controller
}
</code>```

So then the next view controller should use this object:

```<code>class NextViewController: UIViewController {
    var loginData: LoginData?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.label.text = loginData?.username
    }

...
</code>```

In some cases though (which seems like yours) it might make sense to preserve data globally. To do so all you need is a static variable. In your case I suggest you create a new object User.

```<code>class User {
    static var current: User?

    var loginData: LoginData?
}
</code>```

Now here User only contains login data but there is also a placeholder to add an instance of a current user which may be used whenever inside the app.

Now for this case the first view controller does not need to pass the data to next view controller but rather set the current user:

```<code>@IBAction onNextPressed() {
    let loginData = LoginData() // Create object
    loginData.username = self.textField.text // Set data to it

    let newUser = User() // Create a new user
    newUser.loginData = loginData // Assign login data to it
    User.current = newUser // Set current user

    let nextController = UIStoryboard(...) // Generate new view controller
    navigationController.push(... nextController ...) // Show controller
}
</code>```

And the new view controller does not need a reference to login data:

```<code>class NextViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.label.text = User.current?.loginData?.username
    }

...
</code>```

This is great when you need to use these data all over the app so as you mentioned some url you can now call anywhere User.current?.serviceURL if you implement:

```<code>extension User {
   var serviceURL: URL? {
      guard let username = username else {
         return nil
      }
      return URL(string: "https://some.pat/\(username)/resource_name")
   }
}
</code>```

I hope this clears a few things about passing data in Swift.

Body:
I am trying to make an iOS app that takes a username from a text field, turns it into a string and passes it to another file I have called HomeModel.swift. This file is NOT a ViewController but I need that variable name to add to a URL.

Currently, my app is set up with an initial view controller that has a text field for a username and a Login button. When I click the login button it takes the textfield entry and turns it into a string which I then use to turn into a label on the next ViewController. My issue is taking the username variable (that I used to turn into a label) and passing it to a non-ViewController swift file so I can do some "behind-the-scenes" stuff with it.

Any help would be greatly appreciated as I have spent hours trying to find an answer but came up short handed.

This is my initial ViewController

import UIKit

class Home: UIViewController, UITextFieldDelegate {

@IBOutlet var TextField: UITextField!
@IBOutlet var PasswordField: UITextField!
@IBOutlet var LoginBtn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.TextField.delegate = self
    self.PasswordField.delegate = self

    func checkField(sender: Any?) {
        if (TextField.text?.isEmpty)! || (PasswordField.text?.isEmpty)!
        {
            LoginBtn.isEnabled = false

        }
        else
        {
            LoginBtn.isEnabled = true
        }
    }
}

//Hide keyboard when touched outisde keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    PasswordField.resignFirstResponder()
    return (true)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController : ViewTwo = segue.destination as! ViewTwo

    DestViewController.PasswordText = PasswordField.text!
    DestViewController.LabelText = TextField.text!
}

}

This is the HomeModel.swift file

import Foundation

protocol HomeModelProtocol: class {
func itemsDownloaded(items: NSArray)
}

class HomeModel: NSObject, URLSessionDataDelegate {

//properties

weak var delegate: HomeModelProtocol!

func viewDidLoad() {

}

func downloadItems() {

    let myusername = //Variable from initial controller here

    let urlPath = "http://urlhere.com/index.php?username="+myusername //this is where the list of users are

    let url: URL = URL(string: urlPath)!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
    let task = defaultSession.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("Failed to download data")
        }
        else {
            print("Contact List Data Downloaded")
            self.parseJSON(data!)
        }
    }
    task.resume()
}

func parseJSON(_ data:Data) {
    var jsonResult = NSArray()
    print (jsonResult)

    do {
        jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

    }
    catch let error as NSError {
        print(error)
    }

    var jsonElement = NSDictionary()
    let locations = NSMutableArray()

    for i in 0 ..< jsonResult.count
    {
        jsonElement = jsonResult[i] as! NSDictionary

        let location = LocationModel()

        //the following insures none of the JsonElement values are nil through optional binding
        if let name = jsonElement["name"] as? String,
            let phone = jsonElement["phone"] as? String
        {
            location.name = name
            location.phone = phone
        }

        locations.add(location)
    }

    DispatchQueue.main.async(execute: { () -> Void in

        self.delegate.itemsDownloaded(items: locations)

    })
}
}

Body:
Generally from what you are describing this is simply passing your object between view controllers you are having. Assume having:

class LoginData {
   var username: String?
}

Now your first view controller seems to be your entry point so it is the one that creates it for instance on "next" button pressed. Then this object should be passed to the new view controller:

@IBAction onNextPressed() {
    let loginData = LoginData() // Create object
    loginData.username = self.textField.text // Set data to it

    let nextController = UIStoryboard(...) as! NextViewController // Generate new view controller
    nextController.loginData = loginData // Assign login data
    navigationController.push(... nextController ...) // Show controller
}

So then the next view controller should use this object:

class NextViewController: UIViewController {
    var loginData: LoginData?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.label.text = loginData?.username
    }

...

In some cases though (which seems like yours) it might make sense to preserve data globally. To do so all you need is a static variable. In your case I suggest you create a new object User.

class User {
    static var current: User?

    var loginData: LoginData?
}

Now here User only contains login data but there is also a placeholder to add an instance of a current user which may be used whenever inside the app.

Now for this case the first view controller does not need to pass the data to next view controller but rather set the current user:

@IBAction onNextPressed() {
    let loginData = LoginData() // Create object
    loginData.username = self.textField.text // Set data to it

    let newUser = User() // Create a new user
    newUser.loginData = loginData // Assign login data to it
    User.current = newUser // Set current user

    let nextController = UIStoryboard(...) // Generate new view controller
    navigationController.push(... nextController ...) // Show controller
}

And the new view controller does not need a reference to login data:

class NextViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.label.text = User.current?.loginData?.username
    }

...

This is great when you need to use these data all over the app so as you mentioned some url you can now call anywhere User.current?.serviceURL if you implement:

extension User {
   var serviceURL: URL? {
      guard let username = username else {
         return nil
      }
      return URL(string: "https://some.pat/\(username)/resource_name")
   }
}

I hope this clears a few things about passing data in Swift.


问:
C# Not able to serialize class with List<CustomObject> as property
Hi
I am trying to serialize

```<code>FileStream fileStream = new FileStream("batches.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>));
List<Batche> listOfBatches = new List<Batche>();

[Serializable]
[XmlRoot("Batch")]
public class Batche
{

    [XmlElement("Title")]
    public string Title
    {
        get;set;
    }

    [XmlArray("ListOfLinks"),XmlArrayItem("Link",Type = typeof(Link))]
    public List<Link> Links
    {
        get;set;
    }
}

[Serializable]
[XmlRoot("Link")]
public class Link
{
   [XmlElement("Uri")]
   public Uri Uri
   {
       get;
       set;
   }

   [XmlElement("Status")]
   public string Status
   {
       get;
       set;
   }

}
</code>```

Getting following error :
There was an error reflecting type 'System.Collections.Generic.List`1[DownloadTRON.Entities.Batche]'.

been trying this since last 4 hours,
can any body point out what i am doing Wrong !

Regards
Pravin

答:
There is no problem with your code or the serialization of generics. Uri doesn't have a default constructor and cannot be serialized. Consider changing it to a string and things will work. If you are only planning on using the XmlSerializer you can remove the Serializable attribute because it isn't used.

When I ran your code with the debugger and saw the exception there was an inner exception with an inner exception with an inner exception and so on. Always a good idea to follow that rabbit down the hole when you can.

Body:
Hi
I am trying to serialize

FileStream fileStream = new FileStream("batches.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(List<Batche>));
List<Batche> listOfBatches = new List<Batche>();

[Serializable]
[XmlRoot("Batch")]
public class Batche
{

    [XmlElement("Title")]
    public string Title
    {
        get;set;
    }

    [XmlArray("ListOfLinks"),XmlArrayItem("Link",Type = typeof(Link))]
    public List<Link> Links
    {
        get;set;
    }
}

[Serializable]
[XmlRoot("Link")]
public class Link
{
   [XmlElement("Uri")]
   public Uri Uri
   {
       get;
       set;
   }

   [XmlElement("Status")]
   public string Status
   {
       get;
       set;
   }

}

Getting following error :
There was an error reflecting type 'System.Collections.Generic.List`1[DownloadTRON.Entities.Batche]'.

been trying this since last 4 hours,
can any body point out what i am doing Wrong !

Regards
Pravin


问:
Select last entry and offset by 1 row then paste value not working
I'm having Run time error 1004 with this code.

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and     perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
  .Title = "Select A Target Folder"
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

    'Loop through each Excel file in folder
  Do While myFile <> ""
'Set variable equal to opened workbook
  Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
  DoEvents

Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")

With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"
' paste
.Range("E" & LastRow + 1) = rng1
End With

'Save and Close Workbook
  wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
  DoEvents

'Get next file name
  myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

I'm using this segment of code to extract data from B15 to E81 from all the excel workbook in the folder.

Upon copying, it will activate the workbook where this code lie

Select last entry from column E

Offset by 1 row

Paste selection to column activated cell

Appreciate all the help I could find. Thanks in advance.

答:
First, as suggested by @teylyn, you should avoid using Select and Activate (99.9% of the time they are not needed, and the only thing they do "contribute" is time wasting, since it takes the code longer to run).

Second, you should also specify which Worksheet you want to paste in ThisWorkbook object.

Code

```<code>Dim LastRow As Long

wb.Worksheets(1).Range("B15:E81").Copy

With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
    LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"

    ' paste
    .Range("E" & LastRow + 1).PasteSpecial Paste:=xlPasteValues
End With
</code>```

Body:
I'm having Run time error 1004 with this code.

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and     perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
  .Title = "Select A Target Folder"
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

    'Loop through each Excel file in folder
  Do While myFile <> ""
'Set variable equal to opened workbook
  Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
  DoEvents

Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")

With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"
' paste
.Range("E" & LastRow + 1) = rng1
End With

'Save and Close Workbook
  wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
  DoEvents

'Get next file name
  myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I'm using this segment of code to extract data from B15 to E81 from all the excel workbook in the folder.

Upon copying, it will activate the workbook where this code lie

Select last entry from column E

Offset by 1 row

Paste selection to column activated cell

Appreciate all the help I could find. Thanks in advance.

Body:
First, as suggested by @teylyn, you should avoid using Select and Activate (99.9% of the time they are not needed, and the only thing they do "contribute" is time wasting, since it takes the code longer to run).

Second, you should also specify which Worksheet you want to paste in ThisWorkbook object.

Code

Dim LastRow As Long

wb.Worksheets(1).Range("B15:E81").Copy

With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
    LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"

    ' paste
    .Range("E" & LastRow + 1).PasteSpecial Paste:=xlPasteValues
End With


问:
Laravel cannot add foreign key
Something broke in my migrations file as I am doing a migrate:fresh and it throws:

```<code>SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: create table `product` (`test` int not null) default character
set utf8mb4 collate utf8mb4_unicode_ci)
</code>```

I have deleted everything in that migration and left only one field in order to debug what may be the issue, and here is the migration as is now and the one which is giving me this error:

```<code>public function up()
{
    Schema::create('product', function (Blueprint $table) {
        $table->integer('test');
    });
}
</code>```

I tried doing composer dump-autoload but nothing changed.

EDIT

After doing vagrant halt and vagrant up the first error I'm getting after migrate:freshis:

```<code>SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write;
duplicate key in table '#sql-4ef_4' (SQL: alter table
`product_shipping_country` add constraint `fk_psc_product` foreign key
(`product_id`) references `product` (`content_id`) on delete CASCADE on
update CASCADE)
</code>```

But immediately after I run migrate:fresh this error is no longer present, and I am getting the old one again

EDIT 2

I tried manually deleting the DB, same thing happens. Also clearing both composer clear-cache and artisan cache:clear

EDIT 3

If I delete that migration, and every migration after that one, the error is gone, so I suppose the error is in that specific migration?

I don't get how can I get foreign-key error when I even don't have foreign keys in the migration??

答: It was some cache issue obviously. I resolved it by completely deleting the DB and creating it again. Migrations and reseeds worked perfectly after that.</p>

Title: Laravel cannot add foreign key

Body:
Something broke in my migrations file as I am doing a migrate:fresh and it throws:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: create table `product` (`test` int not null) default character
set utf8mb4 collate utf8mb4_unicode_ci)

I have deleted everything in that migration and left only one field in order to debug what may be the issue, and here is the migration as is now and the one which is giving me this error:

public function up()
{
    Schema::create('product', function (Blueprint $table) {
        $table->integer('test');
    });
}

I tried doing composer dump-autoload but nothing changed.

EDIT

After doing vagrant halt and vagrant up the first error I'm getting after migrate:freshis:

SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write;
duplicate key in table '#sql-4ef_4' (SQL: alter table
`product_shipping_country` add constraint `fk_psc_product` foreign key
(`product_id`) references `product` (`content_id`) on delete CASCADE on
update CASCADE)

But immediately after I run migrate:fresh this error is no longer present, and I am getting the old one again

EDIT 2

I tried manually deleting the DB, same thing happens. Also clearing both composer clear-cache and artisan cache:clear

EDIT 3

If I delete that migration, and every migration after that one, the error is gone, so I suppose the error is in that specific migration?

I don't get how can I get foreign-key error when I even don't have foreign keys in the migration??


答:
Your problem is that you are trying to call an undefined method on your StaffMember object. In fact the method awardBonus() was not defined in your StaffMember class.

And in the code staff[3].awardBonus(bonus) you were trying to call awardBonus() on staff[3] which is a StaffMember instance.

Title: Errors when trying to call a method


问:
How to handle calls to multiple functions in the same web service?
This is a super newbie question on Flex.  While I am a seasoned programmer, this is my first ever Flex application; please bear with me for my Flex codes.

I have a web service written in ColdFusion.  In this web service, there are two functions; one is to return all the questions in a quiz and the other one is to return all the answer selections to the questions in a quiz.

```<code>            [Bindable]
        private var questionArray:ArrayCollection;
        private var cfquiz:RemoteObject;

        private function loadQuestions():void {
            currentQuestionCounter = 0;
            btnPrev.enabled = false;
            btnNext.enabled = false;
            cfquiz = new RemoteObject("ColdFusion");
            cfquiz.source = "CFCertExam.cfquiz";
            cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
        }

        private function resultHandler(event:ResultEvent):void {
            questionArray = event.result as ArrayCollection;

            txt1Questions.htmlText = questionArray.getItemAt(currentQuestionCounter).Question_Text;
            btnNext.enabled = true;
        }
</code>```

I have the codes above.  loadQuestions is called at creationComplete to retrieve the questions.  Things are working fine.  What I want to do is to call another function within the same web service, returnAnswers, to return the answer options for a question.  Since I have cfquiz associated to the web service already, I was using cfquiz to call returnAnswers.  However, there is an event listener associated to cfquiz already, resultHandler is being called when returnAnswers comes back with the results.

My questions are, first, is it possible to check which function returns the results within resultHandler?  If so, how?  And second, what is the best way to handle calls to multiple functions within the same web service?

Thanks in advance,
Monte

答: Yes you can. You need to specify a handler function for each method which in turn calls a different webservice.</p>

Body:
This is a super newbie question on Flex.  While I am a seasoned programmer, this is my first ever Flex application; please bear with me for my Flex codes.

I have a web service written in ColdFusion.  In this web service, there are two functions; one is to return all the questions in a quiz and the other one is to return all the answer selections to the questions in a quiz.

            [Bindable]
        private var questionArray:ArrayCollection;
        private var cfquiz:RemoteObject;

        private function loadQuestions():void {
            currentQuestionCounter = 0;
            btnPrev.enabled = false;
            btnNext.enabled = false;
            cfquiz = new RemoteObject("ColdFusion");
            cfquiz.source = "CFCertExam.cfquiz";
            cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
        }

        private function resultHandler(event:ResultEvent):void {
            questionArray = event.result as ArrayCollection;

            txt1Questions.htmlText = questionArray.getItemAt(currentQuestionCounter).Question_Text;
            btnNext.enabled = true;
        }

I have the codes above.  loadQuestions is called at creationComplete to retrieve the questions.  Things are working fine.  What I want to do is to call another function within the same web service, returnAnswers, to return the answer options for a question.  Since I have cfquiz associated to the web service already, I was using cfquiz to call returnAnswers.  However, there is an event listener associated to cfquiz already, resultHandler is being called when returnAnswers comes back with the results.

My questions are, first, is it possible to check which function returns the results within resultHandler?  If so, how?  And second, what is the best way to handle calls to multiple functions within the same web service?

Thanks in advance,
Monte


问:
Azure App Service Usage
I have deployed my web service in   microsoft azure as App Service(Basic B1). recently i observed that i was not using entire resources(CPU,Memory) in Basic B1 . so i decided to scale down my resources(CPU,Memory).

i know that Shared is the next low plan to Basic B1. But i need more Resources(CPU,Memory)  than Shared plan  is providing.

My Questions Are

1) is there any intermediary plan between (Basic B1) and Shared.

2) Why Azure is not costing based on the amount of the resources what i have used?

答:
1) No. The tier below Basic B1 is Shared.

2) You are reserving capacity from a host. You are billed based on that. This way if your app should need more CPU/memory, it already has it available.

Title: Azure App Service Usage


问:
Sqlite3 stores data as text instead of integer
I have created a table in Sqlite3 as following:

```<code>def create_table(self):
    """create a database table if it does not exist already"""
    self.cur.execute('''CREATE TABLE IF NOT EXISTS jobs(title text, \
                                                        job_id integer PRIMARY KEY,
                                                        age integer)''')
</code>```

"age" is defined as an integer. But when I executed this query in DB Browser for SQLite:

```<code>Pragma table_info(jobs);
</code>```

I got this response:

```<code>Query executed successfully: Pragma table_info(jobs); (took 1ms)

cid name type  pk
2   age  text  0 //rows title and job_id have been ignored as they are as expected
</code>```

"age" is of data type text?!?!

The possible cause is:

when a row of data is inserted, the data inserted into age column is of text, but if this is the case, then it comes with one more question, does sqlite3 not check data type before inserting it?

答:
Does the issue persist if you drop the table and recreate it? Since you are creating it only if it does not exist, it might be an artifact from an old version.

Results are as expected on my end:

```<code>0|title|text|0||0
1|job_id|integer|0||1
2|age|integer|0||0
</code>```

Body:
I have created a table in Sqlite3 as following:

def create_table(self):
    """create a database table if it does not exist already"""
    self.cur.execute('''CREATE TABLE IF NOT EXISTS jobs(title text, \
                                                        job_id integer PRIMARY KEY,
                                                        age integer)''')

"age" is defined as an integer. But when I executed this query in DB Browser for SQLite:

Pragma table_info(jobs);

I got this response:

Query executed successfully: Pragma table_info(jobs); (took 1ms)

cid name type  pk
2   age  text  0 //rows title and job_id have been ignored as they are as expected

"age" is of data type text?!?!

The possible cause is:

when a row of data is inserted, the data inserted into age column is of text, but if this is the case, then it comes with one more question, does sqlite3 not check data type before inserting it?

Body:
Does the issue persist if you drop the table and recreate it? Since you are creating it only if it does not exist, it might be an artifact from an old version.

Results are as expected on my end:

0|title|text|0||0
1|job_id|integer|0||1
2|age|integer|0||0


问:
Issue with returning object from a function in asp.net MVC
i am little confused about my code:

Here is some function from my controller:

```<code>  public void signIn(string userName, string userPass)
        {
            User user = new User();
            user.getUser(userName , userPass);

            if (user.userName != null)
            {
                Response.Redirect("/Home/Menu");
            }
            else
            {
                Response.Redirect("/Index/Index?Fail=" + "fail");
            }
        }
</code>```

the " user.getUser" suppose to return a User object.. here is the code from my Model directory:

```<code>public class User
{
    public ObjectId _id { get; set; }
    public string userName { get; set; }
    public string userPass { get; set; }

    public User getUser(string name , string pass)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var db = client.GetDatabase("testdb");
        var coll = db.GetCollection<User>("user");

        List<User> list = coll.Find(x => x.userName == name && x.userPass == pass).ToList<User>();

        User uObj = new User();
        uObj = list.FirstOrDefault();

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

when i am debugging the code i can see the uJob object contain values. but when the function end and i return to the controller i see that the user object contain only null values, and the condition - "   if (user.userName != null)" is returning FALSE!.. instead of TRUE..

i would like to get some help. Thanks !

答:
You have to assign it.</p>

```<code> user = user.getUser(userName , userPass);
</code>```

Body:
i am little confused about my code:

Here is some function from my controller:

  public void signIn(string userName, string userPass)
        {
            User user = new User();
            user.getUser(userName , userPass);

            if (user.userName != null)
            {
                Response.Redirect("/Home/Menu");
            }
            else
            {
                Response.Redirect("/Index/Index?Fail=" + "fail");
            }
        }

the " user.getUser" suppose to return a User object.. here is the code from my Model directory:

public class User
{
    public ObjectId _id { get; set; }
    public string userName { get; set; }
    public string userPass { get; set; }

    public User getUser(string name , string pass)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var db = client.GetDatabase("testdb");
        var coll = db.GetCollection<User>("user");

        List<User> list = coll.Find(x => x.userName == name && x.userPass == pass).ToList<User>();

        User uObj = new User();
        uObj = list.FirstOrDefault();

        return uObj;
    }
}

when i am debugging the code i can see the uJob object contain values. but when the function end and i return to the controller i see that the user object contain only null values, and the condition - "   if (user.userName != null)" is returning FALSE!.. instead of TRUE..

i would like to get some help. Thanks !

Body:
You have to assign it.

 user = user.getUser(userName , userPass);


答:
Because at the value of i = 0 you getting array of values of hobbey thats y its not inserting, try it with implode it generate a string of array and then insert that string to your table,</p>

```<code>    $hobbey=$_POST["hobbey"][$i];
    $hby=implode(',',$hobbey);
    $query .= "('$firstname','$lastname','$age','$hby')";
</code>```

Title: How can I insert multiple dynamically checkbox value in insert?

Body:
when i insert this form all field is inserted but the problem is multiple checkbox value is not insert?

This is my HTML Code:

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">

    <?php
        $j=3;

        for($i=0;$i< $j; $i++)
        {
            ?>
            First name :: <input name="firstname[]" type="text" value=""/>

            <input name="loop" type="hidden" value="<?php echo $j ?>"/>
            Last name :: <input name="lastname[]" type="text" value="" />

            Age :: <input name="age[]" type="text" value="" />

            <input name="hobbey[]" type="checkbox" value="Cricket" />Cricket
            <input name="hobbey[]" type="checkbox" value="Football" />Football
            <input name="hobbey[]" type="checkbox" value="Tennis" />Tennis

            <?php
        }
    ?>

    <input name="btnsubmit" type="submit" value="Submit" />
</form>

This is my PHP Code:

    $query = "insert into register (firstname,lastname,age,hobbey) values";

    for($i=0; $i<$_POST["loop"]; $i++)
    {
        $firstname=$_POST["firstname"][$i];
        $lastname=$_POST["lastname"][$i];
        $age=$_POST["age"][$i];

        $hobbey=$_POST["hobbey"][$i];

        $query .= "('$firstname','$lastname','$age','$hobbey')";
    }

Body:
Because at the value of i = 0 you getting array of values of hobbey thats y its not inserting, try it with implode it generate a string of array and then insert that string to your table,

    $hobbey=$_POST["hobbey"][$i];
    $hby=implode(',',$hobbey);
    $query .= "('$firstname','$lastname','$age','$hby')";


问:
Best practice for acceptance tests in Java
We have a program that that we would like to do acceptance tests on it.
The input is an XML file with different "tasks".
The output is another XML file with results.

What would be the best practice to automate acceptance tests for it?

We will probably have to store pairs of input and output files, run the program on the inputs and compare result to the provided outputs.

Is Ant good for this task?

Should the acceptance tests cover all corner cases, or only test that the functionality is in general working.

Any other tips regarding acceptance tests in java would be appreciated.

答: I think DDSteps will be a lot of help for this.</p>


问:
Highcharts Gauge chart is rounding down max number
The problem occurs when max is set to a very large number such as 666772. Highcharts will take the number and round it down depending on what tickPixelInterval is set to.

If I set the tickPixelInterval value closer to 0, then the max number on the Gauge chart starts getting closer to 666772, but is still rounded. I would like for the min to start at 0 (which it does), and then for the max to be the exact number (666772), or even a rounded down version (667k).

Is there a way to do this with only the min and the max showing on the Gauge chart?

```<code>   var gaugeOptions = {

    chart: {
      type: 'solidgauge'
    },

    title: null,

    pane: {
      center: ['50%', '85%'],
      size: '140%',
      startAngle: -90,
      endAngle: 90,
      background: {
        backgroundColor: '#EEE',
        innerRadius: '60%',
        outerRadius: '100%',
        shape: 'arc'
      }
    },

    // the value axis
    yAxis: {
      stops: [
        [0.1, '#DF5353'], // green
        [0.5, '#DDDF0D'], // yellow
        [0.9, 'green'] // red
      ],
      lineWidth: 0,
      minorTickInterval: null,
      tickPixelInterval: 400,
      tickWidth: 0,
      endOnTick: false,
      maxPadding: 0,
      title: {
        y: -70
      },
      labels: {
        y: 10,
        format: '{value}'
      }
    },

    credits: {
      enabled: false
    },

    tooltip: {
        enabled: false
    },

    plotOptions: {
      solidgauge: {
        dataLabels: {
          y: 5,
          borderWidth: 0,
          useHTML: true
        }
      }
    }

  };

  // Quarter1
  jQuery('#quarter1').highcharts(Highcharts.merge(gaugeOptions, {
    yAxis: {
      min: 0,
      max: 666772,
      title: {
        text: 'Quarter 1'
      }
    },

    series: [{
      name: 'Quarter 1',
      data: [50],
      dataLabels: {
        format: '<div style="text-align:center"><span style="font-size:25px;color:' +
          ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">${y}</span><br/>' +
          '<span style="font-size:12px;color:silver">Quota</span><br/><span>Bonus Elegible</span></div>'
      }
    }]

  }));
</code>```

答:
Use this code for displaying the min and max of exact amount. </p>

```<code>yAxis: {
min: 0,
max: 2602,
tickPositioner: function() {
  return [this.min, this.max];
}
</code>```

Body:
The problem occurs when max is set to a very large number such as 666772. Highcharts will take the number and round it down depending on what tickPixelInterval is set to.

If I set the tickPixelInterval value closer to 0, then the max number on the Gauge chart starts getting closer to 666772, but is still rounded. I would like for the min to start at 0 (which it does), and then for the max to be the exact number (666772), or even a rounded down version (667k).

Is there a way to do this with only the min and the max showing on the Gauge chart?

   var gaugeOptions = {

    chart: {
      type: 'solidgauge'
    },

    title: null,

    pane: {
      center: ['50%', '85%'],
      size: '140%',
      startAngle: -90,
      endAngle: 90,
      background: {
        backgroundColor: '#EEE',
        innerRadius: '60%',
        outerRadius: '100%',
        shape: 'arc'
      }
    },

    // the value axis
    yAxis: {
      stops: [
        [0.1, '#DF5353'], // green
        [0.5, '#DDDF0D'], // yellow
        [0.9, 'green'] // red
      ],
      lineWidth: 0,
      minorTickInterval: null,
      tickPixelInterval: 400,
      tickWidth: 0,
      endOnTick: false,
      maxPadding: 0,
      title: {
        y: -70
      },
      labels: {
        y: 10,
        format: '{value}'
      }
    },

    credits: {
      enabled: false
    },

    tooltip: {
        enabled: false
    },

    plotOptions: {
      solidgauge: {
        dataLabels: {
          y: 5,
          borderWidth: 0,
          useHTML: true
        }
      }
    }

  };

  // Quarter1
  jQuery('#quarter1').highcharts(Highcharts.merge(gaugeOptions, {
    yAxis: {
      min: 0,
      max: 666772,
      title: {
        text: 'Quarter 1'
      }
    },

    series: [{
      name: 'Quarter 1',
      data: [50],
      dataLabels: {
        format: '
${y}
' +
          'Quota
Bonus Elegible
'
      }
    }]

  }));

Body:
Use this code for displaying the min and max of exact amount.

yAxis: {
min: 0,
max: 2602,
tickPositioner: function() {
  return [this.min, this.max];
}