问:
FPDF/FPDI Error: Fatal error: Class 'setasign\Fpdi\FpdfTpl' not found in
I am attempting to watermark an existing PDF document, and this error has been tripping me up for the past two days...

I have the FPDI library in fpdi/src/, and the fpdf library in /fpdf/

The file throwing the error is Fpdi.php (line 27).  Here are the first 30 lines:

<?php
/**
 * This file is part of FPDI
 *
 * @package   setasign\Fpdi
 * @copyright Copyright (c) 2017 Setasign - Jan Slabon (https://www.setasign.com)
 * @license   http://opensource.org/licenses/mit-license The MIT License
 * @version   2.0.0
 */

namespace setasign\Fpdi;

use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException;
use setasign\Fpdi\PdfParser\Type\PdfIndirectObject;
use setasign\Fpdi\PdfParser\Type\PdfNull;
//use setasign\Fpdi\FpdfTpl;

/**
 * Class Fpdi
 *
 * This class let you import pages of existing PDF documents into a reusable structure for FPDF.
 *
 * @package setasign\Fpdi
 */
class Fpdi extends FpdfTpl
{
    use FpdiTrait;```
</div>
</div>
</p>

<p>Here is my file that I am using to watermark the .pdf document on the fly:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
 $fullPathToFile = $_GET['fileToWaterMark'];

 require('rotation.php');

    require_once('fpdf/fpdf.php');
 require_once 'fpdi/src/fpdi.php';
 require_once('fpdi/src/FpdfTpl.php');

 class PDF_Rotate extends FPDI {

 var $angle = 0;

 function Rotate($angle, $x = -1, $y = -1) {
  if ($x == -1)
   $x = $this->x;
  if ($y == -1)
   $y = $this->y;
  if ($this->angle != 0)
   $this->_out('Q');
  $this->angle = $angle;
  if ($angle != 0) {
   $angle*=M_PI / 180;
   $c = cos($angle);
   $s = sin($angle);
   $cx = $x * $this->k;
   $cy = ($this->h - $y) * $this->k;
   $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', $c, $s, -$s, $c, $cx, $cy, -$cx, -$cy));
  }
 }

 function _endpage() {
  if ($this->angle != 0) {
   $this->angle = 0;
   $this->_out('Q');
  }
  parent::_endpage();
 }

 }

 //$fullPathToFile = "chinmay235.pdf";

 class PDF extends PDF_Rotate {

 var $_tplIdx;

 function Header() {
  global $fullPathToFile;

  //Put the watermark
  $this->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World', 40, 100, 100, 0, 'PNG');
  $this->SetFont('Arial', 'B', 50);
  $this->SetTextColor(255, 192, 203);
  $this->RotatedText(20, 230, 'Raddyx Technologies Pvt. Ltd.', 45);

  if (is_null($this->_tplIdx)) {

   // THIS IS WHERE YOU GET THE NUMBER OF PAGES
   $this->numPages = $this->setSourceFile($fullPathToFile);
   $this->_tplIdx = $this->importPage(1);
  }
  $this->useTemplate($this->_tplIdx, 0, 0, 200);

 }

 function RotatedText($x, $y, $txt, $angle) {
  //Text rotated around its origin
  $this->Rotate($angle, $x, $y);
  $this->Text($x, $y, $txt);
  $this->Rotate(0);
 }

 }

 $pdf = new PDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial', '', 12);
 $pdf->Output();
 ?></code>```

I am fairly competent with PHP, but this error has really thrown me for a loop.  If any more information is needed, let me know and I will provide it.

答:
What happens if you change this:

```<code>require_once('fpdf/fpdf.php');
require_once 'fpdi/src/fpdi.php';
require_once('fpdi/src/FpdfTpl.php');
</code>```

To this?

```<code>require_once('fpdf/fpdf.php');
require_once('fpdi/src/autoload.php');
</code>```

Or if you don't have autoload then you maybe need to add:

```<code>require_once('fpdi/src/FpdiTrait.php');
</code>```

Body:
I am attempting to watermark an existing PDF document, and this error has been tripping me up for the past two days...

I have the FPDI library in fpdi/src/, and the fpdf library in /fpdf/

The file throwing the error is Fpdi.php (line 27).  Here are the first 30 lines:

<?php
/**
 * This file is part of FPDI
 *
 * @package   setasign\Fpdi
 * @copyright Copyright (c) 2017 Setasign - Jan Slabon (https://www.setasign.com)
 * @license   http://opensource.org/licenses/mit-license The MIT License
 * @version   2.0.0
 */

namespace setasign\Fpdi;

use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException;
use setasign\Fpdi\PdfParser\Type\PdfIndirectObject;
use setasign\Fpdi\PdfParser\Type\PdfNull;
//use setasign\Fpdi\FpdfTpl;

/**
 * Class Fpdi
 *
 * This class let you import pages of existing PDF documents into a reusable structure for FPDF.
 *
 * @package setasign\Fpdi
 */
class Fpdi extends FpdfTpl
{
    use FpdiTrait;

Here is my file that I am using to watermark the .pdf document on the fly:

<?php
 $fullPathToFile = $_GET['fileToWaterMark'];

 require('rotation.php');

    require_once('fpdf/fpdf.php');
 require_once 'fpdi/src/fpdi.php';
 require_once('fpdi/src/FpdfTpl.php');

 class PDF_Rotate extends FPDI {

 var $angle = 0;

 function Rotate($angle, $x = -1, $y = -1) {
  if ($x == -1)
   $x = $this->x;
  if ($y == -1)
   $y = $this->y;
  if ($this->angle != 0)
   $this->_out('Q');
  $this->angle = $angle;
  if ($angle != 0) {
   $angle*=M_PI / 180;
   $c = cos($angle);
   $s = sin($angle);
   $cx = $x * $this->k;
   $cy = ($this->h - $y) * $this->k;
   $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', $c, $s, -$s, $c, $cx, $cy, -$cx, -$cy));
  }
 }

 function _endpage() {
  if ($this->angle != 0) {
   $this->angle = 0;
   $this->_out('Q');
  }
  parent::_endpage();
 }

 }

 //$fullPathToFile = "chinmay235.pdf";

 class PDF extends PDF_Rotate {

 var $_tplIdx;

 function Header() {
  global $fullPathToFile;

  //Put the watermark
  $this->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World', 40, 100, 100, 0, 'PNG');
  $this->SetFont('Arial', 'B', 50);
  $this->SetTextColor(255, 192, 203);
  $this->RotatedText(20, 230, 'Raddyx Technologies Pvt. Ltd.', 45);

  if (is_null($this->_tplIdx)) {

   // THIS IS WHERE YOU GET THE NUMBER OF PAGES
   $this->numPages = $this->setSourceFile($fullPathToFile);
   $this->_tplIdx = $this->importPage(1);
  }
  $this->useTemplate($this->_tplIdx, 0, 0, 200);

 }

 function RotatedText($x, $y, $txt, $angle) {
  //Text rotated around its origin
  $this->Rotate($angle, $x, $y);
  $this->Text($x, $y, $txt);
  $this->Rotate(0);
 }

 }

 $pdf = new PDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial', '', 12);
 $pdf->Output();
 ?>

I am fairly competent with PHP, but this error has really thrown me for a loop.  If any more information is needed, let me know and I will provide it.

Body:
What happens if you change this:

require_once('fpdf/fpdf.php');
require_once 'fpdi/src/fpdi.php';
require_once('fpdi/src/FpdfTpl.php');

To this?

require_once('fpdf/fpdf.php');
require_once('fpdi/src/autoload.php');

Or if you don't have autoload then you maybe need to add:

require_once('fpdi/src/FpdiTrait.php');


来源: stackexchange

问:
Side by side display of two sections
I'm a beginner, and, as it is in case of most beginners, I'm struggling with something I feel should be simpler than it is for me at the moment.

As a part of my task, I am to create a layout for a blog entry, whereby the date and the author would be represented in the column to the left (roundel-container in the code below), whereas the content itself (articlebody) and the footer with "read more" button and links to comments (readmore-footer) would form the second, wider column to the right. This image represents a simplified vision of what I want to achieve.

I've been playing around with position:, left:, right: and float:, but to mediocre results (which I might well owe to lack of practice). Here's how the code looks like now:

HTML

```<code><section class="articlebox">
    <section class="roundel-container">
        <div class="roundel left"><span class="bold">11 Nov 2013</span></div>
        <div class="roundel left"><span class="bold">by John Doe</span></div>
    </section>
    <section class="articlebody">
        <p class="readable">Lorem ipsum ...</p>
    </section>
    <footer id="readmore-footer">
        <div class="button bold white" id="readmore-button">Read More</div>
        <section class="right">
            <p><a class="darkblue">10 likes</a> <a class="darkblue">22 comments</a></p>
        </section>
    </footer>
</section>
</code>```

CSS

```<code>.articlebody {
    position: relative;
    left: 0;
    padding: 0px 15px 10px 15px;
}

.articlebox {
    position: relative;
    width: 100%;
    overflow: hidden;
}

.roundel {
    height: 80px;
    width: 80px;
    border-radius: 40px;
    margin: 10px;
    color: white;
    background-color: #22aaec;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    align-items: center;
}

.roundel-container {
    position: relative;
    left: 0;
    min-width: 220px;
}

#readmore-footer {
    margin-top: 25px;
    position: relative;
    left: 0;
}

.left {
    float: left;
    width: 45%;
}

.button {
    padding: 5px 15px;
    margin-left: 12px;
    margin-right: 12px;
}

.right {
    float: right;
    width: 45%;
}
</code>```

I'd appreciate help with this one, as well as any tips and tricks you might give regarding the above. Thanks!

答:
I recently started flex-boxing all of the things to achieve layouts such as the one you ask for. Read this article, it should help you get the structure you are looking for. I try to stay away from using floats when possible.

http://markheath.net/post/simple-css-blog-layout-flexbox

ContentLicense: CC BY-SA 3.0

Title: Side by side display of two sections

Body:
I'm a beginner, and, as it is in case of most beginners, I'm struggling with something I feel should be simpler than it is for me at the moment.

As a part of my task, I am to create a layout for a blog entry, whereby the date and the author would be represented in the column to the left (roundel-container in the code below), whereas the content itself (articlebody) and the footer with "read more" button and links to comments (readmore-footer) would form the second, wider column to the right. This image represents a simplified vision of what I want to achieve.

I've been playing around with position:, left:, right: and float:, but to mediocre results (which I might well owe to lack of practice). Here's how the code looks like now:

HTML

11 Nov 2013

by John Doe

Lorem ipsum ...

Read More

10 likes 22 comments

CSS

.articlebody {
    position: relative;
    left: 0;
    padding: 0px 15px 10px 15px;
}

.articlebox {
    position: relative;
    width: 100%;
    overflow: hidden;
}

.roundel {
    height: 80px;
    width: 80px;
    border-radius: 40px;
    margin: 10px;
    color: white;
    background-color: #22aaec;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    align-items: center;
}

.roundel-container {
    position: relative;
    left: 0;
    min-width: 220px;
}

#readmore-footer {
    margin-top: 25px;
    position: relative;
    left: 0;
}

.left {
    float: left;
    width: 45%;
}

.button {
    padding: 5px 15px;
    margin-left: 12px;
    margin-right: 12px;
}

.right {
    float: right;
    width: 45%;
}

I'd appreciate help with this one, as well as any tips and tricks you might give regarding the above. Thanks!


问:
Does `+=` operator always create a new string object?
If pool memory already has an object with similar content, then if we try to create the same object with different reference variable then only a new reference variable is created, NO NEW OBJECT IS CREATED.eg;

```<code>String s7="1";
String s8 ="1";
System.out.print(s7==s8);  //True
</code>```

Here only one object is created.
But in the following example

```<code>public class JavaApplication1 {
    public static void main(String[] args) {
        String s1 = "1", s2 = "2", s4 = s1 + s2, s5 = "12";
        final String s3 = s1 + s2;
        s1 += s2;
        System.out.print((s1 == s3) + "" + (s1 == s5) + "" + "" (s3 == s5));
    }
}
</code>```

Output is false false false
Even is s3 is declared as an final expression!, why?

答:
This is because

1) Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

2) Strings computed by concatenation at run time are newly created and therefore distinct.

Here's an example:

```<code>    String s7 = "77";
    String s8 = "77";

    String s10 = "7";
    String s11 = "7";

    String s9 = s10+s11;
    String s12 = "7"+"7";

    //printing the address
    System.out.println(System.identityHashCode(s7));
    System.out.println(System.identityHashCode(s8));
    System.out.println(System.identityHashCode(s9));
    System.out.println(System.identityHashCode(s12));

    System.out.println(s7==s9);
    System.out.println(s7==s12);
</code>```

Output:

```<code>705927765
705927765
366712642  ---> address is different
705927765
false
true
</code>```

Although I also went through about this just now. But here's my assumption:

All the literals except String s9 = s10+s11; are computed at compile time. That's why we are getting different address.

Follow the String literals javadoc for more details.

Body:
If pool memory already has an object with similar content, then if we try to create the same object with different reference variable then only a new reference variable is created, NO NEW OBJECT IS CREATED.eg;

String s7="1";
String s8 ="1";
System.out.print(s7==s8);  //True

Here only one object is created.
But in the following example

public class JavaApplication1 {
    public static void main(String[] args) {
        String s1 = "1", s2 = "2", s4 = s1 + s2, s5 = "12";
        final String s3 = s1 + s2;
        s1 += s2;
        System.out.print((s1 == s3) + "" + (s1 == s5) + "" + "" (s3 == s5));
    }
}

Output is false false false
Even is s3 is declared as an final expression!, why?

Body:
This is because

1) Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

2) Strings computed by concatenation at run time are newly created and therefore distinct.

Here's an example:

    String s7 = "77";
    String s8 = "77";

    String s10 = "7";
    String s11 = "7";

    String s9 = s10+s11;
    String s12 = "7"+"7";

    //printing the address
    System.out.println(System.identityHashCode(s7));
    System.out.println(System.identityHashCode(s8));
    System.out.println(System.identityHashCode(s9));
    System.out.println(System.identityHashCode(s12));

    System.out.println(s7==s9);
    System.out.println(s7==s12);

Output:

705927765
705927765
366712642  ---> address is different
705927765
false
true

Although I also went through about this just now. But here's my assumption:

All the literals except String s9 = s10+s11; are computed at compile time. That's why we are getting different address.

Follow the String literals javadoc for more details.


问:
About alarmManager and perfomance/battery issue
Android beginner here:
i'm writing a pills' reminder app using alarmManager, but i was wondering if i need to implement a daily scheduler and a database to store the alarms that don't need to set off today, or does the alarmManager do everything by itself, avoiding excessive performance issues and battery drain? i'm asking it because, let's say that we have 30 alarms per 30 pills every week, i think that having all the alarms "ticking" when i only need to take a couple of pills a day is very expensive.
I tried to read the documentation but it's seem very generic.
thank you</p>

答: If you really want to use AlarmManager to set repeating reminders, the Android Developer Docs recommends AlarmManager.setInexactRepeating() which allows you to set intervals like AlarmManager.INTERVAL_DAY to repeat everyday and synchronizes repeating alarms from multiple apps to fire at the same time. If you want to consider other options instead of AlarmManager you should watch this talk from Joanna Smith https://www.youtube.com/watch?v=7maNuWjL3Wc</p>


问:
One line recursive loop in python
I want to rewrite this function to regular loop:

```<code>def combine(n,k):
    if k == 0:
        return [[]]

    return [pre + [i] for i in range(1, n + 1) for pre in combine(i - 1, k - 1)]
</code>```

Cause I can't debug each step of the loop. For example, what does pre store in an internal loop?

Here is a task:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

答:
The list comprehension at the heart of this function is building up an implicit list that ultimately gets returned.  We can unwind the function, remove the comprehension, and use an explicit list:

```<code>def combine(n, k):
    """
    Given two integers n and k, return all possible
    combinations of k numbers out of 1 ... n.
    """

    result = []

    if k == 0:
        result.append([])
    else:
        for i in range(1, n + 1):
            for pre in combine(i - 1, k - 1):
                result.append(pre + [i])

    return result

print(combine(7, 4))
</code>```

what does pre store in an internal loop?

The pre variable store individual elements of the recursion.  For example, to get all four digit combinations of seven digits, the code uses recursion to calculate all the three digit combinations and then augments them.  That elements of that recursive result, each three digit combination, is stored, in turn, in pre.

Title: One line recursive loop in python

Body:
I want to rewrite this function to regular loop:

def combine(n,k):
    if k == 0:
        return [[]]

    return [pre + [i] for i in range(1, n + 1) for pre in combine(i - 1, k - 1)]

Cause I can't debug each step of the loop. For example, what does pre store in an internal loop?

Here is a task:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Body:
The list comprehension at the heart of this function is building up an implicit list that ultimately gets returned.  We can unwind the function, remove the comprehension, and use an explicit list:

def combine(n, k):
    """
    Given two integers n and k, return all possible
    combinations of k numbers out of 1 ... n.
    """

    result = []

    if k == 0:
        result.append([])
    else:
        for i in range(1, n + 1):
            for pre in combine(i - 1, k - 1):
                result.append(pre + [i])

    return result

print(combine(7, 4))

what does pre store in an internal loop?

The pre variable store individual elements of the recursion.  For example, to get all four digit combinations of seven digits, the code uses recursion to calculate all the three digit combinations and then augments them.  That elements of that recursive result, each three digit combination, is stored, in turn, in pre.


问:
Is the "link" element necessary when I want to modify the style of a webpage with CSS?
I was studying this example:

```<code><!DOCTYPE html>
<html>
<head>
<title>Introducing to CSS</title>
<link href="css/example.css" type="text/css"
rel="stylesheet" />
</head>
<body>
<h1>From Garden to Plate</h1>
<p> A <i>potager</i> or kitchen garden...</p>
<h2>What to plant</h2>
<p>Plant are chosen as...</p>
</body>
</html>

body {
font-family: Arial, Verdana, sans-serif;}
h1, h2 {
color: #ee3e80;}
p {
color: #665544;}
</code>```

The result was I couldn't make any change on my webpage.  The CSS rules don't work. I don't know why. My second question is: Is the "link" element necessary when I want to modify the style of a webpage with CSS?

答:
If you want your CSS to work, you can do it in 2 main ways:

Use  inside the head or body like this:

```<code><style>
body {
   font-family: Arial, Verdana, sans-serif;
}
h1, h2 {
   color: #ee3e80;
}
p {
   color: #665544;
}
</style>
</code>```

Using <link> tag.

You already have this  line of code in your example:

<link href="css/example.css" type="text/css" rel="stylesheet" />

Assuming you have css folder with example.css file inside it, you can put your styles there and it will work as well.

Usually it's more preferrable to use second variant , because it keeps your CSS in separate file and your HTML stays clean.

Body:
I was studying this example:

<!DOCTYPE html>

<title>Introducing to CSS</title>
<link href="css/example.css" type="text/css"
rel="stylesheet" />

From Garden to Plate

 A potager or kitchen garden...

What to plant

Plant are chosen as...

body {
font-family: Arial, Verdana, sans-serif;}
h1, h2 {
color: #ee3e80;}
p {
color: #665544;}

The result was I couldn't make any change on my webpage.  The CSS rules don't work. I don't know why. My second question is: Is the "link" element necessary when I want to modify the style of a webpage with CSS?

Body:
If you want your CSS to work, you can do it in 2 main ways:

Use <style> tag.

You can enclose you CSS code into <style></style> inside the head or body like this:

<style>
body {
   font-family: Arial, Verdana, sans-serif;
}
h1, h2 {
   color: #ee3e80;
}
p {
   color: #665544;
}
</style>

Using <link> tag.

You already have this  line of code in your example:

<link href="css/example.css" type="text/css" rel="stylesheet" />

Assuming you have css folder with example.css file inside it, you can put your styles there and it will work as well.

Usually it's more preferrable to use second variant , because it keeps your CSS in separate file and your HTML stays clean.


问:
How can I get the public IP and port my WCF service runs on?
I'm fairly new to WCF. I want to send the client an URL, which points to a file on the server, so the client can download\view it.

So my idea is that I add the relative path to the IP the service is listening on.

Like http://86.1.2.3:8123/myfolder/myfile.rar

The problem is, that every solution I found gives back

```<code>   localhost:someport/mysite
</code>```

Obviously, this is not really useful for the client.

Is there even a way to get the public IP from the code on which the service is hosted?

Or should I just include the address in the config file, and change it whenever the IP changes?

EDIT: Thanks for the quick help guys, I will just include it in the config file then.

答: You need to call an external service, like whatismyip.com, and parse the response. There is no standard format for the response, hence not very reliable. Answered here: Get public/external IP address?</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to WCF. I want to send the client an URL, which points to a file on the server, so the client can download\view it.

So my idea is that I add the relative path to the IP the service is listening on.

Like http://86.1.2.3:8123/myfolder/myfile.rar

The problem is, that every solution I found gives back

   localhost:someport/mysite

Obviously, this is not really useful for the client.

Is there even a way to get the public IP from the code on which the service is hosted?

Or should I just include the address in the config file, and change it whenever the IP changes?

EDIT: Thanks for the quick help guys, I will just include it in the config file then.


问:
Insert into Impala table vs write to HDFS
I have about 10 thousand records (stored as ArrayList in Java). I want to insert these records to Impala.

Should I use insert into table partition values to directly insert to impala. (I am not sure how many records can be inserted in one sql statement.)

Or should I write these records to HDFS then alter impala table?

Which way is preferred? Or is there any other solutions?

And also if I do these in every 5 minutes, how can I avoid so many small files in one partition (partitioned by hour)? These will produce 12 small files in each partition, so will this affect the query speed?

答:
The best you can do is to do:

Create your table in impala as an external table associated with an HDFS route

Make the insertions directly in HDFS, if possible daily, per hour is probably little

Execute the invalidate metada $ TABLE_NAME command so that the data is visible

I hope the answer serves you

Regards!


问:
How to handle exceptions you want propagated up to the caller?
I'm a Pythonista moving into Java/Scala, and I am wondering how to handle the case where you want an exception to be thrown if it occurs.  Take the following toy example:

```<code>public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

In Python I would want this to throw an error if the file isn't found, and let the calling code handle the exception.  Is it convention just to re-throw the same exception?

答:
In any part of your code you can throw a throwable object, such as an Exception.

You should also state it in the method signature, letting the JVM know you'll handle that Exception in a caller's block.

Example:

```<code>public void save(List<Person> people) throws FileNotFoundException{
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I'm a Pythonista moving into Java/Scala, and I am wondering how to handle the case where you want an exception to be thrown if it occurs.  Take the following toy example:

public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In Python I would want this to throw an error if the file isn't found, and let the calling code handle the exception.  Is it convention just to re-throw the same exception?

Body:
In any part of your code you can throw a throwable object, such as an Exception.

You should also state it in the method signature, letting the JVM know you'll handle that Exception in a caller's block.

Example:

public void save(List<Person> people) throws FileNotFoundException{
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


问:
json schema semantics validation
I have been given a json input which is a jsonschema and I need to validate that it is a valid jsonschema as in semantically.

I am using newtonsoft and didn't find any api which validates the jsonschema itself to be a valid one. For instance if I want to validate a uri, I can use a constructor to make sure the input uri string is valid.

Is there a way to validate the semantics of jsonschema?

Thanks!

答: You'll want to use the "meta schema".  Found here under the Meta Schema heading.  They are specifically schema's for validating other schemas depending on what feature set you're using.</p>

Title: json schema semantics validation


问:
YouTrackSharp: can't get it to work
Trying to open an issue from a C# app.

Few issues:

1) UPDATE: I realize it only supports .NET Standard 1.3 = Framework 4.6; So no issue here.

2) I install version 2.0.31 (and less) - When I try to set up a connection, it says "Method not allowed":

```<code>var connection = new Connection("xxxx.myjetbrains.com", 80, false, "youtrack");
connection.Authenticate("xxxxx", "xxxxxx");
var issueManagement = new IssueManagement(connection);
dynamic issue = new Issue();
issue.Assignee = "xxxxx";
issue.ProjectShortName = "CV";
issue.Type = "Bug";
issue.Summary = "Test";
issue.Description = "Testing 1 2 3 ...";
issueManagement.CreateIssue(issue);
</code>```

connection.Authenticate throws the error.

3) If I don't specify other parameters in Connection  and leave only the basic url, I get the following error (again in connection.Authenticate):

For security reasons DTD is prohibited in this XML document. To enable
  DTD processing set the DtdProcessing property on XmlReaderSettings to
  Parse and pass the settings into XmlReader.Create method.

Can't seem to find much info on this online. Anyone has any idea what to do?

答:
For anyone else getting stuck:

my YouTrack account was like this:

https://mycompanyname.myjetbrains.com/youtrack

Since it uses SSL (i.e. https) I had to mark the SSL parameter true instead of false, and mark port 443 instead of 80. Also I had to add the "youtrack" as a parameter. So the end result looks like this:

```<code>var connection = new Connection("xxxx.myjetbrains.com", 443, true, "youtrack");
connection.Authenticate("xxxx@xxxx.xxx", "xxxx");
</code>```

I only had to do this in v.2, as I mentioned, v.3.0.0+ has working examples in their blog.

Title: YouTrackSharp: can't get it to work

Body:
Trying to open an issue from a C# app.

Few issues:

1) UPDATE: I realize it only supports .NET Standard 1.3 = Framework 4.6; So no issue here.

2) I install version 2.0.31 (and less) - When I try to set up a connection, it says "Method not allowed":

var connection = new Connection("xxxx.myjetbrains.com", 80, false, "youtrack");
connection.Authenticate("xxxxx", "xxxxxx");
var issueManagement = new IssueManagement(connection);
dynamic issue = new Issue();
issue.Assignee = "xxxxx";
issue.ProjectShortName = "CV";
issue.Type = "Bug";
issue.Summary = "Test";
issue.Description = "Testing 1 2 3 ...";
issueManagement.CreateIssue(issue);

connection.Authenticate throws the error.

3) If I don't specify other parameters in Connection  and leave only the basic url, I get the following error (again in connection.Authenticate):

For security reasons DTD is prohibited in this XML document. To enable
  DTD processing set the DtdProcessing property on XmlReaderSettings to
  Parse and pass the settings into XmlReader.Create method.

Can't seem to find much info on this online. Anyone has any idea what to do?

Body:
For anyone else getting stuck:

my YouTrack account was like this:

https://mycompanyname.myjetbrains.com/youtrack

Since it uses SSL (i.e. https) I had to mark the SSL parameter true instead of false, and mark port 443 instead of 80. Also I had to add the "youtrack" as a parameter. So the end result looks like this:

var connection = new Connection("xxxx.myjetbrains.com", 443, true, "youtrack");
connection.Authenticate("xxxx@xxxx.xxx", "xxxx");

I only had to do this in v.2, as I mentioned, v.3.0.0+ has working examples in their blog.


问:
Split string into multiple string separated
I have a string "What is Facebook?.| A. Website B. Internet C. Social Network D. Game"
How can I split and stored that string into 5 string separated in C# programming? I try to split with my code but the result I have just a mess.

What result I expect is that after split, I have 5 string variable separated like:

```<code>string A = "What is Facebook?"
string B = "A. Website"
string C = "B. Internet"
string D = "C. Social Network"
string E = "D. Game"
</code>```

That is my code:

```<code>String value = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";
Char delimiter = '|';
String[] substrings = value.Split(delimiter);
</code>```

答:
You can split by \|?\s+(?=[A-Z]\.) :

```<code>string[] substrings = Regex.Split(value, @"\|?\s+(?=[A-Z]\.)");
</code>```

Body:
I have a string "What is Facebook?.| A. Website B. Internet C. Social Network D. Game"
How can I split and stored that string into 5 string separated in C# programming? I try to split with my code but the result I have just a mess.

What result I expect is that after split, I have 5 string variable separated like:

string A = "What is Facebook?"
string B = "A. Website"
string C = "B. Internet"
string D = "C. Social Network"
string E = "D. Game"

That is my code:

String value = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";
Char delimiter = '|';
String[] substrings = value.Split(delimiter);

Body:
You can split by \|?\s+(?=[A-Z]\.) :

string[] substrings = Regex.Split(value, @"\|?\s+(?=[A-Z]\.)");


问:
Refreshing App.config after modifying bindingRedirect
I'm working with WinForms a project that has a couple of oddball requirements. This is an existing business system that is installed in numerous locations under a fairly wide variety of environments. Part of this variety is a mixture of SQL Server versions, and--of particular importance--SQL Server Reporting Services versions. Everyone is on at least 2005, but about 50% of our users are on some flavor of 2008.

Unfortunately for me, I need to be able to run a client-side report that's written in 2008-version RDL. I can't modify the report in any substantive way at this point, so rewriting it in 2005-version RDL isn't an option. The catch is that this report (as it's written in 2008) requires the 2008 ReportViewer control. However, the 2008 ReportViewer control cannot connect to 2005 SSRS.

The solution that I've come up with is more than a little hacky, but it will alleviate 90% of the problems introduced. I've left the references pointing to the 2005 version of ReportViewer, and I'm modifying the application configuration on startup to add assembly binding redirection tags moving from version 9.0.0.0 to 10.0.0.0 for ReportViewer.Common and ReportViewer.WinForms if the user's target report server is running 2008.

As twitch-inducing as this solution is, it's working for me. The users running SSRS 2005 can still access their existing reports, just not the new one. The users running SSRS 2008 can access everything. My only problem is that I haven't been able to find a way to refresh the configuration data. I'm updating this info before any of the assemblies are loaded, but calling ConfigurationManager.RefreshSection("runtime") doesn't appear to have any effect. Once the app restarts, the proper assemblies are loaded, but I'd really like to be able to have this change take effect immediately.

Any thoughts on how I can force the runtime to reload the binding redirection information from the App.config file at runtime?

答: Once the AppDomain is created, the configuration data that affects binding is fixed.  Which happens on the default CLR when the primary AD is created, before your code starts running.  If you are really desperate then you could create a secondary AppDomain and give it a custom AppDomainSetup with another ConfigurationFile.  And loads and run your regular startup code in that AD.  Not exactly sure what kind of side effects this might have.</p>

ContentLicense: CC BY-SA 2.5


问:
Matplotlib table formatting - change width of row label cells

I have an obvious problem with this table, because the row labels are outside of the figure and I don't know how to fix it. I know I can go into child artists and change things like height and width there, but I already tried it and it didn't work, so maybe you can help me now.

Here is the code I'm using for this, hope it isn't too hard to read.... :

```<code>ind1=np.arange(5)

figure()
axes([0.2, 0.45, 0.7, 0.45])

## define different bars
l1=bar((ind1-0.45),mean_morphing_cc[0:5],width=0.2,bottom=0,color='darkblue',yerr=[min_dif_morphing_cc[0:5],max_dif_morphing_cc[0:5]],error_kw=dict(elinewidth=2, ecolor='darkkhaki'))

l2=bar((ind1-0.25),mean_persistence_cc[0:5],width=0.2,bottom=0,color='darkred',yerr=[min_dif_persistence_cc[0:5],max_dif_persistence_cc[0:5]],error_kw=dict(elinewidth=2, ecolor='darkkhaki'))

l3=bar((ind1+0.05),mean_m_vs_p_cc[0:5],width=0.2,bottom=0,color='purple',yerr=[min_dif_m_vs_p_cc[0:5],max_dif_m_vs_p_cc[0:5]],error_kw=dict(elinewidth=2, ecolor='darkkhaki'))

## print grid and a horizontal line at "0"
grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)

hlines(0, -0.5,(max(ind1)+0.5), colors='k', linestyles='solid')

ylabel('mean((cloud cover_forecast/cloud cover_observation)-1),\n mean("morphing" - "persistence")',horizontalalignment='right',multialignment='center',size='xx-small')

xlim(-0.5,(max(ind1)+0.5))

xticks(ind1,[])

## print a legend
legend((l1[0],l2[0],l3[0]),('mean morphing cloud cover','mean persistence cloud cover','mean morphing vs persistence error'),'lower center',ncol=2,bbox_to_anchor=(0.5,-0.92),borderpad=0.2,labelspacing=0.2,handlelength=1,handletextpad=0.2)

leg = plt.gca().get_legend()

ltext  = leg.get_texts()  # all the text.Text instance in the legend

llines = leg.get_lines()  # all the lines.Line2D instance in the legend

frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend

frame.set_facecolor('0.90')      # set the frame face color to light gray

plt.setp(ltext, fontsize='x-small')    # the legend text fontsize

## print the title
title('cloud cover over- or underestimation\n morphing forecast compared to persistence',size='small')

## print the table
the_table=plt.table(cellText=[[str(i)[:4] for i in mean_morphing_cc[0:5]],max_morphing_cc[0:5],min_morphing_cc[0:5],mean_persistence_cc[0:5],max_persistence_cc[0:5],min_persistence_cc[0:5],mean_m_vs_p_cc[0:5],max_m_vs_p_cc[0:5],min_m_vs_p_cc[0:5]],
                    rowLabels=['morphing: mean','morphing: max','morphing: min','persistence: mean','persistence: max','persistence: min','morph vs per: mean','morph vs per: max','morph vs per: min'],
                    rowColours=['darkblue','darkblue','darkblue','darkred','darkred','darkred','purple','purple','purple'],colLabels=['t+1','t+2','t+3','t+4','t+5'],loc='bottom')

## change cell properties
table_props=the_table.properties()
table_cells=table_props['child_artists']
for cell in table_cells:
    cell.set_width(0.2)
    cell.set_height(0.065)
    cell.set_fontsize(12)

show()
</code>```

答:
I haven't figured out the perfect answer to this, but I've found a solution that has been useful for my own purposes.

Adjusting both the colWidth and the table width can shrink the rowLabel-column width. In the source code, there's actually a variable they use, rowLabelWidth, but they do not let the user set it. Anyways, first I'm just going to rewrite your existing code so you can see where changes are made. This is the original in a variable format:

```<code>## setting properties to variables to make table function easier to read
data = [[str(i)[:4] for i in mean_morphing_cc[0:5]],max_morphing_cc[0:5],min_morphing_cc[0:5],mean_persistence_cc[0:5],max_persistence_cc[0:5],min_persistence_cc[0:5],mean_m_vs_p_cc[0:5],max_m_vs_p_cc[0:5],min_m_vs_p_cc[0:5]]
rowLabels = ['morphing: mean','morphing: max','morphing: min','persistence: mean','persistence: max','persistence: min','morph vs per: mean','morph vs per: max','morph vs per: min']
rowColours = ['darkblue','darkblue','darkblue','darkred','darkred','darkred','purple','purple','purple']
colLabels = ['t+1','t+2','t+3','t+4','t+5']
loc = 'bottom'

## without changing anything, this is what your table function would look like
the_table=plt.table(cellText = data,
                rowLabels = rowLabels, rowColours = rowColours,
                colLabels = colLabels, loc = loc)
</code>```

Here's what's in the source code for rowLabelWidth, which we'll use to help figure out what to set width and colWidth to.

```<code># Do row labels
if rowLabels is not None:
    for row in xrange(rows):
        table.add_cell(row + offset, -1,
                       width=rowLabelWidth or 1e-15, height=height,
                       text=rowLabels[row], facecolor=rowColours[row],
                       loc=rowLoc)
    if rowLabelWidth == 0:
        table.auto_set_column_width(-1)
</code>```

It appears you have set the chart to a width in axes([0.2, 0.45, 0.7, 0.45]), to 0.7, so we will set that to a variable, tb_width

```<code>tb_width = 0.7
</code>```

The rowLabelWidth gets auto-sized, which doesn't really help us. But if you play around with the following three options for colWidths, you can start to figure out how to make it work the way you want. Add in bbox properties to state specifically where the table should be. An important thing to note is that it appears the rowLabelWidth is not included in the overall table width.

```<code>## standard - essentially what happens when you don't specify colWidths. Takes the table width, divides it by the number of columns, giving each column an equal width.
colWidths = [tb_width/n_cols] * n_cols
## rowLabels stick out on the left

## similar to the above, but the '+1' attempts to account for the fact that another column's width, rowLabels, should fit inside the overall table width
colWidths=[( tb_width / (n_cols + 1) )] * n_cols

## set your own width. this will start messing with the width of the rowLabelsWidth as now the colWidths aren't perfectly proportioned within the table width
tb_colWidth = 0.08
colWidths = [tb_colWidth] * n_cols
</code>```

To ensure that the rowLabels fit right beneath the chart without sticking out on the left, use bbox coordinates. Using the bottom left hand corner of the table as your reference point, position the table: bbox=[x_coordinate, y_coordinate, width, height]. If the x_coordinate is set to account for your tb_colWidth, then it will shift the table over the exact amount necessary to have the rowLabels-column's leftmost side directly under the left corner of the chart above.

```<code>bbox = [tb_colWidth, y_coordinate, tb_width, tb_height]
</code>```

If this now causes the rightmost column to stick out from under the chart, then shrink the width by the size of one column:

```<code>bbox = [tb_colWidth, y_coordinate, tb_width - tb_colWidth, tb_height]
</code>```

Now put it all together:

```<code>the_table=plt.table(cellText = data,
            rowLabels = rowLabels, rowColours = rowColours,
            colLabels = colLabels, loc = 'bottom',
            colWidths = colWidths, bbox = bbox)
</code>```

You shouldn't have to do your final table cell loop of adjusting the cell widths, but instead, can control that using the above tools.

Body:
I have an obvious problem with this table, because the row labels are outside of the figure and I don't know how to fix it. I know I can go into child artists and change things like height and width there, but I already tried it and it didn't work, so maybe you can help me now.

Here is the code I'm using for this, hope it isn't too hard to read.... :

ind1=np.arange(5)

figure()
axes([0.2, 0.45, 0.7, 0.45])

## define different bars
l1=bar((ind1-0.45),mean_morphing_cc[0:5],width=0.2,bottom=0,color='darkblue',yerr=[min_dif_morphing_cc[0:5],max_dif_morphing_cc[0:5]],error_kw=dict(elinewidth=2, ecolor='darkkhaki'))

l2=bar((ind1-0.25),mean_persistence_cc[0:5],width=0.2,bottom=0,color='darkred',yerr=[min_dif_persistence_cc[0:5],max_dif_persistence_cc[0:5]],error_kw=dict(elinewidth=2, ecolor='darkkhaki'))

l3=bar((ind1+0.05),mean_m_vs_p_cc[0:5],width=0.2,bottom=0,color='purple',yerr=[min_dif_m_vs_p_cc[0:5],max_dif_m_vs_p_cc[0:5]],error_kw=dict(elinewidth=2, ecolor='darkkhaki'))

## print grid and a horizontal line at "0"
grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)

hlines(0, -0.5,(max(ind1)+0.5), colors='k', linestyles='solid')

ylabel('mean((cloud cover_forecast/cloud cover_observation)-1),\n mean("morphing" - "persistence")',horizontalalignment='right',multialignment='center',size='xx-small')

xlim(-0.5,(max(ind1)+0.5))

xticks(ind1,[])

## print a legend
legend((l1[0],l2[0],l3[0]),('mean morphing cloud cover','mean persistence cloud cover','mean morphing vs persistence error'),'lower center',ncol=2,bbox_to_anchor=(0.5,-0.92),borderpad=0.2,labelspacing=0.2,handlelength=1,handletextpad=0.2)

leg = plt.gca().get_legend()

ltext  = leg.get_texts()  # all the text.Text instance in the legend

llines = leg.get_lines()  # all the lines.Line2D instance in the legend

frame  = leg.get_frame()  # the patch.Rectangle instance surrounding the legend

frame.set_facecolor('0.90')      # set the frame face color to light gray

plt.setp(ltext, fontsize='x-small')    # the legend text fontsize

## print the title
title('cloud cover over- or underestimation\n morphing forecast compared to persistence',size='small')

## print the table
the_table=plt.table(cellText=[[str(i)[:4] for i in mean_morphing_cc[0:5]],max_morphing_cc[0:5],min_morphing_cc[0:5],mean_persistence_cc[0:5],max_persistence_cc[0:5],min_persistence_cc[0:5],mean_m_vs_p_cc[0:5],max_m_vs_p_cc[0:5],min_m_vs_p_cc[0:5]],
                    rowLabels=['morphing: mean','morphing: max','morphing: min','persistence: mean','persistence: max','persistence: min','morph vs per: mean','morph vs per: max','morph vs per: min'],
                    rowColours=['darkblue','darkblue','darkblue','darkred','darkred','darkred','purple','purple','purple'],colLabels=['t+1','t+2','t+3','t+4','t+5'],loc='bottom')

## change cell properties
table_props=the_table.properties()
table_cells=table_props['child_artists']
for cell in table_cells:
    cell.set_width(0.2)
    cell.set_height(0.065)
    cell.set_fontsize(12)

show()

Body:
I haven't figured out the perfect answer to this, but I've found a solution that has been useful for my own purposes.

Adjusting both the colWidth and the table width can shrink the rowLabel-column width. In the source code, there's actually a variable they use, rowLabelWidth, but they do not let the user set it. Anyways, first I'm just going to rewrite your existing code so you can see where changes are made. This is the original in a variable format:

## setting properties to variables to make table function easier to read
data = [[str(i)[:4] for i in mean_morphing_cc[0:5]],max_morphing_cc[0:5],min_morphing_cc[0:5],mean_persistence_cc[0:5],max_persistence_cc[0:5],min_persistence_cc[0:5],mean_m_vs_p_cc[0:5],max_m_vs_p_cc[0:5],min_m_vs_p_cc[0:5]]
rowLabels = ['morphing: mean','morphing: max','morphing: min','persistence: mean','persistence: max','persistence: min','morph vs per: mean','morph vs per: max','morph vs per: min']
rowColours = ['darkblue','darkblue','darkblue','darkred','darkred','darkred','purple','purple','purple']
colLabels = ['t+1','t+2','t+3','t+4','t+5']
loc = 'bottom'

## without changing anything, this is what your table function would look like
the_table=plt.table(cellText = data,
                rowLabels = rowLabels, rowColours = rowColours,
                colLabels = colLabels, loc = loc)

Here's what's in the source code for rowLabelWidth, which we'll use to help figure out what to set width and colWidth to.

# Do row labels
if rowLabels is not None:
    for row in xrange(rows):
        table.add_cell(row + offset, -1,
                       width=rowLabelWidth or 1e-15, height=height,
                       text=rowLabels[row], facecolor=rowColours[row],
                       loc=rowLoc)
    if rowLabelWidth == 0:
        table.auto_set_column_width(-1)

It appears you have set the chart to a width in axes([0.2, 0.45, 0.7, 0.45]), to 0.7, so we will set that to a variable, tb_width

tb_width = 0.7

The rowLabelWidth gets auto-sized, which doesn't really help us. But if you play around with the following three options for colWidths, you can start to figure out how to make it work the way you want. Add in bbox properties to state specifically where the table should be. An important thing to note is that it appears the rowLabelWidth is not included in the overall table width.

## standard - essentially what happens when you don't specify colWidths. Takes the table width, divides it by the number of columns, giving each column an equal width.
colWidths = [tb_width/n_cols] * n_cols
## rowLabels stick out on the left

## similar to the above, but the '+1' attempts to account for the fact that another column's width, rowLabels, should fit inside the overall table width
colWidths=[( tb_width / (n_cols + 1) )] * n_cols

## set your own width. this will start messing with the width of the rowLabelsWidth as now the colWidths aren't perfectly proportioned within the table width
tb_colWidth = 0.08
colWidths = [tb_colWidth] * n_cols

To ensure that the rowLabels fit right beneath the chart without sticking out on the left, use bbox coordinates. Using the bottom left hand corner of the table as your reference point, position the table: bbox=[x_coordinate, y_coordinate, width, height]. If the x_coordinate is set to account for your tb_colWidth, then it will shift the table over the exact amount necessary to have the rowLabels-column's leftmost side directly under the left corner of the chart above.

bbox = [tb_colWidth, y_coordinate, tb_width, tb_height]

If this now causes the rightmost column to stick out from under the chart, then shrink the width by the size of one column:

bbox = [tb_colWidth, y_coordinate, tb_width - tb_colWidth, tb_height]

Now put it all together:

the_table=plt.table(cellText = data,
            rowLabels = rowLabels, rowColours = rowColours,
            colLabels = colLabels, loc = 'bottom',
            colWidths = colWidths, bbox = bbox)

You shouldn't have to do your final table cell loop of adjusting the cell widths, but instead, can control that using the above tools.


问:
Save data of django form in database
I'm using Django 1.3 and I have a form defined with forms.py:

```<code>class mopa(forms.Form):
    idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 )
    causale = forms.CharField(label="Causale Pagamento *", required=True)
    imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True)
    quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True)
</code>```

and in this file I made the checks.
My models.py file:

```<code>class Mopamodel(models.Model):
    idcarrellosorgente = models.IntegerField()
    cod_ente = models.CharField()
    causale = models.CharField()
    imp_unitario = models.DecimalField()
    quantita_item = models.IntegerField()
</code>```

and my views.py

```<code>def paga(request):

    # If this is a POST request then process the Form data
     if request.method == 'POST':

    #  Create a form instance and populate it with data from the request (binding):
    form = mopa(request.POST)
    print('form: ', form.data) #return a dictionary

    # Check if the form is valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        # p=form.save() <--don't works: error: 'mopa' object has no attribute 'save'
        idcarr = form.cleaned_data['idcarrellosorgente']
        caus = form.cleaned_data['causale']
        imp_u = form.cleaned_data['imp_unitario']
        qta = form.cleaned_data['quantita_item']

        dictmopa={}
        dictmopa['id_carr']=idcarr
        cod_ente = form.cleaned_data['cod_ente']
        mopapay=Mopamodel(idcarrellosorgente=idcarr, cod_ente=cod_ente, causale=causale, imp_unitario=imp_u, quantita_item=qta
        #mopapay.save() <--this produce the error: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType'
        ....
        # redirect to a new URL:
    return HttpResponseRedirect(reverse('viewsdati/') )
</code>```

How can I save the form data in a database postgres?
Other tutorial/questions don't solve my problem, probably are for more recent django versions.

答:
Well, you should use ModelForm in this case. Change forms like this:

```<code>class mopa(forms.ModelForm):
    class Meta:
         model = Mopamodel
         fields = ('idcarrellosorgente ', 'causale', 'imp_unitario', 'quantita_item ', )
</code>```

Then change view to something like this:

```<code>def paga(request):
    if request.method == 'POST':
        form = mopa(request.POST)
        if form.is_valid():
           posted = form.save(commit=False)
           posted.cod_ente = form.cleaned_data['cod_ente']
           posted.save()

           return HttpResponseRedirect(reverse('viewsdati/'))
</code>```

Title: Save data of django form in database

Body:
I'm using Django 1.3 and I have a form defined with forms.py:

class mopa(forms.Form):
    idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 )
    causale = forms.CharField(label="Causale Pagamento *", required=True)
    imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True)
    quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True)

and in this file I made the checks.
My models.py file:

class Mopamodel(models.Model):
    idcarrellosorgente = models.IntegerField()
    cod_ente = models.CharField()
    causale = models.CharField()
    imp_unitario = models.DecimalField()
    quantita_item = models.IntegerField()

and my views.py

def paga(request):

    # If this is a POST request then process the Form data
     if request.method == 'POST':

    #  Create a form instance and populate it with data from the request (binding):
    form = mopa(request.POST)
    print('form: ', form.data) #return a dictionary

    # Check if the form is valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        # p=form.save() <--don't works: error: 'mopa' object has no attribute 'save'
        idcarr = form.cleaned_data['idcarrellosorgente']
        caus = form.cleaned_data['causale']
        imp_u = form.cleaned_data['imp_unitario']
        qta = form.cleaned_data['quantita_item']

        dictmopa={}
        dictmopa['id_carr']=idcarr
        cod_ente = form.cleaned_data['cod_ente']
        mopapay=Mopamodel(idcarrellosorgente=idcarr, cod_ente=cod_ente, causale=causale, imp_unitario=imp_u, quantita_item=qta
        #mopapay.save() <--this produce the error: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType'
        ....
        # redirect to a new URL:
    return HttpResponseRedirect(reverse('viewsdati/') )

How can I save the form data in a database postgres?
Other tutorial/questions don't solve my problem, probably are for more recent django versions.

Body:
Well, you should use ModelForm in this case. Change forms like this:

class mopa(forms.ModelForm):
    class Meta:
         model = Mopamodel
         fields = ('idcarrellosorgente ', 'causale', 'imp_unitario', 'quantita_item ', )

Then change view to something like this:

def paga(request):
    if request.method == 'POST':
        form = mopa(request.POST)
        if form.is_valid():
           posted = form.save(commit=False)
           posted.cod_ente = form.cleaned_data['cod_ente']
           posted.save()

           return HttpResponseRedirect(reverse('viewsdati/'))


问:
When I press 1 button, I want all other buttons to change states
Right now with the code below, my output is 10 buttons with text/color. When I press a button, it uses the method ToggleState() to change its' text/color.

But when I press a button, I want all the OTHER buttons to use the method ToggleState(). So basically, I want the button pressed to stay in the same text/color, and all the other buttons to change text/color.

MyButton class:

```<code>public class MyButton extends JButton implements ActionListener {

private Color col1;
private Color col2;
private String text1;
private String text2;

public MyButton(Color col1, Color col2, String text1, String text2) {
    this.col1 = col1;
    this.col2 = col2;
    this.text1 = text1;
    this.text2 = text2;
    this.setText(text1);
    this.setBackground(col1);
    this.setOpaque(true);
    this.addActionListener(this);
}

public void ToggleState() {
    Color initialBackground = this.getBackground();

    if (initialBackground == col1) {
        this.setBackground(col2);
        this.setText(text2);
    } else if (initialBackground == col2) {
        this.setBackground(col1);
        this.setText(text1);
    }
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this) {
        this.ToggleState();
    }
}
}
</code>```

CMain class:

```<code>public class CMain{

private static JPanel panel = new JPanel();

public static void main(String[] args) {

    Random randomGenerator = new Random();

    JFrame frame = new JFrame("MyButton testing");

    for (int i = 0; i < 10; i++) {

        float r = randomGenerator.nextFloat();float g = randomGenerator.nextFloat();float b = randomGenerator.nextFloat();float r2 = randomGenerator.nextFloat();float g2 = randomGenerator.nextFloat();float b2 = randomGenerator.nextFloat();

        String theText = "button nr: " + i;
        String theOtherText = "SWITCH ME";
        Color theColor = new Color(r, g, b);
        Color theOtherColor = new Color(r2, g2, b2);

        MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
        panel.add(myb);
    }
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
</code>```

I have thought about a few solutions, for example putting in a new actionlistener in the CMain class, this is the code I wrote for that:

```<code>public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this) {
        for (int j=0 ; j < panel.getComponentCount() ; j++) {
            ((CMain)panel.getComponent(j)).ToggleState();
        }
    }
}
</code>```

But it doesn't solve my problem, I have the exact same output as before. When I press 1 button, only that button gets switched. I understand that the code above would ToggleState() all my buttons (and not only the ones that I haven't pressed), I just wanted to try something out.

Maybe I could save all my buttons in a list when I create them in CMain class, and then create a new ToggleState() in CMain that toggles every button not pressed in the list, but I have no idea how a solution like that would look in code.

EDIT:
I tried (after a tip in comment section) removing actionListener from my MyButton class and put it in CMain class, the problem is, that it switches ALL of my buttons, including the one that I pressed. I'm closer now, but I still need the button I've pressed to remain the same:

```<code>ArrayList<MyButton> knappar = new ArrayList<MyButton>();
MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
knappar.add(myb);
panel.add(myb);

myb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == knappar);
            for (int k=0; k<knappar.size();k++) {
            knappar.get(k).ToggleState();
            }
    }
});
</code>```

答:
lost with the if statement, not sure how I should set it up.

The if statement needs to be inside the loop.

```<code>for (int k=0; k<knappar.size();k++)
{
    MyButton button = knappar.get(k);

    if (button != e.getSource())
        button.toggleState();
}
</code>```

Also, note how I renamed the method. Method names should NOT start with an upper case character.

Or you use the following looping syntax:

```<code>for (MyButton button: knapper)
{
    if (button != e.getSource())
        button.toggleState();
}
</code>```

Body:
Right now with the code below, my output is 10 buttons with text/color. When I press a button, it uses the method ToggleState() to change its' text/color.

But when I press a button, I want all the OTHER buttons to use the method ToggleState(). So basically, I want the button pressed to stay in the same text/color, and all the other buttons to change text/color.

MyButton class:

public class MyButton extends JButton implements ActionListener {

private Color col1;
private Color col2;
private String text1;
private String text2;

public MyButton(Color col1, Color col2, String text1, String text2) {
    this.col1 = col1;
    this.col2 = col2;
    this.text1 = text1;
    this.text2 = text2;
    this.setText(text1);
    this.setBackground(col1);
    this.setOpaque(true);
    this.addActionListener(this);
}

public void ToggleState() {
    Color initialBackground = this.getBackground();

    if (initialBackground == col1) {
        this.setBackground(col2);
        this.setText(text2);
    } else if (initialBackground == col2) {
        this.setBackground(col1);
        this.setText(text1);
    }
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this) {
        this.ToggleState();
    }
}
}

CMain class:

public class CMain{

private static JPanel panel = new JPanel();

public static void main(String[] args) {

    Random randomGenerator = new Random();

    JFrame frame = new JFrame("MyButton testing");

    for (int i = 0; i < 10; i++) {

        float r = randomGenerator.nextFloat();float g = randomGenerator.nextFloat();float b = randomGenerator.nextFloat();float r2 = randomGenerator.nextFloat();float g2 = randomGenerator.nextFloat();float b2 = randomGenerator.nextFloat();

        String theText = "button nr: " + i;
        String theOtherText = "SWITCH ME";
        Color theColor = new Color(r, g, b);
        Color theOtherColor = new Color(r2, g2, b2);

        MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
        panel.add(myb);
    }
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

I have thought about a few solutions, for example putting in a new actionlistener in the CMain class, this is the code I wrote for that:

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this) {
        for (int j=0 ; j < panel.getComponentCount() ; j++) {
            ((CMain)panel.getComponent(j)).ToggleState();
        }
    }
}

But it doesn't solve my problem, I have the exact same output as before. When I press 1 button, only that button gets switched. I understand that the code above would ToggleState() all my buttons (and not only the ones that I haven't pressed), I just wanted to try something out.

Maybe I could save all my buttons in a list when I create them in CMain class, and then create a new ToggleState() in CMain that toggles every button not pressed in the list, but I have no idea how a solution like that would look in code.

EDIT:
I tried (after a tip in comment section) removing actionListener from my MyButton class and put it in CMain class, the problem is, that it switches ALL of my buttons, including the one that I pressed. I'm closer now, but I still need the button I've pressed to remain the same:

ArrayList<MyButton> knappar = new ArrayList<MyButton>();
MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
knappar.add(myb);
panel.add(myb);

myb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == knappar);
            for (int k=0; k<knappar.size();k++) {
            knappar.get(k).ToggleState();
            }
    }
});

Body:
lost with the if statement, not sure how I should set it up.

The if statement needs to be inside the loop.

for (int k=0; k<knappar.size();k++)
{
    MyButton button = knappar.get(k);

    if (button != e.getSource())
        button.toggleState();
}

Also, note how I renamed the method. Method names should NOT start with an upper case character.

Or you use the following looping syntax:

for (MyButton button: knapper)
{
    if (button != e.getSource())
        button.toggleState();
}


问:
Feed tensorflow or keras neural nets input with custom dimensions

I would like to feed a neural net inputs of following shape:
Each training entry is a 2D array with dimensions 700x10. There are in total 204 training entries.
Labels is just 1-dimensional array of size 204 (binary output)

I tried to just use Dense layers:

model = Sequential()
model.add(Dense(300, activation='relu', input_shape=(700, 10)))
model.add(Dense(1, activation='sigmoid'))
```

<p>But then I am getting following error (not related to input_shape on the first layer, but during validation of output):</p>

<pre class="lang-py prettyprint-override"><code>ValueError: Error when checking target: expected dense_2 to have 3 dimensions, but got array with shape (204, 1)
</code>```

204 - amount of training data.

Stacktrace:

    model.fit(xTrain, yTrain, epochs=4, batch_size=6)
  File "keras\models.py", line 867, in fit
    initial_epoch=initial_epoch)
  File "keras\engine\training.py", line 1522, in fit
    batch_size=batch_size)
  File "keras\engine\training.py", line 1382, in _standardize_user_data
    exception_prefix='target')
  File "keras\engine\training.py", line 132, in _standardize_input_data
```

What I found out while debugging Keras code:

It fails during validation before training. It validates output array.

According to the neural network structure, first Dense layer produces somehow 700, 1 dimensional output and it fails afterwards, since my output is just 1-d array with 204 in it.

How do I overcome this issue? I tried to add Flatten() after Dense() layer, but it probably affects accuracy in a bad way: I would like to keep information specific to one point from 700 array grouped.

答:
The Dense layers works on only one dimension, the last.

If you're inputting (700,10) to it, it will output (700,units). Check your model.summary() to see this.

A simple solution is to flatten your data before applying dense:

```<code>model.add(Flatten(input_shape=(700,10)))
model.add(Dense(300,...))
model.add(Dense(1,...))
</code>```

This way, the Dense layer will see a simple (7000,) input.

Now if you do want your model to understand those 2 dimensions separately, you should perhaps try more elaborated structures. What to do will depend a lot on what your data is and what you want to do, how you want your model to understand it, etc.

Body:
I would like to feed a neural net inputs of following shape:
Each training entry is a 2D array with dimensions 700x10. There are in total 204 training entries.
Labels is just 1-dimensional array of size 204 (binary output)

I tried to just use Dense layers:

model = Sequential()
model.add(Dense(300, activation='relu', input_shape=(700, 10)))
model.add(Dense(1, activation='sigmoid'))

But then I am getting following error (not related to input_shape on the first layer, but during validation of output):

ValueError: Error when checking target: expected dense_2 to have 3 dimensions, but got array with shape (204, 1)

204 - amount of training data.

Stacktrace:

    model.fit(xTrain, yTrain, epochs=4, batch_size=6)
  File "keras\models.py", line 867, in fit
    initial_epoch=initial_epoch)
  File "keras\engine\training.py", line 1522, in fit
    batch_size=batch_size)
  File "keras\engine\training.py", line 1382, in _standardize_user_data
    exception_prefix='target')
  File "keras\engine\training.py", line 132, in _standardize_input_data

What I found out while debugging Keras code:

It fails during validation before training. It validates output array.

According to the neural network structure, first Dense layer produces somehow 700, 1 dimensional output and it fails afterwards, since my output is just 1-d array with 204 in it.

How do I overcome this issue? I tried to add Flatten() after Dense() layer, but it probably affects accuracy in a bad way: I would like to keep information specific to one point from 700 array grouped.

Body:
The Dense layers works on only one dimension, the last.

If you're inputting (700,10) to it, it will output (700,units). Check your model.summary() to see this.

A simple solution is to flatten your data before applying dense:

model.add(Flatten(input_shape=(700,10)))
model.add(Dense(300,...))
model.add(Dense(1,...))

This way, the Dense layer will see a simple (7000,) input.

Now if you do want your model to understand those 2 dimensions separately, you should perhaps try more elaborated structures. What to do will depend a lot on what your data is and what you want to do, how you want your model to understand it, etc.


问:
javascript loop exceeding call stack
I mostly use LUA and I've been trying to make something with JavaScript with some help from a friend, and I don't understand why this loop is exceeding the call stack.</p>

```<code>var myVar;
(function loop() {
    for (var x = 0, ln = 3; x < ln; x++) {
        myVar = setTimeout(function(i) {
            console.log(i);
        }, x * 333, x);
        clearTimeout(myVar);
    }
    loop();
}());
</code>```

答:
It looks like you are trying to make a recursive loop with a progressive delay. It works pretty much the same in JS as it does in other languages -- you set up an edge condition that stops the loop on a certain condition and then recurse. You can do that in a timeout. There's no need to clear it unless you had to stop a timeout already started. I would do it more like this:

var start = 0;
var ln = 3;

(function loop(i) {
  if (i > ln) return // edge condition
  setTimeout(() => {
    console.log(i);
    loop(i + 1); // recurse
  }, i * 333, i);
})(start);```

Title: javascript loop exceeding call stack

Body:
I mostly use LUA and I've been trying to make something with JavaScript with some help from a friend, and I don't understand why this loop is exceeding the call stack.

var myVar;
(function loop() {
    for (var x = 0, ln = 3; x < ln; x++) {
        myVar = setTimeout(function(i) {
            console.log(i);
        }, x * 333, x);
        clearTimeout(myVar);
    }
    loop();
}());


问:
Red Hat Developer: Subscription Attachment
I installed RHEL7 for developers (NO-Cost subscription) and registered it with my username and password for the customer portal , however it doesn't want to attach the subscription.

So in order to do it manually I need to run the following command

```<code>subscription-manager attach --pool=YourID
</code>```

And in order to find my ID I have to run the command

```<code>subscription-manager list --available
</code>```

Which returns

No available subscription pools to list

I logged in in my account on developers.redhat.com and it says:

But on the customer panel it says I don't have any active subscriptions

What am I doing wrong?

Thank you in advance!!

答:
+1. The registration command is:

subscription-manager register --username= --password=

Are you installing on bare metal or vm?  There are options here: https://developers.redhat.com/products/rhel/hello-world/

Body:
I installed RHEL7 for developers (NO-Cost subscription) and registered it with my username and password for the customer portal , however it doesn't want to attach the subscription.

So in order to do it manually I need to run the following command

subscription-manager attach --pool=YourID

And in order to find my ID I have to run the command

subscription-manager list --available

Which returns

No available subscription pools to list

I logged in in my account on developers.redhat.com and it says:

But on the customer panel it says I don't have any active subscriptions

What am I doing wrong?

Thank you in advance!!


答:
Like @Andrey Nasonov's comment said, this is a good application for regular expressions.

The following will get you your split, though I feel like there must be a better way to represent \s(\w.[\w\s]+ repeating four times.

```<code>Regex splitter = new Regex(@"(.*)\|\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)");
string[] results = splitter.Split(input);

stringA = results[0];
stringB = results[1];
stringC = results[2];
stringD = results[3];
stringE = results[4];
</code>```

Title: Split string into multiple string separated

Body:
Like @Andrey Nasonov's comment said, this is a good application for regular expressions.

The following will get you your split, though I feel like there must be a better way to represent \s(\w.[\w\s]+ repeating four times.

Regex splitter = new Regex(@"(.*)\|\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)\s(\w\.[\w\s]+)");
string[] results = splitter.Split(input);

stringA = results[0];
stringB = results[1];
stringC = results[2];
stringD = results[3];
stringE = results[4];


问:
Save file from web?
how do i save file from a website for example an image?</p>

答: Check out Android's included Apache HTTP Client. Here is a tutorial on how to use the lib. </p>

Title: Save file from web?


问:
What is the most elegant way to insert objects between array elements?
I'm sure there are many ways to achieve that but I'm looking for something "elegant".

```<code>a = [
  'a',
  'b',
  'c'
];

magicArrayJoin(a, {value: 255} ); // insert the same object between each item

result ==  [
  'a',
  {value: 255},
  'b',
  {value: 255}
  'c'
];
</code>```

All proposals are welcome. :)

答:
Using splice as Kamen suggests, you could do something like:</p>

```<code>const numSeparators = arr.length - 1;
for (let i = 1; i <= numSeparators; i++) {
    const index = (i * 2) - 1;
    arr.splice(index, 0, { value: 255 });
}
</code>```

Body:
I'm sure there are many ways to achieve that but I'm looking for something "elegant".

a = [
  'a',
  'b',
  'c'
];

magicArrayJoin(a, {value: 255} ); // insert the same object between each item

result ==  [
  'a',
  {value: 255},
  'b',
  {value: 255}
  'c'
];

All proposals are welcome. :)

Body:
Using splice as Kamen suggests, you could do something like:

const numSeparators = arr.length - 1;
for (let i = 1; i <= numSeparators; i++) {
    const index = (i * 2) - 1;
    arr.splice(index, 0, { value: 255 });
}


问:
More than 12 bootstrap columns with a horizontal scroll
I am trying to make a table using bootstrap grid system. I know that we should use only 12 columns per row. But I wanted to have more than 12 columns with a horizontal scroll for the entire table. So I am trying with the following code snippet

```<code><span class="col-md-2" style="text-align: center;"><b>Field 1</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 2</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 3</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 4</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 5</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 6</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 7</b></span>
<span class="col-md-2" style="text-align: center;"><b>Field 8</b></span>
</code>```

I wanted to display 8 fields like as mentioned above in one line. But after field 6, other two fields are coming down. Is there any way to have all 8 fields in single line with horizontal scroll.

答:
You can split bootstrap col-12 in 2. You have now 24 columns</p>

```<code>    <div class "row">
      <div class="col-6">
        <div class "row">
          <div class="col-1">
            1
          </div>
          <div class="col-1">
            2
          </div>
          <div class="col-1">
            3
          </div>
          <div class="col-1">
            4
          </div>
          <div class="col-1">
            5
          </div>
          <div class="col-1">
            6
          </div>
          <div class="col-1">
            7
          </div>
          <div class="col-1">
            8
          </div>
          <div class="col-1">
            9
          </div>
          <div class="col-1">
            10
          </div>
          <div class="col-1">
            11
          </div>
          <div class="col-1">
            12
          </div>
        </div>
      </div>
      <div class="col-6">
        <div class "row">
          <div class="col-1">
            13
          </div>
          <div class="col-1">
            14
          </div>
          <div class="col-1">
            15
          </div>
          <div class="col-1">
            16
          </div>
          <div class="col-1">
            17
          </div>
          <div class="col-1">
            18
          </div>
          <div class="col-1">
            19
          </div>
          <div class="col-1">
            20
          </div>
          <div class="col-1">
            21
          </div>
          <div class="col-1">
            22
          </div>
          <div class="col-1">
            23
          </div>
          <div class="col-1">
            24
          </div>
        </div>
      </div>
    </div>
</code>```

Body:
I am trying to make a table using bootstrap grid system. I know that we should use only 12 columns per row. But I wanted to have more than 12 columns with a horizontal scroll for the entire table. So I am trying with the following code snippet

Field 1
Field 2
Field 3
Field 4
Field 5
Field 6
Field 7
Field 8

I wanted to display 8 fields like as mentioned above in one line. But after field 6, other two fields are coming down. Is there any way to have all 8 fields in single line with horizontal scroll.

Body:
You can split bootstrap col-12 in 2. You have now 24 columns

    <div class "row">
      <div class="col-6">
        <div class "row">
          <div class="col-1">
            1
          </div>
          <div class="col-1">
            2
          </div>
          <div class="col-1">
            3
          </div>
          <div class="col-1">
            4
          </div>
          <div class="col-1">
            5
          </div>
          <div class="col-1">
            6
          </div>
          <div class="col-1">
            7
          </div>
          <div class="col-1">
            8
          </div>
          <div class="col-1">
            9
          </div>
          <div class="col-1">
            10
          </div>
          <div class="col-1">
            11
          </div>
          <div class="col-1">
            12
          </div>
        </div>
      </div>
      <div class="col-6">
        <div class "row">
          <div class="col-1">
            13
          </div>
          <div class="col-1">
            14
          </div>
          <div class="col-1">
            15
          </div>
          <div class="col-1">
            16
          </div>
          <div class="col-1">
            17
          </div>
          <div class="col-1">
            18
          </div>
          <div class="col-1">
            19
          </div>
          <div class="col-1">
            20
          </div>
          <div class="col-1">
            21
          </div>
          <div class="col-1">
            22
          </div>
          <div class="col-1">
            23
          </div>
          <div class="col-1">
            24
          </div>
        </div>
      </div>
    </div>


问:
How do you compare a value from jQuery with a fixed number?
How do you compare a value from jQuery with a fixed number?

I thought this might work but it doesn't:

```<code>if (parseInt($("#days").value) > 7) {
            alert("more than one week");
        }
</code>```

答:
As well as @redsquare 's answer to use .val(), you should specify the radix:

```<code>if (parseInt($("#days").val(), 10) > 7) {
            alert("more than one week");
        }
</code>```

This is because the value could have a leading 0, in which case parseInt would interpret the value as octal.

OwnerDisplayName: IainMH

Body:
How do you compare a value from jQuery with a fixed number?

I thought this might work but it doesn't:

if (parseInt($("#days").value) > 7) {
            alert("more than one week");
        }

Body:
As well as @redsquare 's answer to use .val(), you should specify the radix:

if (parseInt($("#days").val(), 10) > 7) {
            alert("more than one week");
        }

This is because the value could have a leading 0, in which case parseInt would interpret the value as octal.

OwnerDisplayName: RoBorg


答:
You need to consider if the calling code actually knows what to do with the specific exception. You have defined an API about saving a collection of Person. The calling code knows only about a Person and has no idea ideally where the save is done.

If you throw a lower level exception about the file not found you are leaking the abstraction and you won't be able to change the implementation easily if the calling code is starting to be aware of where things are saved.

The proper approach would be to throw an "business" exception like PersonNotPersisted or PersonNotSaved since this is something the calling code would understand and avoid the low level IO exceptions to the higher layer

Title: How to handle exceptions you want propagated up to the caller?

Body:
I'm a Pythonista moving into Java/Scala, and I am wondering how to handle the case where you want an exception to be thrown if it occurs.  Take the following toy example:

public class PersonSaver {
    private final File file;

    public PersonSaver(File file) {
        this.file = file;
    }

    public void save(List<Person> people) {
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
            output.writeObject(people);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In Python I would want this to throw an error if the file isn't found, and let the calling code handle the exception.  Is it convention just to re-throw the same exception?


问:
Confused about assertEquals not in phpunit anymore
I don't see discussion forums over at phpunit.de so I'm hoping anyone using phpunit in this community can assist.

I downloaded the phpunit 6.4.3 phar and added it to my IDE.  When I tried to extend the test class with PHPUnit_Framework_TestCase and use assertEquals, it throws this error:

"PHPUnit_Framework_TestCase cannot be resolved to a type"

The IDE wants to change TestCase to PHPUnit_Framework_MockObject_Matcher

So I let the IDE make the correction but there isn't an assertEquals method anymore (I checked just to be sure, by changing the phar, that assertEquals is in version 5.7.23 though).

Perhaps I'm overlooking the documentation, but when I Google PHPUnit_Framework_MockObject_Matcher, I'm seeing what the new method is.

Does anyone know to perform an equivalent assertEquals test in version 6.4.3?

=====

EDIT.  Adding screenshots of my phpunit install, the project build path, and the  Eclipse error.

答:
It seems that your IDE doesn't support namespaces or has some trouble with it, check your settings. It's also possible you are using PHP 5.2 or lower which doesn't support namespaces. This underscore notation was used to identify the path to a class in old-school autoloading classes.

```<code><?php
namespace Illuminate\Foundation\Testing;

use PHPUnit\Framework\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase {}
</code>```

BTW. is it a composer project? If yes, it's recommended to download/install phpunit via composer.

```<code>composer require --dev phpunit/phpunit ^6.4
</code>```

Body:
It seems that your IDE doesn't support namespaces or has some trouble with it, check your settings. It's also possible you are using PHP 5.2 or lower which doesn't support namespaces. This underscore notation was used to identify the path to a class in old-school autoloading classes.

<?php
namespace Illuminate\Foundation\Testing;

use PHPUnit\Framework\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase {}

BTW. is it a composer project? If yes, it's recommended to download/install phpunit via composer.

composer require --dev phpunit/phpunit ^6.4


答:
If you declare a method to throws an checkedexception you dont need to catch it or any of it subtypes:

```<code>public void save(List<Person> people) throws IOExcetion {
    try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
        output.writeObject(people);
    }
}
</code>```

If you want to handle the exception before you can also do like:

```<code>public void save(List<Person> people) throws IOException {
    try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
        output.writeObject(people);
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
</code>```

The keyword 'throw' fires the exception to the caller.

Body:
If you declare a method to throws an checkedexception you dont need to catch it or any of it subtypes:

public void save(List<Person> people) throws IOExcetion {
    try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
        output.writeObject(people);
    }
}

If you want to handle the exception before you can also do like:

public void save(List<Person> people) throws IOException {
    try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
        output.writeObject(people);
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

The keyword 'throw' fires the exception to the caller.