问:
Merge XML nodes into one comma separated node
I have an XML structure and I'd like to transform this with XSLT. However, it's important to make this as dynamic as possible. I believe it's possible to make a copy of the feed, and then just select a specific section and transform this. When a new node is added to the original XML, no changed should be necessary in the XSLT to have this new node included in the output of the XSLT.

Example of original XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <option>
          <value_local>Verguld</value_local>
          <value_en>Gold-plated</value_en>
          <slug_value>1750-verguld</slug_value>
        </option>
        <option>
          <value_local>Zilver</value_local>
          <value_en>Silver</value_en>
          <slug_value>1751-silver</slug_value>
        </option>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>
</code>```

Desired output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <value_local>Verguld,Silver</value_local>
        <value_en>Gold-plated,Silver</value_en>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>
</code>```

I came across a SO question that pretty much does what I'm aiming for, but I need to define the complete XML structure in this XSLT. As we might add other XML nodes in a later stage and this XSLT will be used in various places, I want to make this as low maintenance as possible.

I think this SO question shows a low maintenance version but frankly I'm not able to understand how the second xsl:template works.

All help is much appreciated. If XSLT is provided, I'd appreciate it if you could include some comments of what you're doing where.

答:
As you didn't specify the XSLT version, I used 2.0,
which is more powerful and better suited for such a task.

Your script should contain:

An identity template.

A template for case_material elements.

This template should:

Copy all elements other than option.

Provide special handling of option elements.

This special handling should include grouping of all child elements of option
by element name. For each such group you should:

Create an element with the name of the source element (grouping key).

Print out the content of all group members, separated with a comma.

I noticed that you want to "exclude" certain elements (actually only
slug_value), so the loop contains a condition to exclude them.

So the whole script looks like below:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>

  <xsl:template match="case_material">
    <xsl:copy>
      <xsl:apply-templates select="*[name() != 'option']|@*"/>
      <xsl:for-each-group select="option/*" group-by="name()">
        <xsl:if test="current-grouping-key() != 'slug_value'">
         <xsl:element name="{current-grouping-key()}">
           <xsl:value-of select="current-group()" separator=","/>
         </xsl:element>
        </xsl:if>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

It is possible to write such a script in XSLT 1.0, but then you would
have to write much more code, as version 1.0 does not support e.g. grouping.

Body:
I have an XML structure and I'd like to transform this with XSLT. However, it's important to make this as dynamic as possible. I believe it's possible to make a copy of the feed, and then just select a specific section and transform this. When a new node is added to the original XML, no changed should be necessary in the XSLT to have this new node included in the output of the XSLT.

Example of original XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <option>
          <value_local>Verguld</value_local>
          <value_en>Gold-plated</value_en>
          <slug_value>1750-verguld</slug_value>
        </option>
        <option>
          <value_local>Zilver</value_local>
          <value_en>Silver</value_en>
          <slug_value>1751-silver</slug_value>
        </option>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>

Desired output:

<?xml version="1.0" encoding="UTF-8"?>
<catalog week_id="629" generated_at="15.11.2017 23:53" version="2">
  <item>
    <lot>
      <id>2982641</id>
      <title_local><![CDATA[Title]]></title_local>
      <sub_title_local>Subtitle</sub_title_local>
      <promo>false</promo>
    </lot>
    <lot_specifics>
      <case_material>
        <name_local>Materiaal kast</name_local>
        <name_en>Case material</name_en>
        <slug>s-10-materiaal-kast</slug>
        <value_local>Verguld,Silver</value_local>
        <value_en>Gold-plated,Silver</value_en>
      </case_material>
    </lot_specifics>
    <associations>
      <category_id>1</category_id>
      <auction_id>2</auction_id>
    </associations>
  </item>
</catalog>

I came across a SO question that pretty much does what I'm aiming for, but I need to define the complete XML structure in this XSLT. As we might add other XML nodes in a later stage and this XSLT will be used in various places, I want to make this as low maintenance as possible.

I think this SO question shows a low maintenance version but frankly I'm not able to understand how the second xsl:template works.

All help is much appreciated. If XSLT is provided, I'd appreciate it if you could include some comments of what you're doing where.

Body:
As you didn't specify the XSLT version, I used 2.0,
which is more powerful and better suited for such a task.

Your script should contain:

An identity template.

A template for case_material elements.

This template should:

Copy all elements other than option.

Provide special handling of option elements.

This special handling should include grouping of all child elements of option
by element name. For each such group you should:

Create an element with the name of the source element (grouping key).

Print out the content of all group members, separated with a comma.

I noticed that you want to "exclude" certain elements (actually only
slug_value), so the loop contains a condition to exclude them.

So the whole script looks like below:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>

  <xsl:template match="case_material">
    <xsl:copy>
      <xsl:apply-templates select="*[name() != 'option']|@*"/>
      <xsl:for-each-group select="option/*" group-by="name()">
        <xsl:if test="current-grouping-key() != 'slug_value'">
         <xsl:element name="{current-grouping-key()}">
           <xsl:value-of select="current-group()" separator=","/>
         </xsl:element>
        </xsl:if>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
  </xsl:template>
</xsl:stylesheet>

It is possible to write such a script in XSLT 1.0, but then you would
have to write much more code, as version 1.0 does not support e.g. grouping.


来源: stackexchange

问:
Windows 10: The application was unable to start correctly (0xc000a200)
I am developing my QT application on windows 10 . The development is complete (as for now).

After run the application in debug mode from QT-creator, I am trying to run the executable from the build directory. But it shows me an "Application Error" dialog with the following message:

The application was unable to start correctly (0xc000a200). Click OK
  to close the application.

What is the problem and How to fix it ?!

答: I had the same error, but the approved solution wasn't the cure.  What I found is that I had installed the wrong Qt compiler support packages.  For me it was Qt 5.9.1 on Windows 10 64 bit to use with Visual Studio 2017.  When installing Qt I selected the "msvc2017 64-bit" option.  Sound good, right?  Wrong: what I wanted was the "UWP x64 (MSVC2017)".</p>

ContentLicense: CC BY-SA 3.0


问:
css div not being recognized
I have the following css code:

```<code>#Layer3

{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-color: #f1ffff;
}

#Layer3 h1
{
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}

.tableheader {
    border-width:10px; border-style:solid;
}
.tablecontent {
    height: 95%;
    overflow:auto;
}
</code>```

However, when I use this PHP to generate the html

```<code>echo '<div id="tableheader" class="tableheader">';

echo "<h1>{$query} Auctions</h1>" . "\n";
echo "</div>";
echo '<div id="tablecontent" class="tablecontent">';

echo "<table border='0' width='100%'><tr>" . "\n";

echo "<td width='15%'>Seller ID</td>" . "\n";

echo "<td width='10%'>Start Date</td>" . "\n";

echo "<td width='75%'>Description</td>" . "\n";

echo "</tr>\n";

// printing table rows

    foreach ($rows as $row)

    {

        $pk = $row['ARTICLE_NO'];

        echo '<tr>' . "\n";

table contens generated in here

        echo '</tr>' . "\n";

    }
echo "</table>";
}

echo "</div>";
</code>```

which generates this html:

```<code><div id="tableheader" class="tableheader">
<h1>hardy Auctions</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border='0' width='100%'>
<tr>
<td width='15%'>Seller ID</td>
<td width='10%'>Start Date</td>
<td width='75%'>Description</td>
the rest of table stuff
</div>
</code>```

The stylesheet is correctly referenced so I am unsure what is causing the error. But there is no border around tableheader at all. Both of these layers are in Layer3 which no longer displays properly on the page.

答:
```<code>#tableheader {
  border: 10px solid #000;
}
</code>```

Try giving it a color.

EDIT: since its id is tableheader, try changing the style selector to be an id.  You could also try using !important to see if anything is overriding your class selector.

Specificity values:

inline: 1000; id: 100, class: 10, element: 1

!important trumps all other non-important declarations.

ContentLicense: CC BY-SA 2.5

Title: css div not being recognized

Body:
I have the following css code:

#Layer3

{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-color: #f1ffff;
}

#Layer3 h1
{
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}

.tableheader {
    border-width:10px; border-style:solid;
}
.tablecontent {
    height: 95%;
    overflow:auto;
}

However, when I use this PHP to generate the html

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";

echo "Start Date	" . "\n";

echo "Description	" . "\n";

echo "
\n";

// printing table rows

    foreach ($rows as $row)

    {

        $pk = $row['ARTICLE_NO'];

        echo '
' . "\n";

table contens generated in here

        echo '
' . "\n";

    }
echo "
";
}

echo "
";

which generates this html:

hardy Auctions

Seller ID
Start Date
Description
the rest of table stuff

The stylesheet is correctly referenced so I am unsure what is causing the error. But there is no border around tableheader at all. Both of these layers are in Layer3 which no longer displays properly on the page.

Body:
#tableheader {
  border: 10px solid #000;
}

Try giving it a color.

EDIT: since its id is tableheader, try changing the style selector to be an id.  You could also try using !important to see if anything is overriding your class selector.

Specificity values:

inline: 1000; id: 100, class: 10, element: 1

!important trumps all other non-important declarations.


问:
Wrong CurrentCulture when running an nUnit test in TeamCity
I have a unit-test that relies on a specific culture.

In FixtureSetup, I set both Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture to the desired value (en-US).

When I run the test from Resharper, it passes.

When I run the test from TeamCity (using the runner "NUnit 2.4.6"), the test fails, because
CurrentCulture is cs-CZ (the culture of my OS). However CurrentUICulture is still en-US.

答:
You can force a specific culture for running your tests in your current thread System.Threading.Thread.CurrentThread

```<code>// set CurrentCulture to Invariant
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// set UI culture to invariant
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
</code>```

You can also use CultureInfo.GetCultureInfo to provide the culture you want to use. This can be down in the SetUp part of your tests.

Remember to restore the culture to the previous one in your TearDown to ensure isolation

```<code>[TestFixture]
class MyTest {
  CultureInfo savedCulture;

  [SetUp]
  public void SetUp() {
    savedCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  }

  [TearDown]
  public void TearDown() {
    Thread.CurrentThread.CurrentCulture = savedCulture;
  }
}
</code>```

Body:
You can force a specific culture for running your tests in your current thread System.Threading.Thread.CurrentThread

// set CurrentCulture to Invariant
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// set UI culture to invariant
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

You can also use CultureInfo.GetCultureInfo to provide the culture you want to use. This can be down in the SetUp part of your tests.

Remember to restore the culture to the previous one in your TearDown to ensure isolation

[TestFixture]
class MyTest {
  CultureInfo savedCulture;

  [SetUp]
  public void SetUp() {
    savedCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  }

  [TearDown]
  public void TearDown() {
    Thread.CurrentThread.CurrentCulture = savedCulture;
  }
}


问:
How can I add multiple conditions to regex?
I have tried many times but could not find the solution.

One of the rules is if string ends with digit then it must contain one more digit in string anywhere

These are the rules I have - as you can see in the console my test does not work as expected

```<code>/* password length 6-80, */
/* if ends with digit then must contain two digit, */
/* 1 upper case character, 1 lowercase character, 1 digit and 1 special character. */
/* If password starts with uppercase character then 2 uppercase character are required. */
</code>```

var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_*&^%$#@!~])((?=\b[A-Z]).*[A-Z].*[A-Z].*|(?!\b[A-Z]))((?=.*\d$).*\d.*\d.*|(?!.*\d$)){6,80}/g;

console.log("false?",re.test('Aa@sasA1'));
console.log("true?",re.test('Aa@sa1sA1'));```

答:
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_*&^%$#@!~])(?=[A-Z].*[A-Z]|[^A-Z])(?=.*\d.*\d$|.*\D$).{6,80}$/;

console.log("false?",re.test('Aa@sasA1'));
console.log("true?",re.test('Aa@sa1sA1'));```
</div>
</div>
</p>

<p><strong>Explanation:</strong></p>

```(?=[A-Z].*[A-Z]|[^A-Z]) : first character: 1 upper and another one OR not upper
(?=.*\d.*\d$|.*\D$)     : last character: digit and another one before OR not a digit
```

Body:
I have tried many times but could not find the solution.

One of the rules is if string ends with digit then it must contain one more digit in string anywhere

These are the rules I have - as you can see in the console my test does not work as expected

/* password length 6-80, */
/* if ends with digit then must contain two digit, */
/* 1 upper case character, 1 lowercase character, 1 digit and 1 special character. */
/* If password starts with uppercase character then 2 uppercase character are required. */

var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_*&^%$#@!~])((?=\b[A-Z]).*[A-Z].*[A-Z].*|(?!\b[A-Z]))((?=.*\d$).*\d.*\d.*|(?!.*\d$)){6,80}/g;

console.log("false?",re.test('Aa@sasA1'));
console.log("true?",re.test('Aa@sa1sA1'));

Body:
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_*&^%$#@!~])(?=[A-Z].*[A-Z]|[^A-Z])(?=.*\d.*\d$|.*\D$).{6,80}$/;

console.log("false?",re.test('Aa@sasA1'));
console.log("true?",re.test('Aa@sa1sA1'));

Explanation:

(?=[A-Z].*[A-Z]|[^A-Z]) : first character: 1 upper and another one OR not upper
(?=.*\d.*\d$|.*\D$)     : last character: digit and another one before OR not a digit


问:
C# : Removing Columns from Datatable
Suppose I have two tables

Table 1 with following columns (Dots to represent columns in between)

```<code>id int
name varchar
.
.
.
.
LastChanged datetime
</code>```

Table 2 with following columns

```<code>id int
Address varchar
.
.
.
.
LastChanged datetime
</code>```

I executed a query like below in C# and stored the result in a Datatable.

```<code>select * from table1 t1
inner join  table2 t2
on t1.id=t2.id
</code>```

Now I don't want the column LastChanged  in the result.

LastChanged column is present in both tables. Since Datatable doesn't allow duplicate column names, one of the LastChanged column in result is renamed to LastChanged1

So when I try to remove the column using

```<code>if (table.Columns.Contains("LastChanged"))
                table.Columns.Remove("LastChanged");
</code>```

Only one LastChanged is removed. The other one remains.

One solution is to eliminate LastChanged in the query itself
by specifying the required columns.
But it makes query long since almost all columns except LastChanged is needed in result.

Is there a solution in C#?

答:
You can use Linq to achieve this</p>

```<code>var lst = table.Columns.Cast<DataColumn>()
     .Where(x => x.ColumnName.StartsWith("LastChanged"))
     .ToList();

foreach(DataColumn col in lst){
      table.Columns.Remove(col);}
</code>```

Title: C# : Removing Columns from Datatable

Body:
Suppose I have two tables

Table 1 with following columns (Dots to represent columns in between)

id int
name varchar
.
.
.
.
LastChanged datetime

Table 2 with following columns

id int
Address varchar
.
.
.
.
LastChanged datetime

I executed a query like below in C# and stored the result in a Datatable.

select * from table1 t1
inner join  table2 t2
on t1.id=t2.id

Now I don't want the column LastChanged  in the result.

LastChanged column is present in both tables. Since Datatable doesn't allow duplicate column names, one of the LastChanged column in result is renamed to LastChanged1

So when I try to remove the column using

if (table.Columns.Contains("LastChanged"))
                table.Columns.Remove("LastChanged");

Only one LastChanged is removed. The other one remains.

One solution is to eliminate LastChanged in the query itself
by specifying the required columns.
But it makes query long since almost all columns except LastChanged is needed in result.

Is there a solution in C#?

Body:
You can use Linq to achieve this

var lst = table.Columns.Cast<DataColumn>()
     .Where(x => x.ColumnName.StartsWith("LastChanged"))
     .ToList();

foreach(DataColumn col in lst){
      table.Columns.Remove(col);}


问:
modify checkbox using javascript
I had declared 5 checkboxes with name and id attribute in a html:

```<code><input type="checkbox" name="category" value="One" id=11>One<br/>
<input type="checkbox" name="category" value="Two" id=12>Two<br/>
<input type="checkbox" name="category" value="Three" id=13>Three<br/>
<input type="checkbox" name="category" value="Four" id=14>Four<br/>
</code>```

After declaration, I want to run a javascript that would enable the checkbox1 using that checkbox id.

Let me know to clarify something.

答:
Try this for checking the checkbox:

```<code>document.getElementById(<id of first checkbox>).checked = true;
</code>```

Try this for enabling the checkbox:

```<code>document.getElementById(<id of first checkbox>).disabled = false;
</code>```

Title: modify checkbox using javascript

Body:
I had declared 5 checkboxes with name and id attribute in a html:

<input type="checkbox" name="category" value="One" id=11>One

<input type="checkbox" name="category" value="Two" id=12>Two

<input type="checkbox" name="category" value="Three" id=13>Three

<input type="checkbox" name="category" value="Four" id=14>Four

After declaration, I want to run a javascript that would enable the checkbox1 using that checkbox id.

Let me know to clarify something.

Body:
Try this for checking the checkbox:

document.getElementById(<id of first checkbox>).checked = true;

Try this for enabling the checkbox:

document.getElementById(<id of first checkbox>).disabled = false;


问:
Alternative to for and ifelse loops - determining whether elements lie within generated confidence intervals
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

```<code>cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412
</code>```

mu looks like this:

```<code>mu <- c(4, 8)
mu
y0 y1
 4  8
</code>```

The code I have is:

```<code>incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}
</code>```

The result, incinterval, looks like this:

```<code>     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1
</code>```

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

答:
Thank you all for your suggestions and feedback.

I took Ape's suggestion as it was the simplest.

The code is now changed with bold text to:

```<code>incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after treatment modules (can be any number of modules))
  **incinterval <- rbind(as.numeric(mu["y0"] >= cinterval[1,] & mu["y0"] <= cinterval[2,]),
                        as.numeric(mu["y1"] >= cinterval[3,] & mu["y0"] <= cinterval[4,]))**
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}
</code>```

Instead of using for loops and ifelse loops, it's using a simpler way to answer the question with generating vectors with the comparison operators.

Body:
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412

mu looks like this:

mu <- c(4, 8)
mu
y0 y1
 4  8

The code I have is:

incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}

The result, incinterval, looks like this:

     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

Body:
Thank you all for your suggestions and feedback.

I took Ape's suggestion as it was the simplest.

The code is now changed with bold text to:

incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after treatment modules (can be any number of modules))
  **incinterval <- rbind(as.numeric(mu["y0"] >= cinterval[1,] & mu["y0"] <= cinterval[2,]),
                        as.numeric(mu["y1"] >= cinterval[3,] & mu["y0"] <= cinterval[4,]))**
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}

Instead of using for loops and ifelse loops, it's using a simpler way to answer the question with generating vectors with the comparison operators.


问:
Extensible Records and Higher Order Functions
I want to specify a type for records that have an id field whose type is a Uuid. So, I'm using extensible records. The type looks like this:

```<code>type alias WithId a = { a | id : Uuid }
</code>```

So far, so good. But then I went to create a Json.Encoder -- that is, a function of type WithId a -> Value -- for this type. I need a way to encode the underlying value, so I want to take a first argument of type a -> Value. Since I know a is a record, I can safely assume it is encoded to a JSON object, even though Elm doesn't expose the data types for Value.

However, when I create such a function, I get a compile error:

```<code>    The argument to function `encoder` is causing a mismatch.

27|             encoder a
                        ^
Function `encoder` is expecting the argument to be:

    a

But it is:

    WithId a

Hint: Your type annotation uses type variable `a` which means any type of value
can flow through. Your code is saying it CANNOT be anything though! Maybe change
your type annotation to be more specific? Maybe the code has a problem? More at:
<https://github.com/elm-lang/elm-compiler/blob/0.18.0/hints/type-annotations.md>

Detected errors in 1 module.
</code>```

I'm confused. Isn't something of type WithId a going to contain all the fields of a, and therefore shouldn't WithId a be an a through the type alias structural typing?

What am I missing? Why isn't the type alias of WithId a allowing me to use a WithId a as an instance of a, even though it is defined as {a|...}?

ADDENDUM

I've marked an answer below (which amounts to "You just can't do that, but here's what you're supposed to be doing."), but I'm still a bit unsatisfied. I guess I'm confused by the use of the term type alias. My understanding was that records were always a type alias, because they were explicitly specifying a subset of fields among all possible fields...but the underlying type was still the unifying record type (akin to a JS Object).

I guess I don't understand why we say:

```<code>type alias Foo = { bar : Int }
</code>```

instead of

```<code>type Foo = { bar : Int }
</code>```

The former implies to me that any record with { bar : Int } is a Foo, which would imply to me that {a|bar:Int} is both of the same type as a and a Foo. Where am I wrong here? I'm confused. I feel like I'm not grokking records.

ADDENDUM 2

My goal is not just to have a type WithId that specifies there is an .id on a field, but rather to have two types: Foo and WithId Foo where Foo has structure { bar:Int } and WithId Foo has structure { bar:Int, id:Uuid}.  I'd then like to also have a WithId Baz, WithId Quux, etc., etc., with a single encoder and single decoder function for WithId a.

The basic issue is that I have persisted and non-persisted data, which have the exact same structure, except that once something is persisted, I have an id. And want I type-level guarantees that records are persisted in certain cases, so Maybe doesn't work.

答:
Reading your addenda and re-reading your question, I believe you actually can achieve what you want with extensible records in Elm.

Here's a little program that does what you're after and compiles just fine:

```<code>module Main exposing (main)

import Html exposing (Html, pre, text)
import Json.Encode as Json exposing (Value, int, object, string)

main : Html msg
main =
    let
        json =
            Json.encode 2 <|
                encoder recordEncoder record
    in
    pre [] [ text json ]

type alias WithId a =
    { a | id : Int }

type alias Record =
    WithId
        { fieldA : String
        }

record : Record
record =
    { id = 123
    , fieldA = "A"
    }

encoder : (WithId a -> Value) -> WithId a -> Value
encoder recordEncoder value =
    object
        [ ( "id", int value.id )
        , ( "value", recordEncoder value )
        ]

recordEncoder : Record -> Value
recordEncoder record =
    object
        [ ( "fieldA", string record.fieldA ) ]
</code>```

View on Ellie - The Elm Live Editor

As per my first answer I'm still pretty sure it won't work out well if you extend this pattern to your whole program, but the nice thing about Elm is that you can try stuff like this and if it doesn't work out, the compiler is there to help you refactor!

…and if you really need to be able to deal with both persisted and non-persisted records in your program, you can do it with just a little repetition in your type aliases:

```<code>module Main exposing (main)

import Html exposing (Html, pre, text)
import Json.Encode as Json exposing (Value, int, object, string)

main : Html msg
main =
    let
        json =
            Json.encode 2 <|
                encoder recordEncoder record
    in
    pre [] [ text json ]

type alias WithId a =
    { a
        | id : Int
    }

type alias Record a =
    { a
        | fieldA : String
    }

type alias PersistedRecord =
    { id : Int
    , fieldA : String
    }

record : PersistedRecord
record =
    { id = 123
    , fieldA = "A"
    }

encoder : (WithId a -> Value) -> WithId a -> Value
encoder recordEncoder value =
    object
        [ ( "id", int value.id )
        , ( "value", recordEncoder value )
        ]

recordEncoder : Record a -> Value
recordEncoder record =
    object
        [ ( "fieldA", string record.fieldA ) ]
</code>```

View on Ellie - The Elm Live Editor

To answer this part of your addenda directly:

I guess I don't understand why we say:

```<code>type alias Foo = { bar : Int }
</code>```

instead of

```<code>type Foo = { bar : Int }
</code>```

The former implies to me that any record with { bar : Int } is a Foo, which would imply to me that {a|bar:Int} is both of the same type as a and a Foo. Where am I wrong here? I'm confused. I feel like I'm not grokking records.

{ a | bar:Int } is not a Foo, because the Foo type alias specifies a fixed set of fields. Foo contains a bar field and no other fields. If you want to say “a record with these fields and possibly others”, you need to use the extensible record syntax ({ a | …fields… }).

So I think where you're going wrong is in assuming that all record types are extensible. They aren't. When a function says it takes or returns a record with a fixed set of fields, those values will never contain other fields—the compiler guarantees it.

Body:
I want to specify a type for records that have an id field whose type is a Uuid. So, I'm using extensible records. The type looks like this:

type alias WithId a = { a | id : Uuid }

So far, so good. But then I went to create a Json.Encoder -- that is, a function of type WithId a -> Value -- for this type. I need a way to encode the underlying value, so I want to take a first argument of type a -> Value. Since I know a is a record, I can safely assume it is encoded to a JSON object, even though Elm doesn't expose the data types for Value.

However, when I create such a function, I get a compile error:

    The argument to function `encoder` is causing a mismatch.

27|             encoder a
                        ^
Function `encoder` is expecting the argument to be:

    a

But it is:

    WithId a

Hint: Your type annotation uses type variable `a` which means any type of value
can flow through. Your code is saying it CANNOT be anything though! Maybe change
your type annotation to be more specific? Maybe the code has a problem? More at:
<https://github.com/elm-lang/elm-compiler/blob/0.18.0/hints/type-annotations.md>

Detected errors in 1 module.

I'm confused. Isn't something of type WithId a going to contain all the fields of a, and therefore shouldn't WithId a be an a through the type alias structural typing?

What am I missing? Why isn't the type alias of WithId a allowing me to use a WithId a as an instance of a, even though it is defined as {a|...}?

ADDENDUM

I've marked an answer below (which amounts to "You just can't do that, but here's what you're supposed to be doing."), but I'm still a bit unsatisfied. I guess I'm confused by the use of the term type alias. My understanding was that records were always a type alias, because they were explicitly specifying a subset of fields among all possible fields...but the underlying type was still the unifying record type (akin to a JS Object).

I guess I don't understand why we say:

type alias Foo = { bar : Int }

instead of

type Foo = { bar : Int }

The former implies to me that any record with { bar : Int } is a Foo, which would imply to me that {a|bar:Int} is both of the same type as a and a Foo. Where am I wrong here? I'm confused. I feel like I'm not grokking records.

ADDENDUM 2

My goal is not just to have a type WithId that specifies there is an .id on a field, but rather to have two types: Foo and WithId Foo where Foo has structure { bar:Int } and WithId Foo has structure { bar:Int, id:Uuid}.  I'd then like to also have a WithId Baz, WithId Quux, etc., etc., with a single encoder and single decoder function for WithId a.

The basic issue is that I have persisted and non-persisted data, which have the exact same structure, except that once something is persisted, I have an id. And want I type-level guarantees that records are persisted in certain cases, so Maybe doesn't work.

Body:
Reading your addenda and re-reading your question, I believe you actually can achieve what you want with extensible records in Elm.

Here's a little program that does what you're after and compiles just fine:

module Main exposing (main)

import Html exposing (Html, pre, text)
import Json.Encode as Json exposing (Value, int, object, string)

main : Html msg
main =
    let
        json =
            Json.encode 2 <|
                encoder recordEncoder record
    in
    pre [] [ text json ]

type alias WithId a =
    { a | id : Int }

type alias Record =
    WithId
        { fieldA : String
        }

record : Record
record =
    { id = 123
    , fieldA = "A"
    }

encoder : (WithId a -> Value) -> WithId a -> Value
encoder recordEncoder value =
    object
        [ ( "id", int value.id )
        , ( "value", recordEncoder value )
        ]

recordEncoder : Record -> Value
recordEncoder record =
    object
        [ ( "fieldA", string record.fieldA ) ]

View on Ellie - The Elm Live Editor

As per my first answer I'm still pretty sure it won't work out well if you extend this pattern to your whole program, but the nice thing about Elm is that you can try stuff like this and if it doesn't work out, the compiler is there to help you refactor!

…and if you really need to be able to deal with both persisted and non-persisted records in your program, you can do it with just a little repetition in your type aliases:

module Main exposing (main)

import Html exposing (Html, pre, text)
import Json.Encode as Json exposing (Value, int, object, string)

main : Html msg
main =
    let
        json =
            Json.encode 2 <|
                encoder recordEncoder record
    in
    pre [] [ text json ]

type alias WithId a =
    { a
        | id : Int
    }

type alias Record a =
    { a
        | fieldA : String
    }

type alias PersistedRecord =
    { id : Int
    , fieldA : String
    }

record : PersistedRecord
record =
    { id = 123
    , fieldA = "A"
    }

encoder : (WithId a -> Value) -> WithId a -> Value
encoder recordEncoder value =
    object
        [ ( "id", int value.id )
        , ( "value", recordEncoder value )
        ]

recordEncoder : Record a -> Value
recordEncoder record =
    object
        [ ( "fieldA", string record.fieldA ) ]

View on Ellie - The Elm Live Editor

To answer this part of your addenda directly:

I guess I don't understand why we say:

type alias Foo = { bar : Int }

instead of

type Foo = { bar : Int }

The former implies to me that any record with { bar : Int } is a Foo, which would imply to me that {a|bar:Int} is both of the same type as a and a Foo. Where am I wrong here? I'm confused. I feel like I'm not grokking records.

{ a | bar:Int } is not a Foo, because the Foo type alias specifies a fixed set of fields. Foo contains a bar field and no other fields. If you want to say “a record with these fields and possibly others”, you need to use the extensible record syntax ({ a | …fields… }).

So I think where you're going wrong is in assuming that all record types are extensible. They aren't. When a function says it takes or returns a record with a fixed set of fields, those values will never contain other fields—the compiler guarantees it.


问:
Spring 5.0.1 namedJdbcTemplate batchUpdate ORA-01000: maximum open cursors exceeded
I have recently upgraded my project from Spring Framework 4.3.10 to 5.0.1.
After the upgrade the namedParameterJdbcTemplate.batchUpdate started to fail with this error

ORA-01000: maximum open cursors exceeded.

The batch updates 250 records a time which has not changed and was working fine with Spring 4.3.x.

Has anyone came across a similar issue with Spring 5.0.1 ?

I haven't seen any changes in the Spring documentation related to usage of batchUpdate.

Any clues or is it a candidate for jire issue.

I have rolled back spring-jdbc alone to version 4.3.10 which resolved the issue.
I have also raised a Jira regression defect https://jira.spring.io/browse/SPR-16139

答:
After exchanging information via Spring JIRA ticket the following resolved the issue:

Upgrading to the latest Oracle JDBC driver 12.2.0.1 (ojdbc8.jar)

Creating spring.properties file with entry:spring.jdbc.getParameterType.ignore=true

The Oracle driver upgrade resolves the cursor leaking issue. The spring.properties file resolves performance issue with spring-jdbc version 5.0.1.

I expect that there will be some changes in spring-jdbc 5.0.2 that will resolve the issue without having to create custom spring.properties file.

The issue was resolved thanks to Juergen Hoeller from Spring team.


问:
How to get id of minprice in mysql query php
I want to select the exact id of the minprice in mysql query below in my mysql query

```<code>Select min(p.Price) as minprice,GROUP_CONCAT(p.vendor_id) as v_ids,p.*
from my_table as p GROUP BY `SKU` order by Price ASC
</code>```

I also tried this

```<code>Select min(p.Price) as minprice,
  GROUP_CONCAT(p.PRODUCT_ID) as IDS,
  GROUP_CONCAT(p.Price) as prices,
  GROUP_CONCAT(p.vendor_id) as v_ids,p.* from `my_table` as p
  GROUP BY `SKU` order by Price ASC
</code>```

but it does not help me out

Please to get the id of minprice

答:
```<code>SELECT MT.* FROM MY_TABLE MT
INNER JOIN
(
SELECT PRODUCT_ID ID,SKU,MIN(P.PRICE) FROM MY_TABLE GROUP BY PRODUCT_ID,SKU
)Z ON Z.ID=MT.PRODUCT_ID AND Z.SKU=MT.SKU
</code>```

You can try above code.

ContentLicense: CC BY-SA 4.0

Body:
I want to select the exact id of the minprice in mysql query below in my mysql query

Select min(p.Price) as minprice,GROUP_CONCAT(p.vendor_id) as v_ids,p.*
from my_table as p GROUP BY `SKU` order by Price ASC

I also tried this

Select min(p.Price) as minprice,
  GROUP_CONCAT(p.PRODUCT_ID) as IDS,
  GROUP_CONCAT(p.Price) as prices,
  GROUP_CONCAT(p.vendor_id) as v_ids,p.* from `my_table` as p
  GROUP BY `SKU` order by Price ASC

but it does not help me out

Please to get the id of minprice

Body:
SELECT MT.* FROM MY_TABLE MT
INNER JOIN
(
SELECT PRODUCT_ID ID,SKU,MIN(P.PRICE) FROM MY_TABLE GROUP BY PRODUCT_ID,SKU
)Z ON Z.ID=MT.PRODUCT_ID AND Z.SKU=MT.SKU

You can try above code.


问:
How to run jupyter notebook in the background ? No need to keep one terminal for it
Often we run jupyter notebook to pop up a page in browser to use notebook. However, the terminal opening the server remains there. Is there a way that we can close that terminal with server running in the back ?

答:
You can put the process into the background by using jupyter notebook --no-browser & disown. You can close the terminal afterwards and the process will still be running.

If you're using zsh you can also use a shorter version that does the same: jupyter notebook --no-browser &!.

To kill the process you can use pgrep jupyter to find the PID of the process and then kill 1234, replacing 1234 with the PID you just found.

Explanation

The --no-browser flag makes jupyter not open the browser automatically, it also works without this flag.

The & puts it into the background of the currently running shell.

The disown then removes the job from the background of the currently running shell and makes it run independently of the shell so that you may close it.

In the zsh version the &! is a built-in function that does the same as & disown.


问:
How to remove margin-left and margin-right of col class in bootstrap?
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

```<code><div class="container">
    <div class="row">
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
        <div class="col-sm-6">
            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
        </div>
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
    </div>
</div>
</code>```

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

答:
As Yorki Bonilla said you can do something like this:

```<code><div class="container">
<div class="row no-marginLR">
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
    <div class="col-sm-6 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
    </div>
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
</div>
</code>```

And add a class in your CSS

```<code>.no-padding {
    padding: 0px;
}
</code>```

But at the same time you have to remember to remove the left and right margin to the row that contains your columns by doing:

```<code>.no-marginLR {
    margin-left:0;
    margin-right:0;
}
</code>```

Note that I've added the .no-marginLR class to the row

Body:
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

Body:
As Yorki Bonilla said you can do something like this:

<div class="container">
<div class="row no-marginLR">
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
    <div class="col-sm-6 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
    </div>
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
</div>

And add a class in your CSS

.no-padding {
    padding: 0px;
}

But at the same time you have to remember to remove the left and right margin to the row that contains your columns by doing:

.no-marginLR {
    margin-left:0;
    margin-right:0;
}

Note that I've added the .no-marginLR class to the row


问:
Use blackberry camera in java app to select a photo that was already on file
I know you can use

```<code>Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, null);
</code>```

to get the blackberry camera application to be shown and allow the user to take photos. From which you can use a FileJournalListener to find any created files.

(As shown/implied in this forum post: http://supportforums.blackberry.com/t5/Java-Development/How-to-use-FileJournalListener/td-p/295424)

There are times however, when the user chooses not to take a photo but selects one from the file system.  Since this wasn't created at the time I opened it, using the FileJournalListener is not going to meet my needs.

What should I use to get the selected file?

EDIT: The functionality I'm trying to produce I've seen in the Twitter for blackberry application

答:
I think you should create a file picker first,

http://docs.blackberry.com/en/developers/deliverables/11958/Create_a_file_picker_856986_11.jsp

After that in the application, user could select whether to capture new picture or browse from their storage.
If user select the later, open up this file picker and for every images found user can view the image, and the application can save the path where the images located for further processing.

Body:
I know you can use

Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, null);

to get the blackberry camera application to be shown and allow the user to take photos. From which you can use a FileJournalListener to find any created files.

(As shown/implied in this forum post: http://supportforums.blackberry.com/t5/Java-Development/How-to-use-FileJournalListener/td-p/295424)

There are times however, when the user chooses not to take a photo but selects one from the file system.  Since this wasn't created at the time I opened it, using the FileJournalListener is not going to meet my needs.

What should I use to get the selected file?

EDIT: The functionality I'm trying to produce I've seen in the Twitter for blackberry application


问:
Gradle project sync failed on newly created Android project
I created an Android project in Intellij Idea (which I'm using instead of Android Studio because I also need to manage some React code in the project as well). I created a basic Activity which was the default for building the project:

```<code>package com.example.mypackage.reacttoastex;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

However, I am getting this error message in Intellij:

```<code>Gradle project sync failed. Basic functionality (e.g. editing, debugging) will not work properly
</code>```

If I run Build Project, I am getting this:

```<code>Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not find any version that matches com.android.support:appcompat-v7:27.+.
     Versions that do not match:
         26.0.0-alpha1
         25.3.1
         25.3.0
         25.2.0
         25.1.1
         + 31 more
     Required by:
         project :app
</code>```

In the logs, I am getting this:

```<code>2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - IntelliJ IDEA 2017.2.5  Build #IU-172.4343.14
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - JDK: 1.8.0_152-release
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - VM: OpenJDK 64-Bit Server VM
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - Vendor: JetBrains s.r.o
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - OS: Mac OS X
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - Last Action: GotoAction
2017-11-14 14:31:38,434 [4841813]   INFO - ea.sdk.wizard.SdkQuickfixUtils - Downloading https://dl.google.com/android/repository/repository2-1.xml
2017-11-14 14:31:38,434 [4841813]  ERROR - .intellij.util.io.HttpRequests - Assertion failed: Network shouldn't be accessed in EDT or inside read action
java.lang.Throwable
    at com.intellij.openapi.diagnostic.Logger.assertTrue(Logger.java:168)
    at com.intellij.util.io.HttpRequests.process(HttpRequests.java:384)
    at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:60)
    at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:262)
    at com.intellij.util.io.RequestBuilder.saveToFile(RequestBuilder.java:67)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:86)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:98)
    at com.android.tools.idea.sdk.StudioDownloader.downloadAndStream(StudioDownloader.java:54)
    at com.android.repository.impl.manager.RemoteRepoLoaderImpl.fetchPackages(RemoteRepoLoaderImpl.java:100)
    at com.android.repository.impl.manager.RepoManagerImpl$LoadTask.run(RepoManagerImpl.java:550)
    at com.android.repository.api.RepoManager$DummyProgressRunner.runSyncWithProgress(RepoManager.java:397)
    at com.android.repository.impl.manager.RepoManagerImpl.load(RepoManagerImpl.java:364)
    at com.android.repository.api.RepoManager.loadSynchronously(RepoManager.java:290)
    at com.android.tools.idea.sdk.wizard.SdkQuickfixUtils.createDialog(SdkQuickfixUtils.java:129)
    at com.android.tools.idea.sdk.wizard.SdkQuickfixUtils.createDialogForPaths(SdkQuickfixUtils.java:85)
    at com.android.tools.idea.gradle.project.sync.hyperlink.InstallRepositoryHyperlink.execute(InstallRepositoryHyperlink.java:41)
    at com.android.tools.idea.gradle.project.sync.hyperlink.NotificationHyperlink.executeIfClicked(NotificationHyperlink.java:38)
    at com.android.tools.idea.gradle.notification.QuickFixNotificationListener.hyperlinkActivated(QuickFixNotificationListener.java:37)
    at com.intellij.notification.NotificationListener$Adapter.hyperlinkUpdate(NotificationListener.java:31)
    at com.intellij.openapi.externalSystem.service.notification.NotificationData$1.hyperlinkActivated(NotificationData.java:77)
    at com.intellij.notification.NotificationListener$Adapter.hyperlinkUpdate(NotificationListener.java:31)
    at com.intellij.openapi.externalSystem.service.notification.EditableNotificationMessageElement$MyCellEditor$ActivatedHyperlinkListener.hyperlinkUpdate(EditableNotificationMessageElement.java:186)
    at javax.swing.JEditorPane.fireHyperlinkUpdate(JEditorPane.java:342)
    at javax.swing.text.html.HTMLEditorKit$LinkController.activateLink(HTMLEditorKit.java:875)
    at javax.swing.text.html.HTMLEditorKit$LinkController.mouseClicked(HTMLEditorKit.java:674)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:269)
    at java.awt.Component.processMouseEvent(Component.java:6544)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6306)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4897)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4719)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4719)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.awt.EventQueue$4.run(EventQueue.java:735)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.d(IdeEventQueue.java:821)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:645)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:365)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

What could be the cause of this?
Maybe the Android SDK is not seen?

答:
Had this a similar issue today
Resolved it by adding the google maven repo:

```<code>repositories {
    mavenLocal()
    mavenCentral()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}
</code>```

Not my idea though (I'm brand new to Android development and only a bit familiar with Java), I found the answer here:
https://stackoverflow.com/a/47165271/8036618

Not sure what the cause is, but I'm behind a proxy, so maybe IDEA can't download from its default repo but it can download from the google maven repo?

Body:
I created an Android project in Intellij Idea (which I'm using instead of Android Studio because I also need to manage some React code in the project as well). I created a basic Activity which was the default for building the project:

package com.example.mypackage.reacttoastex;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

However, I am getting this error message in Intellij:

Gradle project sync failed. Basic functionality (e.g. editing, debugging) will not work properly

If I run Build Project, I am getting this:

Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not find any version that matches com.android.support:appcompat-v7:27.+.
     Versions that do not match:
         26.0.0-alpha1
         25.3.1
         25.3.0
         25.2.0
         25.1.1
         + 31 more
     Required by:
         project :app

In the logs, I am getting this:

2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - IntelliJ IDEA 2017.2.5  Build #IU-172.4343.14
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - JDK: 1.8.0_152-release
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - VM: OpenJDK 64-Bit Server VM
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - Vendor: JetBrains s.r.o
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - OS: Mac OS X
2017-11-14 14:31:38,156 [4841535]  ERROR - .intellij.util.io.HttpRequests - Last Action: GotoAction
2017-11-14 14:31:38,434 [4841813]   INFO - ea.sdk.wizard.SdkQuickfixUtils - Downloading https://dl.google.com/android/repository/repository2-1.xml
2017-11-14 14:31:38,434 [4841813]  ERROR - .intellij.util.io.HttpRequests - Assertion failed: Network shouldn't be accessed in EDT or inside read action
java.lang.Throwable
    at com.intellij.openapi.diagnostic.Logger.assertTrue(Logger.java:168)
    at com.intellij.util.io.HttpRequests.process(HttpRequests.java:384)
    at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:60)
    at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:262)
    at com.intellij.util.io.RequestBuilder.saveToFile(RequestBuilder.java:67)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:86)
    at com.android.tools.idea.sdk.StudioDownloader.downloadFully(StudioDownloader.java:98)
    at com.android.tools.idea.sdk.StudioDownloader.downloadAndStream(StudioDownloader.java:54)
    at com.android.repository.impl.manager.RemoteRepoLoaderImpl.fetchPackages(RemoteRepoLoaderImpl.java:100)
    at com.android.repository.impl.manager.RepoManagerImpl$LoadTask.run(RepoManagerImpl.java:550)
    at com.android.repository.api.RepoManager$DummyProgressRunner.runSyncWithProgress(RepoManager.java:397)
    at com.android.repository.impl.manager.RepoManagerImpl.load(RepoManagerImpl.java:364)
    at com.android.repository.api.RepoManager.loadSynchronously(RepoManager.java:290)
    at com.android.tools.idea.sdk.wizard.SdkQuickfixUtils.createDialog(SdkQuickfixUtils.java:129)
    at com.android.tools.idea.sdk.wizard.SdkQuickfixUtils.createDialogForPaths(SdkQuickfixUtils.java:85)
    at com.android.tools.idea.gradle.project.sync.hyperlink.InstallRepositoryHyperlink.execute(InstallRepositoryHyperlink.java:41)
    at com.android.tools.idea.gradle.project.sync.hyperlink.NotificationHyperlink.executeIfClicked(NotificationHyperlink.java:38)
    at com.android.tools.idea.gradle.notification.QuickFixNotificationListener.hyperlinkActivated(QuickFixNotificationListener.java:37)
    at com.intellij.notification.NotificationListener$Adapter.hyperlinkUpdate(NotificationListener.java:31)
    at com.intellij.openapi.externalSystem.service.notification.NotificationData$1.hyperlinkActivated(NotificationData.java:77)
    at com.intellij.notification.NotificationListener$Adapter.hyperlinkUpdate(NotificationListener.java:31)
    at com.intellij.openapi.externalSystem.service.notification.EditableNotificationMessageElement$MyCellEditor$ActivatedHyperlinkListener.hyperlinkUpdate(EditableNotificationMessageElement.java:186)
    at javax.swing.JEditorPane.fireHyperlinkUpdate(JEditorPane.java:342)
    at javax.swing.text.html.HTMLEditorKit$LinkController.activateLink(HTMLEditorKit.java:875)
    at javax.swing.text.html.HTMLEditorKit$LinkController.mouseClicked(HTMLEditorKit.java:674)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:269)
    at java.awt.Component.processMouseEvent(Component.java:6544)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6306)
    at java.awt.Container.processEvent(Container.java:2237)
    at java.awt.Component.dispatchEventImpl(Component.java:4897)
    at java.awt.Container.dispatchEventImpl(Container.java:2295)
    at java.awt.Component.dispatchEvent(Component.java:4719)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    at java.awt.Container.dispatchEventImpl(Container.java:2281)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4719)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:737)
    at java.awt.EventQueue$4.run(EventQueue.java:735)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at com.intellij.ide.IdeEventQueue.d(IdeEventQueue.java:821)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:645)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:365)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

What could be the cause of this?
Maybe the Android SDK is not seen?

Body:
Had this a similar issue today
Resolved it by adding the google maven repo:

repositories {
    mavenLocal()
    mavenCentral()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

Not my idea though (I'm brand new to Android development and only a bit familiar with Java), I found the answer here:
https://stackoverflow.com/a/47165271/8036618

Not sure what the cause is, but I'm behind a proxy, so maybe IDEA can't download from its default repo but it can download from the google maven repo?


问:
Loading/Parsing Mathematical Programming System files
In order not to reinvent the wheel I tried to find some code to parse
 Mathematical Programming System files but I didnt find any implementations in python.

Is there any code allready available for this?

Update

Reading Mathematical Prog. files

Example MPS (afiro.mps: link1, link2)

Contains:

objective function, one row, n columns

table with restrictions, m rows, n columns

right table, one column, m rows

Many languages have packages for reading and writing these files.

答:
The question does not address the specifics, e.g. pure python vs. c-wrapper-based, nor any license-issues.

But well... two things which worked for me in the past (the former was more tested for my own IPM-method on the netlib dataset; the latter looked good too):

Dirty code to use netlib's test cases with scipy's solvers based on the former approach.

cvxopt

MPS-reading is somewhat hidden here and here.

Looks pretty much python-only to me.

One should be careful about potentially modifications already done to the problem by cvxopt, at least when asking cvxopt for the matrix-form. I don't remember right now what to expect here (and it also did not matter much in my cases).

Warning: cvxopt is known for a non-trivial installation-process on windows, if you try to install the whole project!

There are also some warnings about what features of MPS-files are not supported.

GLPK + swiglpk

Basically swig-based bindings for GLPK. Available here (probably most newest python-bindings to GLPK). If using this, use it together with GLPK's manual and some understanding of SWIG (or else ).

This one should be more controllable in terms of what we read (see manual)!


问:
Using module (which is collector of modules) in particular module
This is my code:

```<code>Program Module_in_module

Use Module_collection

Implicit none

! Something...

End Program Module_in_module

Module Module_collection

Use Number_01
Use Number_02

End Module Module_collection

Module Number_01

Implicit none

! Something......

End Module Number_01

Module Number_02

Use Module_collection

Implicit none

! Something......

End Module Number_02
</code>```

I have an intention to use module Module_collection like one module which use all rest modules in the project. For example, if I want to use, in some other module, which is already in Module_collection, all modules from project with Use Module_collection i got this message:
Fatal Error: Can't open module file 'module_collection.mod' for reading at (1): No such file or directory
Is there any equivalent for Only: Some_varable which can be used for excluding module with using Module_collection (Use all others modules in project but only exclude just, in this case, Module Number_02?

答:
Now you tell us

I also got this message: it seems you have a circular dependency in
  Fortran files. Check your USE or INCLUDE statements.

and your error is blindingly obvious.  The module module_collection uses module number_02 and module number_02 uses module module_collection.  Since Fortran requires that a module be compiled before it is referenced (in a use statement) and since there is this circular dependency the compiler can't continue.

Resolve the circular dependency.  It looks a bit odd that the the collector is referenced by one of its collection.

I expect this is a duplicate of another question I haven't found yet.

Body:
This is my code:

Program Module_in_module

Use Module_collection

Implicit none

! Something...

End Program Module_in_module

Module Module_collection

Use Number_01
Use Number_02

End Module Module_collection

Module Number_01

Implicit none

! Something......

End Module Number_01

Module Number_02

Use Module_collection

Implicit none

! Something......

End Module Number_02

I have an intention to use module Module_collection like one module which use all rest modules in the project. For example, if I want to use, in some other module, which is already in Module_collection, all modules from project with Use Module_collection i got this message:
Fatal Error: Can't open module file 'module_collection.mod' for reading at (1): No such file or directory
Is there any equivalent for Only: Some_varable which can be used for excluding module with using Module_collection (Use all others modules in project but only exclude just, in this case, Module Number_02?


问:
Nested IIF/SWITCH in Report Builder: Error BC30201 Expression Expected
I'm doing some Background Colour formatting in Report Builder 3, but I'm having difficulty with this expression. Is it too complicated for the report to run, or am I missing something?

Pseudo Code - If Marks is Null (True), Background Colour is White, else if Coursecode is L1 English (number), Format Grades (Switch 1) else format grades (Switch 2).

```<code>=IIF(IsNothing(Fields!Marks.Value),
    "White",
    IIF(Fields!CourseCode.Value = '50089109',
        SWITCH(
            Fields!Marks.Value > 57, "YellowGreen",
            Fields!Marks.Value >= 48 AND Fields!Marks.Value <= 57 , "Orange",
            Fields!Marks.Value < 48, "Firebrick"
        )
        ,
        SWITCH(
            Fields!Marks.Value > 61, "YellowGreen",
            Fields!Marks.Value >= 52 AND Fields!Marks.Value <= 61 , "Orange",
            Fields!Marks.Value < 52, "Firebrick"
        )
    )
)
</code>```

This was my other approach for the same problem - starting by evaluating if the course code is true, then applying formatting based on that:

```<code>=IIF(Fields!CourseCode.Value = '50089109',
    IIF(IsNothing(Fields!Marks.Value), "White",
    SWITCH(
        Fields!Marks.Value > 57, "YellowGreen",
        Fields!Marks.Value >= 48 AND Fields!Marks.Value <= 57 , "Orange",
        Fields!Marks.Value < 48, "Firebrick"
        )
    ),
    IIF(IsNothing(Fields!Marks.Value), "White",
    SWITCH(
        Fields!Marks.Value > 61, "YellowGreen",
        Fields!Marks.Value >= 52 AND Fields!Marks.Value <= 61 , "Orange",
        Fields!Marks.Value < 52, "Firebrick"
        )
    )
)
</code>```

答:
I can't really see much wrong with your expression so it might be that some values are not being trapped. For testing purposes I would set a background color other than white so you can see if the first condition is being met. You can also clean up the SWITCH statements a little.

So, for testing purposes I would use the following expression

Test Version

```<code>=IIF(IsNothing(Fields!Marks.Value),
    "LimeGreen",
    IIF(Fields!CourseCode.Value = "50089109",
        SWITCH(
            Fields!Marks.Value > 57, "YellowGreen",
            Fields!Marks.Value >= 48, "Orange",
            Fields!Marks.Value < 48, "Firebrick",
            True, "HotPink"
        )
        ,
        SWITCH(
            Fields!Marks.Value > 61, "YellowGreen",
            Fields!Marks.Value >= 52, "Orange",
            Fields!Marks.Value < 52, "Firebrick",
            True, "HotPink"
        )
    )
)
</code>```

Anything trapped by the True part of the IIF will be LimeGreen and anything that is on the false part, but does not match any of the switch statements will be pink. You'll also notice that I have removed part of the middle expressions in the switch statement. These are not required as switch statements stop when the first true condition is met. You'll see that in the 'production' version below, we can remove even more.

We have also added a final switch expression, true. As Switch stops at the first true expression the true in our new expression acts like an else

Once you have fixed any issues, the production version would look like this.

Production Version

```<code>=IIF(IsNothing(Fields!Marks.Value),
    Nothing,
    IIF(Fields!CourseCode.Value = "50089109",
        SWITCH(
            Fields!Marks.Value > 57, "YellowGreen",
            Fields!Marks.Value >= 48, "Orange",
            True, "Firebrick"
        )
        ,
        SWITCH(
            Fields!Marks.Value > 61, "YellowGreen",
            Fields!Marks.Value >= 52, "Orange",
            True, "Firebrick"
        )
    )
)
</code>```

Body:
I'm doing some Background Colour formatting in Report Builder 3, but I'm having difficulty with this expression. Is it too complicated for the report to run, or am I missing something?

Pseudo Code - If Marks is Null (True), Background Colour is White, else if Coursecode is L1 English (number), Format Grades (Switch 1) else format grades (Switch 2).

=IIF(IsNothing(Fields!Marks.Value),
    "White",
    IIF(Fields!CourseCode.Value = '50089109',
        SWITCH(
            Fields!Marks.Value > 57, "YellowGreen",
            Fields!Marks.Value >= 48 AND Fields!Marks.Value <= 57 , "Orange",
            Fields!Marks.Value < 48, "Firebrick"
        )
        ,
        SWITCH(
            Fields!Marks.Value > 61, "YellowGreen",
            Fields!Marks.Value >= 52 AND Fields!Marks.Value <= 61 , "Orange",
            Fields!Marks.Value < 52, "Firebrick"
        )
    )
)

This was my other approach for the same problem - starting by evaluating if the course code is true, then applying formatting based on that:

=IIF(Fields!CourseCode.Value = '50089109',
    IIF(IsNothing(Fields!Marks.Value), "White",
    SWITCH(
        Fields!Marks.Value > 57, "YellowGreen",
        Fields!Marks.Value >= 48 AND Fields!Marks.Value <= 57 , "Orange",
        Fields!Marks.Value < 48, "Firebrick"
        )
    ),
    IIF(IsNothing(Fields!Marks.Value), "White",
    SWITCH(
        Fields!Marks.Value > 61, "YellowGreen",
        Fields!Marks.Value >= 52 AND Fields!Marks.Value <= 61 , "Orange",
        Fields!Marks.Value < 52, "Firebrick"
        )
    )
)

Body:
I can't really see much wrong with your expression so it might be that some values are not being trapped. For testing purposes I would set a background color other than white so you can see if the first condition is being met. You can also clean up the SWITCH statements a little.

So, for testing purposes I would use the following expression

Test Version

=IIF(IsNothing(Fields!Marks.Value),
    "LimeGreen",
    IIF(Fields!CourseCode.Value = "50089109",
        SWITCH(
            Fields!Marks.Value > 57, "YellowGreen",
            Fields!Marks.Value >= 48, "Orange",
            Fields!Marks.Value < 48, "Firebrick",
            True, "HotPink"
        )
        ,
        SWITCH(
            Fields!Marks.Value > 61, "YellowGreen",
            Fields!Marks.Value >= 52, "Orange",
            Fields!Marks.Value < 52, "Firebrick",
            True, "HotPink"
        )
    )
)

Anything trapped by the True part of the IIF will be LimeGreen and anything that is on the false part, but does not match any of the switch statements will be pink. You'll also notice that I have removed part of the middle expressions in the switch statement. These are not required as switch statements stop when the first true condition is met. You'll see that in the 'production' version below, we can remove even more.

We have also added a final switch expression, true. As Switch stops at the first true expression the true in our new expression acts like an else

Once you have fixed any issues, the production version would look like this.

Production Version

=IIF(IsNothing(Fields!Marks.Value),
    Nothing,
    IIF(Fields!CourseCode.Value = "50089109",
        SWITCH(
            Fields!Marks.Value > 57, "YellowGreen",
            Fields!Marks.Value >= 48, "Orange",
            True, "Firebrick"
        )
        ,
        SWITCH(
            Fields!Marks.Value > 61, "YellowGreen",
            Fields!Marks.Value >= 52, "Orange",
            True, "Firebrick"
        )
    )
)


问:
JPA tests hang while obtaining HSQL connection from Maven Command Line
Tests work individually within Eclipse (right click, run as Junit), but when I run them from the command line with maven, it stops while trying to obtain a DataSource connection to the HSQL database.

```<code>LogicalConnectionImpl [DEBUG] Obtaining JDBC connection
</code>```

The oddest part to me is that if I limit the tests being run to 10 (not classes, but individual @Test methods), it will work.  But once that 11th test is run it bombs out.  The test combinations do not matter, so if I have 30 tests, and I choose 11 or more to run, then it will fail. This made me think it is a DataSource connection max issue, but so far no luck with details of that.  I have tried adding heap size just for giggles, but that did not work.

So prior to this hang, I have multiple successful JDBC connection and releases.

Here is my applicationContext-HSQL.xml, which is used for both the in Eclipse and Command Line versions.  I know b/c I have forced each of them to fail by messing with the Class values below.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-3.0.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.company"/>

    <import resource="classpath*:/application-context-cxf.xml"/>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceXmlLocation" value="META-INF/persistence.xml"  />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="false" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
            </bean>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <property name="url" value="jdbc:hsqldb:mem:test" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
        <property name="entityManagerFactory" ref="entityManagerFactory"  />
    </bean>
</beans>
</code>```

All of my Test classes utilize Spring 3.2.5, JPA, DBUnit and extend AbstractInMemoryTests.java

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext-hsqldb.xml"})
public class AbstractInMemoryTests {

private static final String FLAT_XML_DATASET = "FlatXmlDataSet.xml";

@Autowired
BasicDataSource bds;

@Before
public void setUp() throws Exception {
    DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
}

@SuppressWarnings("deprecation")
private IDataSet getDataSet() throws Exception {
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(FLAT_XML_DATASET);
    IDataSet dataset = new FlatXmlDataSet(inputStream);
    return dataset;
}

private IDatabaseConnection getConnection() throws Exception {
    Connection jdbcConnection = bds.getConnection();
    IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
    return connection;
}
}
</code>```

Any ideas on why I may be hanging on that connection, or an idea of how to troubleshoot?

Thanks,
     Sean

答:
If the hanging comes after few page access, (maybe 8 which is the default maxTotal), you are not never closing the connection and opening in every request.
Just use entityManager.close(); after the db queries or check if the a connection already exists before creating a new one.

The accepted answer is setting the maxTotal connections to unlimited. Connections will just keep pilling up.

Body:
Tests work individually within Eclipse (right click, run as Junit), but when I run them from the command line with maven, it stops while trying to obtain a DataSource connection to the HSQL database.

LogicalConnectionImpl [DEBUG] Obtaining JDBC connection

The oddest part to me is that if I limit the tests being run to 10 (not classes, but individual @Test methods), it will work.  But once that 11th test is run it bombs out.  The test combinations do not matter, so if I have 30 tests, and I choose 11 or more to run, then it will fail. This made me think it is a DataSource connection max issue, but so far no luck with details of that.  I have tried adding heap size just for giggles, but that did not work.

So prior to this hang, I have multiple successful JDBC connection and releases.

Here is my applicationContext-HSQL.xml, which is used for both the in Eclipse and Command Line versions.  I know b/c I have forced each of them to fail by messing with the Class values below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-3.0.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.company"/>

    <import resource="classpath*:/application-context-cxf.xml"/>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceXmlLocation" value="META-INF/persistence.xml"  />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="false" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
            </bean>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <property name="url" value="jdbc:hsqldb:mem:test" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
        <property name="entityManagerFactory" ref="entityManagerFactory"  />
    </bean>
</beans>

All of my Test classes utilize Spring 3.2.5, JPA, DBUnit and extend AbstractInMemoryTests.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext-hsqldb.xml"})
public class AbstractInMemoryTests {

private static final String FLAT_XML_DATASET = "FlatXmlDataSet.xml";

@Autowired
BasicDataSource bds;

@Before
public void setUp() throws Exception {
    DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
}

@SuppressWarnings("deprecation")
private IDataSet getDataSet() throws Exception {
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(FLAT_XML_DATASET);
    IDataSet dataset = new FlatXmlDataSet(inputStream);
    return dataset;
}

private IDatabaseConnection getConnection() throws Exception {
    Connection jdbcConnection = bds.getConnection();
    IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
    return connection;
}
}

Any ideas on why I may be hanging on that connection, or an idea of how to troubleshoot?

Thanks,
     Sean


问:
External Translations in .NET
Good morning,

I am interested in developing an application which supports external GUI translation files to be added as desired by the users. I thought about using the localization methods built into .NET, but I think this way I cannot distribute isolated files with translations (can I?) after the application is built.

What is the better way to achieve localization using external files in C#?

Thank you very much.

答:
I've seen a lot of people implementing their own localization system for .net, but personally, I would stay with the built in structure.

Now, you can just add additional .resx files and recompile the app afterwards. But I guess this is not what you want?

Or you can implement your own Resource Provider and for example get all localization strings from a DB.

Example:

http://msdn.microsoft.com/en-us/library/aa905797.aspx#exaspnet20rpm_topic4

Title: External Translations in .NET


问:
Conditional ftplugin settings in vim
I am trying to achieve different ts, sts, sw and (no)et settings depending on project.

My idea was to have an alias, kvim f.ex., looking like alias kvim="vim -u ~/.kvimrc" with ~/.kvimrc containing only:

```<code>let g:IsKernelCode="yes"
source ~/.vimrc
</code>```

And then in my ~/.vim/ftplugin/c/c.vim I could have sections like:

```<code>if exists("g:IsKernelCode")
     "kernel-code-settings
...
</code>```

This seams to work when I open a single file. But kvim -p a_bunch_of_files*.c will result in only the first file having my kernel-code-settings.

What am I missing?

答:
You don't need to define an entire alternative vimrc configuration if you just want to set a flag variable. You can do that with --cmd:

```<code>alias kvim='vim --cmd "let g:IsKernelCode=\"yes\""'
</code>```

As you use a global flag (with the g: prefix), this will apply to all opened files (both on startup and later interactively with :edit). For each opened file, the ftplugin/c/c.vim will be sourced again. You can check by putting :echomsg commands in there.

Note that using special settings for a project or subdirectory is a common use case. Various solutions have been devised for this; here's an overview:

Central configuration

If it's okay to configure the specific commands / local exceptions centrally, you can put such autocmds into your ~/.vimrc:

```<code>:autocmd BufRead,BufNewFile /path/to/dir/* setlocal ts=4 sw=4
</code>```

It is important to use :setlocal instead of :set, and likewise :map <buffer> ... and :command! -buffer ....

On the other hand, if you want the specific configuration stored with the project (and don't want to embed this in all files via modelines), you have the following two options:

Local config with built-in functionality

If you always start Vim from the project root directory, the built-in

```<code>:set exrc
</code>```

enables the reading of a .vimrc file from the current directory. You can place the :set ts=4 sw=4 commands in there.

Local config through plugin

Otherwise, you need the help of a plugin; there are several on vim.org; I can recommend the localrc plugin (especially with my own enhancements), which even allows local filetype-specific configuration.

Note that reading configuration from the file system has security implications; you may want to :set secure.

Title: Conditional ftplugin settings in vim

Body:
I am trying to achieve different ts, sts, sw and (no)et settings depending on project.

My idea was to have an alias, kvim f.ex., looking like alias kvim="vim -u ~/.kvimrc" with ~/.kvimrc containing only:

let g:IsKernelCode="yes"
source ~/.vimrc

And then in my ~/.vim/ftplugin/c/c.vim I could have sections like:

if exists("g:IsKernelCode")
     "kernel-code-settings
...

This seams to work when I open a single file. But kvim -p a_bunch_of_files*.c will result in only the first file having my kernel-code-settings.

What am I missing?

Body:
You don't need to define an entire alternative vimrc configuration if you just want to set a flag variable. You can do that with --cmd:

alias kvim='vim --cmd "let g:IsKernelCode=\"yes\""'

As you use a global flag (with the g: prefix), this will apply to all opened files (both on startup and later interactively with :edit). For each opened file, the ftplugin/c/c.vim will be sourced again. You can check by putting :echomsg commands in there.

Note that using special settings for a project or subdirectory is a common use case. Various solutions have been devised for this; here's an overview:

Central configuration

If it's okay to configure the specific commands / local exceptions centrally, you can put such autocmds into your ~/.vimrc:

:autocmd BufRead,BufNewFile /path/to/dir/* setlocal ts=4 sw=4

It is important to use :setlocal instead of :set, and likewise :map <buffer> ... and :command! -buffer ....

On the other hand, if you want the specific configuration stored with the project (and don't want to embed this in all files via modelines), you have the following two options:

Local config with built-in functionality

If you always start Vim from the project root directory, the built-in

:set exrc

enables the reading of a .vimrc file from the current directory. You can place the :set ts=4 sw=4 commands in there.

Local config through plugin

Otherwise, you need the help of a plugin; there are several on vim.org; I can recommend the localrc plugin (especially with my own enhancements), which even allows local filetype-specific configuration.

Note that reading configuration from the file system has security implications; you may want to :set secure.


问:
aws batch: submit job using lambda
Context: AWS, S3, Lambda, Batch.

I have a lambda that is triggered when a file is uploaded in a S3 Bucket. I want that the lambda submit a Batch job.

(edit: Between S3 and Lambda everything works fine. The problem is between Lambda and Batch.)

Q: What is the role I have to give to the lambda in order to be able to submit the batch job?

My lambda gets an AccessDeniedException and fail to submit the job when:

```<code>const params = {
  jobDefinition: BATCH_JOB_DEFINITION,
  jobName: BATCH_JOB_NAME,
  jobQueue: BATCH_JOB_QUEUE,
};

Batch.submitJob(params).promise() .then .......
</code>```

答:
You can Create a Policy like AWS Batch Managed Policy,

The following Policy Allows Admin Access,You can modify it as per your needs:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "batch:*",
                "cloudwatch:GetMetricStatistics",
                "ec2:DescribeSubnets",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeKeyPairs",
                "ecs:DescribeClusters",
                "ecs:Describe*",
                "ecs:List*",
                "logs:Describe*",
                "logs:Get*",
                "logs:TestMetricFilter",
                "logs:FilterLogEvents",
                "iam:ListInstanceProfiles",
                "iam:ListRoles"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": ["iam:PassRole"],
            "Resource": [
                "arn:aws:iam::*:role/AWSBatchServiceRole",
                "arn:aws:iam::*:role/ecsInstanceRole",
                "arn:aws:iam::*:role/iaws-ec2-spot-fleet-role",
                "arn:aws:iam::*:role/aws-ec2-spot-fleet-role",
                "arn:aws:iam::*:role/AWSBatchJobRole*"
            ]
        }
    ]
}
</code>```

Attach the policy to lambda and try it again , Refer AWS Documentation

Title: aws batch: submit job using lambda

Body:
Context: AWS, S3, Lambda, Batch.

I have a lambda that is triggered when a file is uploaded in a S3 Bucket. I want that the lambda submit a Batch job.

(edit: Between S3 and Lambda everything works fine. The problem is between Lambda and Batch.)

Q: What is the role I have to give to the lambda in order to be able to submit the batch job?

My lambda gets an AccessDeniedException and fail to submit the job when:

const params = {
  jobDefinition: BATCH_JOB_DEFINITION,
  jobName: BATCH_JOB_NAME,
  jobQueue: BATCH_JOB_QUEUE,
};

Batch.submitJob(params).promise() .then .......

Body:
You can Create a Policy like AWS Batch Managed Policy,

The following Policy Allows Admin Access,You can modify it as per your needs:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "batch:*",
                "cloudwatch:GetMetricStatistics",
                "ec2:DescribeSubnets",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeKeyPairs",
                "ecs:DescribeClusters",
                "ecs:Describe*",
                "ecs:List*",
                "logs:Describe*",
                "logs:Get*",
                "logs:TestMetricFilter",
                "logs:FilterLogEvents",
                "iam:ListInstanceProfiles",
                "iam:ListRoles"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": ["iam:PassRole"],
            "Resource": [
                "arn:aws:iam::*:role/AWSBatchServiceRole",
                "arn:aws:iam::*:role/ecsInstanceRole",
                "arn:aws:iam::*:role/iaws-ec2-spot-fleet-role",
                "arn:aws:iam::*:role/aws-ec2-spot-fleet-role",
                "arn:aws:iam::*:role/AWSBatchJobRole*"
            ]
        }
    ]
}

Attach the policy to lambda and try it again , Refer AWS Documentation