问:
validate date format in python [with regex or any built in method]
I am having the python code that needs to validate the following date format:

YYYYMMDD

Above format does not contain any special characters like [:,-,/].

I have mentioned example like :

20170922

We need to validate that above is valid date format by following YYYYMMDD format.

if it's not, then it should raise some sort of error.

答:
you can use datetime for this (in python 2.7)

```<code>from datetime import datetime

date_string = '20170808'

if len(date_string) == 8:
   datetime.strptime(date_string, '%Y%m%d')
else:
   raise ValueError('date need to be in format YYYYMMDD ')
</code>```

if you date is not valid than you get:

a ValueError Exception

```<code>ValueError: unconverted data remains: 0
</code>```

Body:
you can use datetime for this (in python 2.7)

from datetime import datetime

date_string = '20170808'

if len(date_string) == 8:
   datetime.strptime(date_string, '%Y%m%d')
else:
   raise ValueError('date need to be in format YYYYMMDD ')

if you date is not valid than you get:

a ValueError Exception

ValueError: unconverted data remains: 0


来源: stackexchange

问:
Ranking MarkLogic search results
I am trying figure out a way to rank search results according to a field that is not part of the search criteria. i.e. relevance of the search not only depend on the matches but documents also have a default relevance rank among themselves.

My searches so far has failed and could not confirm if it is even a supported feature; most cts:search documentation is about ranking matches.

So, is there a built-in marklogic feature that allow us to assign a value multiplier to documents; based on element values for example.

thanks a lot,
K.

PS: I use marklogic 9.

答: Look at cts:boost-query: it takes a primary query that has to match and a secondary query that just affects the score.

ContentLicense: CC BY-SA 3.0

Title: Ranking MarkLogic search results


问:
How to map + filter in single loop
I have asked this question on SO before but I cannot find the question/answers!

Basically I want to create this:

```<code>Array.prototype.filterAndMap = function(){};
</code>```

where I can use it like so:

```<code>[1,2,3,4,5].filterAndMap(function(){
     if(i % 2 === 0){
        return i*2;
     }
});
</code>```

the above would return:

```<code>  [4,8]
</code>```

I think the best way to implement this is using Array.prototype.reduce...but I am not sure.

What I am trying to avoid, is iterating through the list twice:

```<code>   [1,2,3,4,5].filter(function(){
         return i % 2 === 0;
    })
    .map(function(i){
         return i * 2;
    });
</code>```

答:
reduce would certainly do the trick:

```<code>[1,2,3,4,5].reduce((arr, cur) => {
   if(cur % 2 == 0){
      arr.push(cur * 2);
   }
   return arr;
}, []);   // => [2, 4]
</code>```

Title: How to map + filter in single loop

Body:
I have asked this question on SO before but I cannot find the question/answers!

Basically I want to create this:

Array.prototype.filterAndMap = function(){};

where I can use it like so:

[1,2,3,4,5].filterAndMap(function(){
     if(i % 2 === 0){
        return i*2;
     }
});

the above would return:

  [4,8]

I think the best way to implement this is using Array.prototype.reduce...but I am not sure.

What I am trying to avoid, is iterating through the list twice:

   [1,2,3,4,5].filter(function(){
         return i % 2 === 0;
    })
    .map(function(i){
         return i * 2;
    });

Body:
reduce would certainly do the trick:

[1,2,3,4,5].reduce((arr, cur) => {
   if(cur % 2 == 0){
      arr.push(cur * 2);
   }
   return arr;
}, []);   // => [2, 4]


问:
Split string into multiple alpha and numeric segments
I have a string like "ABCD232ERE44RR". How can I split it into separate segments by letters/numbers. I need:
Segment1: ABCD
Segment2: 232
Segment3: ERE
Segment4: 44

There could be any number of segments. I am thinking go Regex but don't understand how to write it properly

答:
You can do it like this;</p>

```<code>using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main()
    {
        var substrings = Regex.Split("ABCD232ERE44RR", @"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");
        Console.WriteLine(string.Join(",",substrings));
    }
}

Output : ABCD,232,ERE,44,RR
</code>```

Body:
You can do it like this;

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main()
    {
        var substrings = Regex.Split("ABCD232ERE44RR", @"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");
        Console.WriteLine(string.Join(",",substrings));
    }
}

Output : ABCD,232,ERE,44,RR


问:
Play Two Audio Waveforms Simultaneously, One Per Stereo Channel LabVIEW
I have two sine waves I built in LabVIEW, and I need to take these two separate waves and play them at the same time, one in my left stereo speaker and the other in my right. My channels are built, but I cannot figure out how to not play the wave in both speakers, so it just sounds like they are both playing in both speakers. They are formatted as waveform outputs, and I think I might need to mess with array indexes but I am not sure. Any help is appreciated!</p>

答: You should be able to send an array of waveforms to the Sound Output Write.vi; iirc, the 0 index will be left and the 1 index will be right.</p>


答:
It's likely impossible to combine these two methods (.map and .filter) since .filter doesn't do any logic on elements and .map always return every element from given array. Hovewer you could try .reduce approach, to return only that element, which fulfills given condition.

const arr = [1,2,3,4,5];

const r = arr.reduce((s, a) => (a % 2 ? null : s.push(a * 2), s), []);

console.log(r);```

Title: How to map + filter in single loop


问:
Formatting is sporadic in Spreadsheet::WriteExcel
In attempting to create a spreadsheet using cell properties previously defined, I'm having issues where the cell formatting is only sporadically being written in the cells.  The values are there, but the font color, etc. is not always there.

Here's my code:

```<code>$result_file = $toxls . ".excel_props.xls";
$property_file = "properties.txt";
open (PROP, ">$property_file");

my $parser          = Spreadsheet::ParseExcel->new();
my $workbook_parse  = $parser->parse( $toxls );

my $worksheet_parse = $workbook_parse->Worksheet( $totab );
my ( $col_min, $col_max ) = $worksheet_parse->col_range();
my ( $row_min, $row_max ) = $worksheet_parse->row_range();

my $workbook   = Spreadsheet::WriteExcel->new( $result_file );
my $worksheet  = $workbook->addworksheet( $totab );
my %bkgd_color = ();

$worksheet->set_column('A:A', 12);
$worksheet->set_column('C:C', 15);
$worksheet->set_column('D:D', 30);
$worksheet->set_column('E:E', 30);
$worksheet->set_column('F:F', 35);
$worksheet->set_column('G:G', 40);
$worksheet->set_column('I:I', 40);

for my $col ( $col_min .. $col_max ) {

    for my $row ( $row_min .. $row_max ) {

        # Return the cell object at $row and $col

        my $cell = $worksheet_parse->get_cell( $row, $col );
        next unless $cell;

        my $value     = $cell->value();
        my $format    = $cell->get_format();

        my $pattern   = $format->{Fill}->[0];
        my $color1    = $format->{Fill}->[1];
        my $color2    = $format->{Fill}->[2];

        my $font      = $format->{Font};
        my $fontcolor = $font->{Color};

        ## Change value if font color = black
        if ($fontcolor eq '32767') {
            $fontcolor = "8";
        }

        my $wrap      = $format->{Wrap};
        my $bold      = $font->{Bold};

        print PROP "\nRow, Col = ($row, $col)\n";
        print PROP "Pattern    = $pattern\n";
        print PROP "Value      = $value\n";
        print PROP "Fill       = $pattern $color1 $color2\n";
        print PROP "Wrap       = $wrap\n";
        print PROP "Font       = $fontcolor\n";
        print PROP "Bold       = $bold\n";

        if (index($value,"B\=baseline") > -1 || index($value,"B\=Baseline") > -1) {
           $worksheet->set_row($row, 150);
        }

        if ($pattern == 1 ){

          if ( ! exists $bkgd_color{$color1} ){

             $bkgd_color{$color1}    =  $workbook->add_format(
                                           pattern  => $pattern,
                                           bg_color => $color1,
                                           align => 'left',
                                           valign => 'top',
                                           text_wrap => $wrap,
                                           border   => 1,
                                           color  => $fontcolor,
                                           bold    => $bold
                                     );
             print PROP "Print segment = not exist bkgd_color\n";

          }

          $worksheet->write( $row, $col, $value, $bkgd_color{$color1});

        } else {

          $format = $workbook->add_format();
          $format->set_pattern($pattern);
          $format->set_align('left');
          $format->set_valign('top');
          $format->set_bg_color($color2);
          $format->set_fg_color($color1);
          $format->set_color($fontcolor);
          $format->set_text_wrap($wrap);
          $format->set_border();
          $format->set_bold($bold);

          print PROP "Fontcolor  = $fontcolor\n";

          $worksheet->write( $row, $col, $value, $format);

       }
    }
}
</code>```

The properties.txt file shows what I expect when I parse the $toxls spreadsheet, which I'm using to test with.  Yet, it doesn't always produce the formatting (font color, Align, and AlignH) that is being saved from the parse, when I write back out to the $result_file.  Any ideas?

The properties.txt file looks good:

```<code>Row, Col = (2, 3)
Pattern    = 1
Value      = Password Requirements
Fill       = 1 22 31
Wrap       = 1
Font       = 10  <-- red text
Bold       = 1

Row, Col = (3, 3)
Pattern    = 1
Value      = Logging
Fill       = 1 22 31
Wrap       = 1
Font       = 12   <--- blue text
Bold       = 0

Row, Col = (4, 3)
Pattern    = 0
Value      = Logging
Fill       = 0 64 65
Wrap       = 1
Font       = 12
Bold       = 0
Fontcolor  = 12

Row, Col = (5, 3)
Pattern    = 1
Value      = AntiVirus
Fill       = 1 22 31
Wrap       = 1
Font       = 8  <-- black text
Bold       = 0
</code>```

My goal is simply to read in an existing spreadsheet, then create a new one with the exception of altering the font color or fill color on some cells.  I tried this snippet, and it even missed formatting on many of the cells:

```<code>for my $col ( $col_min .. $col_max ) {
    for my $row ( $row_min .. $row_max ) {

       # Return the cell object at $row and $col

       my $cell = $worksheet_parse->get_cell( $row, $col );
       next unless $cell;

       my $value     = $cell->value();
       my $format    = $cell->get_format();

       $worksheet->write( $row, $col, $value, $format);

    }
}
</code>```

答:
See this new code removing the bgcolor logic.  Yet, the resulting spreadsheet is only partially formatted correctly:</p>

```<code>my $parser          = Spreadsheet::ParseExcel->new();
my $workbook_parse  = $parser->parse( $toxls );

my $worksheet_parse = $workbook_parse->Worksheet( $totab );
my ( $col_min, $col_max ) = $worksheet_parse->col_range();
my ( $row_min, $row_max ) = $worksheet_parse->row_range();

my $workbook   = Spreadsheet::WriteExcel->new( $result_file );
my $worksheet  = $workbook->addworksheet( $totab );

$worksheet->set_column('A:A', 12);
$worksheet->set_column('C:C', 15);
$worksheet->set_column('D:D', 30);
$worksheet->set_column('E:E', 30);
$worksheet->set_column('F:F', 35);
$worksheet->set_column('G:G', 40);
$worksheet->set_column('I:I', 40);

for my $row ( $row_min .. $row_max ) {
    for my $col ( $col_min .. $col_max ) {

    # Return the cell object at $row and $col

    my $cell = $worksheet_parse->get_cell($row,$col);
    next unless $cell;

    my $value      = $cell->value();
    my $format     = $cell->get_format();

    my $pattern    = $format->{Fill}->[0];
    my $color1     = $format->{Fill}->[1];
    my $color2     = $format->{Fill}->[2];
    my $wrap       = $format->{Wrap};
    my $font       = $format->{Font};
    my $fontcolor  = $font->{Color};
    my $bold       = $font->{Bold};

    ## Change value if font color = black
    if ($fontcolor eq '32767') {
        $fontcolor = "8";
    }

    ##  Freeze after the header row

    if (index($value,"B\=baseline") > -1 || index($value,"B\=Baseline") > -1) {
       $worksheet->set_row($row, 150);
       $freezerow = $row + 1;
       $worksheet->freeze_panes($freezerow, 0);
    }

    my $updformat = $workbook->add_format(
              pattern => $pattern,
              fg_color => $color1,
              bg_color => $color2,
              align => 'left',
              valign => 'top',
              text_wrap => $wrap,
              border => 1,
              color => $fontcolor,
              bold => $bold
    );

    $worksheet->write( $row, $col, $value, $updformat);

    }
}
</code>```

Body:
In attempting to create a spreadsheet using cell properties previously defined, I'm having issues where the cell formatting is only sporadically being written in the cells.  The values are there, but the font color, etc. is not always there.

Here's my code:

$result_file = $toxls . ".excel_props.xls";
$property_file = "properties.txt";
open (PROP, ">$property_file");

my $parser          = Spreadsheet::ParseExcel->new();
my $workbook_parse  = $parser->parse( $toxls );

my $worksheet_parse = $workbook_parse->Worksheet( $totab );
my ( $col_min, $col_max ) = $worksheet_parse->col_range();
my ( $row_min, $row_max ) = $worksheet_parse->row_range();

my $workbook   = Spreadsheet::WriteExcel->new( $result_file );
my $worksheet  = $workbook->addworksheet( $totab );
my %bkgd_color = ();

$worksheet->set_column('A:A', 12);
$worksheet->set_column('C:C', 15);
$worksheet->set_column('D:D', 30);
$worksheet->set_column('E:E', 30);
$worksheet->set_column('F:F', 35);
$worksheet->set_column('G:G', 40);
$worksheet->set_column('I:I', 40);

for my $col ( $col_min .. $col_max ) {

    for my $row ( $row_min .. $row_max ) {

        # Return the cell object at $row and $col

        my $cell = $worksheet_parse->get_cell( $row, $col );
        next unless $cell;

        my $value     = $cell->value();
        my $format    = $cell->get_format();

        my $pattern   = $format->{Fill}->[0];
        my $color1    = $format->{Fill}->[1];
        my $color2    = $format->{Fill}->[2];

        my $font      = $format->{Font};
        my $fontcolor = $font->{Color};

        ## Change value if font color = black
        if ($fontcolor eq '32767') {
            $fontcolor = "8";
        }

        my $wrap      = $format->{Wrap};
        my $bold      = $font->{Bold};

        print PROP "\nRow, Col = ($row, $col)\n";
        print PROP "Pattern    = $pattern\n";
        print PROP "Value      = $value\n";
        print PROP "Fill       = $pattern $color1 $color2\n";
        print PROP "Wrap       = $wrap\n";
        print PROP "Font       = $fontcolor\n";
        print PROP "Bold       = $bold\n";

        if (index($value,"B\=baseline") > -1 || index($value,"B\=Baseline") > -1) {
           $worksheet->set_row($row, 150);
        }

        if ($pattern == 1 ){

          if ( ! exists $bkgd_color{$color1} ){

             $bkgd_color{$color1}    =  $workbook->add_format(
                                           pattern  => $pattern,
                                           bg_color => $color1,
                                           align => 'left',
                                           valign => 'top',
                                           text_wrap => $wrap,
                                           border   => 1,
                                           color  => $fontcolor,
                                           bold    => $bold
                                     );
             print PROP "Print segment = not exist bkgd_color\n";

          }

          $worksheet->write( $row, $col, $value, $bkgd_color{$color1});

        } else {

          $format = $workbook->add_format();
          $format->set_pattern($pattern);
          $format->set_align('left');
          $format->set_valign('top');
          $format->set_bg_color($color2);
          $format->set_fg_color($color1);
          $format->set_color($fontcolor);
          $format->set_text_wrap($wrap);
          $format->set_border();
          $format->set_bold($bold);

          print PROP "Fontcolor  = $fontcolor\n";

          $worksheet->write( $row, $col, $value, $format);

       }
    }
}

The properties.txt file shows what I expect when I parse the $toxls spreadsheet, which I'm using to test with.  Yet, it doesn't always produce the formatting (font color, Align, and AlignH) that is being saved from the parse, when I write back out to the $result_file.  Any ideas?

The properties.txt file looks good:

Row, Col = (2, 3)
Pattern    = 1
Value      = Password Requirements
Fill       = 1 22 31
Wrap       = 1
Font       = 10  <-- red text
Bold       = 1

Row, Col = (3, 3)
Pattern    = 1
Value      = Logging
Fill       = 1 22 31
Wrap       = 1
Font       = 12   <--- blue text
Bold       = 0

Row, Col = (4, 3)
Pattern    = 0
Value      = Logging
Fill       = 0 64 65
Wrap       = 1
Font       = 12
Bold       = 0
Fontcolor  = 12

Row, Col = (5, 3)
Pattern    = 1
Value      = AntiVirus
Fill       = 1 22 31
Wrap       = 1
Font       = 8  <-- black text
Bold       = 0

My goal is simply to read in an existing spreadsheet, then create a new one with the exception of altering the font color or fill color on some cells.  I tried this snippet, and it even missed formatting on many of the cells:

for my $col ( $col_min .. $col_max ) {
    for my $row ( $row_min .. $row_max ) {

       # Return the cell object at $row and $col

       my $cell = $worksheet_parse->get_cell( $row, $col );
       next unless $cell;

       my $value     = $cell->value();
       my $format    = $cell->get_format();

       $worksheet->write( $row, $col, $value, $format);

    }
}

Body:
See this new code removing the bgcolor logic.  Yet, the resulting spreadsheet is only partially formatted correctly:

my $parser          = Spreadsheet::ParseExcel->new();
my $workbook_parse  = $parser->parse( $toxls );

my $worksheet_parse = $workbook_parse->Worksheet( $totab );
my ( $col_min, $col_max ) = $worksheet_parse->col_range();
my ( $row_min, $row_max ) = $worksheet_parse->row_range();

my $workbook   = Spreadsheet::WriteExcel->new( $result_file );
my $worksheet  = $workbook->addworksheet( $totab );

$worksheet->set_column('A:A', 12);
$worksheet->set_column('C:C', 15);
$worksheet->set_column('D:D', 30);
$worksheet->set_column('E:E', 30);
$worksheet->set_column('F:F', 35);
$worksheet->set_column('G:G', 40);
$worksheet->set_column('I:I', 40);

for my $row ( $row_min .. $row_max ) {
    for my $col ( $col_min .. $col_max ) {

    # Return the cell object at $row and $col

    my $cell = $worksheet_parse->get_cell($row,$col);
    next unless $cell;

    my $value      = $cell->value();
    my $format     = $cell->get_format();

    my $pattern    = $format->{Fill}->[0];
    my $color1     = $format->{Fill}->[1];
    my $color2     = $format->{Fill}->[2];
    my $wrap       = $format->{Wrap};
    my $font       = $format->{Font};
    my $fontcolor  = $font->{Color};
    my $bold       = $font->{Bold};

    ## Change value if font color = black
    if ($fontcolor eq '32767') {
        $fontcolor = "8";
    }

    ##  Freeze after the header row

    if (index($value,"B\=baseline") > -1 || index($value,"B\=Baseline") > -1) {
       $worksheet->set_row($row, 150);
       $freezerow = $row + 1;
       $worksheet->freeze_panes($freezerow, 0);
    }

    my $updformat = $workbook->add_format(
              pattern => $pattern,
              fg_color => $color1,
              bg_color => $color2,
              align => 'left',
              valign => 'top',
              text_wrap => $wrap,
              border => 1,
              color => $fontcolor,
              bold => $bold
    );

    $worksheet->write( $row, $col, $value, $updformat);

    }
}


问:
method for assigning value on each field of value null
If I have an object with many fields, a part of them is null at beginning, is there a method to assign these variable by given a collection of value as input without repeating

```<code>(if x == null) x = a;
</code>```

something like:

```<code>methodAssign(Object o, Collections c)
</code>```

答:
Using BeanUtils  you can create a method and pass your object and a hashmap with your fields name as a keys and values.

```<code>public Object methodAssign(Object object, HashMap<String, Object> fields) {
   for(Entry<String, Object> entry : fields.entrySet()) {
     if(BeanUtils.getProperty(object, entry.getKey()) == null)
         BeanUtils.setProperty(object, entry.getKey(), entry.getValue());
   }
   return object;
}
</code>```

Example:

```<code>   Car carToInit = new Car();
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.add("field", 10);

    methodAssign(carToInit, map);
</code>```

Body:
If I have an object with many fields, a part of them is null at beginning, is there a method to assign these variable by given a collection of value as input without repeating

(if x == null) x = a;

something like:

methodAssign(Object o, Collections c)

Body:
Using BeanUtils  you can create a method and pass your object and a hashmap with your fields name as a keys and values.

public Object methodAssign(Object object, HashMap<String, Object> fields) {
   for(Entry<String, Object> entry : fields.entrySet()) {
     if(BeanUtils.getProperty(object, entry.getKey()) == null)
         BeanUtils.setProperty(object, entry.getKey(), entry.getValue());
   }
   return object;
}

Example:

   Car carToInit = new Car();
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.add("field", 10);

    methodAssign(carToInit, map);


问:
What is Inversion of Control?
Inversion of Control (IoC) can be quite confusing when it is first encountered.

What is it?

Which problem does it solve?

When is it appropriate to use and when not?

答:
It seems that the most confusing thing about "IoC" the acronym and the name for which it stands is that it's too glamorous of a name - almost a noise name.

Do we really need a name by which to describe the difference between procedural and event driven programming? OK, if we need to, but do we need to pick a brand new "bigger than life" name that confuses more than it solves?

ContentLicense: CC BY-SA 4.0

Title: What is Inversion of Control?

ContentLicense: CC BY-SA 2.5


答:
First introduce a free variable mu with the constraint:

```<code>   mu = sum(i, x(i))/n
</code>```

Then introduce non-negative variables y(i) with:

```<code>   -y(i) <= x(i) - mu <= y(i)
</code>```

Now you can minimize

```<code>   min sum(i,y(i))
</code>```

This is now a straight LP (linear objective and linear constraints) and can be solved with any LP solver.

Title: scipy.optimize Constrained Minimization SLSQP - Cannot Match the target 100%

Body:
I am trying to get the minimized weight that's closer to average weight combined. My current problem is using the SLSQP solver I cannot find the right weight that meet the target 100%. Is there another solver I could use to solve my problem? Or any math suggestions. Please help.

My math right now is

           **min(∑|x-mean(x)|)**

           **s.t.** Aw-b=0, w>=0

           **bound** 0.2'<'x<0.5

Data

  nRow# Variable1   Variable2   Variable3

  1 3582.00 233445193.00    559090945.00

  2 3394.00 217344811.00    496500751.00

  3 3356.00 237746918.00    493639029.00

  4 3256.00 219204892.00    461547877.00

  5 3415.00 225272825.00    501057960.00

  6 3505.00 242819442.00    505073223.00

  7 3442.00 215258725.00    490458632.00

  8 3381.00 227681178.00    503102998.00

  9 3392.00 215189377.00    487026744.00

    w1          w2                     w3
  Target    8531.00 429386951.00    1079115532.00

Question: Find the minimized weight that are closer to average

Python Code:

A = np.array([[3582.000000, 3394.000000, 3356.000000, 3256.000000, 3415.000000,
        3505.000000, 3442.000000, 3381.000000, 3392.000000],
       [233445193.000000, 217344811.000000, 237746918.000000,
        219204892.000000, 225272825.000000, 242819442.000000,
        215258725.000000, 227681178.000000, 215189377.000000],
       [559090945.000000, 496500751.000000, 493639029.000000,
        461547877.000000, 501057960.000000, 505073223.000000,
        490458632.000000, 503102998.000000, 487026744.000000]])

b = np.array([8531, 1079115532, 429386951])

n=9
def fsolveMin(A,b,n):

    # The constraints: Ax = b

    def cons(x):
        return A.dot(x)-b

    cons = ({'type':'eq','fun':cons},

            {'type':'ineq','fun':lambda x:x[0]})

    # The minimizing constraints: the total absolute difference between the coefficients

    def fn(x):
        return np.sum(np.abs(x-np.mean(x)))

    # Initialize the coefficients randomly
    z0 = abs(np.random.randn(len(A[1,:])))

    # Set up bound
   # bnds = [(0, None)]*n

    # Solve the problem

    sol = minimize(fn, x0 = z0, constraints = cons, method = 'SLSQP', options={'disp': True})

    #expected 35%
    print(sol.x)
    print(A.dot(sol.x))

    #print(fn(sol.x))

print(str(fsolveMin(A,b,n))+"\n\n")

Body:
First introduce a free variable mu with the constraint:

   mu = sum(i, x(i))/n

Then introduce non-negative variables y(i) with:

   -y(i) <= x(i) - mu <= y(i)

Now you can minimize

   min sum(i,y(i))

This is now a straight LP (linear objective and linear constraints) and can be solved with any LP solver.


答:
As you say, reduce is probably the way to go:

const myArray = [1, 2, 3, 4, 5];

function mapAndFilter(array, filterFunc, mapFunc) {
    return array.reduce((p, c) => {
        if (filterFunc(c)) p.push(mapFunc(c));
        return p;
    }, []);
}

const mapFilteredArray = mapAndFilter(myArray, x => x % 2 === 0, x => x*2);
console.log(mapFilteredArray);```

Adapt that function to go on the array prototype as you please.

Title: How to map + filter in single loop

Body:
As you say, reduce is probably the way to go:

const myArray = [1, 2, 3, 4, 5];

function mapAndFilter(array, filterFunc, mapFunc) {
    return array.reduce((p, c) => {
        if (filterFunc(c)) p.push(mapFunc(c));
        return p;
    }, []);
}

const mapFilteredArray = mapAndFilter(myArray, x => x % 2 === 0, x => x*2);
console.log(mapFilteredArray);

Adapt that function to go on the array prototype as you please.


问:
Javascript regular expression to match French characters
I need to match a word with a French character (dérange) with a regular expression. So far I have this:

    var text = "An inconvenient (qui dérange) truth";
    var splitText = text.trim().match(/\w+|\s+|[^\s\w]+/g);

    console.log(splitText);```

However, it treats the é as a separate letter. Why?

I need a regex within the match() method so that the splitText object also contains the word déranger and not the three words d, é and range as it does now.

答:
You can try the split method with regex to get all the words in your text, here is a working example:

var text = "An inconvenient (qui dérange) truth";

var splitText = text.trim().split(/\s+/);

console.log(splitText);```

Body:
I need to match a word with a French character (dérange) with a regular expression. So far I have this:

    var text = "An inconvenient (qui dérange) truth";
    var splitText = text.trim().match(/\w+|\s+|[^\s\w]+/g);

    console.log(splitText);

However, it treats the é as a separate letter. Why?

I need a regex within the match() method so that the splitText object also contains the word déranger and not the three words d, é and range as it does now.


问:
Group repeated elements of a list
I am trying to create a function that receives a list and return another list with the repeated elements.

For example for the input A = [2,2,1,1,3,2] (the list is not sorted) and the function would return result = [[1,1], [2,2,2]]. The result doesn't need to be sorted.

I already did it in Wolfram Mathematica but now I have to translate it to python3, Mathematica has some functions like Select, Map and Split that makes it very simple without using long loops with a lot of instructions.

答:
Simple approach:

```<code>def grpBySameConsecutiveItem(l):
    rv= []
    last = None
    for elem in l:
        if last == None:
            last = [elem]
            continue
        if elem == last[0]:
            last.append(elem)
            continue
        if len(last) > 1:
            rv.append(last)
        last = [elem]
    return rv

print grpBySameConsecutiveItem([1,2,1,1,1,2,2,3,4,4,4,4,5,4])
</code>```

Output:

```<code>[[1, 1, 1], [2, 2], [4, 4, 4, 4]]
</code>```

You can sort your output afterwards if you want to have it sorted or sort your inputlist , then you wouldnt get consecutive identical numbers any longer though.

See this https://stackoverflow.com/a/4174955/7505395 for how to sort lists of lists depending on an index (just use 0) as all your inner lists are identical.

You could also use itertools - it hast things like TakeWhile - that looks much smarter if used

This will ignore consecutive ones, and just collect them all:

```<code>def grpByValue(lis):
    d = {}
    for key in lis:
        if key in d:
            d[key] += 1
        else:
            d[key] = 1
    print(d)

    rv = []
    for k in d:
        if (d[k]<2):
            continue
        rv.append([])
        for n in range(0,d[k]):
            rv[-1].append(k)
    return rv

data = [1,2,1,1,1,2,2,3,4,4,4,4,5,4]

print grpByValue(data)
</code>```

Output:

```<code>[[1, 1, 1, 1], [2, 2, 2], [4, 4, 4, 4, 4]]
</code>```

Title: Group repeated elements of a list

Body:
Simple approach:

def grpBySameConsecutiveItem(l):
    rv= []
    last = None
    for elem in l:
        if last == None:
            last = [elem]
            continue
        if elem == last[0]:
            last.append(elem)
            continue
        if len(last) > 1:
            rv.append(last)
        last = [elem]
    return rv

print grpBySameConsecutiveItem([1,2,1,1,1,2,2,3,4,4,4,4,5,4])

Output:

[[1, 1, 1], [2, 2], [4, 4, 4, 4]]

You can sort your output afterwards if you want to have it sorted or sort your inputlist , then you wouldnt get consecutive identical numbers any longer though.

See this https://stackoverflow.com/a/4174955/7505395 for how to sort lists of lists depending on an index (just use 0) as all your inner lists are identical.

You could also use itertools - it hast things like TakeWhile - that looks much smarter if used

This will ignore consecutive ones, and just collect them all:

def grpByValue(lis):
    d = {}
    for key in lis:
        if key in d:
            d[key] += 1
        else:
            d[key] = 1
    print(d)

    rv = []
    for k in d:
        if (d[k]<2):
            continue
        rv.append([])
        for n in range(0,d[k]):
            rv[-1].append(k)
    return rv

data = [1,2,1,1,1,2,2,3,4,4,4,4,5,4]

print grpByValue(data)

Output:

[[1, 1, 1, 1], [2, 2, 2], [4, 4, 4, 4, 4]]


问:
Is there an event for when the title attribute shows the tooltip?
So, let's say I have this span with a title attribute:

Span```
</div>
</div>
</p>

<p>This shows the tooltip just fine, but I'd like to attach some kind of event listener for when the title shows with either JavaScript or JQuery. e.g. something like (obviously <code>"title"</code> isn't a valid event):</p>

```document.getElementById("mySpan").addEventListener("title", function () {
    console.log("Tooltip shown");
});
```

<hr>

<p>I know that I could create my own tooltip with JavaScript and a <code>mouseover</code> event like this:</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-js lang-js prettyprint-override"><code>document.getElementById("mySpan").addEventListener("mouseover", function (event) {
    console.log("Tooltip shown");
    document.getElementById("myTooltip").style.display = 'block';
    document.getElementById("myTooltip").style.top = (event.clientY + 5) + 'px';
    document.getElementById("myTooltip").style.left = (event.clientX + 5) + 'px';
});

document.getElementById("mySpan").addEventListener("mouseout", function () {
    document.getElementById("myTooltip").style.display = 'none';
});</code>```

#myTooltip {
    position: absolute;
    background-color: lightgray;
    padding: 2px 4px;
    font-size: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="mySpan">Span</span>
<span id="myTooltip" style="display: none;">Tooltip</span></code>```

But this means I have to recreate the style of the title attribute from scratch, which changes from browser to browser, and from OS to OS, and I'd really rather not change the standard tooltip that the user is used to seeing.

So, in summary, is it possible to attach some sort of event listener for when the title attribute displays?

答:
You can use jQuery-ui Tooltip Widget

$( document ).tooltip();
$("#inputhelp").tooltip({
    open: function( event, ui ) {
     console.log('Text tooltip');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>
  Anchor text
  <input id="inputhelp" title="Input help">
</p></code>```

Body:
So, let's say I have this span with a title attribute:

Span

This shows the tooltip just fine, but I'd like to attach some kind of event listener for when the title shows with either JavaScript or JQuery. e.g. something like (obviously "title" isn't a valid event):

document.getElementById("mySpan").addEventListener("title", function () {
    console.log("Tooltip shown");
});

I know that I could create my own tooltip with JavaScript and a mouseover event like this:

document.getElementById("mySpan").addEventListener("mouseover", function (event) {
    console.log("Tooltip shown");
    document.getElementById("myTooltip").style.display = 'block';
    document.getElementById("myTooltip").style.top = (event.clientY + 5) + 'px';
    document.getElementById("myTooltip").style.left = (event.clientX + 5) + 'px';
});

document.getElementById("mySpan").addEventListener("mouseout", function () {
    document.getElementById("myTooltip").style.display = 'none';
});

#myTooltip {
    position: absolute;
    background-color: lightgray;
    padding: 2px 4px;
    font-size: 10px;
}

Span
Tooltip

But this means I have to recreate the style of the title attribute from scratch, which changes from browser to browser, and from OS to OS, and I'd really rather not change the standard tooltip that the user is used to seeing.

So, in summary, is it possible to attach some sort of event listener for when the title attribute displays?

Body:
You can use jQuery-ui Tooltip Widget

$( document ).tooltip();
$("#inputhelp").tooltip({
    open: function( event, ui ) {
     console.log('Text tooltip');
    }
});

<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>
  <a href="#" title="Anchor description">Anchor text</a>
  <input id="inputhelp" title="Input help">
</p>


问:
Implementing operator<=> for optional<T>
With operator<=> being added into C++20, I wanted to try to reason about how to implement this operator for those cases where it's not a simple member-wise comparison.

How would you implement the spaceship operator for comparing an optional<T> to an optionalor a U, which is a case where we either have to compare the T to the U or compare underlying states, getting the correct return type? There isn't such an example in the latest paper.

答:
With <=> we have to make a decision: what do we want to do if the underlying comparison we need does not yet implement <=>?

One option is: don't care. Just use <=> and if the relevant types don't provide it, we're not comparable. That makes for a very concise implementation (note that you need to do the same thing for == for a total of six functions):

```<code>template <typename T>
class optional {
public:
    // ...

    template <typename U>
    constexpr std::compare_three_way_result_t<T, U>
    operator<=>(optional<U> const& rhs) const
    {
        if (has_value() && rhs) {
            return **this <=> *rhs;
        } else {
            return has_value() <=> rhs.has_value();
        }
    }

    template <typename U>
    constexpr std::compare_three_way_result_t<T, U>
    operator<=>(U const& rhs) const
    {
        if (has_value()) {
            return **this <=> *rhs;
        } else {
            return strong_ordering::less;
        }
    }

    constexpr strong_ordering operator<=>(nullopt_t ) const {
        return has_value() ? strong_ordering::greater
                           : strong_ordering::equal;
    }
};
</code>```

The three-way comparison between bools yields std::strong_ordering, which is implicitly convertible to the other comparison categories. Likewise, strong_ordering::less being implicitly convertible to weak_ordering::less, partial_ordering::less, strong_equality::unequal, or weak_equality::nonequivalent, as appropriate.

The above is the super nice, happy answer. And hopefully as time progresses, people will adopt <=> and more and more code will be able to rely on the happy answer.

Another option is: we do care, and want to fallback to synthesizing an ordering. That is, if we need to compare a T and a U and they don't provide a <=>, we can use one of the new customization point objects in the standard library. Which one though? The most conservative option is to synthesize a partial_ordering with compare_partial_order_fallback. This guarantees that we will always get the right answer.

For the optional<T> vs optional comparison, that looks like:

```<code>template <typename T>
class optional {
public:
    // ...

    template <typename U>
    constexpr auto operator<=>(optional<U> const& rhs) const
        -> decltype(std::compare_partial_order_fallback(**this, *rhs))
    {
        if (has_value() && rhs) {
            return std::compare_partial_order_fallback(**this, *rhs);
        } else {
            return has_value() <=> rhs.has_value();
        }
    }

    // ...
};
</code>```

Unfortunately, as implemented above, our comparison now always returns partial_ordering -- even between two optional<int>s. So a better alternative might be to use whatever <=> returns and use the conservative fallback otherwise. I have no idea how to name this concept yet, so I'll just go with:

```<code>template <typename T, std::three_way_comparable_with<T> U>
constexpr auto spaceship_or_fallback(T const& t, U const& u) {
    return t <=> u;
}

template <typename T, typename U>
constexpr auto spaceship_or_fallback(T const& t, U const& u)
    -> decltype(std::compare_partial_order_fallback(t, u))
{
    return std::compare_partial_order_fallback(t, u);
}
</code>```

and use that:

```<code>template <typename T>
class optional {
public:
    // ...

    template <typename U>
    constexpr auto operator<=>(optional<U> const& rhs) const
        -> decltype(spaceship_or_fallback(**this, *rhs))
    {
        if (has_value() && rhs) {
            return spaceship_or_fallback(**this, *rhs);
        } else {
            return has_value() <=> rhs.has_value();
        }
    }

    // ...
};
</code>```

A third option, the most conservative option, is what the Standard Library will take. Provide both the relational operators and the three-way comparison:

```<code>template <typename T> class optional { /* ... */ };

template <typename T, typename U>
constexpr bool operator<(optional<T> const&, optional<U> const&);
template <typename T, typename U>
constexpr bool operator>(optional<T> const&, optional<U> const&);
template <typename T, typename U>
constexpr bool operator<=(optional<T> const&, optional<U> const&);
template <typename T, typename U>
constexpr bool operator>=(optional<T> const&, optional<U> const&);

template <typename T, std::three_way_comparable_with<T> U>
std::compare_three_way_result_t<T, U>
operator<=>(optional<T> const& x, optional<U> const& y) {
    if (x && y) {
        return *x <=> *y;
    } else {
        return x.has_value() <=> y.has_value();
    }
}
</code>```

This is the most conservative option as it effectively takes both the C++17-and-earlier comparison implementation strategy and the C++20 comparison implementation strategy. As in: the "Why not both?" strategy. The use of the concept on operator<=> is what ensures that a < b invokes <=> where possible, instead of <.

It's by far the most tedious and verbose approach, with lots of boilerplate, but it ensures that for existing, single-object comparison types, existing comparisons continue to work and do the same thing. The standard library has to be conservative like this.

But new code doesn't.

Body:
With <=> we have to make a decision: what do we want to do if the underlying comparison we need does not yet implement <=>?

One option is: don't care. Just use <=> and if the relevant types don't provide it, we're not comparable. That makes for a very concise implementation (note that you need to do the same thing for == for a total of six functions):

template <typename T>
class optional {
public:
    // ...

    template <typename U>
    constexpr std::compare_three_way_result_t<T, U>
    operator<=>(optional<U> const& rhs) const
    {
        if (has_value() && rhs) {
            return **this <=> *rhs;
        } else {
            return has_value() <=> rhs.has_value();
        }
    }

    template <typename U>
    constexpr std::compare_three_way_result_t<T, U>
    operator<=>(U const& rhs) const
    {
        if (has_value()) {
            return **this <=> *rhs;
        } else {
            return strong_ordering::less;
        }
    }

    constexpr strong_ordering operator<=>(nullopt_t ) const {
        return has_value() ? strong_ordering::greater
                           : strong_ordering::equal;
    }
};

The three-way comparison between bools yields std::strong_ordering, which is implicitly convertible to the other comparison categories. Likewise, strong_ordering::less being implicitly convertible to weak_ordering::less, partial_ordering::less, strong_equality::unequal, or weak_equality::nonequivalent, as appropriate.

The above is the super nice, happy answer. And hopefully as time progresses, people will adopt <=> and more and more code will be able to rely on the happy answer.

Another option is: we do care, and want to fallback to synthesizing an ordering. That is, if we need to compare a T and a U and they don't provide a <=>, we can use one of the new customization point objects in the standard library. Which one though? The most conservative option is to synthesize a partial_ordering with compare_partial_order_fallback. This guarantees that we will always get the right answer.

For the optional<T> vs optional<U> comparison, that looks like:

template <typename T>
class optional {
public:
    // ...

    template <typename U>
    constexpr auto operator<=>(optional<U> const& rhs) const
        -> decltype(std::compare_partial_order_fallback(**this, *rhs))
    {
        if (has_value() && rhs) {
            return std::compare_partial_order_fallback(**this, *rhs);
        } else {
            return has_value() <=> rhs.has_value();
        }
    }

    // ...
};

Unfortunately, as implemented above, our comparison now always returns partial_ordering -- even between two optional<int>s. So a better alternative might be to use whatever <=> returns and use the conservative fallback otherwise. I have no idea how to name this concept yet, so I'll just go with:

template <typename T, std::three_way_comparable_with<T> U>
constexpr auto spaceship_or_fallback(T const& t, U const& u) {
    return t <=> u;
}

template <typename T, typename U>
constexpr auto spaceship_or_fallback(T const& t, U const& u)
    -> decltype(std::compare_partial_order_fallback(t, u))
{
    return std::compare_partial_order_fallback(t, u);
}

and use that:

template <typename T>
class optional {
public:
    // ...

    template <typename U>
    constexpr auto operator<=>(optional<U> const& rhs) const
        -> decltype(spaceship_or_fallback(**this, *rhs))
    {
        if (has_value() && rhs) {
            return spaceship_or_fallback(**this, *rhs);
        } else {
            return has_value() <=> rhs.has_value();
        }
    }

    // ...
};

A third option, the most conservative option, is what the Standard Library will take. Provide both the relational operators and the three-way comparison:

template <typename T> class optional { /* ... */ };

template <typename T, typename U>
constexpr bool operator<(optional<T> const&, optional<U> const&);
template <typename T, typename U>
constexpr bool operator>(optional<T> const&, optional<U> const&);
template <typename T, typename U>
constexpr bool operator<=(optional<T> const&, optional<U> const&);
template <typename T, typename U>
constexpr bool operator>=(optional<T> const&, optional<U> const&);

template <typename T, std::three_way_comparable_with<T> U>
std::compare_three_way_result_t<T, U>
operator<=>(optional<T> const& x, optional<U> const& y) {
    if (x && y) {
        return *x <=> *y;
    } else {
        return x.has_value() <=> y.has_value();
    }
}

This is the most conservative option as it effectively takes both the C++17-and-earlier comparison implementation strategy and the C++20 comparison implementation strategy. As in: the "Why not both?" strategy. The use of the concept on operator<=> is what ensures that a < b invokes <=> where possible, instead of <.

It's by far the most tedious and verbose approach, with lots of boilerplate, but it ensures that for existing, single-object comparison types, existing comparisons continue to work and do the same thing. The standard library has to be conservative like this.

But new code doesn't.


问:
Google Play App Signing and Instant Apps
Fairly straight forward question. Does anyone happen to know if Google Play App Signing supports Instant Apps? The reason I ask:

Enter your app’s signing config, or select a keystore file. While it’s possible to use a debug config or keystore during testing, the generated Digital Asset Links file won’t be compatible with the release version of your app. If you do upload a Digital Asset Links file that uses a debug config or keystore, then before publishing your app you’ll need to generate and upload a new Digital Asset Links that uses your app’s release key.

From Blog post:- How to Create an Instant App Feature

If this claim is true, does the play console provide a means for generating a assetlinks.json? This is the file that you must host on the domain you are claiming to be affiliated with.

答:
Yes, Google Play App Signing supports Instant Apps. You will use your Signing key instead of the Upload key because Google Play will re-sign your app with the signing key.

Android Studio provides a way to generate the assetlinks.json, just go to Tools > App Links Assistant > Associate Website, then you can select the  correct keystore file.

Add Android App Links > Associate your app with your website

You can also manually do it through the Statement List Generator and Tester

Other posts have also addressed this

Digital Asset Link verified by Android Studio, but not pass in Google Play Console

Instant App - Digital Asset Links Protocol


问:
node.js "Connection reset by peer" when client in same process as server
I am just beginning a node.js project and am at the stage where I am writing my first unit tests.

In the unit test I start up a server then I create a client and send a request to the server.  I will be doing an assert on the response.

Now, if I do this using two separate js files, one for starting the server, the other for the client, and I run them in separate node instances, it works fine.  The server starts up, I run the other js and the client makes the request successfully.

However, if I put the same code into a single js and run it within a single node instance, I get "Connection reset by peer" error when the client tries to connect.  I tried using a setTimeout to delay the request for a few seconds after the server started, and I tried catching the error on the socket.  Neither approach seems to help.

I would really like to be able to run this as a single process.  It makes writing and managing the unit tests so much easier.  Does anyone have any idea what I am doing wrong?

Thanks
Martin

答:
From the documentation

server.listen(port, [hostname],
  [callback]) Begin accepting
  connections on the specified port and
  hostname. If the hostname is omitted,
  the server will accept connections
  directed to any IPv4 address
  (INADDR_ANY).

To listen to a unix socket, supply a
  filename instead of port and hostname.

This function is asynchronous. The
  last parameter callback will be called
  when the server has been bound to the
  port.

server.listen(path, [callback])

I think you should do your unit test from inside the callback?

At least it worked for me. I am using express.js because it is awesome. I also am using wwwdude to make http request, but the following snippet does work for me:

```<code>const PORT = 1234;
const HOST = 'localhost';

const assert = require('assert');
const wwwdude = require('wwwdude');
const express = require('express');
const app = module.exports = express.createServer();
const client = wwwdude.createClient({
    headers: { 'User-Agent': 'wwwdude test 42' },
});

app.use(
    express.staticProvider(__dirname + '/public')
);

app.get('/', function(req, res) {
    res.send('Hello World!');
});

if (!module.parent) {
    app.listen(PORT, HOST, function() {
        client.get('http://localhost:1234')
        .addListener('error', function (err) {
        }).addListener('success', function (data, resp) {
            assert.equal('Hello World!', data);
            process.exit();
        }).send();
    });
}
</code>```

Body:
From the documentation

server.listen(port, [hostname],
  [callback]) Begin accepting
  connections on the specified port and
  hostname. If the hostname is omitted,
  the server will accept connections
  directed to any IPv4 address
  (INADDR_ANY).

To listen to a unix socket, supply a
  filename instead of port and hostname.

This function is asynchronous. The
  last parameter callback will be called
  when the server has been bound to the
  port.

server.listen(path, [callback])

I think you should do your unit test from inside the callback?

At least it worked for me. I am using express.js because it is awesome. I also am using wwwdude to make http request, but the following snippet does work for me:

const PORT = 1234;
const HOST = 'localhost';

const assert = require('assert');
const wwwdude = require('wwwdude');
const express = require('express');
const app = module.exports = express.createServer();
const client = wwwdude.createClient({
    headers: { 'User-Agent': 'wwwdude test 42' },
});

app.use(
    express.staticProvider(__dirname + '/public')
);

app.get('/', function(req, res) {
    res.send('Hello World!');
});

if (!module.parent) {
    app.listen(PORT, HOST, function() {
        client.get('http://localhost:1234')
        .addListener('error', function (err) {
        }).addListener('success', function (data, resp) {
            assert.equal('Hello World!', data);
            process.exit();
        }).send();
    });
}


问:
Running multiple ECS services in single EC2 instance using Elastic beanstalk
I have created 10 microservice dockers for web services and pushed the created images to ECS and deployed them using elastic beanstalk. Placed all the dockers in single Task definition and created a service for application-level auto-scaling. It created another task by duplicate it while auto-scaling. </p>

<p>I want to apply the auto scaling only for dockers, not for the task. If one docker affected by CPU or memory load, auto-scaling should create the copy of the particular docker only(not the whole task). How can I achieve this in ECS using Elastic Beanstalk? Is it possible to create 10 services and each contains single task and single docker container to resolve this problem? </p>

答:
If one docker affected by CPU or memory load, auto-scaling should create the copy of the particular docker only(not the whole task). How can I achieve this in ECS using Elastic Beanstalk?

ECS can only scale whole task definitions. This is defined at the ECS service level using service auto scaling. Unfortunately I can't speak to how Elastic Beanstalk handles this, as I don't use it for container management.

Is it possible to create 10 services and each contains single task and single docker container to resolve this problem?

In short, yes, this is how you would solve your problem. Those 10 services can still coexist on as many or as few cluster instances as you like.

Body:
I have created 10 microservice dockers for web services and pushed the created images to ECS and deployed them using elastic beanstalk. Placed all the dockers in single Task definition and created a service for application-level auto-scaling. It created another task by duplicate it while auto-scaling.

I want to apply the auto scaling only for dockers, not for the task. If one docker affected by CPU or memory load, auto-scaling should create the copy of the particular docker only(not the whole task). How can I achieve this in ECS using Elastic Beanstalk? Is it possible to create 10 services and each contains single task and single docker container to resolve this problem?


答:
It seems you want to part whitespaces from non-whitespaces. However, there are two expressions for non-whitespaces: \w+ (matching [a-zA-Z_0-9]+) and [^\s\w]+ (matching everything else, except also whitespace - so this is matching the é individually. Just combine these two into [^\s]+ or - simpler - \S+:

var text = "An inconvenient (qui dérange) truth";
var splitText = text.trim().match(/\S+|\s+/g);
console.log(splitText);```

Title: Javascript regular expression to match French characters


问:
User Input in C++ like in Python
```<code>#Python code
user = input("Please enter your name \n")

print ("Your name is,", user)
</code>```

How can I make this in C++?

答:
I don't exactly know what you want to achieve, but I think this is what you're looking for.</p>

```<code>#include<iostream>
#include<string>

using namespace std;

int main()
{
   string user;

   /* ---- This part is in place of your python code --- */

   cout << "Please Enter your name"; cin >> user;
   cout << "Your name is" << user;

   /* --------------------- */

   return 0;
}
</code>```

Title: User Input in C++ like in Python

Body:
#Python code
user = input("Please enter your name \n")

print ("Your name is,", user)

How can I make this in C++?

Body:
I don't exactly know what you want to achieve, but I think this is what you're looking for.

#include<iostream>
#include<string>

using namespace std;

int main()
{
   string user;

   /* ---- This part is in place of your python code --- */

   cout << "Please Enter your name"; cin >> user;
   cout << "Your name is" << user;

   /* --------------------- */

   return 0;
}


问:
Binary classification always outputs 1
I'm making my first steps on keras and I'm trying to do binary classification on the cancer dataset available in scikit-learn

```<code># load dataset
from sklearn import datasets
cancer = datasets.load_breast_cancer()
cancer.data

# dataset into pd.dataframe
import pandas as pd
donnee = pd.concat([pd.DataFrame(data = cancer.data, columns = cancer.feature_names),
                   pd.DataFrame(data = cancer.target, columns = ["target"])
                      ], axis = 1)

# train/test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(donnee.loc[:, donnee.columns != "target"], donnee.target, test_size = 0.25, random_state = 1)
</code>```

I'm trying to follow keras' tutorial here : https://keras.io/#getting-started-30-seconds-to-keras

The thing is, I always get the same loss value (6.1316862406430541), and the same accuracy (0.61538461830232527), because the predictions are always 1.

I'm not sure if it's because of a code error :

I don't know, maybe the shape of X_train is wrong ?

Or maybe I'm doing something wrong with epochs and/or batch_size.

Or if it's because of the network itself :

if I'm not mistaken, all 1 predictions is possible if there's no biases to the layers, and I don't know yet how they're initialized

But maybe it's something else, maybe 1 layer only is too few ? (if so, I wonder why keras' tutorial is 1 layer only...)

Here is my code, if you have any idea :

```<code>import keras
from keras.models import Sequential

model = Sequential()

from keras.layers import Dense

model.add(Dense(units=64, activation='relu', input_dim=30))
model.add(Dense(units=1, activation='sigmoid'))
model.summary()

model.compile(loss = keras.losses.binary_crossentropy,
              optimizer = 'rmsprop',
              metrics=['accuracy']
              )

model.fit(X_train.as_matrix(), y_train.as_matrix().reshape(426, -1), epochs=5, batch_size=32)

loss_and_metrics = model.evaluate(X_test.as_matrix(), y_test.as_matrix(), batch_size=128)
loss_and_metrics

classes = model.predict(X_test.as_matrix(), batch_size=128)
classes
</code>```

答: This is a very usual case. If you check the histogram of your data you will see that there are data points in your dataset which coordinates spans from 0 to 100. When you feed such data to neural network input to sigmoid might be so big that it will suffer from underflow. In order to scale data, you could use either MinMaxScaler or StandardScaler thanks to what you'll make your data to have a span suitable for neural network computations.

Title: Binary classification always outputs 1

Body:
I'm making my first steps on keras and I'm trying to do binary classification on the cancer dataset available in scikit-learn

# load dataset
from sklearn import datasets
cancer = datasets.load_breast_cancer()
cancer.data

# dataset into pd.dataframe
import pandas as pd
donnee = pd.concat([pd.DataFrame(data = cancer.data, columns = cancer.feature_names),
                   pd.DataFrame(data = cancer.target, columns = ["target"])
                      ], axis = 1)

# train/test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(donnee.loc[:, donnee.columns != "target"], donnee.target, test_size = 0.25, random_state = 1)

I'm trying to follow keras' tutorial here : https://keras.io/#getting-started-30-seconds-to-keras

The thing is, I always get the same loss value (6.1316862406430541), and the same accuracy (0.61538461830232527), because the predictions are always 1.

I'm not sure if it's because of a code error :

I don't know, maybe the shape of X_train is wrong ?

Or maybe I'm doing something wrong with epochs and/or batch_size.

Or if it's because of the network itself :

if I'm not mistaken, all 1 predictions is possible if there's no biases to the layers, and I don't know yet how they're initialized

But maybe it's something else, maybe 1 layer only is too few ? (if so, I wonder why keras' tutorial is 1 layer only...)

Here is my code, if you have any idea :

import keras
from keras.models import Sequential

model = Sequential()

from keras.layers import Dense

model.add(Dense(units=64, activation='relu', input_dim=30))
model.add(Dense(units=1, activation='sigmoid'))
model.summary()

model.compile(loss = keras.losses.binary_crossentropy,
              optimizer = 'rmsprop',
              metrics=['accuracy']
              )

model.fit(X_train.as_matrix(), y_train.as_matrix().reshape(426, -1), epochs=5, batch_size=32)

loss_and_metrics = model.evaluate(X_test.as_matrix(), y_test.as_matrix(), batch_size=128)
loss_and_metrics

classes = model.predict(X_test.as_matrix(), batch_size=128)
classes


问:
How to check how much char space in 1 string
Lets say I have a string with some text:

```<code>String str="Hello My Name Is Help!"
</code>```

And I want to check how much space chars I have in the following String str. I would like a make a method that takes that following string and returns the number of whitespaces in that string. For example if I name my method getNumberOfWhiteSpaces(String str) and call it a I should get back the number of whitespaces.

```<code>if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}
</code>```

答:
Try:</p>

```<code>String str="Hello My Name Is Help!";
int spaces = str.length() - str.replace(" ", "").length();
if(spaces > 3){
    System.out.println("There are more then 3 spaces in this string");
}
</code>```

Body:
Lets say I have a string with some text:

String str="Hello My Name Is Help!"

And I want to check how much space chars I have in the following String str. I would like a make a method that takes that following string and returns the number of whitespaces in that string. For example if I name my method getNumberOfWhiteSpaces(String str) and call it a I should get back the number of whitespaces.

if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}

Body:
Try:

String str="Hello My Name Is Help!";
int spaces = str.length() - str.replace(" ", "").length();
if(spaces > 3){
    System.out.println("There are more then 3 spaces in this string");
}


问:
compute an approximation of pi using cuda in python
I would like to use this simple formula to compute an approximation of pi :
pi approx formula

Here is my code :

```<code>def pi(iteration):
    pi = 0.0
    sign = 1
    b = 1.0

    for i in range(iteration):
        pi += 4.0*sign/b

        b += 2
        sign *= -1

    print pi

pi(100000)
</code>```

How to make this code be computed by the GPU?

答:
use this PyCUDA allows you to run code on GPU, here are docs

But I must say is not a good idea just to mess around with it. Be careful of overheating.

also another alternative is this PyGPU

Body:
I would like to use this simple formula to compute an approximation of pi :
pi approx formula

Here is my code :

def pi(iteration):
    pi = 0.0
    sign = 1
    b = 1.0

    for i in range(iteration):
        pi += 4.0*sign/b

        b += 2
        sign *= -1

    print pi

pi(100000)

How to make this code be computed by the GPU?


问:
flask-jwt-extended: customizing error message
When the flask-jwt-extended token has expired, a HTTP request will result in this JSON response

{
  "msg": "Token has expired"
}
```

<p>My application has a fixed error response format:</p>

<pre class="lang-js prettyprint-override"><code>{
    "message": "Project name 'Test 8' already exist.",
    "error": {
        "resource": "Project",
        "field": "project_name",
        "code": "already_exists",
        "stack_trace": "(psycopg2.IntegrityError) duplicate key value violates unique constraint \"project_name_idx\"\nDETAIL:  Key (project_name)=(Test 8) already exists.\n [SQL: 'INSERT INTO project (project_name, project_root, deadline_id) VALUES (%(project_name)s, %(project_root)s, %(deadline_id)s) RETURNING project.project_id'] [parameters: {'project_name': 'Test 8', 'project_root': 'P:\\\\Test8', 'deadline_id': 2}]"
    }
}
</code>```

How do I customize flask-jwt-extended error response?

答:
Examples of this are documented here: http://flask-jwt-extended.readthedocs.io/en/latest/changing_default_behavior.html

The API docs are here: http://flask-jwt-extended.readthedocs.io/en/latest/api.html#module-flask_jwt_extended

Body:
When the flask-jwt-extended token has expired, a HTTP request will result in this JSON response

{
  "msg": "Token has expired"
}

My application has a fixed error response format:

{
    "message": "Project name 'Test 8' already exist.",
    "error": {
        "resource": "Project",
        "field": "project_name",
        "code": "already_exists",
        "stack_trace": "(psycopg2.IntegrityError) duplicate key value violates unique constraint \"project_name_idx\"\nDETAIL:  Key (project_name)=(Test 8) already exists.\n [SQL: 'INSERT INTO project (project_name, project_root, deadline_id) VALUES (%(project_name)s, %(project_root)s, %(deadline_id)s) RETURNING project.project_id'] [parameters: {'project_name': 'Test 8', 'project_root': 'P:\\\\Test8', 'deadline_id': 2}]"
    }
}

How do I customize flask-jwt-extended error response?


问:
Second array in different way
```<code>import java.util.Scanner;
import java.util.Random;

public class Ld364rmc641 {

public static void main(String[] args) {

double A[]=new double[20];
double B;
int K,i,n;

Scanner sc = new Scanner(System.in);

System.out.println("Ld");

System.out.print("K=");

if (sc.hasNextInt())

    K = sc.nextInt();

else {
    System.out.println("input-output error");
    sc.close();
    return;
}
sc.close();
if (K==0){
    Random r = new Random();
    i=0;
    while ( i<20){
        A[i] = r.nextDouble()*20-10;
        i++;
    }
}
else {
    i=1;
    while(i<20){
        A[0]=0.5;
        A[i]= A[i-1]+K;
        i++;
    }
}
System.out.println("A:");
i=0;
do{
    System.out.printf("%.2f\t", A[i]);
    if (i==9)System.out.println();
    i++;
}
while (i<20);
for (i=0; i<20; i=i+1) {
    if(i%2==0) {
enter code here
        B = A[i];
        A[i] = A[(i+1)/2];
        A[(i+1)/2] = B;
    }
    else {
        B = A[i];
        A[i]=A[i];
    A[i]=B;
}

System.out.println("\nA:");
for (i=0; i<20; i++) {
    System.out.printf("%.2f\t", A[i]);
</code>```

Needs to make the second array like this:

A0 becomes A0

A1 becomes A19

A2 becomes A1

A3 becomes A18

A4 becomes A2

A5 becomes A17

And so on.

Where is written to write code, code needs to be changed, where is penultimate for. Rest of the code is alright. Maybe someone did this task and could help me.

答:
This should arrange the items in the array as you specified:</p>

```<code>for (i=1; i<20; i++) {
   if(i%2==0) {
      B[i] = A[i/2];
   }
   else {
      B[i] = A[20-(i+1)/2)];
   }
}
// If you want to change your original array, then just move each element in B to A:
for (i=1; i<20; i++) {
   A[i] = B[i];
}
</code>```

Title: Second array in different way

Body:
import java.util.Scanner;
import java.util.Random;

public class Ld364rmc641 {

public static void main(String[] args) {

double A[]=new double[20];
double B;
int K,i,n;

Scanner sc = new Scanner(System.in);

System.out.println("Ld");

System.out.print("K=");

if (sc.hasNextInt())

    K = sc.nextInt();

else {
    System.out.println("input-output error");
    sc.close();
    return;
}
sc.close();
if (K==0){
    Random r = new Random();
    i=0;
    while ( i<20){
        A[i] = r.nextDouble()*20-10;
        i++;
    }
}
else {
    i=1;
    while(i<20){
        A[0]=0.5;
        A[i]= A[i-1]+K;
        i++;
    }
}
System.out.println("A:");
i=0;
do{
    System.out.printf("%.2f\t", A[i]);
    if (i==9)System.out.println();
    i++;
}
while (i<20);
for (i=0; i<20; i=i+1) {
    if(i%2==0) {
enter code here
        B = A[i];
        A[i] = A[(i+1)/2];
        A[(i+1)/2] = B;
    }
    else {
        B = A[i];
        A[i]=A[i];
    A[i]=B;
}

System.out.println("\nA:");
for (i=0; i<20; i++) {
    System.out.printf("%.2f\t", A[i]);

Needs to make the second array like this:

A0 becomes A0

A1 becomes A19

A2 becomes A1

A3 becomes A18

A4 becomes A2

A5 becomes A17

And so on.

Where is written to write code, code needs to be changed, where is penultimate for. Rest of the code is alright. Maybe someone did this task and could help me.

Body:
This should arrange the items in the array as you specified:

for (i=1; i<20; i++) {
   if(i%2==0) {
      B[i] = A[i/2];
   }
   else {
      B[i] = A[20-(i+1)/2)];
   }
}
// If you want to change your original array, then just move each element in B to A:
for (i=1; i<20; i++) {
   A[i] = B[i];
}


问:
weird looping chain of synonyms error on plsql package
i can't compile this package body because i get "looping chain of synonyms"

i don't even reference any synonyms

i have checked the table dba_synonyms, there is nothing referencing the table in the select from

to be more specific, when i comment out the cursor select portion, it compiles fine

if you notice below, i am again selecting from the same table, only for count(*), this select works fine, but not the previous one

this is on oracle 12c

```<code>create or replace
package body dm_mnmi2407_pkg
is
    procedure create_appl_process_log(
        l_user_err_message_capl in varchar2,
        process_status_code_capl in varchar2,
        linecnt_capl in int
    )
    is
        l_action_taken      varchar2(50) := 'DICE Provider Demographic Feed To BRIGHTER';
        l_module_name       varchar2(20) := 'dm_mnmi2407.sqr';
        l_p_key             int := 1;
        l_p_error           char := ' ';
    begin
        dm_common_pkg.application_process_log(  l_action_taken,
                                                l_module_name,
                                                process_status_code_capl,
                                                NULL,
                                                NULL,
                                                l_user_err_message_capl,
                                                linecnt_capl,
                                                NULL,
                                                NULL,
                                                l_p_key,
                                                l_p_error
                                            );
    end create_appl_process_log;

    procedure write_records(
        full_feed_flag_wr in char,
        last_run_tmstmp_wr in date,
        process_start_tmstmp_wr in date,
        output_dir_wr in varchar2
        )
    is
        out_file        utl_file.file_type;
        out_filename    varchar2(70) := 'cdhprovdem' || '_' || process_start_tmstmp_wr ||'.dat';
        header_record   varchar2(20) := 'H, ' || process_start_tmstmp_wr;
        trailer_record  varchar2(20);

        cursor recordset is
            select  prov_donas_id as a
                    ,replace(replace(prov_id,',',' '),' ',' ') as b
                    ,lpad(prov_type1_npi,10,'0') as c
                    ,to_char(prov_eff_date,'YYYYMMDD') as d
                    ,replace(replace(prov_fee_sched,',',' '),' ',' ') as e
                    ,dppo_advantage_network_ind as f
                    ,donas_primary_fee_sched_ind as g
                    ,to_char(prov_fee_sched_eff_date,'YYYYMMDD') as h
                    ,to_char(prov_fee_sched_inactive_date,'YYYYMMDD') as i
                    ,to_char(prov_inactive_date,'YYYYMMDD') as j
                    ,prov_type as k
                    ,replace(replace(prov_title_code,',',' '),' ',' ') as l
                    ,replace(replace(prov_first_name,',',' '),' ',' ') as m
                    ,replace(replace(prov_middle_initial,',',' '),' ',' ') as n
                    ,replace(replace(prov_last_name,',',' '),' ',' ') as o
                    ,replace(replace(prov_speclty_code,',',' '),' ',' ') as p
                    ,prov_board_cert_speclty_flag as q
                    ,Prov_board_elig_speclty_flag as r
                    ,prov_donas_license_num as s
                    ,replace(replace(prov_donas_license_state_code,',',' '),' ',' ') as t
                    ,to_char(prov_experience_start_date,'YYYYMMDD') as u
                    ,to_char(prov_birth_date,'YYYYMMDD') as v
                    ,nvl(rpad(prov_foreign_lang_string,50,' '),'') as w
                    ,prov_gender as x
                    ,replace(replace(prov_dental_school_name,',',' '),' ',' ') as y
                    ,prov_primary_license_num as z
                    ,replace(replace(prov_primary_license_state_cd,',',' '),' ',' ') as aa
                    ,prov_accepting_new_pats_flag as bb
                    ,rpad(lpad(prov_type2_npi_1,10,'0')||' '||lpad(prov_type2_npi_2,10,'0')||' '|| lpad(prov_type2_npi_3,10,'0')||' '||lpad(prov_type2_npi_4,10,'0')||' '|| lpad(prov_type2_npi_5,10,'0')||' '||lpad(prov_type2_npi_6,10,'0')||' '|| lpad(prov_type2_npi_7,10,'0')||' '||lpad(prov_type2_npi_8,10,'0')||' '|| lpad(prov_type2_npi_9,10,'0')||' '||lpad(prov_type2_npi_10,10,'0')||' '|| lpad(prov_type2_npi_11,10,'0')||' '||lpad(prov_type2_npi_12,10,'0')||' '|| lpad(prov_type2_npi_13,10,'0')||' '||lpad(prov_type2_npi_14,10,'0')||' '|| lpad(prov_type2_npi_15,10,'0'),164,' ') as cc
                    ,dental_ofc_id as kk
                    ,lpad(replace(replace(dental_ofc_tax_id,',',' '),' ',' '),9,'0') as ll
                    ,replace(replace(dental_ofc_group_name,',',' '),' ',' ') as mm
                    ,replace(replace(dental_ofc_loc_addr_1,',',' '),' ',' ') as nn
                    ,replace(replace(dental_ofc_loc_addr_2,',',' '),' ',' ') as oo
                    ,replace(replace(dental_ofc_loc_city,',',' '),' ',' ') as pp
                    ,replace(replace(dental_ofc_loc_zip_county_name,',',' '),' ',' ') as qq
                    ,replace(replace(dental_ofc_loc_state_code,',',' '),' ',' ') as rr
                    ,replace(replace(dental_ofc_loc_zip_code,',',' '),' ',' ') as ss
                    ,replace(replace(dental_ofc_loc_zip_plus_4,',',' '),' ',' ') as tt
                    ,dental_ofc_phone_num as uu
                    ,dental_ofc_elec_remit_flag as vv
                    ,nvl(rpad(dental_ofc_foreign_lang_string,50,' '),'') as ww
                    ,dental_ofc_handicap_accss_flag as xx
                    ,replace(replace(dental_ofc_pmt_addr_1,',',' '),' ',' ') as yy
                    ,replace(replace(dental_ofc_pmt_addr_2,',',' '),' ',' ') as zz
                    ,replace(replace(dental_ofc_pmt_city,',',' '),' ',' ') as aaa
                    ,replace(replace(dental_ofc_pmt_zip_county_name,',',' '),' ',' ') as bbb
                    ,replace(replace(dental_ofc_pmt_name,',',' '),' ',' ') as ccc
                    ,replace(replace(dental_ofc_pmt_state_code,',',' '),' ',' ') as ddd
                    ,replace(replace(dental_ofc_pmt_zip_code,',',' '),' ',' ') as eee
                    ,replace(replace(dental_ofc_pmt_zip_plus_4,',',' '),' ',' ') as fff
                    ,replace(replace(geo_area_code,',',' '),' ',' ') as ggg
                    ,DECODE(full_feed_flag_wr,'Y','A',last_action_ind) as hhh
            from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
            where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
            and     (full_feed_flag_wr = 'N' OR last_action_ind !='D')
      ;
    begin

        out_file := utl_file.fopen(output_dir_wr,out_filename,'w');

        --write header record
        utl_file.put(out_file, header_record);

        --write detail records
        for detail_record in recordset
        loop
            detail_record :=
                a || ',' ||
                b || ',' ||
                c || ',' ||
                d || ',' ||
                e || ',' ||
                f || ',' ||
                g || ',' ||
                h || ',' ||
                i || ',' ||
                g || ',' ||
                k || ',' ||
                l || ',' ||
                m || ',' ||
                n || ',' ||
                o || ',' ||
                p || ',' ||
                q || ',' ||
                r || ',' ||
                s || ',' ||
                t || ',' ||
                u || ',' ||
                v || ',' ||
                w || ',' ||
                x || ',' ||
                y || ',' ||
                z || ',' ||
                aa || ',' ||
                bb || ',' ||
                cc || ',' ||
                kk || ',' ||
                ll || ',' ||
                mm || ',' ||
                nn || ',' ||
                oo || ',' ||
                pp || ',' ||
                qq || ',' ||
                rr || ',' ||
                ss || ',' ||
                tt || ',' ||
                uu || ',' ||
                vv || ',' ||
                ww || ',' ||
                xx || ',' ||
                yy || ',' ||
                zz || ',' ||
                aaa || ',' ||
                bbb || ',' ||
                ccc || ',' ||
                ddd || ',' ||
                eee || ',' ||
                fff || ',' ||
                ggg || ',' ||
                hhh || ',' ||
        utl_file.put_line (out_file, detail_record);
        END LOOP;

        --write trailer record
        select  count(*)
        into    linecnt
        from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
        where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
        and     (full_feed_flag_wr = 'N' OR last_action_ind !='D');

        trailer_record := 'T, ' || linecnt;
        utl_file.put_line(out_file,trailer_record);

        --close file
        utl_file.fclose(out_file);

    end write_records;

    procedure create_output_file(
        full_feed_flag in char,
        last_run_tmstmp in date,
        process_start_tmstmp in date,
        output_dir in varchar2
        )
    is
        l_user_err_message  varchar2(40);
        process_status_code varchar2(5);
    begin
        l_user_err_message  := 'Brighter Provider Feed started...';
        process_status_code := 'M';
        linecnt := 0;
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);

        write_records(full_feed_flag,last_run_tmstmp,process_start_tmstmp, output_dir);

        l_user_err_message  := 'Brighter Provider Feed Completed';
        process_status_code := 'M';
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);
    end create_output_file;

end dm_mnmi2407_pkg;
/
show errors;
</code>```

答:
As ORA-01775: looping chain of synonyms is the standard Oracle error for an attempt to reference a public synonym after dropping the underlying object (and the object and synonym had the same name, so now the only object left with that name is the synonym itself), I would look for those first. Does the following query return anything likely?

```<code>select s.table_owner, s.synonym_name
from   all_synonyms s
       join dba_objects o
            on  o.owner= s.owner
            and o.object_name = s.synonym_name
where  s.owner = 'PUBLIC'
and    s.table_owner <> 'SYS'
and    s.table_name = s.synonym_name
and    s.synonym_name not like '%/%'
and    o.object_type = 'SYNONYM'
and    o.sharing = 'NONE'
minus
select o.owner, o.object_name
from   dba_objects o
where  o.subobject_name is null;
</code>```

(dba_objects.sharing = 'NONE' is quesswork based trial and error, but seems to be what distinguishes ORA-00980: synonym translation is no longer valid from ORA-01775: looping chain of synonyms in some edge cases I don't quite understand.)

By the way, I'm a bit puzzled by this:

```<code>where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
and     (full_feed_flag_wr = 'N' OR last_action_ind !='D')
</code>```

I'm trying to work out what combination of factors are needed for those both to be true. I think it's possible but thinking about it is making my head hurt.

Body:
i can't compile this package body because i get "looping chain of synonyms"

i don't even reference any synonyms

i have checked the table dba_synonyms, there is nothing referencing the table in the select from

to be more specific, when i comment out the cursor select portion, it compiles fine

if you notice below, i am again selecting from the same table, only for count(*), this select works fine, but not the previous one

this is on oracle 12c

create or replace
package body dm_mnmi2407_pkg
is
    procedure create_appl_process_log(
        l_user_err_message_capl in varchar2,
        process_status_code_capl in varchar2,
        linecnt_capl in int
    )
    is
        l_action_taken      varchar2(50) := 'DICE Provider Demographic Feed To BRIGHTER';
        l_module_name       varchar2(20) := 'dm_mnmi2407.sqr';
        l_p_key             int := 1;
        l_p_error           char := ' ';
    begin
        dm_common_pkg.application_process_log(  l_action_taken,
                                                l_module_name,
                                                process_status_code_capl,
                                                NULL,
                                                NULL,
                                                l_user_err_message_capl,
                                                linecnt_capl,
                                                NULL,
                                                NULL,
                                                l_p_key,
                                                l_p_error
                                            );
    end create_appl_process_log;

    procedure write_records(
        full_feed_flag_wr in char,
        last_run_tmstmp_wr in date,
        process_start_tmstmp_wr in date,
        output_dir_wr in varchar2
        )
    is
        out_file        utl_file.file_type;
        out_filename    varchar2(70) := 'cdhprovdem' || '_' || process_start_tmstmp_wr ||'.dat';
        header_record   varchar2(20) := 'H, ' || process_start_tmstmp_wr;
        trailer_record  varchar2(20);

        cursor recordset is
            select  prov_donas_id as a
                    ,replace(replace(prov_id,',',' '),' ',' ') as b
                    ,lpad(prov_type1_npi,10,'0') as c
                    ,to_char(prov_eff_date,'YYYYMMDD') as d
                    ,replace(replace(prov_fee_sched,',',' '),' ',' ') as e
                    ,dppo_advantage_network_ind as f
                    ,donas_primary_fee_sched_ind as g
                    ,to_char(prov_fee_sched_eff_date,'YYYYMMDD') as h
                    ,to_char(prov_fee_sched_inactive_date,'YYYYMMDD') as i
                    ,to_char(prov_inactive_date,'YYYYMMDD') as j
                    ,prov_type as k
                    ,replace(replace(prov_title_code,',',' '),' ',' ') as l
                    ,replace(replace(prov_first_name,',',' '),' ',' ') as m
                    ,replace(replace(prov_middle_initial,',',' '),' ',' ') as n
                    ,replace(replace(prov_last_name,',',' '),' ',' ') as o
                    ,replace(replace(prov_speclty_code,',',' '),' ',' ') as p
                    ,prov_board_cert_speclty_flag as q
                    ,Prov_board_elig_speclty_flag as r
                    ,prov_donas_license_num as s
                    ,replace(replace(prov_donas_license_state_code,',',' '),' ',' ') as t
                    ,to_char(prov_experience_start_date,'YYYYMMDD') as u
                    ,to_char(prov_birth_date,'YYYYMMDD') as v
                    ,nvl(rpad(prov_foreign_lang_string,50,' '),'') as w
                    ,prov_gender as x
                    ,replace(replace(prov_dental_school_name,',',' '),' ',' ') as y
                    ,prov_primary_license_num as z
                    ,replace(replace(prov_primary_license_state_cd,',',' '),' ',' ') as aa
                    ,prov_accepting_new_pats_flag as bb
                    ,rpad(lpad(prov_type2_npi_1,10,'0')||' '||lpad(prov_type2_npi_2,10,'0')||' '|| lpad(prov_type2_npi_3,10,'0')||' '||lpad(prov_type2_npi_4,10,'0')||' '|| lpad(prov_type2_npi_5,10,'0')||' '||lpad(prov_type2_npi_6,10,'0')||' '|| lpad(prov_type2_npi_7,10,'0')||' '||lpad(prov_type2_npi_8,10,'0')||' '|| lpad(prov_type2_npi_9,10,'0')||' '||lpad(prov_type2_npi_10,10,'0')||' '|| lpad(prov_type2_npi_11,10,'0')||' '||lpad(prov_type2_npi_12,10,'0')||' '|| lpad(prov_type2_npi_13,10,'0')||' '||lpad(prov_type2_npi_14,10,'0')||' '|| lpad(prov_type2_npi_15,10,'0'),164,' ') as cc
                    ,dental_ofc_id as kk
                    ,lpad(replace(replace(dental_ofc_tax_id,',',' '),' ',' '),9,'0') as ll
                    ,replace(replace(dental_ofc_group_name,',',' '),' ',' ') as mm
                    ,replace(replace(dental_ofc_loc_addr_1,',',' '),' ',' ') as nn
                    ,replace(replace(dental_ofc_loc_addr_2,',',' '),' ',' ') as oo
                    ,replace(replace(dental_ofc_loc_city,',',' '),' ',' ') as pp
                    ,replace(replace(dental_ofc_loc_zip_county_name,',',' '),' ',' ') as qq
                    ,replace(replace(dental_ofc_loc_state_code,',',' '),' ',' ') as rr
                    ,replace(replace(dental_ofc_loc_zip_code,',',' '),' ',' ') as ss
                    ,replace(replace(dental_ofc_loc_zip_plus_4,',',' '),' ',' ') as tt
                    ,dental_ofc_phone_num as uu
                    ,dental_ofc_elec_remit_flag as vv
                    ,nvl(rpad(dental_ofc_foreign_lang_string,50,' '),'') as ww
                    ,dental_ofc_handicap_accss_flag as xx
                    ,replace(replace(dental_ofc_pmt_addr_1,',',' '),' ',' ') as yy
                    ,replace(replace(dental_ofc_pmt_addr_2,',',' '),' ',' ') as zz
                    ,replace(replace(dental_ofc_pmt_city,',',' '),' ',' ') as aaa
                    ,replace(replace(dental_ofc_pmt_zip_county_name,',',' '),' ',' ') as bbb
                    ,replace(replace(dental_ofc_pmt_name,',',' '),' ',' ') as ccc
                    ,replace(replace(dental_ofc_pmt_state_code,',',' '),' ',' ') as ddd
                    ,replace(replace(dental_ofc_pmt_zip_code,',',' '),' ',' ') as eee
                    ,replace(replace(dental_ofc_pmt_zip_plus_4,',',' '),' ',' ') as fff
                    ,replace(replace(geo_area_code,',',' '),' ',' ') as ggg
                    ,DECODE(full_feed_flag_wr,'Y','A',last_action_ind) as hhh
            from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
            where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
            and     (full_feed_flag_wr = 'N' OR last_action_ind !='D')
      ;
    begin

        out_file := utl_file.fopen(output_dir_wr,out_filename,'w');

        --write header record
        utl_file.put(out_file, header_record);

        --write detail records
        for detail_record in recordset
        loop
            detail_record :=
                a || ',' ||
                b || ',' ||
                c || ',' ||
                d || ',' ||
                e || ',' ||
                f || ',' ||
                g || ',' ||
                h || ',' ||
                i || ',' ||
                g || ',' ||
                k || ',' ||
                l || ',' ||
                m || ',' ||
                n || ',' ||
                o || ',' ||
                p || ',' ||
                q || ',' ||
                r || ',' ||
                s || ',' ||
                t || ',' ||
                u || ',' ||
                v || ',' ||
                w || ',' ||
                x || ',' ||
                y || ',' ||
                z || ',' ||
                aa || ',' ||
                bb || ',' ||
                cc || ',' ||
                kk || ',' ||
                ll || ',' ||
                mm || ',' ||
                nn || ',' ||
                oo || ',' ||
                pp || ',' ||
                qq || ',' ||
                rr || ',' ||
                ss || ',' ||
                tt || ',' ||
                uu || ',' ||
                vv || ',' ||
                ww || ',' ||
                xx || ',' ||
                yy || ',' ||
                zz || ',' ||
                aaa || ',' ||
                bbb || ',' ||
                ccc || ',' ||
                ddd || ',' ||
                eee || ',' ||
                fff || ',' ||
                ggg || ',' ||
                hhh || ',' ||
        utl_file.put_line (out_file, detail_record);
        END LOOP;

        --write trailer record
        select  count(*)
        into    linecnt
        from    EXT_DICE_PROV_DEMOGRAPHIC_FEED
        where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
        and     (full_feed_flag_wr = 'N' OR last_action_ind !='D');

        trailer_record := 'T, ' || linecnt;
        utl_file.put_line(out_file,trailer_record);

        --close file
        utl_file.fclose(out_file);

    end write_records;

    procedure create_output_file(
        full_feed_flag in char,
        last_run_tmstmp in date,
        process_start_tmstmp in date,
        output_dir in varchar2
        )
    is
        l_user_err_message  varchar2(40);
        process_status_code varchar2(5);
    begin
        l_user_err_message  := 'Brighter Provider Feed started...';
        process_status_code := 'M';
        linecnt := 0;
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);

        write_records(full_feed_flag,last_run_tmstmp,process_start_tmstmp, output_dir);

        l_user_err_message  := 'Brighter Provider Feed Completed';
        process_status_code := 'M';
        create_appl_process_log(l_user_err_message, process_status_code, linecnt);
    end create_output_file;

end dm_mnmi2407_pkg;
/
show errors;

Body:
As ORA-01775: looping chain of synonyms is the standard Oracle error for an attempt to reference a public synonym after dropping the underlying object (and the object and synonym had the same name, so now the only object left with that name is the synonym itself), I would look for those first. Does the following query return anything likely?

select s.table_owner, s.synonym_name
from   all_synonyms s
       join dba_objects o
            on  o.owner= s.owner
            and o.object_name = s.synonym_name
where  s.owner = 'PUBLIC'
and    s.table_owner <> 'SYS'
and    s.table_name = s.synonym_name
and    s.synonym_name not like '%/%'
and    o.object_type = 'SYNONYM'
and    o.sharing = 'NONE'
minus
select o.owner, o.object_name
from   dba_objects o
where  o.subobject_name is null;

(dba_objects.sharing = 'NONE' is quesswork based trial and error, but seems to be what distinguishes ORA-00980: synonym translation is no longer valid from ORA-01775: looping chain of synonyms in some edge cases I don't quite understand.)

By the way, I'm a bit puzzled by this:

where   (full_feed_flag_wr = 'Y' OR (z_update_tmstmp between last_run_tmstmp_wr and process_start_tmstmp_wr))
and     (full_feed_flag_wr = 'N' OR last_action_ind !='D')

I'm trying to work out what combination of factors are needed for those both to be true. I think it's possible but thinking about it is making my head hurt.


问:
Build a UIView in Interface Builder
There are similar posts about this topic, but my situation seems to be a little different. With that said, it also feels like it should be a common problem to overcome.

I have a view controller (StatsViewController) that has a blank UIScrollView at the moment. What I'd like to do is create a custom UIView class, and lay it out using Interface Builder and then have the StatsViewController use this view multiple times. But it's an unknown number of times currently. Basically, the StatsViewController will be pulling in some JSON from a web service, looping through the service, and for each "loop" I'd like to instantiate a new view using my custom UIView and add it to the UIScrollView within the StatsViewController.

My problem is when I create the UIView in interface builder, I can't figure out how to instantiate it using the nib through the loop. I read that you load view controllers using a nib, and not plain UIView's... but at the same time, I read that you can't (or shouldn't) have nested UIViewControllers, so I'm at a loss.

If I create a custom view in Interface Builder, how can I instantiate it multiple times on the same view controller?

答:
Each view will be it's own object. If you store each into an array, you can get to each view via the array. This would allow you to control them all with one controller.

And no, you load nib's with the nib loader. They might describe whatever. It doesn't need to have a controller in it.

Title: Build a UIView in Interface Builder


问:
Python v3 , Beautifoulsoup - multiple div tags with same name
```<code> soup = BeautifulSoup(html, "html.parser") # BeautifulSoup(markup, "lxml")
 items = soup.find_all("div","_3u1 _gli _uvb", recursive=True)
   for item in items:
      abouts = item.find_all("div", {"class":"_glo"}, recursive = True)[0].text
   print (abouts)
</code>```

HTML page:

```<code>          <div class="_glo">
            <div>
              <div class="_ajw">
                <div class="_52eh">
                    "text
                </div>
              </div>
              <div class="_ajw">
                <div class="_52eh">
                    "text"
                </div>
              </div>
              <div class="_ajw">
                <div class="_52eh">
                   "text"
                </div>
              </div>
            </div>
          </div>
</code>```

Afternoon , i am trying to scrape a webpage using beautifullsoup, python. I need al the "text" strings in a separate variable. When i print abouts i get :"text text text" I want it to be seperated.

Kind regards

答:
Try this:

```<code>items = soup.find_all('div', attrs={'class':'_ajw'})
dict = {}
for i in range(len(items)):
    dict['text'+str(i+1)] = item[i].find('div', attrs={'class':'_52eh'}).text
print(dict)
</code>```

This will give you something like this:

```<code>{'text1': text, 'text2': text, 'text3': text}
</code>```

Body:
 soup = BeautifulSoup(html, "html.parser") # BeautifulSoup(markup, "lxml")
 items = soup.find_all("div","_3u1 _gli _uvb", recursive=True)
   for item in items:
      abouts = item.find_all("div", {"class":"_glo"}, recursive = True)[0].text
   print (abouts)

HTML page:

                    "text

                    "text"

                   "text"

Afternoon , i am trying to scrape a webpage using beautifullsoup, python. I need al the "text" strings in a separate variable. When i print abouts i get :"text text text" I want it to be seperated.

Kind regards

Body:
Try this:

items = soup.find_all('div', attrs={'class':'_ajw'})
dict = {}
for i in range(len(items)):
    dict['text'+str(i+1)] = item[i].find('div', attrs={'class':'_52eh'}).text
print(dict)

This will give you something like this:

{'text1': text, 'text2': text, 'text3': text}


问:
Radiobutton in Android Quiz app
I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:

```<code>int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}
</code>```

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

答:
You could disable the RadioButton or RadioGroup by setEnabled(boolean).

For example, you could disable the radio button that was selected by

```<code>radiobutton1.setEnabled(false);
</code>```

I would suggest disabling all the radio buttons at that point, to prevent a user from changing their answer. You could do this all at once by calling setEnabled(boolean) on the radio group.

```<code>RadioGroup group = (RadioGroup) findViewById(R.id.myRadioGroup);
group.setEnabled(false);
</code>```

Title: Radiobutton in Android Quiz app

Body:
I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:

int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

Body:
You could disable the RadioButton or RadioGroup by setEnabled(boolean).

For example, you could disable the radio button that was selected by

radiobutton1.setEnabled(false);

I would suggest disabling all the radio buttons at that point, to prevent a user from changing their answer. You could do this all at once by calling setEnabled(boolean) on the radio group.

RadioGroup group = (RadioGroup) findViewById(R.id.myRadioGroup);
group.setEnabled(false);