问:
error on sequelize raw query: query is not a function
I'm trying to use raw queries from sequelize in an express app.
My folder structure is:

```<code>/
/index.js
/models/index.js
/models/price.js
/controllers/price.js
</code>```

I want to use sequelize which I already define in /models/index.js from a controller.

This is /models/index.js:

```<code>"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require('sequelize')
  , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {
      dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
      port:    3306, // or 5432 (for postgres)
      timezone:'America/Sao_Paulo',
});

sequelize
  .authenticate()
  .then(function(err) {
    console.log('Connection has been established successfully.');
  }, function (err) {
    console.log('Unable to connect to the database:', err);
  });

var db = {};
fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf(".") !== 0) && (file !== "index.js");
  })
  .forEach(function(file) {
    var model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if ("associate" in db[modelName]) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
module.exports.db = db;
</code>```

I want to use a raw query in my price controller:

```<code>exports.index = function(req, res, next) {

    // var environment_hash = req.session.passport.user.environment_hash;

    var Price  = require('../models/index').Price;
    var db  = require('../models/index').db;

    console.log(db);

    db.query(`SELECT ... `).spread((results, metadata) => {
        // Results will be an empty array and metadata will contain the number of affected rows.
        console.log(results);
    });

    var values = {
                    where: { symbol: 'xxx' },
                };

    Price
        .findOne(values)
        .then(function(price) {
            console.log("found!!!!!");
            console.log(price);
            res.render('home/home.ejs', {
                    price: price
                });
      });
};
</code>```

But I'm getting this error message:

```<code>db: [Circular] }
TypeError: db.query is not a function
</code>```

How can I fix this?

答:
The Sequelize library is being assigned to a variable on the db object.

The error is in the second file instead of calling

```<code>db.query
</code>```

We should call

```<code>db.sequelize.query
</code>```

In the first case we have called a function that does not exist. In another case we could assign the query function to a property on the db object.

```<code>db.query = db.sequelize.query
</code>```

or you can de-structure using ES6

```<code>db.query = { query } = db.sequelize
</code>```

Now we can run db.query as expected.

Body:
I'm trying to use raw queries from sequelize in an express app.
My folder structure is:

/
/index.js
/models/index.js
/models/price.js
/controllers/price.js

I want to use sequelize which I already define in /models/index.js from a controller.

This is /models/index.js:

"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require('sequelize')
  , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {
      dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
      port:    3306, // or 5432 (for postgres)
      timezone:'America/Sao_Paulo',
});

sequelize
  .authenticate()
  .then(function(err) {
    console.log('Connection has been established successfully.');
  }, function (err) {
    console.log('Unable to connect to the database:', err);
  });

var db = {};
fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf(".") !== 0) && (file !== "index.js");
  })
  .forEach(function(file) {
    var model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if ("associate" in db[modelName]) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
module.exports.db = db;

I want to use a raw query in my price controller:

exports.index = function(req, res, next) {

    // var environment_hash = req.session.passport.user.environment_hash;

    var Price  = require('../models/index').Price;
    var db  = require('../models/index').db;

    console.log(db);

    db.query(`SELECT ... `).spread((results, metadata) => {
        // Results will be an empty array and metadata will contain the number of affected rows.
        console.log(results);
    });

    var values = {
                    where: { symbol: 'xxx' },
                };

    Price
        .findOne(values)
        .then(function(price) {
            console.log("found!!!!!");
            console.log(price);
            res.render('home/home.ejs', {
                    price: price
                });
      });
};

But I'm getting this error message:

db: [Circular] }
TypeError: db.query is not a function

How can I fix this?

Body:
The Sequelize library is being assigned to a variable on the db object.

The error is in the second file instead of calling

db.query

We should call

db.sequelize.query

In the first case we have called a function that does not exist. In another case we could assign the query function to a property on the db object.

db.query = db.sequelize.query

or you can de-structure using ES6

db.query = { query } = db.sequelize

Now we can run db.query as expected.


来源: stackexchange

问:
Lowercase and Uppercase are the same JS
I am creating a program that will pull up the first non repeated word within a string. While doing this I bump into a logic problem where I need to count a word in uppercase and lowercase the same but still returns the original uppercase version of the string.

Here's my codes:

```<code>function firstNonRepeatingLetter(str) {
 // split the array and transform it to lowercase
 str = str.split('');

 // create an obj that will hold the counter of each characters
 let myObj = {};

 // create a new arr for all the char w/ 1 value
 let uniq = [];

 // iterate through the splitted array
 str.forEach((char) => {
    // if the obj contains the same key (char)
   if(myObj.hasOwnProperty(char)){
      // we add 1 to its value
     myObj[char]++;
   }else{
      // otherwise we set the key value to 1
     myObj[char] = 1;
   }
 });

 // check the obj with 1 value,
 for(let prop in myObj){
  // and then push the key inside a
   // new arr with only 1 counter
   if(myObj[prop] === 1){
     uniq.push(prop);
   }
 }

 console.log(myObj);

 // return the first elem in the arr
 return uniq.length !== 0 ? uniq[0] : '';
}

firstNonRepeatingLetter('sTress') // => must return 'T' instead return 't'
firstNonRepeatingLetter('NecEssarY') // => must return 'N' instead return 'n'
</code>```

The object looks like this: { N: 1, e: 1, c: 1, E: 1, s: 2, a: 1, r: 1, Y: 1 }it counts the 'N' and 'n'separately.

Any idea how to retain the actual case without affecting the functionality?

Thanks!

答:
The first way that came to mind is to convert to upper-case for the object property names so that you can count "A" and "a" together, but then in addition to storing the count store the case of the first one found. So within your existing loop:

```<code>   let upperChar = char.toUpperCase();
   if(myObj.hasOwnProperty(upperChar)){
     myObj[upperChar].count++;                     // add 1 to its count
   } else {
     myObj[upperChar] = { first: char, count: 1 }; // otherwise set count to 1
   }
</code>```

In context with your full code:

function firstNonRepeatingLetter(str) {
 str = str.split('');

 let myObj = {};
 let uniq = [];

 str.forEach((char) => {
    // if the obj contains the same key (char)
   let upperChar = char.toUpperCase();
   if(myObj.hasOwnProperty(upperChar)){
     myObj[upperChar].count++;                     // add 1 to its count
   }else{
     myObj[upperChar] = { first: char, count: 1 }; // otherwise set count to 1
   }
 });

 for(let prop in myObj){              // check the obj with 1 value,
   if(myObj[prop].count === 1){       // and then push the key inside a
     uniq.push(myObj[prop].first);    // new arr with only 1 counter
   }
 }

 console.log(myObj);

 return uniq.length !== 0 ? uniq[0] : ''; // return the first elem in the arr
}

console.log(firstNonRepeatingLetter('sTress')); // => must return 'T'
console.log(firstNonRepeatingLetter('NecEssarY')); // => must return 'N'
console.log(firstNonRepeatingLetter('Stress')); // => must return 't' ```

ContentLicense: CC BY-SA 3.0

Title: Lowercase and Uppercase are the same JS

Body:
I am creating a program that will pull up the first non repeated word within a string. While doing this I bump into a logic problem where I need to count a word in uppercase and lowercase the same but still returns the original uppercase version of the string.

Here's my codes:

function firstNonRepeatingLetter(str) {
 // split the array and transform it to lowercase
 str = str.split('');

 // create an obj that will hold the counter of each characters
 let myObj = {};

 // create a new arr for all the char w/ 1 value
 let uniq = [];

 // iterate through the splitted array
 str.forEach((char) => {
    // if the obj contains the same key (char)
   if(myObj.hasOwnProperty(char)){
      // we add 1 to its value
     myObj[char]++;
   }else{
      // otherwise we set the key value to 1
     myObj[char] = 1;
   }
 });

 // check the obj with 1 value,
 for(let prop in myObj){
  // and then push the key inside a
   // new arr with only 1 counter
   if(myObj[prop] === 1){
     uniq.push(prop);
   }
 }

 console.log(myObj);

 // return the first elem in the arr
 return uniq.length !== 0 ? uniq[0] : '';
}

firstNonRepeatingLetter('sTress') // => must return 'T' instead return 't'
firstNonRepeatingLetter('NecEssarY') // => must return 'N' instead return 'n'

The object looks like this: { N: 1, e: 1, c: 1, E: 1, s: 2, a: 1, r: 1, Y: 1 }it counts the 'N' and 'n'separately.

Any idea how to retain the actual case without affecting the functionality?

Thanks!

Body:
The first way that came to mind is to convert to upper-case for the object property names so that you can count "A" and "a" together, but then in addition to storing the count store the case of the first one found. So within your existing loop:

   let upperChar = char.toUpperCase();
   if(myObj.hasOwnProperty(upperChar)){
     myObj[upperChar].count++;                     // add 1 to its count
   } else {
     myObj[upperChar] = { first: char, count: 1 }; // otherwise set count to 1
   }

In context with your full code:

function firstNonRepeatingLetter(str) {
 str = str.split('');

 let myObj = {};
 let uniq = [];

 str.forEach((char) => {
    // if the obj contains the same key (char)
   let upperChar = char.toUpperCase();
   if(myObj.hasOwnProperty(upperChar)){
     myObj[upperChar].count++;                     // add 1 to its count
   }else{
     myObj[upperChar] = { first: char, count: 1 }; // otherwise set count to 1
   }
 });

 for(let prop in myObj){              // check the obj with 1 value,
   if(myObj[prop].count === 1){       // and then push the key inside a
     uniq.push(myObj[prop].first);    // new arr with only 1 counter
   }
 }

 console.log(myObj);

 return uniq.length !== 0 ? uniq[0] : ''; // return the first elem in the arr
}

console.log(firstNonRepeatingLetter('sTress')); // => must return 'T'
console.log(firstNonRepeatingLetter('NecEssarY')); // => must return 'N'
console.log(firstNonRepeatingLetter('Stress')); // => must return 't'


问:
Docker containers as virtual desktop clones
I see that a number of people have set up Docker containers with Guacamole or other tools to allow them to remote in to GUI as if the container was a remote Linux desktop.  A friend of mine had a conversation with a professor who told him that they set up Ubuntu desktop access for their students via ubuntu/rdp docker containers.

It's an attractive concept for efficiently packed cloned desktops since you don't need 50 copies of the guest OS, but how would you manage such a swarm without a connection broker like a VDI solution or a hypervizer console like a KVM setup?  Would you simply use standard docker (or swarm) management tools to manage the containers themselves, then some separate remote client for the actual remote control connections?

I'm currently reading up on Docker, but unclear:  If each desktop is the same, so say Firefox, LibreOffice, etc.  Is there any way to gain efficiency by sharing these resources as well?  For instance, could there be a container with those resources that the others all connect to... or have it shared on a lower level like the OS?  Looking for any way to gain efficiency, lower overall cpu, ram, etc for all combined machines on server.  Really looking for anything other than a separate copy of the same thing in each container.

I see that there are solutions for shared persistent storage in containers like Hatchway.  Are there other issues caused by statelessness of the container that this does not address?

Also, I see a few ways people have cobbled together internet connectivity for docker containers (like IP per container), but most of the older posts are people frustrated with the process.  Is there now a standard or preferred way to do something like this?

Or, if docker/containers are absolutely the wrong way to go about setting up the most efficient possible Linux remote desktop clones, I'd love to understand exactly what part does not work so I can find the right way.

答: I see after days of reading that LXD is actually what I'm looking for (Linux machine containers) instead of Docker (process containers).</p>


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
Change the body of initTree as follows:</p>

```<code>tree* myTree = (tree *)malloc(sizeof(tree));
node *myNode = (node *)malloc(sizeof(node));
myTree->nodes[0] = myNode;
return myTree;
</code>```

ContentLicense: CC BY-SA 2.5

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?

Body:
Change the body of initTree as follows:

tree* myTree = (tree *)malloc(sizeof(tree));
node *myNode = (node *)malloc(sizeof(node));
myTree->nodes[0] = myNode;
return myTree;


问:
TypeError: 'str' object is not callable when trying to click "datepicker"
The relevant HTML

```<code><div id="datepickerbox" class="ym-gbox-left">
 <div class="datepick_label">
  <div id="datepicker" class="hasDatepicker">
   <div class="ui-datepicker-inline ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" style="display: block;">
</code>```

My code

```<code>self.driver.find_element(By.XPATH('//*[@id="datepicker"]')).click()
dateWidget = self.driver.find_element(By.ID("ui-datepicker-div"))
rows = dateWidget.find_element_by_tag_name("tr")
columns = dateWidget.find_element_by_tag_name("td")
for cell in columns: self.driver.findElement(By.LINK_TEXT("20")).click()
</code>```

The error I'm getting

```<code>self.driver.find_element(By.XPATH('//*[@id="datepicker"]')).click()
TypeError: 'str' object is not callable
</code>```

How can I make this work?

答:
So what I've found out from this error, is that sometimes a website will load a frame, which by printing the html -> print(driver.page_source) will give you what the driver can "see". If you can't find your element in page source, then there's your problem.

I fixed this by finding a .php link inside of the frame element and then adding that link to the current url, here's an example: Given www.site.com/login print the page source, and, if this is the issue, there will be a .php link that's inside the frame (ex. /loginPage.php. Click the link, copy it and execute the .get([new url]). This took me to an identical page, but you're able to access your html elements like normal!

Edit: Thank you Stephen for showing me the ropes to adding code for the first time!

Body:
The relevant HTML

My code

self.driver.find_element(By.XPATH('//*[@id="datepicker"]')).click()
dateWidget = self.driver.find_element(By.ID("ui-datepicker-div"))
rows = dateWidget.find_element_by_tag_name("tr")
columns = dateWidget.find_element_by_tag_name("td")
for cell in columns: self.driver.findElement(By.LINK_TEXT("20")).click()

The error I'm getting

self.driver.find_element(By.XPATH('//*[@id="datepicker"]')).click()
TypeError: 'str' object is not callable

How can I make this work?


问:
How to pass multiple webjobs as a parameter to the PowerShell script
The below script is provided to start the Webjobs in the azure.But I am including the Json file into the Powershell script and running the Webjobs.Its good for only one environment.But I want the same script to be used for multiple environments with different Webjob names.So how can I modify this script so that I can stop and start the Webjobs in VSTS at release definition,Currently,I have 4 Webjobs for Dev Environment and I have 8 Webjobs for Int Environment with different azure subscriptions.So how can I use the below script for different environments.Kindly help me on this.I can't use the below script for all the environments because I am importing the only one json file.So it will only accept the particular json parameters.But in my case the json parameters would be different for different environments.So how can I import different json file contents into the below script? Is there is any possibility to include multiple json files and script can only accept particular Json script based on the environment which I run at the release definition in VSTS and can run accordingly.

Parameter.json:

```<code>{
    "userName": "user1",
    "password": "password1",
    "webAppName": "webapp1",
    "resourceGroup": "resourceGroup1",
    "webJobs": [
      {
        "name": "abc",
        "typeName": "continuous"
      },
      {
        "name": "def",
        "typeName": "continuous"
      }
    ]
  }
</code>```

Script:

```<code>[object]$paramObj=Get-Content "PowerShellModuleProject1\parameter2.json"|ConvertFrom-Json
        $userName =$paramObj.userName
        $password =$paramObj.password
        $webAppName =$paramObj.webAppName
        $resourceGroup=$paramObj.resourceGroup
        [object[]]$webJobs=$paramObj.webJobs
        foreach($wj in $webjobs){
         if($wj.typeName -eq "continuous")
         {
    Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName "$webAppName/$($wj.name)" -Action start -ApiVersion 2015-08-01 -Force
          Write-Host "continuous"
         Write-Host $wj.name
         }
         else{
         Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName "$webAppName/$($wj.name)" -Action run -ApiVersion 2015-08-01 -force
         Write-Host "triggered"
         Write-Host $wj.name
         }
         }
</code>```

答:
You can update Parameter.json file (parameter2.json) like this:

```<code>{
  "Dev": {
    "userName": "user1",
    "password": "password1",
    "webAppName": "webapp1",
    "resourceGroup": "resourceGroup1",
    "webJobs": [
      {
        "name": "abcDev",
        "typeName": "continuous"
      },
      {
        "name": "defDev",
        "typeName": "continuous"
      }
    ]
  },
  "Int": {
    "userName": "userInt",
    "password": "passwordInt",
    "webAppName": "webappInt",
    "resourceGroup": "resourceGroupInt",
    "webJobs": [
      {
        "name": "abcInt",
        "typeName": "continuous"
      },
      {
        "name": "defInt",
        "typeName": "continuous"
      }
    ]
  }
}
</code>```

Script:

```<code>param(
[string]$currentEnv
)
[object]$paramObj=Get-Content "PowerShellModuleProject1\parameter2.json"|ConvertFrom-Json
$userName =$paramObj.$currentEnv.userName
$password =$paramObj.$currentEnv.password
$webAppName =$paramObj.$currentEnv.webAppName
$resourceGroup=$paramObj.$currentEnv.resourceGroup
[object[]]$webJobs=$paramObj.$currentEnv.webJobs
foreach($wj in $webjobs){
         if($wj.typeName -eq "continuous")
         {
    Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName "$webAppName/$($wj.name)" -Action start -ApiVersion 2015-08-01 -Force
          Write-Host "continuous"
         Write-Host $wj.name
         }
         else{
         Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName "$webAppName/$($wj.name)" -Action run -ApiVersion 2015-08-01 -force
         Write-Host "triggered"
         Write-Host $wj.name
         }
         }
</code>```

Arguments: -currentEnv $(Release.EnvironmentName). Modify each environment’s name in release definition.

Or you can add environment variables with the same name (e.g. currentEnv) for each environment of release, and the Arguments: -currentEnv $(currentEnv)

Body:
The below script is provided to start the Webjobs in the azure.But I am including the Json file into the Powershell script and running the Webjobs.Its good for only one environment.But I want the same script to be used for multiple environments with different Webjob names.So how can I modify this script so that I can stop and start the Webjobs in VSTS at release definition,Currently,I have 4 Webjobs for Dev Environment and I have 8 Webjobs for Int Environment with different azure subscriptions.So how can I use the below script for different environments.Kindly help me on this.I can't use the below script for all the environments because I am importing the only one json file.So it will only accept the particular json parameters.But in my case the json parameters would be different for different environments.So how can I import different json file contents into the below script? Is there is any possibility to include multiple json files and script can only accept particular Json script based on the environment which I run at the release definition in VSTS and can run accordingly.

Parameter.json:

{
    "userName": "user1",
    "password": "password1",
    "webAppName": "webapp1",
    "resourceGroup": "resourceGroup1",
    "webJobs": [
      {
        "name": "abc",
        "typeName": "continuous"
      },
      {
        "name": "def",
        "typeName": "continuous"
      }
    ]
  }

Script:

[object]$paramObj=Get-Content "PowerShellModuleProject1\parameter2.json"|ConvertFrom-Json
        $userName =$paramObj.userName
        $password =$paramObj.password
        $webAppName =$paramObj.webAppName
        $resourceGroup=$paramObj.resourceGroup
        [object[]]$webJobs=$paramObj.webJobs
        foreach($wj in $webjobs){
         if($wj.typeName -eq "continuous")
         {
    Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName "$webAppName/$($wj.name)" -Action start -ApiVersion 2015-08-01 -Force
          Write-Host "continuous"
         Write-Host $wj.name
         }
         else{
         Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName "$webAppName/$($wj.name)" -Action run -ApiVersion 2015-08-01 -force
         Write-Host "triggered"
         Write-Host $wj.name
         }
         }

Body:
You can update Parameter.json file (parameter2.json) like this:

{
  "Dev": {
    "userName": "user1",
    "password": "password1",
    "webAppName": "webapp1",
    "resourceGroup": "resourceGroup1",
    "webJobs": [
      {
        "name": "abcDev",
        "typeName": "continuous"
      },
      {
        "name": "defDev",
        "typeName": "continuous"
      }
    ]
  },
  "Int": {
    "userName": "userInt",
    "password": "passwordInt",
    "webAppName": "webappInt",
    "resourceGroup": "resourceGroupInt",
    "webJobs": [
      {
        "name": "abcInt",
        "typeName": "continuous"
      },
      {
        "name": "defInt",
        "typeName": "continuous"
      }
    ]
  }
}

Script:

param(
[string]$currentEnv
)
[object]$paramObj=Get-Content "PowerShellModuleProject1\parameter2.json"|ConvertFrom-Json
$userName =$paramObj.$currentEnv.userName
$password =$paramObj.$currentEnv.password
$webAppName =$paramObj.$currentEnv.webAppName
$resourceGroup=$paramObj.$currentEnv.resourceGroup
[object[]]$webJobs=$paramObj.$currentEnv.webJobs
foreach($wj in $webjobs){
         if($wj.typeName -eq "continuous")
         {
    Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName "$webAppName/$($wj.name)" -Action start -ApiVersion 2015-08-01 -Force
          Write-Host "continuous"
         Write-Host $wj.name
         }
         else{
         Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroup -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName "$webAppName/$($wj.name)" -Action run -ApiVersion 2015-08-01 -force
         Write-Host "triggered"
         Write-Host $wj.name
         }
         }

Arguments: -currentEnv $(Release.EnvironmentName). Modify each environment’s name in release definition.

Or you can add environment variables with the same name (e.g. currentEnv) for each environment of release, and the Arguments: -currentEnv $(currentEnv)


问:
403 Forbidden if input contains "script"
I am facing one kinda odd problem and I'd appreciate any help.
I am looking to have a page submit a Google Adsense code and then save it to the database (I have a input field to accept GA code and a submit button, very simple form)
The thing is, I always get 403 forbidden when submiting a form, if input field contain "

答:
I had this problem, I needed to use  tags in the form I was submitting in the admin system (embedding a google adsense ad).

To fix I edited the .htaccess file and added the line
SecFilterEngine Off

I only needed to do this temporarily to get the job done & turn it back on when I'm done.


问:
Django, redirect user for unrecognized url (not just 404 template)
I thought I had this figured out, but just discovered something weird.

In urls I have

```<code>url('^page_1/$', handle_page_1),
url('^page_2/$', handle_page_2),
url('^.*/$', handle_page_not_found),
</code>```

handle_page_not_found() redirect the user appropriately if the url is not recognized.

That works fine, but I discovered something weird.

If a function returns

```<code>return HttpResponse("ok")
</code>```

then "ok" is returned and everything seems to work fine. BUT, I just saw that handle_page_not_found() is also called (I tested with a print statement). It's still "ok" that is returned, but it's first executing the code in handle_page_not_found().

So, how can I have a function that is called for unrecognized urls, but that is not called by a HttpResponse object?

EDIT: Based on answer, saw that my code is actually fine except in special test situation. It's all good so long as the HttpResponse is returned to an ajax call (which is when I normally use it).

答:
It works for my app with Django v1.11.3 and python v3.6.

Step 1. add view_404 in views.py as following.

```<code>def view_404(request):
    # do something
    return redirect('/')
</code>```

Step 2. add handler on urls.py.

```<code>url(r'^.*/$', views.view_404)
</code>```

Body:
I thought I had this figured out, but just discovered something weird.

In urls I have

url('^page_1/$', handle_page_1),
url('^page_2/$', handle_page_2),
url('^.*/$', handle_page_not_found),

handle_page_not_found() redirect the user appropriately if the url is not recognized.

That works fine, but I discovered something weird.

If a function returns

return HttpResponse("ok")

then "ok" is returned and everything seems to work fine. BUT, I just saw that handle_page_not_found() is also called (I tested with a print statement). It's still "ok" that is returned, but it's first executing the code in handle_page_not_found().

So, how can I have a function that is called for unrecognized urls, but that is not called by a HttpResponse object?

EDIT: Based on answer, saw that my code is actually fine except in special test situation. It's all good so long as the HttpResponse is returned to an ajax call (which is when I normally use it).

Body:
It works for my app with Django v1.11.3 and python v3.6.

Step 1. add view_404 in views.py as following.

def view_404(request):
    # do something
    return redirect('/')

Step 2. add handler on urls.py.

url(r'^.*/$', views.view_404)


问:
String.replacingOccurrences with large String memory issue
In our app we generate a PDF file. So we use an HTML file as template and load this template to String then replace all placeholders with correct values:

```<code>let template = Bundle.main.path(forResource: “reportTemplate”, ofType: "html")
do {
    var htmlTemplate = try String(contentsOfFile: template!)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#LOGO#”, with: logoBase64)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#TITLE#”, with: “PDF FILE“)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#IMAGE1#”, with: reportImageBase64)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#IMAGE2#”, with: reportImageBase64)
    //…
} catch {
    print(“\(error)“)
}
</code>```

The PDF may contain numbers of images thus the string grow bigger as we converting these images to Base64.

We then notice that this cause issue on memory as it goes high when we run the generation code. And we receive random crash reports due to NSMallocException pointing to this.

Any suggestion to avoid this?

答:
Try to mutate your String in-place as this might substantially reduce your memory usage. For instance:

```<code>let token = htmlTemplate.range(of: “#LOGO#”)!
htmlTemplate.replaceSubrange(token, with: logoBase64)
...
</code>```

If a token might appear more than once — or not at all! — you need to account for that as well:

```<code>while let token = htmlTemplate.range(of: “#LOGO#”) {
    htmlTemplate.replaceSubrange(token, with: logoBase64)
}
...
</code>```

Body:
In our app we generate a PDF file. So we use an HTML file as template and load this template to String then replace all placeholders with correct values:

let template = Bundle.main.path(forResource: “reportTemplate”, ofType: "html")
do {
    var htmlTemplate = try String(contentsOfFile: template!)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#LOGO#”, with: logoBase64)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#TITLE#”, with: “PDF FILE“)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#IMAGE1#”, with: reportImageBase64)
    htmlTemplate = htmlTemplate.replacingOccurrences(of: “#IMAGE2#”, with: reportImageBase64)
    //…
} catch {
    print(“\(error)“)
}

The PDF may contain numbers of images thus the string grow bigger as we converting these images to Base64.

We then notice that this cause issue on memory as it goes high when we run the generation code. And we receive random crash reports due to NSMallocException pointing to this.

Any suggestion to avoid this?

Body:
Try to mutate your String in-place as this might substantially reduce your memory usage. For instance:

let token = htmlTemplate.range(of: “#LOGO#”)!
htmlTemplate.replaceSubrange(token, with: logoBase64)
...

If a token might appear more than once — or not at all! — you need to account for that as well:

while let token = htmlTemplate.range(of: “#LOGO#”) {
    htmlTemplate.replaceSubrange(token, with: logoBase64)
}
...


问:
Alias to record all commands and std output to a file
I am looking to figure out a way to get my documentation done quicker for my project work. One thing that would help me would be to record my history and each commands output to a file. However, I don't want to have this on all the time and I would rather not have it as a toggle option for the risk of forgetting to turn it off and recording a load of junk that I will have to just go and delete later.

The idea I had was to create an alias, lets say 'verbatim', so that I could enter the command as so:

```<code>verbatim <command>
</code>```

And then the alias would remove 'verbatim', take whatever  that was entered and prepend/append it with:

```<code>echo -n \[\$(date)\] >> output_file | echo "<command>" >> output_file | <command> | fee -a output_file | echo " " >> output_file
</code>```

where the output will be:

```<code><timestamp>
<command>
<outputOfTheCommand>
<newLine>
</code>```

could also add comments by

```<code>verbatim #some comment to go in line
</code>```

example:

```<code>verbatim #deploying the production stack upgrade
verbatim <someDeployCommand>
</code>```

This way by typing just one word extra per line I can record everything that happens as I am doing a deployment for example, which can be used to basically do all of my documentation for me since it is saved to a file in order, all I have to do is remove anything that is irrelevant in hindsight. And the fact that all the data is timestamped means it could also speed up RCA if something goes wrong.

Thanks in advance, any and all advice welcome

答:
I would just do my deployment as usual, and then add
head -n 20 ~/.bash_history
and edit the 20 depending on the history size I want.

Body:
I am looking to figure out a way to get my documentation done quicker for my project work. One thing that would help me would be to record my history and each commands output to a file. However, I don't want to have this on all the time and I would rather not have it as a toggle option for the risk of forgetting to turn it off and recording a load of junk that I will have to just go and delete later.

The idea I had was to create an alias, lets say 'verbatim', so that I could enter the command as so:

verbatim <command>

And then the alias would remove 'verbatim', take whatever  that was entered and prepend/append it with:

echo -n \[\$(date)\] >> output_file | echo "<command>" >> output_file | <command> | fee -a output_file | echo " " >> output_file

where the output will be:

<timestamp>
<command>
<outputOfTheCommand>
<newLine>

could also add comments by

verbatim #some comment to go in line

example:

verbatim #deploying the production stack upgrade
verbatim <someDeployCommand>

This way by typing just one word extra per line I can record everything that happens as I am doing a deployment for example, which can be used to basically do all of my documentation for me since it is saved to a file in order, all I have to do is remove anything that is irrelevant in hindsight. And the fact that all the data is timestamped means it could also speed up RCA if something goes wrong.

Thanks in advance, any and all advice welcome


问:
Django Timezone Awareness - Data to be stored in UTC

This is my first time developing a timezone aware web app.  I'm using Django 1.11.7.  I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o

I'm making a booking app with start_time and end_time for each reservation.

I expect the user to be able to enter dates and times as he experiences them in his timezone.  On the other hand, I want these dates and times stored in a postgresql database in UTC format.

If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).

Right?

Django Internationalization settings:

```<code>LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_TZ = True
USE_L10N = True
USE_I18N = True
</code>```

During database creation:

```<code>start_time      TIMESTAMP WITH TIME ZONE NOT NULL,
end_time        TIMESTAMP WITH TIME ZONE NOT NULL
</code>```

Using Django's built in admin page feature, I enter the following information:

But when I look up the results in the database, here's what I get:

```<code>2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05
</code>```

The stored result changed in the opposite direction of what I was expecting.  I was expecting:

```<code>2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05
</code>```

If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.

Otherwise, if my expectations where right, I would appreciate any advice.

Thank you.

答:
https://www.google.co.jp/search?dcr=0&q=ottawa+timezone&spell=1&sa=X&ved=0ahUKEwjX0LnA5_bXAhVFjJQKHXCdBDYQvwUIJigA&biw=1394&bih=803

Ottawa timezone is -5.

You can manually test in a template that's the timezones are properly registered by showing the time you've registered in different timezones with this filter:

https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/#std:templatefilter-timezone

Body:
This is my first time developing a timezone aware web app.  I'm using Django 1.11.7.  I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o

I'm making a booking app with start_time and end_time for each reservation.

I expect the user to be able to enter dates and times as he experiences them in his timezone.  On the other hand, I want these dates and times stored in a postgresql database in UTC format.

If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).

Right?

Django Internationalization settings:

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_TZ = True
USE_L10N = True
USE_I18N = True

During database creation:

start_time      TIMESTAMP WITH TIME ZONE NOT NULL,
end_time        TIMESTAMP WITH TIME ZONE NOT NULL

Using Django's built in admin page feature, I enter the following information:

But when I look up the results in the database, here's what I get:

2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05

The stored result changed in the opposite direction of what I was expecting.  I was expecting:

2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05

If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.

Otherwise, if my expectations where right, I would appreciate any advice.

Thank you.


问:
Finding Percentages of elements inside an ArrayList<model>
So I am doing a project which I want to built a library with two ArrayLists one of the ArrayList'<'Book'>' BookList contains an element named quantity has to greater or equivalent to zero if the quantity of the book is above zero another element called status in the BookList is set to In-stock if it's equal to zero it's set to borrowed. I'm trying to create a method that looks at the BookList and shows the percentage of books that are borrowed. I have done this by going through the list and each time it finds a book with quantity below 1 in other words 0 the counter goes up by one so in the end I just substract the counter from the BookList.size(), divide the result with the BookList.size(), multiply it by 100 and fially print it.

Main Class

```<code>public class Main {
    public static void main(String[] args) {
    Scanner keyb = new Scanner(System.in);
    int uinput;
    Library nag;
    try{
    nag = new Library();
    do{
        System.out.println("Type 1 to add a book.");
        System.out.println("Type 2 to show how many books are borrowed.");
        uinput = keyb.nextInt();
        if (uinput==1){
            nag.addBook();
        }
        if (uinput==2){
            nag.statistics();
        }
    }while (uinput > 0);
    }
    catch(Exception e){
        System.out.println("Invalid entry.");
    }
}//end of main
}//end of class
</code>```

Book Class

```<code>public class Book {

    private String Title;
    private String Author;
    private String ISBN;
    private String Publisher;
    private String Publication_Date;
    private String Price;
    private int Quantity;
    private String Status;

    public Book(){
        Title= "";
        Author="";
        ISBN="";
        Publisher="";
        Publication_Date="";
        Price="";
        Quantity=1;
        Status="IN-STOCK";
    }

    //getters
    public String gettitle(){return Title;}
    public String getauthor(){return Author;}
    public String getisbn(){return ISBN;}
    public String getpublisher(){return Publisher;}
    public String getpublication_date(){return Publication_Date;}
    public String getprice(){return Price;}
    public int getquantity(){return Quantity;}
    public String getstatus(){return Status;}

    //setters
    public void settitle(String t){Title = t;}
    public void setauthor(String a){Author = a;}
    public void setisbn(String is){ISBN = is;}
    public void setpublisher(String p){Publisher = p;}
    public void setpublication_date(String pd){Publication_Date = pd;}
    public void setprice(String pr){Price = pr;}
    public void setquantity(int q){Quantity = q;}
    public void setstatus(String s){Status = s;}

}//end of class
</code>```

Library Class

```<code>public class Library {

private ArrayList<Book> BookList;

public Library(){
    BookList = new ArrayList<Book>();
}//end of constructor 1

public Library(ArrayList<Book> l) {
    BookList = l;
}//end of constructor 3

public void addBook(){
    try{
        Scanner keyb = new Scanner(System.in);
        Book bo = new Book();

        System.out.println("Type the title: ");
        String title_input;
        title_input = keyb.nextLine();
        bo.settitle(title_input);

        System.out.println("Type the author: ");
        String author_input;
        author_input = keyb.nextLine();
        bo.setauthor(author_input);

        System.out.println("Type the isbn: ");
        String isbn_input;
        isbn_input = keyb.nextLine();
        bo.setisbn(isbn_input);

        System.out.println("Type the publisher: ");
        String publisher_input;
        publisher_input = keyb.nextLine();
        bo.setpublisher(publisher_input);

        System.out.println("Type the publication date: ");
        String publication_date_input;
        publication_date_input = keyb.nextLine();
        bo.setpublication_date(publication_date_input);

        System.out.println("Type the price: ");
        String price_input;
        price_input = keyb.nextLine();
        bo.setprice(price_input);

        System.out.println("Type the quantity: ");
        int quantity_input = Integer.parseInt(keyb.nextLine());
        if (quantity_input >= 0){
            bo.setquantity(quantity_input);
            if (quantity_input > 0){
                bo.setstatus("IN_STOCK");
            }
            if(quantity_input == 0){
                bo.setstatus("BORROWED");
            }
            BookList.add(bo);
            System.out.println("Book added successfully.");
        }
    }catch(Exception e){
        System.out.println("Invalid entry");
    }//end of addBook()

public void statistics(){
    Book bo = new Book();
    int counter = 0;
    for(int i=0; i < BookList.size();i++){
        bo= BookList.get(i);
        int holdquantity = bo.getquantity();
        if (holdquantity  < 1){
            counter++;
        }
    }
    double substraction=BookList.size() - counter;
    double division= substraction/BookList.size();
    double percentage = division * 100;
    System.out.print(percentage + "%");
}//end of statistics()
}//end of class
</code>```

The problem is that it keeps printing 100.0% when I have a book with quantity of zero and another book with quantity above zero.
So I wanted to know if the problem lies within this code or elsewhere.

答:
Let's say your Book class is as follows:

```<code>package com.company;

public class Book {

    private int quantity;

    public Book(int quantity) {
        this.quantity = quantity;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}
</code>```

And your Main is as follows:

```<code>package com.company;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main (String[]args) {

        List<Book> bookList = new ArrayList<>(){{
            add(new Book(4));
            add(new Book(0));
            add(new Book(3));
            add(new Book(7));
            add(new Book(0));
            add(new Book(0));
            add(new Book(1));
            add(new Book(9));
            add(new Book(0));
            add(new Book(5));
        }};

        int booksOutOfStock = 0;

        for (int i = 0; i < bookList.size(); i++) {
            if (bookList.get(i).getQuantity() == 0)
                booksOutOfStock++;
        }

        double percentage = 100d / bookList.size() * booksOutOfStock;

        System.out.printf("Out of total %d books, %d are out of stock, which makes %.2f%%", bookList.size(), booksOutOfStock,
                                                                                percentage);
    }
}
</code>```

So check this code, compare it to yours and see where could the error be, or post complete code here so we can help more.

Output of code above:

Out of total 10 books, 4 are out of stock, which makes 40.00%

OK, so after you posted your code I reviewed it, and apart from doing some things the hard way, your code is "working", all I had to do was add a closing brace in Library class at the end of addBook() method after catch block:

```<code>catch(Exception e){
        System.out.println("Invalid entry");
    } --> } <--- (added)

    //end of addBook()
</code>```

And I fixed your percentage code logic, you code would print out the number of non borrowed books as borrowed percentage, here is that code changed:

```<code>    double division= (double)counter/BookList.size();
    double percentage = division * 100;
    System.out.printf("%.2f", percentage);
</code>```

Body:
So I am doing a project which I want to built a library with two ArrayLists one of the ArrayList'<'Book'>' BookList contains an element named quantity has to greater or equivalent to zero if the quantity of the book is above zero another element called status in the BookList is set to In-stock if it's equal to zero it's set to borrowed. I'm trying to create a method that looks at the BookList and shows the percentage of books that are borrowed. I have done this by going through the list and each time it finds a book with quantity below 1 in other words 0 the counter goes up by one so in the end I just substract the counter from the BookList.size(), divide the result with the BookList.size(), multiply it by 100 and fially print it.

Main Class

public class Main {
    public static void main(String[] args) {
    Scanner keyb = new Scanner(System.in);
    int uinput;
    Library nag;
    try{
    nag = new Library();
    do{
        System.out.println("Type 1 to add a book.");
        System.out.println("Type 2 to show how many books are borrowed.");
        uinput = keyb.nextInt();
        if (uinput==1){
            nag.addBook();
        }
        if (uinput==2){
            nag.statistics();
        }
    }while (uinput > 0);
    }
    catch(Exception e){
        System.out.println("Invalid entry.");
    }
}//end of main
}//end of class

Book Class

public class Book {

    private String Title;
    private String Author;
    private String ISBN;
    private String Publisher;
    private String Publication_Date;
    private String Price;
    private int Quantity;
    private String Status;

    public Book(){
        Title= "";
        Author="";
        ISBN="";
        Publisher="";
        Publication_Date="";
        Price="";
        Quantity=1;
        Status="IN-STOCK";
    }

    //getters
    public String gettitle(){return Title;}
    public String getauthor(){return Author;}
    public String getisbn(){return ISBN;}
    public String getpublisher(){return Publisher;}
    public String getpublication_date(){return Publication_Date;}
    public String getprice(){return Price;}
    public int getquantity(){return Quantity;}
    public String getstatus(){return Status;}

    //setters
    public void settitle(String t){Title = t;}
    public void setauthor(String a){Author = a;}
    public void setisbn(String is){ISBN = is;}
    public void setpublisher(String p){Publisher = p;}
    public void setpublication_date(String pd){Publication_Date = pd;}
    public void setprice(String pr){Price = pr;}
    public void setquantity(int q){Quantity = q;}
    public void setstatus(String s){Status = s;}

}//end of class

Library Class

public class Library {

private ArrayList<Book> BookList;

public Library(){
    BookList = new ArrayList<Book>();
}//end of constructor 1

public Library(ArrayList<Book> l) {
    BookList = l;
}//end of constructor 3

public void addBook(){
    try{
        Scanner keyb = new Scanner(System.in);
        Book bo = new Book();

        System.out.println("Type the title: ");
        String title_input;
        title_input = keyb.nextLine();
        bo.settitle(title_input);

        System.out.println("Type the author: ");
        String author_input;
        author_input = keyb.nextLine();
        bo.setauthor(author_input);

        System.out.println("Type the isbn: ");
        String isbn_input;
        isbn_input = keyb.nextLine();
        bo.setisbn(isbn_input);

        System.out.println("Type the publisher: ");
        String publisher_input;
        publisher_input = keyb.nextLine();
        bo.setpublisher(publisher_input);

        System.out.println("Type the publication date: ");
        String publication_date_input;
        publication_date_input = keyb.nextLine();
        bo.setpublication_date(publication_date_input);

        System.out.println("Type the price: ");
        String price_input;
        price_input = keyb.nextLine();
        bo.setprice(price_input);

        System.out.println("Type the quantity: ");
        int quantity_input = Integer.parseInt(keyb.nextLine());
        if (quantity_input >= 0){
            bo.setquantity(quantity_input);
            if (quantity_input > 0){
                bo.setstatus("IN_STOCK");
            }
            if(quantity_input == 0){
                bo.setstatus("BORROWED");
            }
            BookList.add(bo);
            System.out.println("Book added successfully.");
        }
    }catch(Exception e){
        System.out.println("Invalid entry");
    }//end of addBook()

public void statistics(){
    Book bo = new Book();
    int counter = 0;
    for(int i=0; i < BookList.size();i++){
        bo= BookList.get(i);
        int holdquantity = bo.getquantity();
        if (holdquantity  < 1){
            counter++;
        }
    }
    double substraction=BookList.size() - counter;
    double division= substraction/BookList.size();
    double percentage = division * 100;
    System.out.print(percentage + "%");
}//end of statistics()
}//end of class

The problem is that it keeps printing 100.0% when I have a book with quantity of zero and another book with quantity above zero.
So I wanted to know if the problem lies within this code or elsewhere.

Body:
Let's say your Book class is as follows:

package com.company;

public class Book {

    private int quantity;

    public Book(int quantity) {
        this.quantity = quantity;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

And your Main is as follows:

package com.company;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main (String[]args) {

        List<Book> bookList = new ArrayList<>(){{
            add(new Book(4));
            add(new Book(0));
            add(new Book(3));
            add(new Book(7));
            add(new Book(0));
            add(new Book(0));
            add(new Book(1));
            add(new Book(9));
            add(new Book(0));
            add(new Book(5));
        }};

        int booksOutOfStock = 0;

        for (int i = 0; i < bookList.size(); i++) {
            if (bookList.get(i).getQuantity() == 0)
                booksOutOfStock++;
        }

        double percentage = 100d / bookList.size() * booksOutOfStock;

        System.out.printf("Out of total %d books, %d are out of stock, which makes %.2f%%", bookList.size(), booksOutOfStock,
                                                                                percentage);
    }
}

So check this code, compare it to yours and see where could the error be, or post complete code here so we can help more.

Output of code above:

Out of total 10 books, 4 are out of stock, which makes 40.00%

OK, so after you posted your code I reviewed it, and apart from doing some things the hard way, your code is "working", all I had to do was add a closing brace in Library class at the end of addBook() method after catch block:

catch(Exception e){
        System.out.println("Invalid entry");
    } --> } <--- (added)

    //end of addBook()

And I fixed your percentage code logic, you code would print out the number of non borrowed books as borrowed percentage, here is that code changed:

    double division= (double)counter/BookList.size();
    double percentage = division * 100;
    System.out.printf("%.2f", percentage);


问:
missing the return statement in the if statement which is in the for loop
The problem that's occurring is that the error is "missing return statement"; How do I go about solving this?. The actual point of the code is to add the balance of all the companions together as well as the balance, then see if it is enough for the holiday.
I have also declared another field variable called </p>

```<code>private int every1nzBalance;

public boolean checkMoney(Holiday holiday)
{

    // For each friend i.e in the list

    for(Friend friend:companions)
    {
        if(friend.getMoney()+ balance>=holiday.getPrice())
        {

         System.out.println("You including your friends have sufficient funds to pay for the"+holiday+" holiday.");

         return true;
        }

        else

        {
            System.out.println("Please ensure that you and your friends have sufficient amount of money for the holiday");

            return false;
        }
      }

    }
</code>```

答:
It's simple. If the for does not have anything to iterate over (say the array is empty), then it  won't execute at all. You  need a default return statement at the end:

```<code>private int every1nzBalance;

public boolean checkMoney(Holiday holiday) {

if(companions == null) return false; //also default return

for(Friend friend : companions)
{
    if(friend.getMoney()+ balance>=holiday.getPrice())
    {

     System.out.println("You including your friends have sufficient funds to pay for the"+holiday+" holiday.");

     return true;
    }

    else

    {
        System.out.println("Please ensure that you and your friends have sufficient amount of money for the holiday");

        return false;
    }
  }
  return  false; //default return
}
</code>```

Body:
The problem that's occurring is that the error is "missing return statement"; How do I go about solving this?. The actual point of the code is to add the balance of all the companions together as well as the balance, then see if it is enough for the holiday.
I have also declared another field variable called

private int every1nzBalance;

public boolean checkMoney(Holiday holiday)
{

    // For each friend i.e in the list

    for(Friend friend:companions)
    {
        if(friend.getMoney()+ balance>=holiday.getPrice())
        {

         System.out.println("You including your friends have sufficient funds to pay for the"+holiday+" holiday.");

         return true;
        }

        else

        {
            System.out.println("Please ensure that you and your friends have sufficient amount of money for the holiday");

            return false;
        }
      }

    }

Body:
It's simple. If the for does not have anything to iterate over (say the array is empty), then it  won't execute at all. You  need a default return statement at the end:

private int every1nzBalance;

public boolean checkMoney(Holiday holiday) {

if(companions == null) return false; //also default return

for(Friend friend : companions)
{
    if(friend.getMoney()+ balance>=holiday.getPrice())
    {

     System.out.println("You including your friends have sufficient funds to pay for the"+holiday+" holiday.");

     return true;
    }

    else

    {
        System.out.println("Please ensure that you and your friends have sufficient amount of money for the holiday");

        return false;
    }
  }
  return  false; //default return
}


问:
What server does ng serve use when using Angular CLI 1.6.0?
What server does this Angular CLI command use, when using Angular CLI 1.6.0?

```<code>ng serve
</code>```

Since webpack is now being used by the Angular CLI for the website bundling, does that mean ng-serve is using the webpack-dev-server (which is a Node.js Express server)? There is some indication in the following Q/A that ng serve possibly used to piggyback off a server used by Ember:

What happens when you run ng serve?

答:
Try ng eject
This command will override your package.json and also generates a file called webpack.config.js in your root directory.

That will give you all the current webpack configuration that your project is using.

When you do that, in your package.json, this is what you'll find :

```<code>"scripts": {
    "eject": "ddc eject",
    "build": "webpack",
    "start": "webpack-dev-server",
    "test": "karma start ./karma.conf.js",
    "pree2e": "webdriver-manager update --standalone false --gecko false --quiet",
    "e2e": "protractor ./protractor.conf.js"
  },
</code>```

As you can see, npm start is using webpack-dev-server.

NOTE: To undo your changes, use git, otherwise AngularCli doesn't provide a way of undoing

ContentLicense: CC BY-SA 4.0

Body:
What server does this Angular CLI command use, when using Angular CLI 1.6.0?

ng serve

Since webpack is now being used by the Angular CLI for the website bundling, does that mean ng-serve is using the webpack-dev-server (which is a Node.js Express server)? There is some indication in the following Q/A that ng serve possibly used to piggyback off a server used by Ember:

What happens when you run ng serve?

Body:
Try ng eject
This command will override your package.json and also generates a file called webpack.config.js in your root directory.

That will give you all the current webpack configuration that your project is using.

When you do that, in your package.json, this is what you'll find :

"scripts": {
    "eject": "ddc eject",
    "build": "webpack",
    "start": "webpack-dev-server",
    "test": "karma start ./karma.conf.js",
    "pree2e": "webdriver-manager update --standalone false --gecko false --quiet",
    "e2e": "protractor ./protractor.conf.js"
  },

As you can see, npm start is using webpack-dev-server.

NOTE: To undo your changes, use git, otherwise AngularCli doesn't provide a way of undoing


问:
How to get the parameter from url in codeigniter?
I couldn't get the parameter value from url in codeigniter.
For instance: localhost/log/job/php here log/ is my folder, job/ is my controller and php is my parameter.

I want to get this parameter in controller 'job'.
How can I do that?

答:
Use:

```<code>$param = $this->uri->segment(3);
</code>```

add .htaccess on your folder (on your case is "log") :

```<code>RewriteEngine On
RewriteBase /log/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /log/index.php/$1 [L]
</code>```

Body:
Use:

$param = $this->uri->segment(3);

add .htaccess on your folder (on your case is "log") :

RewriteEngine On
RewriteBase /log/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /log/index.php/$1 [L]


问:
How to overload a function when you only need to change a parameter data type
I have a function SelectNext() that takes a collection parameter (of type IEnumerable) and it selects the next item in the collection and return that item.

```<code>'BaseListTypes is an Enum
Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of Object)) As Object
    Dim res As Object

   'function body here....

    Return res
End Function
</code>```

The above function works great for any List(Of T) where T is an object or string.

However it fails when I pass it a List(Of My_STRUCTURE) (custom structure I have, which contains 3 string variables)

Obviously since Structure is like integer and other base types are a value types.
While objects are reference types. I can see why I am getting an error at runtime.

My question is, is there a better way than just overloading my function into something like:

```<code>Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of My_STRUCTURE)) As Object
</code>```

答:
You can go with generic impelementation like SelectNext<T>

```<code>class Program
{
    Program()
    {
        //SelectNext_Old(new List<object>(0));  it works
        //SelectNext_Old(new List<Point>(0));   id doesn't work

        SelectNext(new List<object>(0));
        SelectNext(new List<Point>(0));
    }

    public object SelectNext_Old(BaseListTypes listType, IEnumerable<object> lst)
    {
        return null;
    }

    public object SelectNext<T>(BaseListTypes listType, IEnumerable<T> lst)
    {
        return null;
    }
}
</code>```

I dont know VB but I guess you can get the idea!

Body:
I have a function SelectNext() that takes a collection parameter (of type IEnumerable) and it selects the next item in the collection and return that item.

'BaseListTypes is an Enum
Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of Object)) As Object
    Dim res As Object

   'function body here....

    Return res
End Function

The above function works great for any List(Of T) where T is an object or string.

However it fails when I pass it a List(Of My_STRUCTURE) (custom structure I have, which contains 3 string variables)

Obviously since Structure is like integer and other base types are a value types.
While objects are reference types. I can see why I am getting an error at runtime.

My question is, is there a better way than just overloading my function into something like:

Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of My_STRUCTURE)) As Object

Body:
You can go with generic impelementation like SelectNext<T>

class Program
{
    Program()
    {
        //SelectNext_Old(new List<object>(0));  it works
        //SelectNext_Old(new List<Point>(0));   id doesn't work

        SelectNext(new List<object>(0));
        SelectNext(new List<Point>(0));
    }

    public object SelectNext_Old(BaseListTypes listType, IEnumerable<object> lst)
    {
        return null;
    }

    public object SelectNext<T>(BaseListTypes listType, IEnumerable<T> lst)
    {
        return null;
    }
}

I dont know VB but I guess you can get the idea!


问:
Don't want icons on my TabWidget
I'm still learning about Android, and while playing around with TabHost and TabWidget, I can't help but notice that there's no option to turn off the icons.

It's eating up valuable space even when I don't actually set an icon into the TabSpec. Is there any way to reduce the height of the tab bar? It's really hard to find small icons (at 3 different sizes) that perfectly fits what I intended those tabs to contain. I have zero skills with graphics.

答:
I have this:

```<code>        TabHost tabHost = getTabHost();  // The activity TabHost
</code>```

Add code to add tabs into tab host... and then finally

```<code>        tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 25;
        tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 30;
        tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = 35;
        tabHost.getTabWidget().getChildAt(3).getLayoutParams().height = 50;
</code>```

Which (if you do not have pics) results in this:

It looks like 35 is a good number.. Perhaps it needs to be changed for different dpi.

Title: Don't want icons on my TabWidget

Body:
I have this:

        TabHost tabHost = getTabHost();  // The activity TabHost

Add code to add tabs into tab host... and then finally

        tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 25;
        tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 30;
        tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = 35;
        tabHost.getTabWidget().getChildAt(3).getLayoutParams().height = 50;

Which (if you do not have pics) results in this:

It looks like 35 is a good number.. Perhaps it needs to be changed for different dpi.


问:
How to find the installed pandas version
I am having trouble with some of pandas functionalities. How do I check what is my installation version?</p>

答:
Run

```<code>pip freeze
</code>```

It works the same as above.

```<code>pip show pandas
</code>```

Displays information about a specific package.
For more information, check out pip help

Body:
Run

pip freeze

It works the same as above.

pip show pandas

Displays information about a specific package.
For more information, check out pip help


问:
Azure Container Instances stuck in "Creating" state
Whether I have the azure agent plugin for Jenkins make my container, or if I do it manually, it seems like either way it never enters a running state.

```<code>az container create \
    --os-type Windows \
    --location eastus \
    --registry-login-server SERVER.azurecr.io \
    --registry-password PASSWORD \
    --registry-username USERNAME \
    --image namespace/image \
    --name jenkins-permanent \
    --resource-group devops-aci \
    --cpu 2 \
    --memory 3.5 \
    --restart-policy Always \
    --command-line "-jnlpUrl http://host:8080/computer/NAME/slave-agent.jnlp -secret SECRET -workDir \"C:\\jenkins\""
</code>```

I've gone through all the troubleshooting steps that apply, tried a different region, but to no avail.

Here's a current event that I got which seems to be the most progress I've had yet:

```<code>          {
            "count": 1,
            "firstTimestamp": "2017-12-07T03:02:56+00:00",
            "lastTimestamp": "2017-12-07T03:02:56+00:00",
            "message": "Failed to pull image \"MYREPO.azurecr.io/my-company/windows-agent:latest\": Error response from da
emon: {\"message\":\"Get https://MYREPO.azurecr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout
exceeded while awaiting headers)\"}",
            "name": "Failed",
            "type": "Warning"
          }
</code>```

The funny thing is, this event happens before and after one case of the instance working (but unfortunately my entrypoint command was wrong, so it never started).

I really feel like Azure is punting on this and I just have no way to change the order I do anything.  It's simply one command.

答:
How big is your image? You can always debug with 2 steps.

Run az container show -g devops-aci -n jenkins-permanent. It should contain a list of container events in the container json object. The event message should give you hint what's going on.

Run az container logs -g devops-aci -n jenkins-permanent. It should give you the logs of your container. If it's a problem within your image, you should be able to see some error output.

Body:
Whether I have the azure agent plugin for Jenkins make my container, or if I do it manually, it seems like either way it never enters a running state.

az container create \
    --os-type Windows \
    --location eastus \
    --registry-login-server SERVER.azurecr.io \
    --registry-password PASSWORD \
    --registry-username USERNAME \
    --image namespace/image \
    --name jenkins-permanent \
    --resource-group devops-aci \
    --cpu 2 \
    --memory 3.5 \
    --restart-policy Always \
    --command-line "-jnlpUrl http://host:8080/computer/NAME/slave-agent.jnlp -secret SECRET -workDir \"C:\\jenkins\""

I've gone through all the troubleshooting steps that apply, tried a different region, but to no avail.

Here's a current event that I got which seems to be the most progress I've had yet:

          {
            "count": 1,
            "firstTimestamp": "2017-12-07T03:02:56+00:00",
            "lastTimestamp": "2017-12-07T03:02:56+00:00",
            "message": "Failed to pull image \"MYREPO.azurecr.io/my-company/windows-agent:latest\": Error response from da
emon: {\"message\":\"Get https://MYREPO.azurecr.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout
exceeded while awaiting headers)\"}",
            "name": "Failed",
            "type": "Warning"
          }

The funny thing is, this event happens before and after one case of the instance working (but unfortunately my entrypoint command was wrong, so it never started).

I really feel like Azure is punting on this and I just have no way to change the order I do anything.  It's simply one command.


问:
ScatterPlot doens't work properly - dots isn't connected
I am developing a project using Core-Plot with Objective-C. The client asks to create a line chart (using Scatter Plot for this) where plots the number of ocurrencies x the time.

Well, after study for almost a week, this isn't working. My dots aren't connected and I don't know why.

This blue line should've been connected, since it is one plot.

Here is my code:

```<code>-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated{
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTTheme themeNamed:kCPTDarkGradientTheme]];

graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingLeft = 20.0;

CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate              = self;

CPTMutableLineStyle *axesLineStyle = [CPTMutableLineStyle lineStyle];
axesLineStyle.lineWidth            = 1.0f;
axesLineStyle.miterLimit           = 1.0f;
axesLineStyle.lineColor            = [CPTColor grayColor];

CPTTextStyle *labelTextStyle = [CPTTextStyle textStyleWithAttributes:@{ NSForegroundColorAttributeName: BoardGraphValueColor, NSFontAttributeName: BoardGraphValueFont}];

CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
NSNumberFormatter * axisFormat = [[NSNumberFormatter alloc] init];
[axisFormat setNumberStyle:NSNumberFormatterNoStyle];
CPTXYAxis *x          = axisSet.xAxis;{
    x.visibleRange                  = [CPTPlotRange plotRangeWithLocation:@(-1.0) length:@(100)];
    x.labelingPolicy                = CPTAxisLabelingPolicyAutomatic;
    x.majorIntervalLength           = @2;
    x.minorTicksPerInterval         = 1;
    x.majorTickLineStyle            = axesLineStyle;
    x.minorTickLineStyle            = axesLineStyle;
    x.axisLineStyle                 = axesLineStyle;

    x.plotSpace                     = plotSpace;
    x.labelTextStyle                = labelTextStyle;
    x.labelFormatter                = axisFormat;
    x.labelOffset                   = 5.0;
}

CPTXYAxis *y = axisSet.yAxis;{
    y.visibleRange   = [CPTPlotRange plotRangeWithLocation:@(-1.0) length:@(200)];
    y.labelingPolicy                = CPTAxisLabelingPolicyAutomatic;
    y.majorIntervalLength           = @30;
    y.minorTicksPerInterval         = 6;
    y.majorTickLineStyle            = axesLineStyle;
    y.minorTickLineStyle            = axesLineStyle;
    y.axisLineStyle                 = axesLineStyle;

    y.plotSpace                     = plotSpace;
    y.labelTextStyle                = labelTextStyle;
    y.labelFormatter                = axisFormat;
    y.labelOffset                   = 5.0;
}

graph.axisSet.axes = @[x, y];

CPTMutableLineStyle *lineStyle = [[CPTMutableLineStyle alloc] init];
lineStyle.lineWidth = 2.0;

CPTScatterPlot *scatterLinePlot = [[CPTScatterPlot alloc] init];
scatterLinePlot.areaBaseValue = @(0.0);

scatterLinePlot.identifier = @(1);
scatterLinePlot.title = @"Title";

lineStyle.lineColor = [CPTColor blueColor];
scatterLinePlot.dataLineStyle = lineStyle;
scatterLinePlot.histogramOption = self.histogramOption;

scatterLinePlot.areaBaseValue = @(0);

scatterLinePlot.delegate                        = self;
scatterLinePlot.plotSymbolMarginForHitDetection = 5.0;
scatterLinePlot.dataSource = self;

[graph addPlot:scatterLinePlot];

CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                          length:@12.0];
plotSpace.globalYRange = globalYRange;

[plotSpace scaleToFitEntirePlots:[graph allPlots]];}
</code>```

This is the code for create just one plot, but I need to create six. I did a loop but it is working that way too.

Here's the datasource:

```<code>-(NSUInteger)numberOfRecordsForPlot:(nonnull CPTPlot *)plot{
return [self.plotData objectAtIndex:0].count;}

-(NSNumber *)numberForPlot:(nonnull CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = nil;
NSString *key;
NSArray *currentDataPoint;

NSString *plotIdentifier = (NSString *)plot.identifier;

if ([plotIdentifier isEqual:@(1)]){
    currentDataPoint = [self.plotData objectAtIndex:0];
} else if ([plotIdentifier isEqual:@(2)]){
    currentDataPoint = [self.plotData objectAtIndex:1];
} else if ([plotIdentifier isEqual:@(3)]){
    currentDataPoint = [self.plotData objectAtIndex:2];
} else if ([plotIdentifier isEqual:@(4)]){
    currentDataPoint = [self.plotData objectAtIndex:3];
} else if ([plotIdentifier isEqual:@(5)]){
    currentDataPoint = [self.plotData objectAtIndex:4];
} else if ([plotIdentifier isEqual:@(6)]){
    currentDataPoint = [self.plotData objectAtIndex:5];
}

if (fieldEnum == CPTScatterPlotFieldX) {

    return @(index);

} else if (fieldEnum == CPTScatterPlotFieldY) {

    key = @"count";
    int number = [[[currentDataPoint objectAtIndex:index] valueForKey:key] intValue];
    NSLog(@"Y value for index %lu is %d", index, number);
    num = [[currentDataPoint objectAtIndex:index] valueForKey:key];
    return num;}

return num;
}
</code>```

What am I doing wrong?

PS: Well, another bug is the color of the bar chart. Each of this should have a different color, but it doesn't work too. The colors provided is that for the legends.

Thanks in advance.

答:
To change the bar color for each bar, implement the -barFillForBarPlot:recordIndex: method in the datasource and return the correct fill for each index. You can also set the border line style for each bar (e.g., to use a different color) with the -barLineStyleForBarPlot:recordIndex: datasource method.

It looks like the data line is getting clipped outside the visible area. Make sure the plot data is available from the datasource when you call -scaleToFitEntirePlots:.

Body:
I am developing a project using Core-Plot with Objective-C. The client asks to create a line chart (using Scatter Plot for this) where plots the number of ocurrencies x the time.

Well, after study for almost a week, this isn't working. My dots aren't connected and I don't know why.

This blue line should've been connected, since it is one plot.

Here is my code:

-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated{
CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds];
[self addGraph:graph toHostingView:layerHostingView];
[self applyTheme:theme toGraph:graph withDefault:[CPTTheme themeNamed:kCPTDarkGradientTheme]];

graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingLeft = 20.0;

CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate              = self;

CPTMutableLineStyle *axesLineStyle = [CPTMutableLineStyle lineStyle];
axesLineStyle.lineWidth            = 1.0f;
axesLineStyle.miterLimit           = 1.0f;
axesLineStyle.lineColor            = [CPTColor grayColor];

CPTTextStyle *labelTextStyle = [CPTTextStyle textStyleWithAttributes:@{ NSForegroundColorAttributeName: BoardGraphValueColor, NSFontAttributeName: BoardGraphValueFont}];

CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
NSNumberFormatter * axisFormat = [[NSNumberFormatter alloc] init];
[axisFormat setNumberStyle:NSNumberFormatterNoStyle];
CPTXYAxis *x          = axisSet.xAxis;{
    x.visibleRange                  = [CPTPlotRange plotRangeWithLocation:@(-1.0) length:@(100)];
    x.labelingPolicy                = CPTAxisLabelingPolicyAutomatic;
    x.majorIntervalLength           = @2;
    x.minorTicksPerInterval         = 1;
    x.majorTickLineStyle            = axesLineStyle;
    x.minorTickLineStyle            = axesLineStyle;
    x.axisLineStyle                 = axesLineStyle;

    x.plotSpace                     = plotSpace;
    x.labelTextStyle                = labelTextStyle;
    x.labelFormatter                = axisFormat;
    x.labelOffset                   = 5.0;
}

CPTXYAxis *y = axisSet.yAxis;{
    y.visibleRange   = [CPTPlotRange plotRangeWithLocation:@(-1.0) length:@(200)];
    y.labelingPolicy                = CPTAxisLabelingPolicyAutomatic;
    y.majorIntervalLength           = @30;
    y.minorTicksPerInterval         = 6;
    y.majorTickLineStyle            = axesLineStyle;
    y.minorTickLineStyle            = axesLineStyle;
    y.axisLineStyle                 = axesLineStyle;

    y.plotSpace                     = plotSpace;
    y.labelTextStyle                = labelTextStyle;
    y.labelFormatter                = axisFormat;
    y.labelOffset                   = 5.0;
}

graph.axisSet.axes = @[x, y];

CPTMutableLineStyle *lineStyle = [[CPTMutableLineStyle alloc] init];
lineStyle.lineWidth = 2.0;

CPTScatterPlot *scatterLinePlot = [[CPTScatterPlot alloc] init];
scatterLinePlot.areaBaseValue = @(0.0);

scatterLinePlot.identifier = @(1);
scatterLinePlot.title = @"Title";

lineStyle.lineColor = [CPTColor blueColor];
scatterLinePlot.dataLineStyle = lineStyle;
scatterLinePlot.histogramOption = self.histogramOption;

scatterLinePlot.areaBaseValue = @(0);

scatterLinePlot.delegate                        = self;
scatterLinePlot.plotSymbolMarginForHitDetection = 5.0;
scatterLinePlot.dataSource = self;

[graph addPlot:scatterLinePlot];

CPTPlotRange *globalYRange = [CPTPlotRange plotRangeWithLocation:@0.0
                                                          length:@12.0];
plotSpace.globalYRange = globalYRange;

[plotSpace scaleToFitEntirePlots:[graph allPlots]];}

This is the code for create just one plot, but I need to create six. I did a loop but it is working that way too.

Here's the datasource:

-(NSUInteger)numberOfRecordsForPlot:(nonnull CPTPlot *)plot{
return [self.plotData objectAtIndex:0].count;}

-(NSNumber *)numberForPlot:(nonnull CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = nil;
NSString *key;
NSArray *currentDataPoint;

NSString *plotIdentifier = (NSString *)plot.identifier;

if ([plotIdentifier isEqual:@(1)]){
    currentDataPoint = [self.plotData objectAtIndex:0];
} else if ([plotIdentifier isEqual:@(2)]){
    currentDataPoint = [self.plotData objectAtIndex:1];
} else if ([plotIdentifier isEqual:@(3)]){
    currentDataPoint = [self.plotData objectAtIndex:2];
} else if ([plotIdentifier isEqual:@(4)]){
    currentDataPoint = [self.plotData objectAtIndex:3];
} else if ([plotIdentifier isEqual:@(5)]){
    currentDataPoint = [self.plotData objectAtIndex:4];
} else if ([plotIdentifier isEqual:@(6)]){
    currentDataPoint = [self.plotData objectAtIndex:5];
}

if (fieldEnum == CPTScatterPlotFieldX) {

    return @(index);

} else if (fieldEnum == CPTScatterPlotFieldY) {

    key = @"count";
    int number = [[[currentDataPoint objectAtIndex:index] valueForKey:key] intValue];
    NSLog(@"Y value for index %lu is %d", index, number);
    num = [[currentDataPoint objectAtIndex:index] valueForKey:key];
    return num;}

return num;
}

What am I doing wrong?

PS: Well, another bug is the color of the bar chart. Each of this should have a different color, but it doesn't work too. The colors provided is that for the legends.

Thanks in advance.


问:
JQuery jScrollPane reinitialise
I'm using the JQuery plugin jScrollPane

I'm intialising it as follows.. It works initially but when I try and change the settings and reinitialise it it doesnt work properly it kindof flickers and then returns to it's previous state, any ideas?

```<code>$(document).ready(function() {
     var api = $('.viewer').jScrollPane().data('jsp');
     api.reinitialise({
         showArrows: true
     });
});
</code>```

Here is my test example

http://www.jsfiddle.net/VxYdJ/

Thanks

答:
It looks like this is a known issue with jScrollPane.  You could modify the source code as one commenter describes in the link above:

```<code>reinitialise: function(s)
{
    s = $.extend({}, settings, s);
    initialise(s);
},
</code>```

That seems to fix the problem: http://www.jsfiddle.net/pNvky/ (The ton of code up front is just the modified plugin)

Title: JQuery jScrollPane reinitialise

Body:
I'm using the JQuery plugin jScrollPane

I'm intialising it as follows.. It works initially but when I try and change the settings and reinitialise it it doesnt work properly it kindof flickers and then returns to it's previous state, any ideas?

$(document).ready(function() {
     var api = $('.viewer').jScrollPane().data('jsp');
     api.reinitialise({
         showArrows: true
     });
});

Here is my test example

http://www.jsfiddle.net/VxYdJ/

Thanks

Body:
It looks like this is a known issue with jScrollPane.  You could modify the source code as one commenter describes in the link above:

reinitialise: function(s)
{
    s = $.extend({}, settings, s);
    initialise(s);
},

That seems to fix the problem: http://www.jsfiddle.net/pNvky/ (The ton of code up front is just the modified plugin)


问:
Java Web Service get smtp email address format
I have a java web service.  The underlying notes db has a form that has a field that is of type "names".  There is a view that is defined that contains a list of all these names.  In the web service there is a function defined returns the email address of the person, given their name.  We recently migrated our email from LotusNotes to outlook so we need this routine to return the email addresses in standard smtp format (jdoe@domain.com)  instead of canonical format.  The current code is below:

public String getSalespersonCommonName(String salesperson) throws Exception {

```<code>    try
    {
        View salespersonView;
        DocumentCollection docs;

        d = s.getCurrentDatabase();

        if (d != null) {
            // get the salesperson
            salespersonView = d.getView("vAllSalespersons");

            docs = salespersonView.getAllDocumentsByKey(salesperson);

            if (docs.getCount() > 0)
            {
                doc = docs.getFirstDocument();

                return doc.getItemValueString("Salesperson");

            } else {
                return "";
            }

        } else {
            return "";
        }

    } catch (Exception e) {
        throw e;
    }

}
</code>```

答:
You will need to look up the user by name in the Domino Directory and get the SMTP address from there. The Directory.LookupNames() method is the "official" way to do this since it works automatically with multiple directories, but I've seen lots of implementations that directly access a view in names.nsf.

But first, you will have to make sure that the user's Outlook SMTP address has actually been entered into the Domino Directory, and you will have to know which field it has been entered into. If the Outlook SMTP address is different from their old Domino SMTP address, it's fairly common practice to enter the Outlook address in the forwarding address field.

Body:
I have a java web service.  The underlying notes db has a form that has a field that is of type "names".  There is a view that is defined that contains a list of all these names.  In the web service there is a function defined returns the email address of the person, given their name.  We recently migrated our email from LotusNotes to outlook so we need this routine to return the email addresses in standard smtp format (jdoe@domain.com)  instead of canonical format.  The current code is below:

public String getSalespersonCommonName(String salesperson) throws Exception {

    try
    {
        View salespersonView;
        DocumentCollection docs;

        d = s.getCurrentDatabase();

        if (d != null) {
            // get the salesperson
            salespersonView = d.getView("vAllSalespersons");

            docs = salespersonView.getAllDocumentsByKey(salesperson);

            if (docs.getCount() > 0)
            {
                doc = docs.getFirstDocument();

                return doc.getItemValueString("Salesperson");

            } else {
                return "";
            }

        } else {
            return "";
        }

    } catch (Exception e) {
        throw e;
    }

}


问:
FCM Function - Recive Notification
I'm developing a social network app and users can follow/unfollow together. How can receive notification from firebase cloud functions when X following A like instagram?

My index.js deployed on firebase

my index.js codes

My Project Appdelegate:

```<code>import UIKit
import Firebase
import UserNotifications

   @UIApplicationMain
 class AppDelegate: UIResponder,
UIApplicationDelegate,UNUserNotificationCenterDelegate,
MessagingDelegate {
 func messaging(_ messaging: Messaging, didRefreshRegistrationToken
 fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UITabBar.appearance().tintColor = .white

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    FirebaseApp.configure()

    let token = Messaging.messaging().fcmToken
    print("FCM token: \(token ?? "")")

    return true

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }
    print("Registration succeeded! Token: ", token)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Registration failed!")
}

func application(_ application: UIApplication,didReceiveRemoteNotification notification: [AnyHashable:Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification){
        completionHandler(UIBackgroundFetchResult.noData)
    }

    // This notification is not auth related, developer should handle it.
}

func applicationDidBecomeActive(_ application: UIApplication) {

    //YFVolumeView.current.updateActiveState()
}

// Firebase notification received
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

    // custom code to handle push while app is in the foreground
    print("Handle push from foreground\(notification.request.content.userInfo)")

    let dict = notification.request.content.userInfo["aps"] as! NSDictionary
    let d : [String : Any] = dict["alert"] as! [String : Any]
    let body : String = d["body"] as! String
    let title : String = d["title"] as! String
    print("Title:\(title) + body:\(body)")
    self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}

func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
    window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here

 }
</code>```

everything like ok but when X followed A, on my device don't receive any notification!

答:
I think that you are using wrong token

 FMC using sprecial its token

 When you received ios Token in didRegisterForRemoteNotificationsWithDeviceToken, you will received FCM token with

let fcmToken = Messaging.messaging().fcmToken

let apnsToken = Messaging.messaging().apnsToken

 Using fcmToken and FCM will send notification to your device

 Hope this help

Title: FCM Function - Recive Notification

Body:
I'm developing a social network app and users can follow/unfollow together. How can receive notification from firebase cloud functions when X following A like instagram?

My index.js deployed on firebase

my index.js codes

My Project Appdelegate:

import UIKit
import Firebase
import UserNotifications

   @UIApplicationMain
 class AppDelegate: UIResponder,
UIApplicationDelegate,UNUserNotificationCenterDelegate,
MessagingDelegate {
 func messaging(_ messaging: Messaging, didRefreshRegistrationToken
 fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UITabBar.appearance().tintColor = .white

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    FirebaseApp.configure()

    let token = Messaging.messaging().fcmToken
    print("FCM token: \(token ?? "")")

    return true

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }
    print("Registration succeeded! Token: ", token)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Registration failed!")
}

func application(_ application: UIApplication,didReceiveRemoteNotification notification: [AnyHashable:Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification){
        completionHandler(UIBackgroundFetchResult.noData)
    }

    // This notification is not auth related, developer should handle it.
}

func applicationDidBecomeActive(_ application: UIApplication) {

    //YFVolumeView.current.updateActiveState()
}

// Firebase notification received
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

    // custom code to handle push while app is in the foreground
    print("Handle push from foreground\(notification.request.content.userInfo)")

    let dict = notification.request.content.userInfo["aps"] as! NSDictionary
    let d : [String : Any] = dict["alert"] as! [String : Any]
    let body : String = d["body"] as! String
    let title : String = d["title"] as! String
    print("Title:\(title) + body:\(body)")
    self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}

func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
    window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here

 }

everything like ok but when X followed A, on my device don't receive any notification!


问:
scala: how to make a superclass' variable implicit in the scope of the subclass
Imagine I had some function that takes a String explicitly and an T implicitly:

```<code>object SomeNamespace {
  def myFunction(arg: String)(implicit t: T)
}
</code>```

And I had a superclass which provides the T

```<code>trait TProvider {
  val t: T = ...
}
</code>```

And in a subclass I use extends TProvider and try to use the function

```<code>class Child extends TProvider {
   SomeNamespace.myFunction("somestring")
}
</code>```

I would get an error "could not find implicit value for parameter t". My workaround is to reassign the superclass val to a new implicit one in the subclass like:

```<code> implicit val subclassImplicitT = t
</code>```

and that works ... but is kind of ugly. Is there some better way to "implicitify" a variable?

答:
Eh... "implicitifying" something after it has already been declared is not really easy to do in Scala. Honestly either just passing it in as an explicit parameter is probably your best bet. Here's an alternative that is marginally nicer at best.</p>

```<code>trait TProvider {
  // Yep it's gotta be a def for this to work, not a val,
  // because you can't call super.t if t is a val
  // (https://issues.scala-lang.org/browse/SI-1938)
  def t: T
}

class Child extends TProvider {
  // You can override it as a val though
  override implicit val t = super.t

  myFunction("something")
}
</code>```

Body:
Imagine I had some function that takes a String explicitly and an T implicitly:

object SomeNamespace {
  def myFunction(arg: String)(implicit t: T)
}

And I had a superclass which provides the T

trait TProvider {
  val t: T = ...
}

And in a subclass I use extends TProvider and try to use the function

class Child extends TProvider {
   SomeNamespace.myFunction("somestring")
}

I would get an error "could not find implicit value for parameter t". My workaround is to reassign the superclass val to a new implicit one in the subclass like:

 implicit val subclassImplicitT = t

and that works ... but is kind of ugly. Is there some better way to "implicitify" a variable?

Body:
Eh... "implicitifying" something after it has already been declared is not really easy to do in Scala. Honestly either just passing it in as an explicit parameter is probably your best bet. Here's an alternative that is marginally nicer at best.

trait TProvider {
  // Yep it's gotta be a def for this to work, not a val,
  // because you can't call super.t if t is a val
  // (https://issues.scala-lang.org/browse/SI-1938)
  def t: T
}

class Child extends TProvider {
  // You can override it as a val though
  override implicit val t = super.t

  myFunction("something")
}


问:
Retain powershell session to Office 365 between commands
I am trying to put together a simple app using PowerShell forms, with buttons to run commands against an Office 365 tenant.

The first button they need to hit connects them to Azure AD, then the other buttons will run the commands.

The problem I have is maintaining the PS session. The form loads, I press the button to kick of the Connect-AzureAD command and it connects fine. Then when I press another button to run another command such as get-msoluser it complains I am not connected to Azure AD.

So how do I use the session I have established from the first button click? I want to connect once when I first load the app and keep that connection for all actions I perform until I close the form.

答:
Connect-AzureAD is a cmdlet of Azure AD V2 Powershell, Get-MsolUser is a cmdlet of MSOnline PowerShell 1.0.

They are two different cmdlet for two module.Before using Get-MsolUser, you must call the Connect-MsolService cmdlet before calling any other cmdlets.

If you want to use both Azure AD V2 Powershell and MSOline Powershell 1.0, you must use  Connect-AzureAD and Connect-MsolService first.