问:
Apache POI rate formula not working if data is big
Rate Formula is not working as expected for big values...

RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0)  in physical file it returns 0.05819488005

if the same formula we tried to set through POI   returns 0.009056339275922086..

Even we tried to save the excel and open same 0.009056339275922086 is returned..

Code used to set in POI :

```<code>XSSFWorkbook workbook = new XSSFWorkbook();
XSSFRow  row = sheet.createRow(1);
XSSFCell  cell = row.createCell(1);
cell.setCellType(CellType.NUMERIC);
cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0)");
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateInCell(cell);
cell.getNumericCellValue();
</code>```

答:
The Rate function of apache poi states that it "// find root by Newton secant method". That's nonsense since Secant method is only a Quasi-Newton method. And "If the initial values are not close enough to the root, then there is no guarantee that the secant method converges.".

So the default guess of 0.1 seems not "close enough" and so if we are using cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.06)"); - note the explicit setting of type and guess properties and having the  guess property "close enough" to the result of 0.05819488005- then the formula evaluates properly.

If apache poi really would use Newton's method, then the function would evaluate properly also using the default guess of 0.1. The disadvantage of Newton's method is that it requires the evaluation of both f and its derivative f′ at every step. So it may be slower than the Secant method in some cases.

Example:

```<code>import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class ExcelRATEFunction {

 private static double calculateRateNewton(double nper, double pmt, double pv, double fv, double type, double guess) {

  int FINANCIAL_MAX_ITERATIONS = 20;
  double FINANCIAL_PRECISION = 0.0000001;

  double y, y1, xN = 0, f = 0, i = 0;

  double rate = guess;

  //find root by Newtons method (https://en.wikipedia.org/wiki/Newton%27s_method), not secant method!
  //Formula see: https://wiki.openoffice.org/wiki/Documentation/How_Tos/Calc:_Derivation_of_Financial_Formulas#PV.2C_FV.2C_PMT.2C_NPER.2C_RATE

  f = Math.pow(1 + rate, nper);
  y = pv * f + pmt * ((f - 1) / rate) * (1 + rate * type) + fv;

  //first derivative:
  //y1 = (pmt * nper * type * Math.pow(rate,2) * f - pmt * f - pmt * rate * f + pmt * nper * rate * f + pmt * rate + pmt + nper * pv * Math.pow(rate,2) * f) / (Math.pow(rate,2) * (rate+1));
  y1 = (f * ((pmt * nper * type + nper * pv) * Math.pow(rate,2) + (pmt * nper - pmt) * rate - pmt) + pmt * rate + pmt) / (Math.pow(rate,3) + Math.pow(rate,2));

  xN = rate - y/y1;

  while ((Math.abs(rate - xN) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) {

   rate = xN;

   f = Math.pow(1 + rate, nper);
   y = pv * f + pmt * ((f - 1) / rate) * (1 + rate * type) + fv;

   //first derivative:
   //y1 = (pmt * nper * type * Math.pow(rate,2) * f - pmt * f - pmt * rate * f + pmt * nper * rate * f + pmt * rate + pmt + nper * pv * Math.pow(rate,2) * f) / (Math.pow(rate,2) * (rate+1));
   y1 = (f * ((pmt * nper * type + nper * pv) * Math.pow(rate,2) + (pmt * nper - pmt) * rate - pmt) + pmt * rate + pmt) / (Math.pow(rate,3) + Math.pow(rate,2));

   xN = rate - y/y1;
   ++i;

   System.out.println(rate+", "+xN+", "+y+", "+y1);
  }

  rate = xN;
  return rate;

 }

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet();
  Row  row = sheet.createRow(1);
  Cell  cell = row.createCell(1);

  cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.06)");
  FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  CellType celltype = evaluator.evaluateFormulaCellEnum(cell);

  double value = 0.0;
  if (celltype == CellType.NUMERIC) {
   value = cell.getNumericCellValue();
   System.out.println(value);
  }

  workbook.setForceFormulaRecalculation(true);

  value = calculateRateNewton(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.1);
  System.out.println(value);

  workbook.write(new FileOutputStream("ExcelRATEFunction.xlsx"));
  workbook.close();

 }

}
</code>```

Body:
Rate Formula is not working as expected for big values...

RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0)  in physical file it returns 0.05819488005

if the same formula we tried to set through POI   returns 0.009056339275922086..

Even we tried to save the excel and open same 0.009056339275922086 is returned..

Code used to set in POI :

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFRow  row = sheet.createRow(1);
XSSFCell  cell = row.createCell(1);
cell.setCellType(CellType.NUMERIC);
cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0)");
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateInCell(cell);
cell.getNumericCellValue();

Body:
The Rate function of apache poi states that it "// find root by Newton secant method". That's nonsense since Secant method is only a Quasi-Newton method. And "If the initial values are not close enough to the root, then there is no guarantee that the secant method converges.".

So the default guess of 0.1 seems not "close enough" and so if we are using cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.06)"); - note the explicit setting of type and guess properties and having the  guess property "close enough" to the result of 0.05819488005- then the formula evaluates properly.

If apache poi really would use Newton's method, then the function would evaluate properly also using the default guess of 0.1. The disadvantage of Newton's method is that it requires the evaluation of both f and its derivative f′ at every step. So it may be slower than the Secant method in some cases.

Example:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class ExcelRATEFunction {

 private static double calculateRateNewton(double nper, double pmt, double pv, double fv, double type, double guess) {

  int FINANCIAL_MAX_ITERATIONS = 20;
  double FINANCIAL_PRECISION = 0.0000001;

  double y, y1, xN = 0, f = 0, i = 0;

  double rate = guess;

  //find root by Newtons method (https://en.wikipedia.org/wiki/Newton%27s_method), not secant method!
  //Formula see: https://wiki.openoffice.org/wiki/Documentation/How_Tos/Calc:_Derivation_of_Financial_Formulas#PV.2C_FV.2C_PMT.2C_NPER.2C_RATE

  f = Math.pow(1 + rate, nper);
  y = pv * f + pmt * ((f - 1) / rate) * (1 + rate * type) + fv;

  //first derivative:
  //y1 = (pmt * nper * type * Math.pow(rate,2) * f - pmt * f - pmt * rate * f + pmt * nper * rate * f + pmt * rate + pmt + nper * pv * Math.pow(rate,2) * f) / (Math.pow(rate,2) * (rate+1));
  y1 = (f * ((pmt * nper * type + nper * pv) * Math.pow(rate,2) + (pmt * nper - pmt) * rate - pmt) + pmt * rate + pmt) / (Math.pow(rate,3) + Math.pow(rate,2));

  xN = rate - y/y1;

  while ((Math.abs(rate - xN) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) {

   rate = xN;

   f = Math.pow(1 + rate, nper);
   y = pv * f + pmt * ((f - 1) / rate) * (1 + rate * type) + fv;

   //first derivative:
   //y1 = (pmt * nper * type * Math.pow(rate,2) * f - pmt * f - pmt * rate * f + pmt * nper * rate * f + pmt * rate + pmt + nper * pv * Math.pow(rate,2) * f) / (Math.pow(rate,2) * (rate+1));
   y1 = (f * ((pmt * nper * type + nper * pv) * Math.pow(rate,2) + (pmt * nper - pmt) * rate - pmt) + pmt * rate + pmt) / (Math.pow(rate,3) + Math.pow(rate,2));

   xN = rate - y/y1;
   ++i;

   System.out.println(rate+", "+xN+", "+y+", "+y1);
  }

  rate = xN;
  return rate;

 }

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet();
  Row  row = sheet.createRow(1);
  Cell  cell = row.createCell(1);

  cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.06)");
  FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  CellType celltype = evaluator.evaluateFormulaCellEnum(cell);

  double value = 0.0;
  if (celltype == CellType.NUMERIC) {
   value = cell.getNumericCellValue();
   System.out.println(value);
  }

  workbook.setForceFormulaRecalculation(true);

  value = calculateRateNewton(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.1);
  System.out.println(value);

  workbook.write(new FileOutputStream("ExcelRATEFunction.xlsx"));
  workbook.close();

 }

}


来源: stackexchange

问:
c# Split string using another string as delimiter and include delimiter as part of the splitted string
I need to split an input string using c# regex.
need to know how to include the delimiter content in the output as given below.

input:

```<code>string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimters = new string[] {"heading1:","heading2:","heading3:"};
</code>```

Expected output:

```<code>outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings
</code>```

What I tried:

```<code>var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);
</code>```

Output I got:

```<code>result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"
</code>```

I couldnt find an API in string.split or in Regex to split as the expect result.

答:
You may use a positive lookahead based solution:

```<code>var result = Regex.Split(content, $@"(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})")
                  .Where(x => !string.IsNullOrEmpty(x))
</code>```

See the C# demo:

```<code>var content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";
var delimiters = new string[] {"heading1:","heading2:","heading3:"};
Console.WriteLine(
    string.Join("\n",
        Regex.Split(content, $@"(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})")
             .Where(x => !string.IsNullOrEmpty(x))
    )
);
</code>```

Output:

```<code>heading1: contents with respect to heading1
heading2: heading2 contents
heading3: heading 3 related contents sample strings
</code>```

The (?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))}) will construct a regex dynamically, it will look like

```<code>(?=heading1:|heading2:|heading3:)
</code>```

See the regex demo. The pattern will basically match any position in the string that is followed with either herring1:,  herring2: or herring3: without consuming these substrings, so they will land in the output.

Note that delimiters.Select(m => Regex.Escape(m)) is there to make sure all special regex metacharacters that might be in the delimiters are escaped and treated as literal chars by the regex engine.

ContentLicense: CC BY-SA 3.0

Body:
I need to split an input string using c# regex.
need to know how to include the delimiter content in the output as given below.

input:

string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimters = new string[] {"heading1:","heading2:","heading3:"};

Expected output:

outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings

What I tried:

var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);

Output I got:

result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"

I couldnt find an API in string.split or in Regex to split as the expect result.

Body:
You may use a positive lookahead based solution:

var result = Regex.Split(content, $@"(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})")
                  .Where(x => !string.IsNullOrEmpty(x))

See the C# demo:

var content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";
var delimiters = new string[] {"heading1:","heading2:","heading3:"};
Console.WriteLine(
    string.Join("\n",
        Regex.Split(content, $@"(?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))})")
             .Where(x => !string.IsNullOrEmpty(x))
    )
);

Output:

heading1: contents with respect to heading1
heading2: heading2 contents
heading3: heading 3 related contents sample strings

The (?={string.Join("|", delimiters.Select(m => Regex.Escape(m)))}) will construct a regex dynamically, it will look like

(?=heading1:|heading2:|heading3:)

See the regex demo. The pattern will basically match any position in the string that is followed with either herring1:,  herring2: or herring3: without consuming these substrings, so they will land in the output.

Note that delimiters.Select(m => Regex.Escape(m)) is there to make sure all special regex metacharacters that might be in the delimiters are escaped and treated as literal chars by the regex engine.


问:
Kotlin - Sort maps collection
I have a function

```<code>fun init(properties: Collection<Map<Any, Any>>?) {
    properties?.filter { it.isNotEmpty() }
}
</code>```

I need to filter out empty maps.

I only need maps which have keys and values of type String.

For the remaining maps, I want to iterate the keys to get the values.

答:
You can use .all { ... } to check that all .keys and .values are Strings:

```<code>properties
    ?.filter {
        it.isNotEmpty() &&
        it.keys.all { key -> key is String } &&
        it.values.all { value -> value is String }
    }
    ?.forEach { /* do some stuff with it */ }
</code>```

Note that you will still need an unchecked cast to operate on the filtered maps as Map<String, String>, because the compiler cannot infer the type from the keys and values check.

ContentLicense: CC BY-SA 4.0

Title: Kotlin - Sort maps collection

Body:
I have a function

fun init(properties: Collection<Map<Any, Any>>?) {
    properties?.filter { it.isNotEmpty() }
}

I need to filter out empty maps.

I only need maps which have keys and values of type String.

For the remaining maps, I want to iterate the keys to get the values.

Body:
You can use .all { ... } to check that all .keys and .values are Strings:

properties
    ?.filter {
        it.isNotEmpty() &&
        it.keys.all { key -> key is String } &&
        it.values.all { value -> value is String }
    }
    ?.forEach { /* do some stuff with it */ }

Note that you will still need an unchecked cast to operate on the filtered maps as Map<String, String>, because the compiler cannot infer the type from the keys and values check.


问:
PHP Sending Automated Mail That Doesn't Goto The SPAM Folder?
I've always been a little troubled when it comes to sending mail through PHP functions.
But it hasn't really been a problem until my latest project.

I'm looking for the absolute best way of sending mail through PHP and not having it end up in the SPAM folder :/

I'm aware that it won't probably work 100% of the time,
I'm just looking for the best option.

Thanks :)

答:
The number one reason mail usually ends up in the SPAM folder (when the content isn't actually spammy) is that the From: header isn't set or is set to a non-existant email address. If the header is empty the message will appear to come from something like webmaster@localdomain.

In the mail() call (refer to the docs) be sure to populate the $additional_headers field like:

```<code>mail('to@example.com', 'Subject', 'Body text...',
             'From: me@realaddress.com');
</code>```

That should get you past almost all spam filters -- assuming you're not actually sending out spammy content! :)

ContentLicense: CC BY-SA 2.5

Body:
The number one reason mail usually ends up in the SPAM folder (when the content isn't actually spammy) is that the From: header isn't set or is set to a non-existant email address. If the header is empty the message will appear to come from something like webmaster@localdomain.

In the mail() call (refer to the docs) be sure to populate the $additional_headers field like:

mail('to@example.com', 'Subject', 'Body text...',
             'From: me@realaddress.com');

That should get you past almost all spam filters -- assuming you're not actually sending out spammy content! :)


问:
Chart Js update legend boxes of graph with graph line style
I want to update legend boxes of my graphs with graph line style.

Actual Consumption  Average Use

Below is my code, but legend label image is not updating. Can anyone help me?

```<code>var ctx = document.getElementById("myChart");
this.myChart = new Chart(ctx,  {
    type: 'line',
    data: {
        labels: ["Jan", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Actual Consumption',
            data:[24, 49, 6, 7, 21, 6],
            backgroundColor: [
                'rgba(225,225,225,0)'
            ],
            borderColor: [
                'rgba(53,91,183,1)'
            ],
            borderWidth: 2.2,
            pointStyle: 'circle',
        },{
            label: 'Average Use ',
            data:[4, 12, 2, 17, 22, 2],
            backgroundColor: [
                'rgba(225,225,225,0)'
            ],
            borderColor: [
                'rgba(230,104,38,1)'

            ],
            borderWidth: 2.2,
            pointStyle: 'rect',

        },{
            label: 'Total Use',
            data:this.data,
            backgroundColor: [
                'rgba(225,225,225,0)'
            ],
            borderColor: [
                'rgba(148,148,148,1)'
            ] ,
            borderWidth: 2.2,
            pointStyle: 'triangle',

        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        **legend: {
            cursor : "pointer",
            useLineStyle: true,
            labels: {
                fontColor: '#000000'
             }
        }**
    }
});
</code>```

答:
There's a legend option called "usePointStyle" that should match the legend style to the style of the graph point.

```<code>legend: {
  labels: {
    usePointStyle: true
  }
}
</code>```

If that doesn't solve your issue, you may have to use the "legendCallback" to create a custom HTML legend.

Body:
I want to update legend boxes of my graphs with graph line style.

Actual Consumption  Average Use

Below is my code, but legend label image is not updating. Can anyone help me?

var ctx = document.getElementById("myChart");
this.myChart = new Chart(ctx,  {
    type: 'line',
    data: {
        labels: ["Jan", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Actual Consumption',
            data:[24, 49, 6, 7, 21, 6],
            backgroundColor: [
                'rgba(225,225,225,0)'
            ],
            borderColor: [
                'rgba(53,91,183,1)'
            ],
            borderWidth: 2.2,
            pointStyle: 'circle',
        },{
            label: 'Average Use ',
            data:[4, 12, 2, 17, 22, 2],
            backgroundColor: [
                'rgba(225,225,225,0)'
            ],
            borderColor: [
                'rgba(230,104,38,1)'

            ],
            borderWidth: 2.2,
            pointStyle: 'rect',

        },{
            label: 'Total Use',
            data:this.data,
            backgroundColor: [
                'rgba(225,225,225,0)'
            ],
            borderColor: [
                'rgba(148,148,148,1)'
            ] ,
            borderWidth: 2.2,
            pointStyle: 'triangle',

        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        **legend: {
            cursor : "pointer",
            useLineStyle: true,
            labels: {
                fontColor: '#000000'
             }
        }**
    }
});

Body:
There's a legend option called "usePointStyle" that should match the legend style to the style of the graph point.

legend: {
  labels: {
    usePointStyle: true
  }
}

If that doesn't solve your issue, you may have to use the "legendCallback" to create a custom HTML legend.


问:
Running SQL batches separated by GO in transaction from Powershell
I need to run the contents of sql file against the server inside transaction. The file contains batches separated by GO statements, so T-SQL TRY-CATCH ROLLBACK is no go.

The Invoke-Sqlcmd -InputFile works perfectly, except while used in conjunction with System.Transactions.TransactionScope the exception states only that transaction was aborted, not outputing useful info (checked inner exceptions, nothing).

So I tried using System.Data.SqlClient.SqlConnection transaction in conjunction with System.Data.SqlClient.SqlCommand, which works great, but chokes on GO statements.

The optimal solution sems to be to use Microsoft.SqlServer.Management.Smo.Server object, but I have a weird problem, that it treats every line as separate batch.

The code:

```<code>$server = New-Object Microsoft.SqlServer.Management.Smo.Server($databaseServer)
$server.ConnectionContext.ConnectionString = $connectionString

$script = Get-Content "$sqlScriptsPath\$scriptName.sql"
try
{
   $server.ConnectionContext.BeginTransaction()
   $server.ConnectionContext.ExecuteNonQuery($script)
   $server.ConnectionContext.CommitTransaction()
}
catch
{
   $server.ConnectionContext.RollBackTransaction()
   throw
}
</code>```

When the file consists only of single line statements (i'm testing it with inserts), it works ok, but whenever the command is multiline, it chokes outputing something like "Incorrect syntax near ')'." or something, depending on the context.

ex.:

```<code>DECLARE @msg varchar(50) = 'test'
PRINT @msg
</code>```

will throw "Must declare the scalar variable "@msg"."

But when the file has both commands in one line separated by ';' it works.

I tried the obvious: $server.ConnectionContext.BatchSeparator = 'GO' but it changes nothing, as 'GO' is already the default separator.

答:
The issue is that the cmdlet Get-Content used without -Raw flag returns an array of lines.

Solution:

```<code>$script = Get-Content "$sqlScriptsPath\$scriptName.sql" -Raw
</code>```

Body:
I need to run the contents of sql file against the server inside transaction. The file contains batches separated by GO statements, so T-SQL TRY-CATCH ROLLBACK is no go.

The Invoke-Sqlcmd -InputFile works perfectly, except while used in conjunction with System.Transactions.TransactionScope the exception states only that transaction was aborted, not outputing useful info (checked inner exceptions, nothing).

So I tried using System.Data.SqlClient.SqlConnection transaction in conjunction with System.Data.SqlClient.SqlCommand, which works great, but chokes on GO statements.

The optimal solution sems to be to use Microsoft.SqlServer.Management.Smo.Server object, but I have a weird problem, that it treats every line as separate batch.

The code:

$server = New-Object Microsoft.SqlServer.Management.Smo.Server($databaseServer)
$server.ConnectionContext.ConnectionString = $connectionString

$script = Get-Content "$sqlScriptsPath\$scriptName.sql"
try
{
   $server.ConnectionContext.BeginTransaction()
   $server.ConnectionContext.ExecuteNonQuery($script)
   $server.ConnectionContext.CommitTransaction()
}
catch
{
   $server.ConnectionContext.RollBackTransaction()
   throw
}

When the file consists only of single line statements (i'm testing it with inserts), it works ok, but whenever the command is multiline, it chokes outputing something like "Incorrect syntax near ')'." or something, depending on the context.

ex.:

DECLARE @msg varchar(50) = 'test'
PRINT @msg

will throw "Must declare the scalar variable "@msg"."

But when the file has both commands in one line separated by ';' it works.

I tried the obvious: $server.ConnectionContext.BatchSeparator = 'GO' but it changes nothing, as 'GO' is already the default separator.

Body:
The issue is that the cmdlet Get-Content used without -Raw flag returns an array of lines.

Solution:

$script = Get-Content "$sqlScriptsPath\$scriptName.sql" -Raw


问:
How to disable auto hide the solution explorer (Visual Studio 2017)
How to disable auto hide solution explorer (Visual Studio 2017)?

Every time after launching the project, the solution explorer does autohide.

How disable it?

答:
There is a separate window layout when debugging.

Just configure tool windows (like solution explorer) how you would like them while debugging. It will be remembered the next time you start debugging.

(Typically there are many tool windows – eg. locals, call stack – that only make sense while debugging, hence the separate layout.)

If a tool window is auto hiding, click on the pin icon in its title to stop it auto hiding. Do this before exiting the debugger to include in the debugging window layout.


问:
Python how to store "\" inside an arrey to use in a subprocess.call bash command
i have a python program that creates a bash command and then uses it in subprocess.call(command)

i wand to send it a file location with spaces.

```<code>import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  "\\ is"
subprocess.call(command)
</code>```

but when it is used by subprocess it becomes a new directory with the name
 this\ is

this is the full code

```<code>import pyxhook
import subprocess

command = [""]
isActive = False
element = 0
isSpace = False

def OnKeyPress(event):
    global command
    global isActive
    global element
    global isSpace
    if event.Ascii == 96:
        if isActive == False:
            isActive = True
        elif isActive == True:
            subprocess.call(command)
            command = [""]
            element = 0
            isActive = False
    elif isActive == True:
        if event.Ascii == 32:
            if isSpace == False:
                command.append("")
                element += 1
            else:
                command[element] += " "
                isSpace = False
        elif event.Key == "BackSpace":
            command[element] = command[element][:-1]
        elif event.Key == "slash":
            command[element] += "/"
        elif event.Key == "Shift_L" :
            command = command
        elif event.Key =="Shift_R":
            command = command
        elif event.Key == "backslash":
            isSpace = True
            command[element] +=  "\\"
        else:
            command[element] += (event.Key)

#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()
</code>```

答:
Pay attention to your command list and how you're appending things:</p>

```<code>$ python
Python 2.7.10 (default, Feb  7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> command = ["mkdir", "/home/matt/Desktop/this"]
>>> command[0] +=  "\\ is"
>>> command
['mkdir\\ is', '/home/matt/Desktop/this']
>>> command = ["mkdir", "/home/matt/Desktop/this"]
>>> command[-1]
'/home/matt/Desktop/this'
>>> command[-1] += " is"
>>> command
['mkdir', '/home/matt/Desktop/this is']
>>> subprocess.call(command)
0
>>> import glob
>>> glob.glob("/home/matt/Desktop/th*")
['/home/matt/Desktop/this is']
>>>
</code>```

Body:
i have a python program that creates a bash command and then uses it in subprocess.call(command)

i wand to send it a file location with spaces.

import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  "\\ is"
subprocess.call(command)

but when it is used by subprocess it becomes a new directory with the name
 this\ is

this is the full code

import pyxhook
import subprocess

command = [""]
isActive = False
element = 0
isSpace = False

def OnKeyPress(event):
    global command
    global isActive
    global element
    global isSpace
    if event.Ascii == 96:
        if isActive == False:
            isActive = True
        elif isActive == True:
            subprocess.call(command)
            command = [""]
            element = 0
            isActive = False
    elif isActive == True:
        if event.Ascii == 32:
            if isSpace == False:
                command.append("")
                element += 1
            else:
                command[element] += " "
                isSpace = False
        elif event.Key == "BackSpace":
            command[element] = command[element][:-1]
        elif event.Key == "slash":
            command[element] += "/"
        elif event.Key == "Shift_L" :
            command = command
        elif event.Key =="Shift_R":
            command = command
        elif event.Key == "backslash":
            isSpace = True
            command[element] +=  "\\"
        else:
            command[element] += (event.Key)

#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()

Body:
Pay attention to your command list and how you're appending things:

$ python
Python 2.7.10 (default, Feb  7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> command = ["mkdir", "/home/matt/Desktop/this"]
>>> command[0] +=  "\\ is"
>>> command
['mkdir\\ is', '/home/matt/Desktop/this']
>>> command = ["mkdir", "/home/matt/Desktop/this"]
>>> command[-1]
'/home/matt/Desktop/this'
>>> command[-1] += " is"
>>> command
['mkdir', '/home/matt/Desktop/this is']
>>> subprocess.call(command)
0
>>> import glob
>>> glob.glob("/home/matt/Desktop/th*")
['/home/matt/Desktop/this is']
>>>


问:
In React, how to bind an input's value when rendering a list of inputs?
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

```<code>class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}
</code>```

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

答:
Links info is in the link property of your tweets array. The property text is not defined.
So, your render function should look like this

```<code>  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => tweet.text= e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.link}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
</code>```

Body:
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (

        {this.tweets.map(tweet =>

            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet

        )}

    );
  }
}

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

Body:
Links info is in the link property of your tweets array. The property text is not defined.
So, your render function should look like this

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => tweet.text= e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.link}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }


问:
Java client and node.js server
im trying to implement a simple comet app to just send data and recive data, my client side is written on java and the server is in node.js, im trying to implement it from the client side with HttpUrlConnection but it seems that when i try to write to the server it doesnt respond me. so how can code the server to respond? (currently using http.createServer(function(req, res){...}).listen(8124);</p>

答:
I'm doing something similar to that with an Android app. I can't say that this is the "right" way to do it, but I'm using these classes in my project (to make POSTs and check the responses):

```<code>import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
</code>```

To implement I'm doing something to the effect of

```<code>HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(/*...(String) url...*/);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "value"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost); // <-- this has useful info
</code>```

To actually get useful stuff from the server I'm using JSON because, IMHO, XML parsing is a huge pain in Java.

So these are the classes I use for parsing the JSON that nodejs spits out at me.

```<code>import org.json.JSONArray;
import org.json.JSONObject;

...

JSONObject jObject = new JSONObject(EntityUtils.toString(response.getEntity()));
JSONArray datasets = jObject.getJSONArray("blahblahblah");
</code>```

Title: Java client and node.js server

Body:
I'm doing something similar to that with an Android app. I can't say that this is the "right" way to do it, but I'm using these classes in my project (to make POSTs and check the responses):

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

To implement I'm doing something to the effect of

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(/*...(String) url...*/);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "value"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost); // <-- this has useful info

To actually get useful stuff from the server I'm using JSON because, IMHO, XML parsing is a huge pain in Java.

So these are the classes I use for parsing the JSON that nodejs spits out at me.

import org.json.JSONArray;
import org.json.JSONObject;

...

JSONObject jObject = new JSONObject(EntityUtils.toString(response.getEntity()));
JSONArray datasets = jObject.getJSONArray("blahblahblah");


问:
Docker - Which environment is actually running on Windows 7?
I’m new to docker, started to learn about it but I’m a little confused.

I need to run app on windows environment.

I have Windows 7 – native Docker is only for Windows 10, so I need to download the Docker toolbox for Windows 7.

The toolbox is actually using a Linux VM to run it.

So, in this state I will actually create a container with windows environment or Linux environment?

Is the Docker for windows 10 also uses Linux?

Thanks

答:
To kinda answer your question: Windows 7 uses a linux to run docker because it needs certain kernelfeatures, which W7 doesn't have.

Windows 10 or Windows Server 2016 adapted to the whole containerization movement and included those features, so Windows Containers can be run from it directly.

Also the problem tgogos referenced, with windows containers not being able to run on linux hosts and vice versa is a problem which (afaik) can be solved by using an additional linux VM on the windows host, so you have both environments. I wouldn't personally recommend it, but I think it's possible.

Anyways, you won't really need this, as windows applications still will be running on Windows hosts and linux applications on linux.

Containers are mainly a more efficient, more manageable way to deploy applications.


问:
Passing Data between functions
I have been trying to figure out how to pass data between functions, I'm new to coding. I have tried multiple way to do it, I am struggling to understand how data is passed my code is below. Help would be awesome.

```<code>x = []
y = []
z = []

def w():   #Welcome greeting the user and asking for their name
    print("Welcome to the BMI Index Calculator.")
    name = input("Enter employee's name or Exit to quit: ")  # Allows the user to input there name as a variable
    if str.isnumeric(name):  # Test as a string
        print("That is not a name.")
        w()
    if name == 'Exit':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        name = x.append(name)

def h():
    height = input("Enter employee's height in inches: ")
    if height == '0':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        height = y.append(height)

def wt():
    weight = input("Enter employee's weight in lbs: ")
    if weight == '0':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        weight = z.append(weight)

def bmi():     #gives the data back to the user
    print(str(x).replace('[', '').replace(']', '').replace("'", '') + "'s " + "BMI profile")
    print("---------------------------")
    print("Height: ", str(y).replace('[', '').replace(']', '').replace("'", ''), '"')
    print("Weight: ", str(z).replace('[', '').replace(']', '').replace("'", ''), "lbs.")

def math_cal():
    bmi_weight = int(z) * 703
    bmi_height = int(y) ** 2
    print("BMI: ", bmi_weight / bmi_height)

def run():
    x = w()
    y = h()
    z = wt()
    xy = bmi()
    xz = math_cal()
    __main__()

run()

__main__()
</code>```

I have been successful in passing the data to other functions but the code fails to see the list as an int. Thus I have found my way here, trying to get ideas of how to rewrite this code in a more efficient manner. I am looking for a way to reference functions to pass data between functions, however I have not been find a clean way to execute that process.

答:
There are to points where values are passed when using functions:

at the start of the function, with parameters

at the end of the function, as return value

let us first take a look at the return value:
For example in your h() function, you ask the user for the height. This value is stored in height

```<code>height = input("Enter employee's height in inches: ")
</code>```

after checking for all the cases you want, you can return one value at the end of the function by using "return":

```<code>return height
</code>```

the complete function becomes:

```<code>def h():
   height = input("Enter employee's height in inches: ")
   if height == '0':  # sets the Exit for the program
      print("Exiting program...")
      exit()  # ends program
   return height
</code>```

This means if you call the function h() it will ask for the height and return the value which it obtained. This could be used by you program like this:

```<code>bmi_height = h()
</code>```

or

```<code>bmi_height = h()*2
</code>```

if you want to multiply the entered value with 2.

The second part, passing values to a function at the start of the function with parameters:

for example you want to use the height and weight when calculating the BMI, then the function becomes:

```<code>def bmi(height, weight)
    print("BMI: ", bmi_weight / bmi_height)
</code>```

this function has to be called like this:

```<code>bmi(170, 85)
</code>```

when entering the values hard-coded or

```<code>height = 170
weight = 85
bmi(height, weight)
</code>```

when you use variables.

Title: Passing Data between functions

Body:
I have been trying to figure out how to pass data between functions, I'm new to coding. I have tried multiple way to do it, I am struggling to understand how data is passed my code is below. Help would be awesome.

x = []
y = []
z = []

def w():   #Welcome greeting the user and asking for their name
    print("Welcome to the BMI Index Calculator.")
    name = input("Enter employee's name or Exit to quit: ")  # Allows the user to input there name as a variable
    if str.isnumeric(name):  # Test as a string
        print("That is not a name.")
        w()
    if name == 'Exit':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        name = x.append(name)

def h():
    height = input("Enter employee's height in inches: ")
    if height == '0':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        height = y.append(height)

def wt():
    weight = input("Enter employee's weight in lbs: ")
    if weight == '0':  # sets the Exit for the program
        print("Exiting program...")
        exit()  # ends program
    else:
        weight = z.append(weight)

def bmi():     #gives the data back to the user
    print(str(x).replace('[', '').replace(']', '').replace("'", '') + "'s " + "BMI profile")
    print("---------------------------")
    print("Height: ", str(y).replace('[', '').replace(']', '').replace("'", ''), '"')
    print("Weight: ", str(z).replace('[', '').replace(']', '').replace("'", ''), "lbs.")

def math_cal():
    bmi_weight = int(z) * 703
    bmi_height = int(y) ** 2
    print("BMI: ", bmi_weight / bmi_height)

def run():
    x = w()
    y = h()
    z = wt()
    xy = bmi()
    xz = math_cal()
    __main__()

run()

__main__()

I have been successful in passing the data to other functions but the code fails to see the list as an int. Thus I have found my way here, trying to get ideas of how to rewrite this code in a more efficient manner. I am looking for a way to reference functions to pass data between functions, however I have not been find a clean way to execute that process.

Body:
There are to points where values are passed when using functions:

at the start of the function, with parameters

at the end of the function, as return value

let us first take a look at the return value:
For example in your h() function, you ask the user for the height. This value is stored in height

height = input("Enter employee's height in inches: ")

after checking for all the cases you want, you can return one value at the end of the function by using "return":

return height

the complete function becomes:

def h():
   height = input("Enter employee's height in inches: ")
   if height == '0':  # sets the Exit for the program
      print("Exiting program...")
      exit()  # ends program
   return height

This means if you call the function h() it will ask for the height and return the value which it obtained. This could be used by you program like this:

bmi_height = h()

or

bmi_height = h()*2

if you want to multiply the entered value with 2.

The second part, passing values to a function at the start of the function with parameters:

for example you want to use the height and weight when calculating the BMI, then the function becomes:

def bmi(height, weight)
    print("BMI: ", bmi_weight / bmi_height)

this function has to be called like this:

bmi(170, 85)

when entering the values hard-coded or

height = 170
weight = 85
bmi(height, weight)

when you use variables.


问:
join two csv file using column reference
I have two csv files
file 1 :

```<code>firstName    lastName     internalId      email         phoneNumber
XX           YY           123             xx@mail.fr    003312345600
ZZ           QQ           147             zz@mail.fr    003371236500
KK           JJ           159             kk@mail.fr    003369865300
</code>```

file 2 :

```<code>internalId    email        phoneNumber
159           ss@mail.fr   003379632500
147           ee@mail.fr   003396325200
</code>```

i like to join file 1 and file 2 to have this result

```<code>firstName    lastName     internalId      email         phoneNumber
XX           YY           123             xx@mail.fr    003312345600
ZZ           QQ           147             ee@mail.fr    003396325200
KK           JJ           159             ss@mail.fr    003369865300
</code>```

modify email and phoneNumber if it finds the same internalId if not I keep the same values

答:
awk solution:

```<code>awk 'NR==FNR{ a[$1]=$2 FS $3; next }
     FNR>1 && ($3 in a){ split(a[$3], b); $4=b[1]; $5=b[2] }1' file2 file1 | column -t
</code>```

NR==FNR - processing the 1st input file i.e. file2

a[$1]=$2 FS $3 - fill the array a with concatenated values of the 2nd $2 and 3rd field $3 of file file2(i.e. email and phoneNumber) indexing it with the 1st field value $1, i.e. internalId

FNR>1 && ($3 in a) - processing the 2nd input file file1, making substitutions on matched internalIds

The output:

```<code>firstName  lastName  internalId  email       phoneNumber
XX         YY        123         xx@mail.fr  003312345600
ZZ         QQ        147         ee@mail.fr  003396325200
KK         JJ        159         ss@mail.fr  003379632500
</code>```

Body:
I have two csv files
file 1 :

firstName    lastName     internalId      email         phoneNumber
XX           YY           123             xx@mail.fr    003312345600
ZZ           QQ           147             zz@mail.fr    003371236500
KK           JJ           159             kk@mail.fr    003369865300

file 2 :

internalId    email        phoneNumber
159           ss@mail.fr   003379632500
147           ee@mail.fr   003396325200

i like to join file 1 and file 2 to have this result

firstName    lastName     internalId      email         phoneNumber
XX           YY           123             xx@mail.fr    003312345600
ZZ           QQ           147             ee@mail.fr    003396325200
KK           JJ           159             ss@mail.fr    003369865300

modify email and phoneNumber if it finds the same internalId if not I keep the same values

Body:
awk solution:

awk 'NR==FNR{ a[$1]=$2 FS $3; next }
     FNR>1 && ($3 in a){ split(a[$3], b); $4=b[1]; $5=b[2] }1' file2 file1 | column -t

NR==FNR - processing the 1st input file i.e. file2

a[$1]=$2 FS $3 - fill the array a with concatenated values of the 2nd $2 and 3rd field $3 of file file2(i.e. email and phoneNumber) indexing it with the 1st field value $1, i.e. internalId

FNR>1 && ($3 in a) - processing the 2nd input file file1, making substitutions on matched internalIds

The output:

firstName  lastName  internalId  email       phoneNumber
XX         YY        123         xx@mail.fr  003312345600
ZZ         QQ        147         ee@mail.fr  003396325200
KK         JJ        159         ss@mail.fr  003379632500


问:
Cannot make XHRs from within a fake async test
Total novice at Karma/Jasmine looking for some assistance. I'm trying to run the following test and I get the error "Cannot make XHRs within a fake async test". I have included the test and the method I am attempting to call. Any help is greatly appreciated.

```<code>import...

fdescribe('CageService', () => {

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule,
            HttpModule
        ],
        providers: [
            BaseRequestOptions,
            MockBackend,
            CageService,
            { provide: 'appHttpService', useClass: AppHttpService },
            { provide: 'appHttpHelperService', useClass: AppHttpHelperService },
            { provide: 'appUtilityService', useClass: AppUtilityService },
            { provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
                return new Http(backend, defaultOptions);
            }, deps: [MockBackend, BaseRequestOptions] }
        ]
    });
});

it('will load cages', inject([CageService, MockBackend], fakeAsync(( cageService, mockBackend\) => {

    var res;
    mockBackend.connections.subscribe( c => {

        expect(c.request.url).toBe('http://example.com');
        let response = new ResponseOptions( { body: '{"name": "charles"}' } );
        c.mockRespond( new Response( response ) );
    });

    cageService.load({}).subscribe((_res) => {

        res = _res;
    });

    tick(100);
    discardPeriodicTasks();
    expect(res.name).toBe('Charles');
})));
});
</code>```

The method I am calling reads

```<code>load ( criteria: Object ) {

    return this.appHttpService.get( this.url + '?' + criteria )
    .map(

        response => {

            let data = response.json();

            this.pagination.total = data.count;
            this.pagination.per_page = data.limit;
            this.pagination.current_page = data.currentPage;
            this.pagination.last_page = data.totalPages;

            let cages = [];
            for( let x = 0; x < data.rows.length; x++ ) {

                cages.push( this.formatCage(new Cage(), data.rows[x] ) );
            }

            this._cages$.next( this.dataStore.cages );

            return data.rows;
        }
    );
}
</code>```

答:
I had the same issue, and I'm not sure what version of angular you're using, but this works with HttpClientModule in , not sure if it works with HttpModule. Here are my versions:

```<code>@angular/cli: 1.4.9
node: 8.8.1
os: linux x64
@angular/animations: 4.4.6
@angular/cdk: 2.0.0-beta.12
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/material: 2.0.0-beta.12
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.9
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.5.3
</code>```

And here is my imports & providers array:

```<code>import { MockBackend } from '@angular/http/testing';
import { HttpClientModule, HttpXhrBackend } from '@angular/common/http';
imports: [
    otherStuff...,
    HttpClientModule
],
providers: [
    otherStuff...,
    SomeService,
    {
        provide: HttpXhrBackend,
        useClass: MockBackend
    }
]
</code>```

If you're not using HttpClient yet, it may be worth updating as it's much easier to use. Hope this helps.

Body:
Total novice at Karma/Jasmine looking for some assistance. I'm trying to run the following test and I get the error "Cannot make XHRs within a fake async test". I have included the test and the method I am attempting to call. Any help is greatly appreciated.

import...

fdescribe('CageService', () => {

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule,
            HttpModule
        ],
        providers: [
            BaseRequestOptions,
            MockBackend,
            CageService,
            { provide: 'appHttpService', useClass: AppHttpService },
            { provide: 'appHttpHelperService', useClass: AppHttpHelperService },
            { provide: 'appUtilityService', useClass: AppUtilityService },
            { provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
                return new Http(backend, defaultOptions);
            }, deps: [MockBackend, BaseRequestOptions] }
        ]
    });
});

it('will load cages', inject([CageService, MockBackend], fakeAsync(( cageService, mockBackend\) => {

    var res;
    mockBackend.connections.subscribe( c => {

        expect(c.request.url).toBe('http://example.com');
        let response = new ResponseOptions( { body: '{"name": "charles"}' } );
        c.mockRespond( new Response( response ) );
    });

    cageService.load({}).subscribe((_res) => {

        res = _res;
    });

    tick(100);
    discardPeriodicTasks();
    expect(res.name).toBe('Charles');
})));
});

The method I am calling reads

load ( criteria: Object ) {

    return this.appHttpService.get( this.url + '?' + criteria )
    .map(

        response => {

            let data = response.json();

            this.pagination.total = data.count;
            this.pagination.per_page = data.limit;
            this.pagination.current_page = data.currentPage;
            this.pagination.last_page = data.totalPages;

            let cages = [];
            for( let x = 0; x < data.rows.length; x++ ) {

                cages.push( this.formatCage(new Cage(), data.rows[x] ) );
            }

            this._cages$.next( this.dataStore.cages );

            return data.rows;
        }
    );
}

Body:
I had the same issue, and I'm not sure what version of angular you're using, but this works with HttpClientModule in , not sure if it works with HttpModule. Here are my versions:

@angular/cli: 1.4.9
node: 8.8.1
os: linux x64
@angular/animations: 4.4.6
@angular/cdk: 2.0.0-beta.12
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/material: 2.0.0-beta.12
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.9
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.5.3

And here is my imports & providers array:

import { MockBackend } from '@angular/http/testing';
import { HttpClientModule, HttpXhrBackend } from '@angular/common/http';
imports: [
    otherStuff...,
    HttpClientModule
],
providers: [
    otherStuff...,
    SomeService,
    {
        provide: HttpXhrBackend,
        useClass: MockBackend
    }
]

If you're not using HttpClient yet, it may be worth updating as it's much easier to use. Hope this helps.


问:
If clause optimization
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

```<code>if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}
</code>```

Is there a cleaner way to write this condition?

Thanks.

答:
First of all, think if you really need to violate Tell don't ask.

Your code gains some status information, to then make decisions based on that. In a good OO model, you simply tell some object: "do the right thing". And then you rely on polymorphism to make sure that doTheRightThing() is the right thing for the current status.

If you don't want to go down that path, you should at least look into the single layer of abstraction principle. Meaning: turn your condition expressions into small helper methods, so that your code reads:

```<code>if (isXCondition()) {
  doX();
}
if (isYCondition()) ...
</code>```

Title: If clause optimization

Body:
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

Is there a cleaner way to write this condition?

Thanks.

Body:
First of all, think if you really need to violate Tell don't ask.

Your code gains some status information, to then make decisions based on that. In a good OO model, you simply tell some object: "do the right thing". And then you rely on polymorphism to make sure that doTheRightThing() is the right thing for the current status.

If you don't want to go down that path, you should at least look into the single layer of abstraction principle. Meaning: turn your condition expressions into small helper methods, so that your code reads:

if (isXCondition()) {
  doX();
}
if (isYCondition()) ...


答:
I'm assuming you need to do this in shell from your tags

Looks like a duplicate of this. Join command is your friend here

Title: join two csv file using column reference


问:
How can I do vectorization for this matlab "for loop"?
I have some matlab code as follow, constructing KNN similarity weight matrix.

```<code>[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
D = D < threshold;
W = zeros(n, n);
for i=1:size(I,2)
    W(I(:,i), i) = D(:,i);
    W(i, I(:,i)) = D(:,i)';
end
</code>```

I want to vectorize the for loop. I have tried

```<code>W(I) = D;
</code>```

but failed to get the correct value.

I add test case here:

```<code>n = 5;

D = [
 1     1     1     1     1
 0     1     1     1     1
 0     0     0     0     0
];

I = [
 1     2     3     4     5
 5     4     5     2     3
 3     1     1     1     1
];
</code>```

答:
You can cut some corners with linear indices but if your matrices are big then you should only take the nonzero components of D. Following copies all values of D

```<code>W = zeros(n);
W(reshape(sub2ind([n,n],I,[1;1;1]*[1:n]),1,[])) = reshape(D,1,[]);
</code>```

Body:
I have some matlab code as follow, constructing KNN similarity weight matrix.

[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
D = D < threshold;
W = zeros(n, n);
for i=1:size(I,2)
    W(I(:,i), i) = D(:,i);
    W(i, I(:,i)) = D(:,i)';
end

I want to vectorize the for loop. I have tried

W(I) = D;

but failed to get the correct value.

I add test case here:

n = 5;

D = [
 1     1     1     1     1
 0     1     1     1     1
 0     0     0     0     0
];

I = [
 1     2     3     4     5
 5     4     5     2     3
 3     1     1     1     1
];

Body:
You can cut some corners with linear indices but if your matrices are big then you should only take the nonzero components of D. Following copies all values of D

W = zeros(n);
W(reshape(sub2ind([n,n],I,[1;1;1]*[1:n]),1,[])) = reshape(D,1,[]);


问:
Find all unique xml first nodes under a parent node using xslt
I'm an xsl n00b and trying to find all unique xml nodes under the
 node

Here's my code:

```<code><section>
   <books>
     <book>
       <title>Child 44</title>
       <author>Thomas Rob Smith</author>
       <price>5.00</price>
     </book>
     <book>
       <title>Atlas Shrugged</title>
       <author>Ayn Rand</author>
       <price>7.00</price>
     </book>
   </books>
   <cds>
     <cd>
       <title>A Passage in time</title>
       <band>Authority Zero</band>
       <price>10.00</price>
      </cd>
   </cds>
</section>
</code>```

Here is my desired output:

```<code>books
cds
</code>```

Thanks in advance!

答:
```<code>/section/*[not(name(.)=name(preceding-sibling::*)) and not(name(.)=name(following-sibling::*))]
</code>```

Body:
I'm an xsl n00b and trying to find all unique xml nodes under the
 node

Here's my code:

   <books>
     <book>
       <title>Child 44</title>
       <author>Thomas Rob Smith</author>
       <price>5.00</price>
     </book>
     <book>
       <title>Atlas Shrugged</title>
       <author>Ayn Rand</author>
       <price>7.00</price>
     </book>
   </books>
   <cds>
     <cd>
       <title>A Passage in time</title>
       <band>Authority Zero</band>
       <price>10.00</price>
      </cd>
   </cds>

Here is my desired output:

books
cds

Thanks in advance!


答:
A possible solution:

```<code>idx1 = reshape(1:n*n,n,n).';
idx2 = bsxfun(@plus,I,0:n:n*size(I,2)-1);

W=zeros(n,n);
W(idx2) = D;
W(idx1(idx2)) = D;
</code>```

Here assumed that you repeatedly want to compute D and I so compute idx only one time and use it repeatedly.

```<code>n = 5;
idx1 = reshape(1:n*n,n,n).';
%for k = 1 : 1000
    %[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
    %D = D < threshold;
    idx2 = bsxfun(@plus,I,0:n:n*size(I,2)-1);
    W=zeros(n,n);
    W(idx2) = D;
    W(idx1(idx2)) = D;
%end
</code>```

But if n isn't constant and it varies in each iteration it is better to change the way idx1 is computed:

```<code>n = 5;
%for k = 1 : 1000
    %n = randi([2 10]);%n isn't constant
    %[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
    %D = D < threshold;
    idx1 = bsxfun(@plus,(0:n:n^2-1).',1:size(I,2));
    idx2 = bsxfun(@plus,I,0:n:n*size(I,2)-1);
    W=zeros(n,n);
    W(idx2) = D;
    W(idx1(idx2)) = D;
%end
</code>```

Title: How can I do vectorization for this matlab "for loop"?

Body:
A possible solution:

idx1 = reshape(1:n*n,n,n).';
idx2 = bsxfun(@plus,I,0:n:n*size(I,2)-1);

W=zeros(n,n);
W(idx2) = D;
W(idx1(idx2)) = D;

Here assumed that you repeatedly want to compute D and I so compute idx only one time and use it repeatedly.

n = 5;
idx1 = reshape(1:n*n,n,n).';
%for k = 1 : 1000
    %[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
    %D = D < threshold;
    idx2 = bsxfun(@plus,I,0:n:n*size(I,2)-1);
    W=zeros(n,n);
    W(idx2) = D;
    W(idx1(idx2)) = D;
%end

But if n isn't constant and it varies in each iteration it is better to change the way idx1 is computed:

n = 5;
%for k = 1 : 1000
    %n = randi([2 10]);%n isn't constant
    %[D,I] = pdist2(X, X, 'squaredeuclidean', 'Smallest', k+1);
    %D = D < threshold;
    idx1 = bsxfun(@plus,(0:n:n^2-1).',1:size(I,2));
    idx2 = bsxfun(@plus,I,0:n:n*size(I,2)-1);
    W=zeros(n,n);
    W(idx2) = D;
    W(idx1(idx2)) = D;
%end


问:
How to Clear Cache in Sybase ASE
I want to clear the cache of Sybase ASE, so that I can test always the worst case scenario in two different queries.

What I found in my research was to use the commands below to clear cache, and sp_helpcache to check objects cached:

```<code>sp_unbindcache <dbname>, <table>
sp_unbindcache_all <cache name>
</code>```

How did I tested it?

I ran a SELECT Count on a table before and after running sp_unbindcache and the second test was to run the query before and after sp_unbindcache_all

What happened?

The first time I ran the query there was physical I/O the subsequent tries did not, only Logical I/O. (Cache preserved despite running the unbindcache commands)

Weird Stuff

When I ran sp_helpcache it didn't show my table on the list of objects in Cache Binding Information (CBI). After running sp_unbindcache_all, sp_helpcache showed no rows on CBI. I then re-run the query and sp_helpcache was still with CBI empty.
This is weird because it might mean that when I run a query, my table is cache somewhere else.

The Question

So I would Like to know how can I find where my table is being cached when I run a query, and then how can I clear it from there?

Other Info

Database: SYBASE ASE 15.7

sp_helpcache only shows "default data cache"

Cache Binding Information(CBI) - is part of sp_helpcache's output

UPDATE:

I Have made a new test where I Bind the table to the "default data cache" to see if it would appear in CBI and it appeared.

答:
To clear cache in "default data cache" you should use dbcc
cachedataremove

for user defined cache you should use sp_unbindcache ,
 or  sp_unbindcache_all

Title: How to Clear Cache in Sybase ASE

Body:
I want to clear the cache of Sybase ASE, so that I can test always the worst case scenario in two different queries.

What I found in my research was to use the commands below to clear cache, and sp_helpcache to check objects cached:

sp_unbindcache <dbname>,

sp_unbindcache_all <cache name>

How did I tested it?

I ran a SELECT Count on a table before and after running sp_unbindcache and the second test was to run the query before and after sp_unbindcache_all

What happened?

The first time I ran the query there was physical I/O the subsequent tries did not, only Logical I/O. (Cache preserved despite running the unbindcache commands)

Weird Stuff

When I ran sp_helpcache it didn't show my table on the list of objects in Cache Binding Information (CBI). After running sp_unbindcache_all, sp_helpcache showed no rows on CBI. I then re-run the query and sp_helpcache was still with CBI empty.
This is weird because it might mean that when I run a query, my table is cache somewhere else.

The Question

So I would Like to know how can I find where my table is being cached when I run a query, and then how can I clear it from there?

Other Info

Database: SYBASE ASE 15.7

sp_helpcache only shows "default data cache"

Cache Binding Information(CBI) - is part of sp_helpcache's output

UPDATE:

I Have made a new test where I Bind the table to the "default data cache" to see if it would appear in CBI and it appeared.


问:
How do I disable all code analysis in eclipse cdt?
I am using Eclipse IDE for C/C++ Developers, Oxygen release (4.7.0).
I have unchecked all boxes in Preferences->Code Analysis.
if I have the following code:

```<code>int main (void)
{
</code>```

Eclipse places a warning symbol in the border next to the bracket, indicating that it is missing a closing bracket.

How do I disable all code analysis?

答: In Window > Preferences: C/C++ > Editor uncheck Report problems as you type.

Body:
I am using Eclipse IDE for C/C++ Developers, Oxygen release (4.7.0).
I have unchecked all boxes in Preferences->Code Analysis.
if I have the following code:

int main (void)
{

Eclipse places a warning symbol in the border next to the bracket, indicating that it is missing a closing bracket.

How do I disable all code analysis?


问:
SQL or PL/SQL to return the value of nodes with same name to one row
From the below XML I would like to return the following.

```<code>ID            Departments
-----------   ------------------------------
EMP10Level1   98,850,876,896,901,908,936,987
</code>```

I have tried a few things, such as parsing the XML and using Listagg, but am getting the same values for every ID.

Hopefully a more enlightenment mind can solve this problem for me.

Is also a column called ID that contains EMP10Level1 which is the value from the PromotionID tag below.

```<code> <Promotion>
    <MajorVersion>1</MajorVersion>
    <MinorVersion>7</MinorVersion>
    <PromotionID>EMP10Level1</PromotionID>
    <MultibuyGroup>
        <UseLowestNetValue>0</UseLowestNetValue>
        <MMGroupID>850</MMGroupID>
        <MMGroupID>901</MMGroupID>
        <MMGroupID>908</MMGroupID>
        <MMGroupID>936</MMGroupID>
        <MMGroupID>896</MMGroupID>
        <MMGroupID>987</MMGroupID>
        <MMGroupID>876</MMGroupID>
        <MMGroupID>98</MMGroupID>
        <TriggerOnLostSales>0</TriggerOnLostSales>
    </MultibuyGroup>
</Promotion>
</code>```

答:
Not very elegant, but here is another which works:</p>

```<code>WITH TBL
     AS (SELECT xmltype (
                   '<Promotion>
                    <MajorVersion>1</MajorVersion>
                    <MinorVersion>7</MinorVersion>
                    <PromotionID>EMP10Level1</PromotionID>
                    <MultibuyGroup>
                        <UseLowestNetValue>0</UseLowestNetValue>
                        <MMGroupID>850</MMGroupID>
                        <MMGroupID>901</MMGroupID>
                        <MMGroupID>908</MMGroupID>
                        <MMGroupID>936</MMGroupID>
                        <MMGroupID>896</MMGroupID>
                        <MMGroupID>987</MMGroupID>
                        <MMGroupID>876</MMGroupID>
                        <MMGroupID>98</MMGroupID>
                        <TriggerOnLostSales>0</TriggerOnLostSales>
                    </MultibuyGroup>
                </Promotion>')
                   Col1
           FROM DUAL)
SELECT EXTRACTVALUE (col1, 'Promotion/PromotionID') AS ID,
       LTRIM (
          REPLACE (
             REPLACE (EXTRACT (col1, 'Promotion/MultibuyGroup/MMGroupID'),
                      '<MMGroupID>',
                      ','),
             '</MMGroupID>'),
          ',')
          AS DEPT
  FROM tbl
</code>```

Body:
From the below XML I would like to return the following.

ID            Departments
-----------   ------------------------------
EMP10Level1   98,850,876,896,901,908,936,987

I have tried a few things, such as parsing the XML and using Listagg, but am getting the same values for every ID.

Hopefully a more enlightenment mind can solve this problem for me.

Is also a column called ID that contains EMP10Level1 which is the value from the PromotionID tag below.

 <Promotion>
    <MajorVersion>1</MajorVersion>
    <MinorVersion>7</MinorVersion>
    <PromotionID>EMP10Level1</PromotionID>
    <MultibuyGroup>
        <UseLowestNetValue>0</UseLowestNetValue>
        <MMGroupID>850</MMGroupID>
        <MMGroupID>901</MMGroupID>
        <MMGroupID>908</MMGroupID>
        <MMGroupID>936</MMGroupID>
        <MMGroupID>896</MMGroupID>
        <MMGroupID>987</MMGroupID>
        <MMGroupID>876</MMGroupID>
        <MMGroupID>98</MMGroupID>
        <TriggerOnLostSales>0</TriggerOnLostSales>
    </MultibuyGroup>
</Promotion>

Body:
Not very elegant, but here is another which works:

WITH TBL
     AS (SELECT xmltype (
                   '<Promotion>
                    <MajorVersion>1</MajorVersion>
                    <MinorVersion>7</MinorVersion>
                    <PromotionID>EMP10Level1</PromotionID>
                    <MultibuyGroup>
                        <UseLowestNetValue>0</UseLowestNetValue>
                        <MMGroupID>850</MMGroupID>
                        <MMGroupID>901</MMGroupID>
                        <MMGroupID>908</MMGroupID>
                        <MMGroupID>936</MMGroupID>
                        <MMGroupID>896</MMGroupID>
                        <MMGroupID>987</MMGroupID>
                        <MMGroupID>876</MMGroupID>
                        <MMGroupID>98</MMGroupID>
                        <TriggerOnLostSales>0</TriggerOnLostSales>
                    </MultibuyGroup>
                </Promotion>')
                   Col1
           FROM DUAL)
SELECT EXTRACTVALUE (col1, 'Promotion/PromotionID') AS ID,
       LTRIM (
          REPLACE (
             REPLACE (EXTRACT (col1, 'Promotion/MultibuyGroup/MMGroupID'),
                      '<MMGroupID>',
                      ','),
             '</MMGroupID>'),
          ',')
          AS DEPT
  FROM tbl


问:
Microsoft Azure access_token not accepted in CRM requests
I am putting together an api integration with Dynamics CRM on premise (v8.1/8.2), on a IFD, using the password grant type.

I am retrieving an access token successfully, however when I then try to call endpoints (e.g /api/data/v8.2/contacts?$select=fullname,contactid ) I get 401 - access denied errors. When I log into the CRM with the user I can successfully view this data and the error occurs on all tested endpoints.

Interestingly this morning I realised the tokens retrieved cannot be base64 decoded - is that correct?

I could use some ideas on what to look at next to resolve the problem. Steps I've taken:

Triple checking the initial token request

Triple checked the Service Root URL

Tried on two CRM/Azure setups

Tried with my own (node) code and internet examples

A wide variety of token setups

Confirmed the user exists in Azure and the CRM

Confirmed user has sufficient permissions

Confirmed the application on Azure has all dynamics permissions granted

Confirmed I am on the same network as Azure and the CRM

It seems apparent that I have a configuration issue somewhere in Azure or the CRM. However no guide or question I can find suggests looking at problems I haven't already checked for and I could really use some input from those who have had to make adjustments in obscure settings ect.

Heres my token request:

```<code>var options = {
    method: 'POST',
    url: 'https://login.microsoftonline.com/<snip>/oauth2/token', //for 'intercity technology' (guid is unique)
    headers:
        {
            'cache-control': 'no-cache',
            'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
    formData:
        {
            grant_type: 'password',
            client_id: ‘<snip>’, //aplication id
            client_secret: ‘<snip>’, //any key in the keys list
            username: ‘<snip>’,
            password: ‘<snip>’, // and their password
            resource: ‘<snip>’ //application id

        }
};

   logger.debug(util.inspect(options));

    request(options, function (error, response, body) {
...
</code>```

Heres my current api request test:

```<code> var options = {
            method: 'GET',
            url: organisation_url + '/api/data/v8.2/contacts?$select=fullname,contactid',
            headers: {
                Authorization: 'Bearer '+token,
                Accept: 'application/json',
                'OData-MaxVersion':4.0,
                'OData-Version': 4.0,
                'Content-Type': 'application/json; charset=utf-8',
                'Prefer': 'odata.maxpagesize=500',
                'Prefer': 'odata.include-annotations=OData.Community.Display.V1.FormattedValue'
            }
            };
            logger.debug(util.inspect(options));

            request(options, function (error, response, body) {
...
</code>```

答:
You'll need to use a grant type of 'client_credentials' instead of 'password' as the later isn't supported.
Something like:

```<code> grant_type: 'client_credentials',
 client_id: ‘<snip>’, //aplication id
 client_secret: ‘<snip>’, //any key in the keys list
 resource: ‘<snip>’ //CRM Url
</code>```

Follow the guide here and all the links to ensure the AAD application is registered correctly and the CRM application user is in place.

Body:
I am putting together an api integration with Dynamics CRM on premise (v8.1/8.2), on a IFD, using the password grant type.

I am retrieving an access token successfully, however when I then try to call endpoints (e.g /api/data/v8.2/contacts?$select=fullname,contactid ) I get 401 - access denied errors. When I log into the CRM with the user I can successfully view this data and the error occurs on all tested endpoints.

Interestingly this morning I realised the tokens retrieved cannot be base64 decoded - is that correct?

I could use some ideas on what to look at next to resolve the problem. Steps I've taken:

Triple checking the initial token request

Triple checked the Service Root URL

Tried on two CRM/Azure setups

Tried with my own (node) code and internet examples

A wide variety of token setups

Confirmed the user exists in Azure and the CRM

Confirmed user has sufficient permissions

Confirmed the application on Azure has all dynamics permissions granted

Confirmed I am on the same network as Azure and the CRM

It seems apparent that I have a configuration issue somewhere in Azure or the CRM. However no guide or question I can find suggests looking at problems I haven't already checked for and I could really use some input from those who have had to make adjustments in obscure settings ect.

Heres my token request:

var options = {
    method: 'POST',
    url: 'https://login.microsoftonline.com/<snip>/oauth2/token', //for 'intercity technology' (guid is unique)
    headers:
        {
            'cache-control': 'no-cache',
            'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
    formData:
        {
            grant_type: 'password',
            client_id: ‘<snip>’, //aplication id
            client_secret: ‘<snip>’, //any key in the keys list
            username: ‘<snip>’,
            password: ‘<snip>’, // and their password
            resource: ‘<snip>’ //application id

        }
};

   logger.debug(util.inspect(options));

    request(options, function (error, response, body) {
...

Heres my current api request test:

 var options = {
            method: 'GET',
            url: organisation_url + '/api/data/v8.2/contacts?$select=fullname,contactid',
            headers: {
                Authorization: 'Bearer '+token,
                Accept: 'application/json',
                'OData-MaxVersion':4.0,
                'OData-Version': 4.0,
                'Content-Type': 'application/json; charset=utf-8',
                'Prefer': 'odata.maxpagesize=500',
                'Prefer': 'odata.include-annotations=OData.Community.Display.V1.FormattedValue'
            }
            };
            logger.debug(util.inspect(options));

            request(options, function (error, response, body) {
...

Body:
You'll need to use a grant type of 'client_credentials' instead of 'password' as the later isn't supported.
Something like:

 grant_type: 'client_credentials',
 client_id: ‘<snip>’, //aplication id
 client_secret: ‘<snip>’, //any key in the keys list
 resource: ‘<snip>’ //CRM Url

Follow the guide here and all the links to ensure the AAD application is registered correctly and the CRM application user is in place.


问:
how to only allow letters to be used python statment
I'm making a Morse code program:

```<code>def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    for key in phrase:
        print("your word or sentence translated to morse code is : ")
        print(morse_code[key], end = " ")
    if phrase == int or float:
        print("try the input")

    retry()
def retry ():
    main()
retry()
main()
</code>```

How do I print an error if someone enters a number?

答:
Using isdigit() will solve your problem also use break to receive new input

```<code>morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in  range(0,len( phrase)):
    if phrase[key].isdigit():
        print("you inderted an digit , Try another input")

        break
    else:
        Morse_Parse.append(morse_code[phrase[key]]+" ")

print("Morse for your input is "Morse_Parse)
</code>```

using flag will improve print task

```<code>morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
flag=1
for key in  range(0,len( phrase)):
    if phrase[key].isdigit():
        print("you inderted an digit , Try another input")
        flag=0
        break
    else:
        Morse_Parse.append(morse_code[phrase[key]]+" ")

if flag==1:

        print("Morse for your input is "Morse_Parse)
</code>```

Body:
I'm making a Morse code program:

def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    for key in phrase:
        print("your word or sentence translated to morse code is : ")
        print(morse_code[key], end = " ")
    if phrase == int or float:
        print("try the input")

    retry()
def retry ():
    main()
retry()
main()

How do I print an error if someone enters a number?

Body:
Using isdigit() will solve your problem also use break to receive new input

morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in  range(0,len( phrase)):
    if phrase[key].isdigit():
        print("you inderted an digit , Try another input")

        break
    else:
        Morse_Parse.append(morse_code[phrase[key]]+" ")

print("Morse for your input is "Morse_Parse)

using flag will improve print task

morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
flag=1
for key in  range(0,len( phrase)):
    if phrase[key].isdigit():
        print("you inderted an digit , Try another input")
        flag=0
        break
    else:
        Morse_Parse.append(morse_code[phrase[key]]+" ")

if flag==1:

        print("Morse for your input is "Morse_Parse)


答: What you want is Preferences -> C/C++ -> Editor -> turn off Report problems as you type:

Title: How do I disable all code analysis in eclipse cdt?


问:
Select div with a text inside in JS
I want to modify a div with a special text inside like this.

```<code><div>
<p>
A global issue
</p>
</div>
</code>```

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

答:
```<code>let i=5;
let divs =Array.from( document.querySelectorAll('div > p')); // it returns array
divs[i].style.display= "none";
</code>```

Edit:

for(let i=0;i<divs.length;i++){ if(divs[i].textContent==="some text"){ divs[i].style.display="none"; } }

if you want to change parent node do divs[i].parentNode.style.display="none"

Title: Select div with a text inside in JS

Body:
I want to modify a div with a special text inside like this.

A global issue

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

Body:
let i=5;
let divs =Array.from( document.querySelectorAll('div > p')); // it returns array
divs[i].style.display= "none";

Edit:

for(let i=0;i<divs.length;i++){ if(divs[i].textContent==="some text"){ divs[i].style.display="none"; } }

if you want to change parent node do divs[i].parentNode.style.display="none"


问:
How can I reference xaml Template from a Converter?
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

```<code>        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>
</code>```

and I have this control using this converter:

```<code><ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>
</code>```

My Converter:

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }
</code>```

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

答: I think you should be able to load the XAML Resource file from the Application Resource dictionaries as described here.</p>

Body:
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>

and I have this control using this converter:

<ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>

My Converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev


问:
Jmeter, How to get one of response result to assign to next request
I have a response for request #1: 2 step codes that correspond with stepId as below.
In next request, I want to use only stepId = stepId that I assign from CSV file

```<code>**content**":[
            {
                "stepId":21,
                "stepCode":"11",
                "stepName":"11",

            },
            {
                "stepId":17,
                "stepCode":"??",
                "stepName":"To be checked",

            }
          ]
</code>```

答:
For example if you need to get stepCode value where stepId is 17 you can use JSON Extractor and the following JSON Path query:

```<code>$..[?(@.stepId == '17')].stepCode
</code>```

Demo:

You can replace this 17 with a variable coming from the CSV Data Set Config like:

```<code>$..[?(@.stepId == '${your_variable_from_csv}')].stepCode
</code>```

References:

Json Path Operators

JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios

Body:
I have a response for request #1: 2 step codes that correspond with stepId as below.
In next request, I want to use only stepId = stepId that I assign from CSV file

**content**":[
            {
                "stepId":21,
                "stepCode":"11",
                "stepName":"11",

            },
            {
                "stepId":17,
                "stepCode":"??",
                "stepName":"To be checked",

            }
          ]

Body:
For example if you need to get stepCode value where stepId is 17 you can use JSON Extractor and the following JSON Path query:

$..[?(@.stepId == '17')].stepCode

Demo:

You can replace this 17 with a variable coming from the CSV Data Set Config like:

$..[?(@.stepId == '${your_variable_from_csv}')].stepCode

References:

Json Path Operators

JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios


问:
Rcpp: call an R function from the Global Environment and use it in the C++ code
How can I call an R function that does not belong to any R package into a C++ code?. I can show you what I mean through a very semplicistic example. Suppose I have an R file where I write

```<code>myRfunction <- function(x){
 return(x+2)
}
</code>```

and I want to use it in a generic c++ code. So, I write something like

```<code>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::export]]

arma::vec myCppfunction(arma::vec y){
 arma::sec results = myRfunction(y);  /* Or whatever I have to do to call it! */
 return results;
}
</code>```

Can someone tell me how to do it? What is the general procedure? Thank you all.

答:
Alternatively, you can pass the R function as an argument to the C++ function, something like this: </p>

```<code>// [[Rcpp::export]]
NumericVector call_r_fun(NumericVector x, Function f) {
  return f(x) ;
}
</code>```

Body:
How can I call an R function that does not belong to any R package into a C++ code?. I can show you what I mean through a very semplicistic example. Suppose I have an R file where I write

myRfunction <- function(x){
 return(x+2)
}

and I want to use it in a generic c++ code. So, I write something like

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::export]]

arma::vec myCppfunction(arma::vec y){
 arma::sec results = myRfunction(y);  /* Or whatever I have to do to call it! */
 return results;
}

Can someone tell me how to do it? What is the general procedure? Thank you all.

Body:
Alternatively, you can pass the R function as an argument to the C++ function, something like this:

// [[Rcpp::export]]
NumericVector call_r_fun(NumericVector x, Function f) {
  return f(x) ;
}


问:
PHP dividing decimal/integer values gives round up output
When I'm dividing,

```<code>echo 50.3228679581385 / 100;
Output:0.50322867958139
</code>```

It should be 0.503228679581385 . Is there any way to avoid default round up?

答: It's not default round up, it's because of the precision limit on double.</p>

Body:
When I'm dividing,

echo 50.3228679581385 / 100;
Output:0.50322867958139

It should be 0.503228679581385 . Is there any way to avoid default round up?


问:
Composer [InvalidArgumentException] Could not find package mtibben/html2text
I have tried to install html2text via composer to my laravel application. Here is a link to the html2text repository. https://github.com/mtibben/html2text

I have tried composer require mtibben/html2text giving this error:

[InvalidArgumentException]

  Could not find package mtibben/html2text at any version for your
  minimum-stability (stable). Check the package spel   ling or your
  minimum-stability

Also I have tried composer require https://github.com/mtibben/html2text.git giving this error:

[UnexpectedValueException]

  Could not parse version constraint //github.com/mtibben/html2text.git:
  Invalid version string "//github.com/mtibben   /html2text.git"

How do I install html2text?

答:
Its a php package, u can't install with composer require

U may want to read this tutorial

http://laraveldaily.com/how-to-use-external-classes-and-php-files-in-laravel-controller/