问:
How can I tell what version of Visual Studio was last used to work on a project?
I'm working with some older code, and I think the person who last built it was using Visual Studio 6. There's no .vcproj file, but the .dsp and .dsw files have the following headers:
(.dsp)

```<code># Microsoft Developer Studio Project File - Name="[redacted]" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
</code>```

(.dsw)

```<code>Microsoft Developer Studio Workspace File, Format Version 6.00
</code>```

Does the "Format Version 6.00" correspond to Visual Studio 6?

答:
When I opened the solution file of a project using a notepad, the version of visual studio was written on the top, with the Format version number, like this -

```<code>Microsoft Visual Studio Solution File, Format Version 10.00
#Visual Studio 2008
</code>```

Body:
I'm working with some older code, and I think the person who last built it was using Visual Studio 6. There's no .vcproj file, but the .dsp and .dsw files have the following headers:
(.dsp)

# Microsoft Developer Studio Project File - Name="[redacted]" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00

(.dsw)

Microsoft Developer Studio Workspace File, Format Version 6.00

Does the "Format Version 6.00" correspond to Visual Studio 6?

Body:
When I opened the solution file of a project using a notepad, the version of visual studio was written on the top, with the Format version number, like this -

Microsoft Visual Studio Solution File, Format Version 10.00
#Visual Studio 2008


来源: stackexchange

问:
*** process.env.ENV is not defined, assuming 'prod' env
I am unable to open My JHipster + Angular 2 (Gateway) Application home page with port 8080 (which is given at server port in application-dev.yml) and
Getting following exception in console

```<code>*** process.env.ENV is not defined, assuming 'prod' env
</code>```

The Same application is running fine on port 9000 (which is given by yarn) and giving exception like below in console.

```<code>process.env.ENV is not defined, assuming 'prod' env
chrome-extension://kbfnbcaeplbcioakkpcpgfkobkghlhen/src/js/bundle.js:4776 ***
</code>```

My problem is if I use 9000 port (Given by yarn) unable to communicate with other microservices applications.

Why am I getting the above exception?

答:
The above warning is not coming from your app. It is actually coming from one of the chrome extension (Grammarly for Chrome). Disabling the extension solved problem!!

check this https://github.com/facebookincubator/create-react-app/issues/2722

ContentLicense: CC BY-SA 3.0

Body:
I am unable to open My JHipster + Angular 2 (Gateway) Application home page with port 8080 (which is given at server port in application-dev.yml) and
Getting following exception in console

*** process.env.ENV is not defined, assuming 'prod' env

The Same application is running fine on port 9000 (which is given by yarn) and giving exception like below in console.

process.env.ENV is not defined, assuming 'prod' env
chrome-extension://kbfnbcaeplbcioakkpcpgfkobkghlhen/src/js/bundle.js:4776 ***

My problem is if I use 9000 port (Given by yarn) unable to communicate with other microservices applications.

Why am I getting the above exception?


问:
chain.DefaultIfException does not catch Exception and sends "Sorry, my bot code is having an issue "
I am working to create a bot with Microsoft bot framework. At this stage I am trying to avoid catching exception and “Sorry, my bot code is having an issue” if for example user clicks the button several times.  I have already looked up and found out that “chain.DefaultIfException” can be used.
I have implemented it as following:

//await Conversation.SendAsync(activity, () => dialog);

```<code>                        var dialog = scope.Resolve<IDialog<object>>(TypedParameter.From(checkOutRouteUri));

                        await Conversation.SendAsync(activity, () => dialog.DefaultIfException());
</code>```

However, it still throws Exception and the error message. Is there anything that I might be missing?

Thank you very much!

答:
to swallow the exception replace

() => dialog.DefaultIfException()

with

() => Chain.From(() =>  dialog).DefaultIfException()

Body:
I am working to create a bot with Microsoft bot framework. At this stage I am trying to avoid catching exception and “Sorry, my bot code is having an issue” if for example user clicks the button several times.  I have already looked up and found out that “chain.DefaultIfException” can be used.
I have implemented it as following:

//await Conversation.SendAsync(activity, () => dialog);

                        var dialog = scope.Resolve<IDialog<object>>(TypedParameter.From(checkOutRouteUri));

                        await Conversation.SendAsync(activity, () => dialog.DefaultIfException());

However, it still throws Exception and the error message. Is there anything that I might be missing?

Thank you very much!


问:
Resize code ruins quality?
So I'm trying to resize HUGE images, like 5500x3500 JPGs down to 1024x768 or less. The following function works, but it really runs the quality, makes the text all fuzzy.

```<code>static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    Bitmap bmp = new Bitmap(newImage);

    return bmp;
}
</code>```

Any idea of a better way to do this?

答:
As suggested in comment, you should use Interpolation mode to control image quality during scaling. To know how to use it, refer to the following doc from Microsoft,

https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-use-interpolation-mode-to-control-image-quality-during-scaling

Title: Resize code ruins quality?

Body:
So I'm trying to resize HUGE images, like 5500x3500 JPGs down to 1024x768 or less. The following function works, but it really runs the quality, makes the text all fuzzy.

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    Bitmap bmp = new Bitmap(newImage);

    return bmp;
}

Any idea of a better way to do this?


问:
if multiple threads are updating the same variable, what should be done so each thread updates the variable correctly?
If multiple threads are updating the same variable, what should I do so each thread updates the variable correctly?

Any help would be greatly appreciated

答:
You should implement locking on the variable in question.
Eg.

http://download.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

ContentLicense: CC BY-SA 2.5


问:
How to skip empty columns in csv file while loading into sql using .ctl file
My CSV file look like this

```<code>111,,Allen,2000,,30
222,,John,3000,,40
333,,Miller,4000,,50
333,,King,5000,,50
</code>```

Some times empty columns may come in different positions,
Can we suggest anything to ctl files ,such that it can skip only empty columns with comma seperated?

答:
actually, I've never it used, but it seems to me usefull:

```<code>LOAD DATA
INFILE 'name.txt'
BADFILE 'name.bad'
DISCARDFILE 'name.dsc'
APPEND
INTO TABLE emp_tab
WHEN emp_id != BLANKS
FIELDS TERMINATED BY ";"
TRAILING NULLCOLS
(emp_id, name, age)
</code>```

WHEN emp_id != BLANKS

Body:
My CSV file look like this

111,,Allen,2000,,30
222,,John,3000,,40
333,,Miller,4000,,50
333,,King,5000,,50

Some times empty columns may come in different positions,
Can we suggest anything to ctl files ,such that it can skip only empty columns with comma seperated?

Body:
actually, I've never it used, but it seems to me usefull:

LOAD DATA
INFILE 'name.txt'
BADFILE 'name.bad'
DISCARDFILE 'name.dsc'
APPEND
INTO TABLE emp_tab
WHEN emp_id != BLANKS
FIELDS TERMINATED BY ";"
TRAILING NULLCOLS
(emp_id, name, age)

WHEN emp_id != BLANKS


问:
Return value instead of a promise [to stop nested deferred promise]
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

```<code>let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }
</code>```

Child 1

```<code>$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }
</code>```

Child 2

```<code>let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}
</code>```

Level 3

```<code>checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })
</code>```

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

```<code>$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }
</code>```

答:
You can run your code as if it was synchronous using nsynjs: it will evaluate code step-by-step, and if some function returns promise, it will pause execution, wait until promise is resolved, and assigns resolve result to data property. So, code below will be paused on level 1 until promise is resolved to actual value.

var getUserPermissions = function(id) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
        resolve({
                id: id,
                isAdmin: "yes he is",
            })
        }, 1000);
    });
};

function synchronousCode() {
    console.log("start");
    var vzid = 35;
    var userInit = function() {
        return getUserPermissions(vzid).data;
    };
    var checkAuthorize = function() {
     return userInit().isAdmin;
    };
    var isAuthorized = checkAuthorize();
    console.log(isAuthorized);
};

nsynjs.run(synchronousCode, null, function(){
 console.log("finish");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script></code>```

Body:
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }

Child 1

$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }

Child 2

let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}

Level 3

checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }

Body:
You can run your code as if it was synchronous using nsynjs: it will evaluate code step-by-step, and if some function returns promise, it will pause execution, wait until promise is resolved, and assigns resolve result to data property. So, code below will be paused on level 1 until promise is resolved to actual value.

var getUserPermissions = function(id) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
        resolve({
                id: id,
                isAdmin: "yes he is",
            })
        }, 1000);
    });
};

function synchronousCode() {
    console.log("start");
    var vzid = 35;
    var userInit = function() {
        return getUserPermissions(vzid).data;
    };
    var checkAuthorize = function() {
     return userInit().isAdmin;
    };
    var isAuthorized = checkAuthorize();
    console.log(isAuthorized);
};

nsynjs.run(synchronousCode, null, function(){
 console.log("finish");
});

<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>


问:
trying to declare a variable local to a function, but get scope error
Here's a small snippet of my code. The purpose of the snippet you see here is twofold 1)present a menu -- that's the menu() function, and 2) prompt the user to make a selection and store it -- selection().

selection() starts on line 18.

I'm trying to declare some variables that will be local to my menu() and selection() functions, but I get errors like this, for everything I try to declare:

warning: unused variable 's'   (it gave this for all my 'char' variables)
or
error: 'snack_selection' was not declared in this scope (it gave this for the two 'int' variables I tried to declare)

but how can that be? I don't know what I'm missing.

patient feedback is appreciated.

```<code>int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
         << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
         << endl  //prompts user to make a selection (until it is valid)
         << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
         << endl
         << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95"
         << endl
         << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50"
         << endl
         << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75"
         << endl
         << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40"
         << endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{

    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch(std::toupper(snack_selection))
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}
</code>```

full code here with superficial info removed:

```<code>#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations:

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
        << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
        << endl  //prompts user to make a selection (until it is valid)
        << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
        << endl
        << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
        endl
        << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
        endl
        << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
        endl
        << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
        endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{
    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch ( std::toupper(snack_selection) )
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement
    char n, q, d; //the char variables needed for the money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    char y;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}
</code>```

答:
The code compiles fine but contains warnings of unused variables. In 3 places you declare char variables which are unused. Removing these declarations gets rid of the warnings. Here I've posted the modified code.

```<code>#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations:

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
        << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
        << endl  //prompts user to make a selection (until it is valid)
        << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
        << endl
        << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
        endl
        << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
        endl
        << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
        endl
        << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
        endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{
    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch ( std::toupper(snack_selection) )
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}
</code>```

Body:
Here's a small snippet of my code. The purpose of the snippet you see here is twofold 1)present a menu -- that's the menu() function, and 2) prompt the user to make a selection and store it -- selection().

selection() starts on line 18.

I'm trying to declare some variables that will be local to my menu() and selection() functions, but I get errors like this, for everything I try to declare:

warning: unused variable 's'   (it gave this for all my 'char' variables)
or
error: 'snack_selection' was not declared in this scope (it gave this for the two 'int' variables I tried to declare)

but how can that be? I don't know what I'm missing.

patient feedback is appreciated.

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
         << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
         << endl  //prompts user to make a selection (until it is valid)
         << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
         << endl
         << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95"
         << endl
         << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50"
         << endl
         << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75"
         << endl
         << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40"
         << endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{

    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch(std::toupper(snack_selection))
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

full code here with superficial info removed:

#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations:

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
        << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
        << endl  //prompts user to make a selection (until it is valid)
        << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
        << endl
        << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
        endl
        << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
        endl
        << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
        endl
        << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
        endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{
    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement
    char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch ( std::toupper(snack_selection) )
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement
    char n, q, d; //the char variables needed for the money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    char y;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

Body:
The code compiles fine but contains warnings of unused variables. In 3 places you declare char variables which are unused. Removing these declarations gets rid of the warnings. Here I've posted the modified code.

#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations:

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

int menu(void)
{
    cout << "Available snacks to select from: " << endl  //presents menu
        << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25"
        << endl  //prompts user to make a selection (until it is valid)
        << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35"
        << endl
        << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" <<
        endl
        << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" <<
        endl
        << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" <<
        endl
        << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" <<
        endl;
    selection();
    return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{
    int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
    char snack_selection = 0; //condition for snack_selection switch case statement

    cout << "Please enter the letter labeling your snack selection: ";
    cin >> snack_selection;
    cout << endl;

    switch ( std::toupper(snack_selection) )
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
        cout << "Invalid selection!";
        menu();
    } //end of switch statement
    return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}


问:
MafftCommandline and io.StringIO
I've been trying to use the Mafft alignment tool from Bio.Align.Applications. Currently, I've had success writing my sequence information out to temporary text files that are then read by MafftCommandline(). However, I'd like to avoid redundant steps as much as possible, so I've been trying to write to a memory file instead using io.StringIO(). This is where I've been having problems. I can't get MafftCommandline() to read internal files made by io.StringIO(). I've confirmed that the internal files are compatible with functions such as AlignIO.read(). The following is my test code:

```<code>from Bio.Align.Applications import MafftCommandline
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import io
from Bio import AlignIO

sequences1 = ["AGGGGC",
             "AGGGC",
             "AGGGGGC",
             "AGGAGC",
             "AGGGGG"]

longest_length = max(len(s) for s in sequences1)
padded_sequences = [s.ljust(longest_length, '-') for s in sequences1] #padded sequences used to test compatibilty with AlignIO

ioSeq = ''
for items in padded_sequences:
    ioSeq += '>unknown\n'
    ioSeq += items + '\n'

newC = io.StringIO(ioSeq)
cLoc = str(newC).strip()
cLocEdit = cLoc[:len(cLoc)] #create string to remove < and >

test1Handle = AlignIO.read(newC, "fasta")
#test1HandleString = AlignIO.read(cLocEdit, "fasta") #fails to interpret cLocEdit string

records = (SeqRecord(Seq(s)) for s in padded_sequences)

SeqIO.write(records, "msa_example.fasta", "fasta")

test1Handle1 = AlignIO.read("msa_example.fasta", "fasta") #alignIO same for both #demonstrates working AlignIO

in_file = '.../msa_example.fasta'
mafft_exe = '/usr/local/bin/mafft'

mafft_cline = MafftCommandline(mafft_exe, input=in_file) #have to change file path
mafft_cline1 = MafftCommandline(mafft_exe, input=cLocEdit) #fails to read string (same as AlignIO)
mafft_cline2 = MafftCommandline(mafft_exe, input=newC)

stdout, stderr = mafft_cline()
print(stdout) #corresponds to MafftCommandline with input file
stdout1, stderr1 = mafft_cline1()
print(stdout1) #corresponds to MafftCommandline with internal file
</code>```

I get the following error messages:

ApplicationError: Non-zero return code 2 from '/usr/local/bin/mafft <_io.StringIO object at 0x10f439798>', message "/bin/sh: -c: line 0: syntax error near unexpected token `newline'"
I believe this results due to the arrows ('<' and '>') present in the file path.

ApplicationError: Non-zero return code 1 from '/usr/local/bin/mafft "_io.StringIO object at 0x10f439af8"', message '/usr/local/bin/mafft: Cannot open _io.StringIO object at 0x10f439af8.'
Attempting to remove the arrows by converting the file path to a string and indexing resulted in the above error.

Ultimately my goal is to reduce computation time. I hope to accomplish this by calling internal memory instead of writing out to a separate text file. Any advice or feedback regarding my goal is much appreciated. Thanks in advance.

答:
I can't get MafftCommandline() to read internal files made by
  io.StringIO().

This is not surprising for a couple of reasons:

As you're aware, Biopython doesn't implement Mafft, it simply
provides a convenient interface to setup a call to mafft in
/usr/local/bin.  The mafft executable runs as a separate process
that does not have access to your Python program's internal memory,
including your StringIO file.

The mafft program only works with an input file, it doesn't even
allow stdin as a data source.  (Though it does allow stdout as a
data sink.)  So ultimately, there must be a file in the file system
for mafft to open.  Thus the need for your temporary file.

Perhaps tempfile.NamedTemporaryFile() or tempfile.mkstemp() might be a reasonable compromise.

Title: MafftCommandline and io.StringIO

Body:
I've been trying to use the Mafft alignment tool from Bio.Align.Applications. Currently, I've had success writing my sequence information out to temporary text files that are then read by MafftCommandline(). However, I'd like to avoid redundant steps as much as possible, so I've been trying to write to a memory file instead using io.StringIO(). This is where I've been having problems. I can't get MafftCommandline() to read internal files made by io.StringIO(). I've confirmed that the internal files are compatible with functions such as AlignIO.read(). The following is my test code:

from Bio.Align.Applications import MafftCommandline
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import io
from Bio import AlignIO

sequences1 = ["AGGGGC",
             "AGGGC",
             "AGGGGGC",
             "AGGAGC",
             "AGGGGG"]

longest_length = max(len(s) for s in sequences1)
padded_sequences = [s.ljust(longest_length, '-') for s in sequences1] #padded sequences used to test compatibilty with AlignIO

ioSeq = ''
for items in padded_sequences:
    ioSeq += '>unknown\n'
    ioSeq += items + '\n'

newC = io.StringIO(ioSeq)
cLoc = str(newC).strip()
cLocEdit = cLoc[:len(cLoc)] #create string to remove < and >

test1Handle = AlignIO.read(newC, "fasta")
#test1HandleString = AlignIO.read(cLocEdit, "fasta") #fails to interpret cLocEdit string

records = (SeqRecord(Seq(s)) for s in padded_sequences)

SeqIO.write(records, "msa_example.fasta", "fasta")

test1Handle1 = AlignIO.read("msa_example.fasta", "fasta") #alignIO same for both #demonstrates working AlignIO

in_file = '.../msa_example.fasta'
mafft_exe = '/usr/local/bin/mafft'

mafft_cline = MafftCommandline(mafft_exe, input=in_file) #have to change file path
mafft_cline1 = MafftCommandline(mafft_exe, input=cLocEdit) #fails to read string (same as AlignIO)
mafft_cline2 = MafftCommandline(mafft_exe, input=newC)

stdout, stderr = mafft_cline()
print(stdout) #corresponds to MafftCommandline with input file
stdout1, stderr1 = mafft_cline1()
print(stdout1) #corresponds to MafftCommandline with internal file

I get the following error messages:

ApplicationError: Non-zero return code 2 from '/usr/local/bin/mafft <_io.StringIO object at 0x10f439798>', message "/bin/sh: -c: line 0: syntax error near unexpected token `newline'"
I believe this results due to the arrows ('<' and '>') present in the file path.

ApplicationError: Non-zero return code 1 from '/usr/local/bin/mafft "_io.StringIO object at 0x10f439af8"', message '/usr/local/bin/mafft: Cannot open _io.StringIO object at 0x10f439af8.'
Attempting to remove the arrows by converting the file path to a string and indexing resulted in the above error.

Ultimately my goal is to reduce computation time. I hope to accomplish this by calling internal memory instead of writing out to a separate text file. Any advice or feedback regarding my goal is much appreciated. Thanks in advance.


问:
Ndb strong consistency and frequent writes
I'm trying to achieve strong consistency with ndb using python.
And looks like I'm missing something as my reads behave like they're not strongly consistent.

The query is:

```<code>links = Link.query(ancestor=lead_key).filter(Link.last_status ==
None).fetch(keys_only=True)

if links:
    do_action()
</code>```

The key structure is:

```<code>Lead root (generic key) -> Lead -> Website (one per lead) -> Link
</code>```

I have many tasks that are executed concurrently using TaskQueue and this query is performed at the end of every task. Sometimes I'm getting "too much contention" exception when updating the last_status field but I deal with it using retries. Can it break strong consistency?

The expected behavior is having do_action() called when there are no links left with last_status equal to None. The actual behavior is inconsistent: sometimes do_action() is called twice and sometimes not called at all.

答:
There is nothing in your sample that ensures that your code is only called once.

For the moment, I am going to assume that your "do_action" function does something to the Link entities, specifically that it sets the "last_status" property.

If you do not perform the query and the write to the Link Entity inside a transaction, then it is possible for two different requests (task queue tasks) to get results back from the query, then both write their new value to the Link entity (with the last write overwriting the previous value).

Remember that even if you do use a transaction, you don't know until the transaction is successfully completed that nobody else tried to perform a write. This is important if you are trying to do something external to datastore (for example, making a http request to an external system), as you may see http requests from transactions that would eventually fail with a concurrent modification exception.

Body:
I'm trying to achieve strong consistency with ndb using python.
And looks like I'm missing something as my reads behave like they're not strongly consistent.

The query is:

links = Link.query(ancestor=lead_key).filter(Link.last_status ==
None).fetch(keys_only=True)

if links:
    do_action()

The key structure is:

Lead root (generic key) -> Lead -> Website (one per lead) -> Link

I have many tasks that are executed concurrently using TaskQueue and this query is performed at the end of every task. Sometimes I'm getting "too much contention" exception when updating the last_status field but I deal with it using retries. Can it break strong consistency?

The expected behavior is having do_action() called when there are no links left with last_status equal to None. The actual behavior is inconsistent: sometimes do_action() is called twice and sometimes not called at all.


问:
Background on the bar not getting removed from Highcharts
I am using highcharts to generate the bar graph. When I hover over the bars a blue background is coming. So, to disable the hover I added the below code snippet,

```<code>series: {
                states: {
                    hover: {
                        enabled: false
                    }
                }
            }
}
</code>```

But, after that also the blue background is not getting removed on hover. I have added jsfiddle
jsfiddle

答:
It looks that your issue is caused by crosshair on xAxis with categories.

It should be possible to disable crosshair feature by setting xAxis.crosshair to false:

```<code>xAxis: {
crosshair: false,
    categories: [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'Jul',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec'
    ],
},
</code>```

http://api.highcharts.com/highcharts/xAxis.crosshair

Live example: http://jsfiddle.net/3q6xxhkm/2/

Body:
I am using highcharts to generate the bar graph. When I hover over the bars a blue background is coming. So, to disable the hover I added the below code snippet,

series: {
                states: {
                    hover: {
                        enabled: false
                    }
                }
            }
}

But, after that also the blue background is not getting removed on hover. I have added jsfiddle
jsfiddle

Body:
It looks that your issue is caused by crosshair on xAxis with categories.

It should be possible to disable crosshair feature by setting xAxis.crosshair to false:

xAxis: {
crosshair: false,
    categories: [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'Jul',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec'
    ],
},

http://api.highcharts.com/highcharts/xAxis.crosshair

Live example: http://jsfiddle.net/3q6xxhkm/2/


问:
How to convert and over write MongoDB date string into ISODate using Python PyMongo?
I'm trying to convert a number of document strings in the format "YYYY-MM-DD" into ISODates in MongoDB and have successfully written this for the console which has the desired effect:

```<code>db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})
</code>```

I'm trying to do the same in Python something like this:

```<code>client = MongoClient(my_mongodb_ip)
db = client.address
result = db.address.find( { "date" : { "$type" : 2 } } );
for r in result:
    print(r['date'])
    r["date"] = datetime.strptime(r["date"], "%Y-%m-%d")
    print(r['date'])
    db.address.update_one({"company": r['company']},
         {"$set": {"date" : r['date']}})
</code>```

Which I'd like to deliver this:

```<code>"date": {
  "$date": "2017-06-28T00:00:00.000Z"
},
</code>```

I don't get any updates to the DB.

答:
You can achieve this goal using the arrow module in python. All You need to do is, just create a small function that can take your date as parameter and convert it into the ISO format.

This is how you can do it:

```<code>import arrow

def convert_to_ISO_Format(self, value):
    date                          = arrow.get(value)
    date                          = date.format("YYYY-MM-DDTHH:mm:ss")
    date                          = date  + "Z"
    self.converted_date_iso = date
</code>```

Or If you know the region of the state and you want to convert it accordingly then you can do like this;

```<code>    def convert_to_ISO_Region(self,value):
        date                      = arrow.get(value)
        date                      = date.to("Asia/Singapore")
        date                      = date.format("YYYY-MM-DD HH:mm:ss")
        date                      = date  + "Z"
        self.converted_date_iso = date

                 OR
</code>```

If you want to convert the present date and time into ISO, it's pretty simple like the below one statement.

```<code>arrow.utcnow().datetime
</code>```

I hope this can be helpful to your problem.

Body:
I'm trying to convert a number of document strings in the format "YYYY-MM-DD" into ISODates in MongoDB and have successfully written this for the console which has the desired effect:

db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})

I'm trying to do the same in Python something like this:

client = MongoClient(my_mongodb_ip)
db = client.address
result = db.address.find( { "date" : { "$type" : 2 } } );
for r in result:
    print(r['date'])
    r["date"] = datetime.strptime(r["date"], "%Y-%m-%d")
    print(r['date'])
    db.address.update_one({"company": r['company']},
         {"$set": {"date" : r['date']}})

Which I'd like to deliver this:

"date": {
  "$date": "2017-06-28T00:00:00.000Z"
},

I don't get any updates to the DB.

Body:
You can achieve this goal using the arrow module in python. All You need to do is, just create a small function that can take your date as parameter and convert it into the ISO format.

This is how you can do it:

import arrow

def convert_to_ISO_Format(self, value):
    date                          = arrow.get(value)
    date                          = date.format("YYYY-MM-DDTHH:mm:ss")
    date                          = date  + "Z"
    self.converted_date_iso = date

Or If you know the region of the state and you want to convert it accordingly then you can do like this;

    def convert_to_ISO_Region(self,value):
        date                      = arrow.get(value)
        date                      = date.to("Asia/Singapore")
        date                      = date.format("YYYY-MM-DD HH:mm:ss")
        date                      = date  + "Z"
        self.converted_date_iso = date

                 OR

If you want to convert the present date and time into ISO, it's pretty simple like the below one statement.

arrow.utcnow().datetime

I hope this can be helpful to your problem.


问:
CSS Help to see stars
I have looked around and have been unable to write a CSS code that is based on a 5 star rating system that will change based upon customer feedback. Any help is appreciated.</p>

答:
You could try a positioned sprite-sheet:

HTML:

```<code><div class="rating one-star"></div>
</code>```

CSS:

```<code>.rating
{
  background-image: url(stars.png);
  background-repeat: no-repeat;
  height: 20px;
  width: 100px;
}

/* assume a star is 20x20 */

.one-star
{
  background-position: -80px 0;
}
.two-star
{
  background-position: -60px 0;
}
.three-star
{
  background-position: -40px 0;
}
.four-star
{
  background-position: -20px 0;
}
.five-star
{
  background-position: 0 0;
}
</code>```

Of course you may want the div to contain 5 links with star outlines, hover effects, or other such things.  It really depends on what you're looking for.

Title: CSS Help to see stars

Body:
You could try a positioned sprite-sheet:

HTML:

<div class="rating one-star"></div>

CSS:

.rating
{
  background-image: url(stars.png);
  background-repeat: no-repeat;
  height: 20px;
  width: 100px;
}

/* assume a star is 20x20 */

.one-star
{
  background-position: -80px 0;
}
.two-star
{
  background-position: -60px 0;
}
.three-star
{
  background-position: -40px 0;
}
.four-star
{
  background-position: -20px 0;
}
.five-star
{
  background-position: 0 0;
}

Of course you may want the div to contain 5 links with star outlines, hover effects, or other such things.  It really depends on what you're looking for.


问:
Change value in NSDictionary
I have data that comes from server and i save it in NSMutableDic but when i change value in that NSMutabelDic it gives me error that i can't change in NSDic!
This is error :

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x7ae250c0'
</code>```

This is my sample server data :

```<code>{
    "data": {
        "My_Tool_Box": {
            "Visual Check": [
                {
                    "que_cat_id": "1",
                    "question_id": "1",
                    "question_name": "Power leads",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "2",
                    "question_name": "Power",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "3",
                    "question_name": "Rcd is operational",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "4",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "5",
                    "question_name": "Safety guards if fitted  to machine ARE OPERATIONAL AND ARE NOT DAMAGED",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "6",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "7",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operational checks": [
                {
                    "que_cat_id": "2",
                    "question_id": "8",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "9",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "10",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operating instructions": [
                {
                    "que_cat_id": "3",
                    "question_id": "11",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ]
        }
    },
    "status": "success",
    "message": "Question Listing"
}
</code>```

So i have to change value of question_ans & question_ans_comments so as when i change it i get error as i mention above.
This is the way i already applied:

```<code>NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];
</code>```

i don't have index in sequence like how i replace that key object!! Is there any easy way that i can apply here ?

This is the way i reset value :

```<code>[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] setObject:@"12" forKey:@"question_ans"];
</code>```

I also tried this :

```<code>    NSDictionary *oldDict = (NSDictionary *)[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
    [newDict setObject:@"12" forKey:@"question_ans"];
    [[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0] mutableCopy] replaceObjectAtIndex:0 withObject:newDict];
</code>```

Giving same error.

答:
try using this method

```<code>+ (instancetype)dictionaryWithDictionary:(NSDictionary<KeyType, ObjectType> *)dict;
</code>```

for example

```<code>NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
</code>```

Edit:
Do something like this

```<code>NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];
</code>```

Title: Change value in NSDictionary

Body:
I have data that comes from server and i save it in NSMutableDic but when i change value in that NSMutabelDic it gives me error that i can't change in NSDic!
This is error :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x7ae250c0'

This is my sample server data :

{
    "data": {
        "My_Tool_Box": {
            "Visual Check": [
                {
                    "que_cat_id": "1",
                    "question_id": "1",
                    "question_name": "Power leads",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "2",
                    "question_name": "Power",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "3",
                    "question_name": "Rcd is operational",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "4",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "5",
                    "question_name": "Safety guards if fitted  to machine ARE OPERATIONAL AND ARE NOT DAMAGED",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "6",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "7",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operational checks": [
                {
                    "que_cat_id": "2",
                    "question_id": "8",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "9",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "10",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operating instructions": [
                {
                    "que_cat_id": "3",
                    "question_id": "11",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ]
        }
    },
    "status": "success",
    "message": "Question Listing"
}

So i have to change value of question_ans & question_ans_comments so as when i change it i get error as i mention above.
This is the way i already applied:

NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];

i don't have index in sequence like how i replace that key object!! Is there any easy way that i can apply here ?

This is the way i reset value :

[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] setObject:@"12" forKey:@"question_ans"];

I also tried this :

    NSDictionary *oldDict = (NSDictionary *)[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
    [newDict setObject:@"12" forKey:@"question_ans"];
    [[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0] mutableCopy] replaceObjectAtIndex:0 withObject:newDict];

Giving same error.

Body:
try using this method

+ (instancetype)dictionaryWithDictionary:(NSDictionary<KeyType, ObjectType> *)dict;

for example

NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];

Edit:
Do something like this

NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];


问:
Editing excel file using vbscript but the edits are taking too long to complete
/* The reason why I am using vb scrips to edit the excel file is: the excel file will be different all the time but the format will be the same and the user does not want to save VBA macro on their workbook.

I am getting values from Column 3 and adding those values to Column 9 at the end of it.

*/

```<code>Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.Workbooks.Open("filepath", 0, true)
xlApp.visible=true

Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet")
row=xlSheet.UsedRange.Rows.Count
col=xlSheet.UsedRange.Columns.Count

dim i

For i=15 to xlSheet.UsedRange.Rows.Count
cell=xlSheet.Cells(i,3).Value
celli=xlSheet.Cells(i,9).Value+"("+cell+")" //I am combining column 3 with column 9

xlSheet.Cells(i,9).Value=celli

Next

xlBook.Save
xlApp.Run "Submit_To_iDesk"
xlBook.Close

xlApp.Quit
Set xlApp=Nothing
Set xlBook=Nothing
WScript.Quit
</code>```

答:
If UsedRange is not returning a useful number, use one of the more reliable ways of finding the last used cell in a column:

```<code>Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.Workbooks.Open("filepath", 0, true)
xlApp.visible=true

Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet")
row=xlSheet.Cells(xlSheet.Rows.Count, 9).End(-4162).Row ' -4162 is equivalent of "xlUp"

dim i

For i=15 to row
    cell=xlSheet.Cells(i,3).Value
    celli=xlSheet.Cells(i,9).Value

    xlSheet.Cells(i,9).Value=celli & "(" & cell & ")"
Next

xlBook.Save
xlApp.Run "Submit_To_iDesk"
xlBook.Close

xlApp.Quit
Set xlApp=Nothing
Set xlBook=Nothing
WScript.Quit
</code>```

Body:
/* The reason why I am using vb scrips to edit the excel file is: the excel file will be different all the time but the format will be the same and the user does not want to save VBA macro on their workbook.

I am getting values from Column 3 and adding those values to Column 9 at the end of it.

*/

Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.Workbooks.Open("filepath", 0, true)
xlApp.visible=true

Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet")
row=xlSheet.UsedRange.Rows.Count
col=xlSheet.UsedRange.Columns.Count

dim i

For i=15 to xlSheet.UsedRange.Rows.Count
cell=xlSheet.Cells(i,3).Value
celli=xlSheet.Cells(i,9).Value+"("+cell+")" //I am combining column 3 with column 9

xlSheet.Cells(i,9).Value=celli

Next

xlBook.Save
xlApp.Run "Submit_To_iDesk"
xlBook.Close

xlApp.Quit
Set xlApp=Nothing
Set xlBook=Nothing
WScript.Quit

Body:
If UsedRange is not returning a useful number, use one of the more reliable ways of finding the last used cell in a column:

Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.Workbooks.Open("filepath", 0, true)
xlApp.visible=true

Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet")
row=xlSheet.Cells(xlSheet.Rows.Count, 9).End(-4162).Row ' -4162 is equivalent of "xlUp"

dim i

For i=15 to row
    cell=xlSheet.Cells(i,3).Value
    celli=xlSheet.Cells(i,9).Value

    xlSheet.Cells(i,9).Value=celli & "(" & cell & ")"
Next

xlBook.Save
xlApp.Run "Submit_To_iDesk"
xlBook.Close

xlApp.Quit
Set xlApp=Nothing
Set xlBook=Nothing
WScript.Quit


问:
Form not validating on usage of [ngClass] in angular 2
I am trying to put validation for empty field as below. But the form is not validating. On adding 3 rows each having 2 columns, error message is only displayed only for first row. Table tag is under form tag. On submit form will go to fetchingFLights method.</p>

```<code><div class="content">
        <form class="form" (ngSubmit)="f.form.valid && fetchingFlights()" #f="ngForm" novalidate>

            <table>
                <tr>
                    <th>
                        <label>Flight Carrier: </label>
                    </th>
                    <td>
                        <div [ngClass]="{ 'has-error': f.submitted && !flightCarrier.valid }"></div>
                        <input type="text" name="flightCarrier" placeholder="Enter Flight Carrier Code" class="textbox" [(ngModel)]="flightInfo.flightCarrierCode" #flightCarrier="ngModel" required>
                        <div class="validation" *ngIf="f.submitted && !flightCarrier.valid" >Carrier code is required</div>
                    </td>

                    <th>
                        <label>Flight Number: </label>
                    </th>
                    <td>
                        <div [ngClass]="{ 'has-error': f.submitted && !flightNumber.valid }"></div>
                        <input type="text" name="flightNumber" placeholder="Enter Flight Number" class="textbox" [(ngModel)]="flightInfo.flightNumber" #flightNumber="ngModel" required >
                        <div class="validation" *ngIf="f.submitted && !flightNumber.valid" >Flight Number is required</div>
                    </td>
                </tr>

                <tr>
                    <th>
                        <label>From Date: </label>
                    </th>
                    <td>

                        <div [ngClass]="{ 'has-error': f.submitted && !fromDate.valid }"></div>
                        <input type="date" name="fromDate"  class="textbox" [(ngModel)]="flightInfo.fromDate" #fromDate="ngModel">
                        <div class="validation" *ngIf="f.submitted && !toDate.valid" >From Date is required</div>
                    </td>

                    <th>
                        <label>To Date: </label>
                    </th>
                    <td>
                        <div [ngClass]="{ 'has-error': f.submitted && !toDate.valid }"></div>
                        <input type="date" name="toDate" class="textbox" [(ngModel)]="flightInfo.toDate" #toDate="ngModel">
                        <div class="validation" *ngIf="f.submitted && !toDate.valid" >To Date is required</div>
                    </td>
                </tr>

                <tr>
                    <th>
                        <label>Board Point: </label>
                    </th>
                    <td>
                        <div [ngClass]="{ 'has-error': f.submitted && !boardPoint.valid }"></div>
                        <input type="text" name="boardPoint" placeholder="Enter Board Point" class="textbox" [(ngModel)]="flightInfo.boardPoint" #boardPoint="ngModel">
                        <div [ngClass]="{ 'has-error': f.submitted && !boardPoint.valid }"></div>
                    </td>

                    <th>
                        <label>Off Point: </label>
                    </th>
                    <td>
                        <div [ngClass]="{ 'has-error': f.submitted && !offPoint.valid }"></div>
                        <input type="text" name="offPoint" placeholder="Enter Off Point" class="textbox" [(ngModel)]="flightInfo.offPoint" #offPoint="ngModel">
                        <div [ngClass]="{ 'has-error': f.submitted && !offPoint.valid }"></div>
                    </td>
                </tr>

            </table>

            <div><button type="submit" value="Go">Go</button></div>
            <div><input type="reset" value="reset"></div>

        </form>
    </div>
</code>```

答:
```<code><form class="form" (ngSubmit)="f.form.valid && fetchingFlights()" #f="ngForm" novalidate>
<table>
 <tr>
    <th><label>Flight Carrier: </label></th>
        <td>
            <div  [ngClass]="{ 'has-error': f.submitted && !flightInfo.flightCarrierCode.valid }"></div>
            <input type="text" name="flightCarrier" placeholder="Enter Flight Carrier Code" class="textbox" [(ngModel)]="flightInfo.flightCarrierCode" #flightCarrier="ngModel" required>
            <div class="validation" *ngIf="f.submitted && !flightInfo.flightCarrierCode.valid" >Carrier code is required</div>
        </td>
</tr>
</table>

<div><button type="submit" value="Go">Go</button></div>
</code>```

Body:
I am trying to put validation for empty field as below. But the form is not validating. On adding 3 rows each having 2 columns, error message is only displayed only for first row. Table tag is under form tag. On submit form will go to fetchingFLights method.

        <form class="form" (ngSubmit)="f.form.valid && fetchingFlights()" #f="ngForm" novalidate>

                        Flight Carrier:

                        <input type="text" name="flightCarrier" placeholder="Enter Flight Carrier Code" class="textbox" [(ngModel)]="flightInfo.flightCarrierCode" #flightCarrier="ngModel" required>

Carrier code is required

                        Flight Number:

                        <input type="text" name="flightNumber" placeholder="Enter Flight Number" class="textbox" [(ngModel)]="flightInfo.flightNumber" #flightNumber="ngModel" required >

Flight Number is required

                        From Date:

                        <input type="date" name="fromDate"  class="textbox" [(ngModel)]="flightInfo.fromDate" #fromDate="ngModel">

From Date is required

                        To Date:

                        <input type="date" name="toDate" class="textbox" [(ngModel)]="flightInfo.toDate" #toDate="ngModel">

To Date is required

                        Board Point:

                        <input type="text" name="boardPoint" placeholder="Enter Board Point" class="textbox" [(ngModel)]="flightInfo.boardPoint" #boardPoint="ngModel">

                        Off Point:

                        <input type="text" name="offPoint" placeholder="Enter Off Point" class="textbox" [(ngModel)]="flightInfo.offPoint" #offPoint="ngModel">

<button type="submit" value="Go">Go</button>

<input type="reset" value="reset">

        </form>


问:
Javascript - returning concatenates instead of sum of variables from input
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

```<code><input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
</code>```

JavaScript

```<code>var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});
</code>```

JSFiddle Demo

答:
Try with parseFloat() on input value

```<code>parseFloat($(this).val()));
</code>```

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = (totalvalue + parseFloat($(this).val()));
    });
    $("#totalvalue").val(totalvalue);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue></code>```

Body:
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>

JavaScript

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});

JSFiddle Demo

Body:
Try with parseFloat() on input value

parseFloat($(this).val()));

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = (totalvalue + parseFloat($(this).val()));
    });
    $("#totalvalue").val(totalvalue);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>


问:
Jenkins "Error cloning remote repo 'origin'" and "Cannot allocate memory"
I have Jenkins running on my server connected with GitHub via webhooks. Unfortunately my builds are failing OCCASIONALLY and I can't figure out why. Sometimes restarting Jenkins (sudo service jenkins restart) solves the problem, sometimes it doesn't. The server is running Ubuntu 16.04 nad Nginx as a proxy. What causes this issue and how can I solve it?

```<code>Started by GitHub push by gaboratorium
Building in workspace /var/lib/jenkins/workspace/kudos.gaboratorium.com
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Done
Cloning the remote Git repository
Cloning repository https://github.com/gaboratorium/kudos.git
> git init /var/lib/jenkins/workspace/kudos.gaboratorium.com # timeout=10
Fetching upstream changes from https://github.com/gaboratorium/kudos.git
> git --version # timeout=10
> git fetch --tags --progress https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Command "git fetch --tags --progress
https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout:
stderr: error: cannot fork() for fetch-pack: Cannot allocate memory

at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1903)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1622)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:348)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:545)
at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1070)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1110)
at hudson.scm.SCM.checkout(SCM.java:495)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1276)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:560)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:485)
at hudson.model.Run.execute(Run.java:1735)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:405)
ERROR: Error cloning remote repo 'origin'
Finished: FAILURE
</code>```

答:
Turned out, it was an OOM (out-of-memory) problem, which could be easy solved by creating some swap space. To do that, I have followed this guide, which solved my issue perfectly: https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04

Also, I have made some notes about the setup myself as well. If you are having issues you might find it helpful: https://archives.gaboratorium.hu/continuous-integration-with-jenkins

Body:
I have Jenkins running on my server connected with GitHub via webhooks. Unfortunately my builds are failing OCCASIONALLY and I can't figure out why. Sometimes restarting Jenkins (sudo service jenkins restart) solves the problem, sometimes it doesn't. The server is running Ubuntu 16.04 nad Nginx as a proxy. What causes this issue and how can I solve it?

Started by GitHub push by gaboratorium
Building in workspace /var/lib/jenkins/workspace/kudos.gaboratorium.com
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Done
Cloning the remote Git repository
Cloning repository https://github.com/gaboratorium/kudos.git
> git init /var/lib/jenkins/workspace/kudos.gaboratorium.com # timeout=10
Fetching upstream changes from https://github.com/gaboratorium/kudos.git
> git --version # timeout=10
> git fetch --tags --progress https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Command "git fetch --tags --progress
https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout:
stderr: error: cannot fork() for fetch-pack: Cannot allocate memory

at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1903)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1622)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:348)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:545)
at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1070)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1110)
at hudson.scm.SCM.checkout(SCM.java:495)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1276)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:560)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:485)
at hudson.model.Run.execute(Run.java:1735)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:405)
ERROR: Error cloning remote repo 'origin'
Finished: FAILURE

ContentLicense: CC BY-SA 4.0


问:
Remove child image from RelativeLayout
I have a set of images in a RelativeLayout, and I'd like to programmatically remove some of them. Is there some kind of metadata property (ie ID, tag etc) that I can assign these images (when adding them to the layout), so that I can easily find and them remove them?

Scenario: As a learning tool I am making a tower defence game. As a unit is killed, I want to remove its image. There are ~20 other units/images in the layout at the time.

thanks

答:
As i faced the same situation in one of project..

I stored all images in one array and assign tag to all imageview and then when to remove the imageview.first of all remove it from array and again load whole your array again to remove all views from that layout..

Hope you  may get help from this.

Title: Remove child image from RelativeLayout


答:
What you're parsing line is saying is

Add the totalValue to the string from the input, then parse the result.

Which is why it's concatenating. Instead, you need to add the totalValue outside of the parseInt() so that it's saying

Take the take the totalValue and add the parsed input value to it.

Like this

```<code>totalvalue = totalvalue + parseInt($(this).val());
</code>```

This can be further shortened to

```<code>totalvalue += parseInt($(this).val());
</code>```

Title: Javascript - returning concatenates instead of sum of variables from input

Body:
What you're parsing line is saying is

Add the totalValue to the string from the input, then parse the result.

Which is why it's concatenating. Instead, you need to add the totalValue outside of the parseInt() so that it's saying

Take the take the totalValue and add the parsed input value to it.

Like this

totalvalue = totalvalue + parseInt($(this).val());

This can be further shortened to

totalvalue += parseInt($(this).val());


问:
Send Emails From AppEngine Locally
The subject of the post says it all: I want to be able to send emails from AppEngine when it is running locally. As far as I understood from this post:

to send emails from Google appengine

I have to setup a mail server. Can anyone tells me some easy steps to install a mail server locally and use it with Google AppEngine?

答:
OK, I found a good solution for this question. Basically, just install sendmail tool, then use the option --enabled_sendmail when calling dev_appserver.py. So here is what I did (I use Ubuntu):

```<code>sudo apt-get install sendmail
</code>```

Then whenever I call dev_appserver.py, I call it like this:

```<code>~/google_appengine/dev_appserver.py --enable_sendmail --port=8081 ./appengine/
</code>```

Notice the --enable_sendmail option.

I believe there can't be an easier solution than this :-)

Title: Send Emails From AppEngine Locally

Body:
OK, I found a good solution for this question. Basically, just install sendmail tool, then use the option --enabled_sendmail when calling dev_appserver.py. So here is what I did (I use Ubuntu):

sudo apt-get install sendmail

Then whenever I call dev_appserver.py, I call it like this:

~/google_appengine/dev_appserver.py --enable_sendmail --port=8081 ./appengine/

Notice the --enable_sendmail option.

I believe there can't be an easier solution than this :-)