问:
python warning exception without stopping program
I just got this error while doing a neural network, this error arise when I pass my nodes in my activation function (sigmoid), I suspect the error arise because its a convolutionnal neural network and so the convolutional layer uses ReLU as an activation function which can make numbers really big; in my sigmoid function:

```<code>def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoidprime(x):
    return np.exp(-x) / ((1 + np.exp(-x))**2)
</code>```

in the function, x is my nodes, but sometime the number can get really big and since the sigmoid function is effectively only usefull between 0 and 1, I believe this is what raise the error BUT when I try it with a single really big number it does not raise the error, plus, the error doesnt actually stop my program. What I want to know is how to prevent the exception and if my activation function is passed even if the error is raised

Warning (from warnings module):
    File "C:\Python27\saves\CNN\CNN_flat_layer.py", line 17
      return np.exp(-x) / ((1 + np.exp(-x))**2)
  RuntimeWarning: overflow encountered in exp

Warning (from warnings module):
    File "C:\Python27\saves\CNN\CNN_flat_layer.py", line 17
      return np.exp(-x) / ((1 + np.exp(-x))**2)
  RuntimeWarning: overflow encountered in square

Warning (from warnings module):
    File "C:\Python27\saves\CNN\CNN_flat_layer.py", line 17
      return np.exp(-x) / ((1 + np.exp(-x))**2)
  RuntimeWarning: invalid value encountered in divide

答: In this instance, the first warning is the one to note. If the absolute value of x is very small or large than the result of np.exp(x) is likely larger or smaller than what its dtype can hold. The fact that it is an overflow error indicates this is most likely what is happening

Body:
I just got this error while doing a neural network, this error arise when I pass my nodes in my activation function (sigmoid), I suspect the error arise because its a convolutionnal neural network and so the convolutional layer uses ReLU as an activation function which can make numbers really big; in my sigmoid function:

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoidprime(x):
    return np.exp(-x) / ((1 + np.exp(-x))**2)

in the function, x is my nodes, but sometime the number can get really big and since the sigmoid function is effectively only usefull between 0 and 1, I believe this is what raise the error BUT when I try it with a single really big number it does not raise the error, plus, the error doesnt actually stop my program. What I want to know is how to prevent the exception and if my activation function is passed even if the error is raised

Warning (from warnings module):
    File "C:\Python27\saves\CNN\CNN_flat_layer.py", line 17
      return np.exp(-x) / ((1 + np.exp(-x))**2)
  RuntimeWarning: overflow encountered in exp

Warning (from warnings module):
    File "C:\Python27\saves\CNN\CNN_flat_layer.py", line 17
      return np.exp(-x) / ((1 + np.exp(-x))**2)
  RuntimeWarning: overflow encountered in square

Warning (from warnings module):
    File "C:\Python27\saves\CNN\CNN_flat_layer.py", line 17
      return np.exp(-x) / ((1 + np.exp(-x))**2)
  RuntimeWarning: invalid value encountered in divide


来源: stackexchange

问:
I am trying to join two tables I want null values to be equivalent to ALL
Lets say that I have two tables:

```<code>table 1 columns: A,B,C
table 2 columns: D,E,F

JOIN Conditions
table1.A = table2.D, table1.B=table2.E, table1.C = table2.F
</code>```

Any column can have a null value. I want null values to be treated as a match for any value. (i.e if A=D and B=E, but C is null. F has two values for A=D and B=E. Both rows should be included in the resultant table)

```<code>Table1:                                Table2:
A:         B:       C:                D:           E:          F:
a          b         c                 a           b           c
e          <null>    f                 e           a           f
o          <null>    q                 e           b           f
h          i         j                 h           i           k
l          <null>    m                 l           a           m
o          <null>    q                 o           <null>      q

results(show table 2 values...):
D:   E:     F:
a    b      c
e    a      f
e    b      f
o   <null>  q
l    a      m
</code>```

答:
I think this does what you want. SQL will actually optimize this rather efficiently.</p>

```<code>DECLARE @t1 AS TABLE
  (
       [A]   NVARCHAR(25)
       , [B] NVARCHAR(25)
       , [C] NVARCHAR(25)
  );
DECLARE @t2 AS TABLE
  (
       [D]   NVARCHAR(25)
       , [E] NVARCHAR(25)
       , [F] NVARCHAR(25)
  );

INSERT INTO @t1
            ([A]
             , [B]
             , [C])
VALUES      (N'one',N'one',N'one'),
            (N'two',N'two',NULL),
            (N'three',N'three',N'three');

INSERT INTO @t2
            ([D]
             , [E]
             , [F])
VALUES      (N'one',N'one',N'one'),
            (N'two',N'two',NULL),
            (N'three',N'three',NULL);

SELECT *
FROM   @t1 AS [t1]
       JOIN @t2 AS [t2]
         ON [t1].[A] = [t2].[D]
            AND [t1].[B] = [t2].[E]
            AND [t1].[C] = [t2].[F];

SELECT *
FROM   @t1 AS [t1]
       JOIN @t2 AS [t2]
         ON
       (
           [t1].[A] = [t2].[D]
            OR [t1].[A] IS NULL
            OR [t2].[D] IS NULL
        )
       AND
       (
           [t1].[B] = [t2].[E]
            OR [t1].[B] IS NULL
            OR [t2].[E] IS NULL
        )
       AND
       (
           [t1].[C] = [t2].[F]
            OR [t1].[C] IS NULL
            OR [t2].[F] IS NULL
        )
;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Lets say that I have two tables:

table 1 columns: A,B,C
table 2 columns: D,E,F

JOIN Conditions
table1.A = table2.D, table1.B=table2.E, table1.C = table2.F

Any column can have a null value. I want null values to be treated as a match for any value. (i.e if A=D and B=E, but C is null. F has two values for A=D and B=E. Both rows should be included in the resultant table)

Table1:                                Table2:
A:         B:       C:                D:           E:          F:
a          b         c                 a           b           c
e          <null>    f                 e           a           f
o          <null>    q                 e           b           f
h          i         j                 h           i           k
l          <null>    m                 l           a           m
o          <null>    q                 o           <null>      q

results(show table 2 values...):
D:   E:     F:
a    b      c
e    a      f
e    b      f
o   <null>  q
l    a      m

Body:
I think this does what you want. SQL will actually optimize this rather efficiently.

DECLARE @t1 AS TABLE
  (
       [A]   NVARCHAR(25)
       , [B] NVARCHAR(25)
       , [C] NVARCHAR(25)
  );
DECLARE @t2 AS TABLE
  (
       [D]   NVARCHAR(25)
       , [E] NVARCHAR(25)
       , [F] NVARCHAR(25)
  );

INSERT INTO @t1
            ([A]
             , [B]
             , [C])
VALUES      (N'one',N'one',N'one'),
            (N'two',N'two',NULL),
            (N'three',N'three',N'three');

INSERT INTO @t2
            ([D]
             , [E]
             , [F])
VALUES      (N'one',N'one',N'one'),
            (N'two',N'two',NULL),
            (N'three',N'three',NULL);

SELECT *
FROM   @t1 AS [t1]
       JOIN @t2 AS [t2]
         ON [t1].[A] = [t2].[D]
            AND [t1].[B] = [t2].[E]
            AND [t1].[C] = [t2].[F];

SELECT *
FROM   @t1 AS [t1]
       JOIN @t2 AS [t2]
         ON
       (
           [t1].[A] = [t2].[D]
            OR [t1].[A] IS NULL
            OR [t2].[D] IS NULL
        )
       AND
       (
           [t1].[B] = [t2].[E]
            OR [t1].[B] IS NULL
            OR [t2].[E] IS NULL
        )
       AND
       (
           [t1].[C] = [t2].[F]
            OR [t1].[C] IS NULL
            OR [t2].[F] IS NULL
        )
;


问:
Easy way to set index.html <title>title</title> to child iframe title?
Is there an easy way to set the <title>*</title> of my index.html by looking at the <title>*</title> of a child iframe?

My site as example

When the content in the iframe changes, will the title change with it then?

答:
For Only Web Pages are on same Domain.

```<code>var title = $("#IframeID").contents().find("title").html();
 $(document).attr('title',title);
</code>```

Body:
For Only Web Pages are on same Domain.

var title = $("#IframeID").contents().find("title").html();
 $(document).attr('title',title);


问:
HTML Problems- Video Autoplay Playback Not working
I have started creating a website using HTML, however I want a video to play when I open the page and I have embedded the video as shown:

<!DOCTYPE HTML>

 Video HERE

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">

  <video width="1920" height="1080" autoplay>
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

```

This is an example video, however, it doesn't work on a local PC. I use Notepad++ to code in, but it doesn't seem to work?

Please help

thanks

yg.swagness

答: I tried it, and it worked try using a different editor I just used this basic one https://htmledit.squarefree.com</p>

Body:
I have started creating a website using HTML, however I want a video to play when I open the page and I have embedded the video as shown:

<!DOCTYPE HTML>

 Video HERE

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">

  <video width="1920" height="1080" autoplay>
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

This is an example video, however, it doesn't work on a local PC. I use Notepad++ to code in, but it doesn't seem to work?

Please help

thanks

yg.swagness


问:
Custom meta data in static html is not being indexed in Azure search
I have nearly 500 static html files. all of them have different custom metadata tags like , ,, ,  etc.. I have uploaded the static htmls in to ablob and indexed the blob, as per azure documentation.
I was successful in searching the index fields  & < description> with relevant content, but for other fields like < region>, ,  it is shown as null.
I have gone through Azure search documentation extensively. I found that it was ready to map Conten-type specific (HTML) metadata tags, shown in the article

https://learn.microsoft.com/en-us/azure/search/search-howto-indexing-azure-blob-storage#indexing-documents-along-with-related-data

But could not get appropriate information about the above 3 missing fields. Please help in this

答:
Currently, Azure Search blob indexer does not support indexing custom metadata tags in HTML files. Please vote for Custom meta data in static html is not being indexed UserVoice suggestion to help us prioritize that feature.

As a workaround, you can add your meta tags to blob metadata, and those will be picked up and indexed by the indexer.


问:
Bootstrap 4 hex colors for rails app
Does anyone know where to find a list of bootstrap 4 colors in hex?  i looked at the docs, maybe i missed it? </p>

<p>My issue is that I'm trying to match some colors on my site to the bootstrap 4 "bg-primary", "btn-primary", etc... colors. </p>

答:
The easiest way to get the default values used in Bootstrap is to check the scss variables in the source. Since the package is available publicly from Github you can do this even without installing it. The variables are set in the bootstrap/scss/_variables.scss
 file.

The default colors are as follows:

```<code>// Colors
$blue:    #007bff !default; // primary
$indigo:  #6610f2 !default;
$purple:  #6f42c1 !default;
$pink:    #e83e8c !default;
$red:     #dc3545 !default; // danger
$orange:  #fd7e14 !default;
$yellow:  #ffc107 !default; // warning
$green:   #28a745 !default; // success
$teal:    #20c997 !default;
$cyan:    #17a2b8 !default; // info

// Grays
$white:    #fff !default;
$gray-100: #f8f9fa !default; // light
$gray-200: #e9ecef !default;
$gray-300: #dee2e6 !default;
$gray-400: #ced4da !default;
$gray-500: #adb5bd !default;
$gray-600: #868e96 !default; // secondary
$gray-700: #495057 !default;
$gray-800: #343a40 !default; // dark
$gray-900: #212529 !default;
$black:    #000 !default;
</code>```

Title: Bootstrap 4 hex colors for rails app

Body:
Does anyone know where to find a list of bootstrap 4 colors in hex?  i looked at the docs, maybe i missed it?

My issue is that I'm trying to match some colors on my site to the bootstrap 4 "bg-primary", "btn-primary", etc... colors.

Body:
The easiest way to get the default values used in Bootstrap is to check the scss variables in the source. Since the package is available publicly from Github you can do this even without installing it. The variables are set in the bootstrap/scss/_variables.scss
 file.

The default colors are as follows:

// Colors
$blue:    #007bff !default; // primary
$indigo:  #6610f2 !default;
$purple:  #6f42c1 !default;
$pink:    #e83e8c !default;
$red:     #dc3545 !default; // danger
$orange:  #fd7e14 !default;
$yellow:  #ffc107 !default; // warning
$green:   #28a745 !default; // success
$teal:    #20c997 !default;
$cyan:    #17a2b8 !default; // info

// Grays
$white:    #fff !default;
$gray-100: #f8f9fa !default; // light
$gray-200: #e9ecef !default;
$gray-300: #dee2e6 !default;
$gray-400: #ced4da !default;
$gray-500: #adb5bd !default;
$gray-600: #868e96 !default; // secondary
$gray-700: #495057 !default;
$gray-800: #343a40 !default; // dark
$gray-900: #212529 !default;
$black:    #000 !default;


答:
I would use something similar to JNevill's approach, but I would find writing it this way to make more sense to me:</p>

```<code>ON (Table1.A=Table2.D OR Table1.A IS NULL OR Table2.D IS NULL)
AND (Table1.B=Table2.E OR Table1.B IS NULL OR Table2.E IS NULL)
AND (Table1.C=Table2.F OR Table1.C IS NULL OR Table2.F IS NULL)
</code>```

Title: I am trying to join two tables I want null values to be equivalent to ALL

Body:
I would use something similar to JNevill's approach, but I would find writing it this way to make more sense to me:

ON (Table1.A=Table2.D OR Table1.A IS NULL OR Table2.D IS NULL)
AND (Table1.B=Table2.E OR Table1.B IS NULL OR Table2.E IS NULL)
AND (Table1.C=Table2.F OR Table1.C IS NULL OR Table2.F IS NULL)


问:
Must Java be installed to run a Java application?
when you write an app in java, people need to have this java installed to use it right?

Sorry if this is a dumb question.

答:
Traroth is correct; your audience needs the Java Runtime in order to use your java.

However, they don't necessarily need that Java, or in other words, they don't need to be using Sun (now Oracle)'s JRE. They could also be using the OpenJDK, or any of the other free java implementations.

Not a silly question at all.

Side Note: As Glenn Nelson stated, there are Ahead-Of-Time compilers, and if you want to go down that route, go ahead. But I'd strongly warn against jumping into that boat, especially if you are just starting off in Java. AOT Java compilers come with their own set of issues.

ContentLicense: CC BY-SA 2.5


问:
Flask is not importing even though I installed it
I'm on Windows 10 and I am using PyCharm to run my application. I'm pretty new to Python and just coding in general.

I typed:

```<code>pip install flask
</code>```

in the cmd prompt but forgot to open cmd prompt under administrator privileges. Could this be the problem? I ended up re-opening the cmd prompt with administrator rights and typed

```<code>pip install flask
</code>```

again and it showed that it was already installed. I'm pretty sure I have flask installed on my system.

When I try to run the python file below which I named test_webapp.py I get the following error:

```<code>from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello():

    return "Hello World!"

if __name__ == "__main__":

    app.run()
</code>```

I get an error:

ModuleNotFoundError: No module named 'flask'

when i type in python --version into the command prompt i get version 3.6.3.

When i type the same code into the Python 3.6 (32-bit) command line, the code works! However, when i try to run it using the IDLE I get a SyntaxError and the number 6 in Python 3.6.3 gets highlighted in red.

Any ideas as to what's going on?

答:
Try to install flask with specific version of python, do something like:

```<code>python[version] -m pip install flask
</code>```

Note: replace [version] with python version (such as python3).

Body:
I'm on Windows 10 and I am using PyCharm to run my application. I'm pretty new to Python and just coding in general.

I typed:

pip install flask

in the cmd prompt but forgot to open cmd prompt under administrator privileges. Could this be the problem? I ended up re-opening the cmd prompt with administrator rights and typed

pip install flask

again and it showed that it was already installed. I'm pretty sure I have flask installed on my system.

When I try to run the python file below which I named test_webapp.py I get the following error:

from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello():

    return "Hello World!"

if __name__ == "__main__":

    app.run()

I get an error:

ModuleNotFoundError: No module named 'flask'

when i type in python --version into the command prompt i get version 3.6.3.

When i type the same code into the Python 3.6 (32-bit) command line, the code works! However, when i try to run it using the IDLE I get a SyntaxError and the number 6 in Python 3.6.3 gets highlighted in red.

Any ideas as to what's going on?

Body:
Try to install flask with specific version of python, do something like:

python[version] -m pip install flask

Note: replace [version] with python version (such as python3).


问:
How to find a specific string in a .c file using the perl api of (Scitools) Understand?
I'm trying to analyse a code base (many .c files) by writing Perl script using (Scitools) Understand's Perl API.

I'm aware that list of variables, functions etc. are easy to obtain for a given .c file.

Probably someone who has worked with Understand Perl API could point me in the right direction to search for a specific string that is present in many lines of a file? and possible return the line number?

答:
Sounds like you simply want</p>

```<code>  use Understand qw( );

  my $db = Understand::open("test.udb");

  # Find all 'File' entities that match test*.cpp
  for my $file_ent ($db->lookup("test*.cpp","File")) {
       my $file_contents = $file_ent->contents();
       printf "File %s matches", $file_ent->name
          if $file_contents =~ /pattern/;
  }
</code>```

Body:
Sounds like you simply want

  use Understand qw( );

  my $db = Understand::open("test.udb");

  # Find all 'File' entities that match test*.cpp
  for my $file_ent ($db->lookup("test*.cpp","File")) {
       my $file_contents = $file_ent->contents();
       printf "File %s matches", $file_ent->name
          if $file_contents =~ /pattern/;
  }


问:
Source code of a String Class in Java
I can't figure out what this lines do:

```<code>this.value = "".value;
</code>```

and

```<code>int len2 = anotherString.value.length;
</code>```

There is an array called "values" in the beginning of the class. It's something like String.Array (Array of chars).

How does it work?

答:
Since the value field contains the characters for the String instance, what you see is the constructor using the value field of the (usually) interned empty string constant.

This way, an empty string created with the empty constructor will all use the same instance of the array. Strings are immutable, so they can and usually do, share the underlying char array to save on memory usage.

Title: Source code of a String Class in Java

Body:
I can't figure out what this lines do:

this.value = "".value;

and

int len2 = anotherString.value.length;

There is an array called "values" in the beginning of the class. It's something like String.Array (Array of chars).

How does it work?


问:
(iOS) crash when view controller property is set
I've problems passing data to a new view controller.

I've two VC. In the "FirstVC" there is a table view with dynamic prototypes cells. The generic cell contains a label and a button and it's assigned to its own class "GenericCell". I want to pass to the SecondVC the text of the cell label when I press the button, but the app crashes with errors:

Unknown class _TtC13testTableView37SecondVC in Interface Builder file.

UIViewController setMyString:]: unrecognized selector sent to instance 0x7fa05e418110

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setMyString:]: unrecognized selector sent to instance 0x7fc8add05710

I tried:

To use the segue (with prepareForSegue method) outside the getText method

1a. Pushing the VC from the outside of the getText method

Implementing and calling set/get method of myString

Adding attributes to myString property

but the app crashes the same.

GenericCell.h

```<code>#import <UIKit/UIKit.h>
@protocol MyCellDelegate
-(void)getText:(NSString *)text;
@end

@interface GenericCell: UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel * label;
@property (assign, nonatomic) id <MyCellDelegate> delegate;
@end
</code>```

GenericCell.m

```<code>#import "GenericCell.h"
@interface GenericCell()
@end

@implementation GenericCell

- (IBAction)buttonPressed {
    if (self.delegate) {
        [self.delegate getText:self.label.text];
    }
}
@end
</code>```

FirstVC.m

```<code>#import "FirstVC.h"
#import "GenericCell.h"
#import "SecondVC.h"

@interface FirstVC() <UITableViewDataSource,UITableViewDelegate, MyCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSString * idToPass;
@end

@implementation FirstVC

NSMutableArray<NSString *> *array;

- (void)viewDidLoad {

    array = [[NSMutableArray alloc]initWithObjects:@"0x22", @"0x11", @"0x24", nil];

    [super viewDidLoad];
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.rowHeight=100;
}

-(void)getText:(NSString *)text {
   self.idToPass = text;

   SecondVC * secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVC"];
   secondVC.myString = self.idToPass;
   [[self navigationController] pushViewController:secondVC animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return array.count;
}

- (GenericCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    GenericCell * cell = [[self tableView]dequeueReusableCellWithIdentifier:@"GenericCell" forIndexPath:indexPath];

    cell.delegate = self;
    cell.label.text = [array objectAtIndex:indexPath.row];
    return cell;
}
@end
</code>```

SecondVC.h

```<code>#import <UIKit/UIKit.h>
@interface SecondVC : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *label;
@property NSString * myString;
@end
</code>```

SecondVC.m

```<code>#import "SecondVC.h"

@interface SecondVC ()
@end

@implementation SecondVC

- (void)viewDidLoad {
    self.label.text = self.myString;
    [super viewDidLoad];
}

@end
</code>```

The "idToPass" is set correctly with delegation.

答:
This work for me: in the buttonPressed method update the if statement like this

```<code>if ([self.delegate respondsToSelector:@selector(getText:)]){
        [self.delegate getText:self.label.text];
}
</code>```

Another option to give SecondVC the data is using

```<code>-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    SecondVC * vc = segue.destinationViewController;
    if ([segue.identifier isEqualToString: @"yourSegue"]) {
        vc.myString = self.idToPass;
    }
}
</code>```

A tip I suggest is to check (with a simple if statement) if your object in SecondVC is nil or !nil

I hope this help :)

Body:
I've problems passing data to a new view controller.

I've two VC. In the "FirstVC" there is a table view with dynamic prototypes cells. The generic cell contains a label and a button and it's assigned to its own class "GenericCell". I want to pass to the SecondVC the text of the cell label when I press the button, but the app crashes with errors:

Unknown class _TtC13testTableView37SecondVC in Interface Builder file.

UIViewController setMyString:]: unrecognized selector sent to instance 0x7fa05e418110

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController setMyString:]: unrecognized selector sent to instance 0x7fc8add05710

I tried:

To use the segue (with prepareForSegue method) outside the getText method

1a. Pushing the VC from the outside of the getText method

Implementing and calling set/get method of myString

Adding attributes to myString property

but the app crashes the same.

GenericCell.h

#import <UIKit/UIKit.h>
@protocol MyCellDelegate
-(void)getText:(NSString *)text;
@end

@interface GenericCell: UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel * label;
@property (assign, nonatomic) id <MyCellDelegate> delegate;
@end

GenericCell.m

#import "GenericCell.h"
@interface GenericCell()
@end

@implementation GenericCell

- (IBAction)buttonPressed {
    if (self.delegate) {
        [self.delegate getText:self.label.text];
    }
}
@end

FirstVC.m

#import "FirstVC.h"
#import "GenericCell.h"
#import "SecondVC.h"

@interface FirstVC() <UITableViewDataSource,UITableViewDelegate, MyCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSString * idToPass;
@end

@implementation FirstVC

NSMutableArray<NSString *> *array;

- (void)viewDidLoad {

    array = [[NSMutableArray alloc]initWithObjects:@"0x22", @"0x11", @"0x24", nil];

    [super viewDidLoad];
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.rowHeight=100;
}

-(void)getText:(NSString *)text {
   self.idToPass = text;

   SecondVC * secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVC"];
   secondVC.myString = self.idToPass;
   [[self navigationController] pushViewController:secondVC animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return array.count;
}

- (GenericCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    GenericCell * cell = [[self tableView]dequeueReusableCellWithIdentifier:@"GenericCell" forIndexPath:indexPath];

    cell.delegate = self;
    cell.label.text = [array objectAtIndex:indexPath.row];
    return cell;
}
@end

SecondVC.h

#import <UIKit/UIKit.h>
@interface SecondVC : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *label;
@property NSString * myString;
@end

SecondVC.m

#import "SecondVC.h"

@interface SecondVC ()
@end

@implementation SecondVC

- (void)viewDidLoad {
    self.label.text = self.myString;
    [super viewDidLoad];
}

@end

The "idToPass" is set correctly with delegation.

Body:
This work for me: in the buttonPressed method update the if statement like this

if ([self.delegate respondsToSelector:@selector(getText:)]){
        [self.delegate getText:self.label.text];
}

Another option to give SecondVC the data is using

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    SecondVC * vc = segue.destinationViewController;
    if ([segue.identifier isEqualToString: @"yourSegue"]) {
        vc.myString = self.idToPass;
    }
}

A tip I suggest is to check (with a simple if statement) if your object in SecondVC is nil or !nil

I hope this help :)


问:
Regex: Endless loop
I'm using the following regex in order to check for a valid URL. But it keeps falling in an endless loop and I don't know why. Keeping away the ?true=bla solves the problem.

```<code>^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
</code>```

with the url
    http://google.com?true=bla

What is the problem in this case?

答:
try:

```<code>(https?:\/\/)([a-zA-Z0-9\_\-]*?)\.([a-zA-Z0-9\_\-\.]*?)\/(.*)
</code>```

This will match http or https URL's with or without subdomains and/or query strings

Title: Regex: Endless loop

Body:
I'm using the following regex in order to check for a valid URL. But it keeps falling in an endless loop and I don't know why. Keeping away the ?true=bla solves the problem.

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

with the url
    http://google.com?true=bla

What is the problem in this case?

Body:
try:

(https?:\/\/)([a-zA-Z0-9\_\-]*?)\.([a-zA-Z0-9\_\-\.]*?)\/(.*)

This will match http or https URL's with or without subdomains and/or query strings


问:
Need help to get Slider popup window
Friend's
   I need to get slider pop up window,when i click a tab control available at bottom.when i click the tab,i need to show the slider pop up from bottom to top animated to show the login button,after login i have to move my actual tab Activity.How can i get the view for slider pop up.

lets refer the screenshots,i attached here what i need exactly..

.
From these when user to choose login at the time second screen appears looks like it.

How can i get the view like this above.
Thanks in advance..

答:
Get the sliding drawer view by id, cast it to a SlidingDrawer and then there is a function the SlidingDrawer object to pop it up.  You might have some weird issues though with screen state if users do stuff like hit back or close the slider.

To do what you need in the screenshot, do a sliding drawer with an empty handle and slide that up from the bottom as needed.  The sliding drawer is just another layout that can contain buttons, etc.

Here is an example:  http://www.androidpeople.com/android-sliding-drawer-example-tutorial/

Title: Need help to get Slider popup window


问:
Writing a list to new excel xlsx with dataframes
I am having some trouble finding the best way to write a list to a loaded excel sheet and then saving the result as an xlsx. What I want my code to do is to take the lists that I have created and put them in specific columns of the loaded workbook. I think there is probably an easier way to do this using dataframes, but I do not know how. Ideally, I would like to save the formatting of the loaded workbook.

```<code>col_test = [1L, 2L, 3L, 4L, 5L]
</code>```

My code is this

```<code>import xlrt
from xlrd import open_workbook
rb = open_workbook("Excel FDT Master_01_update.xlsx")
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(row = r, column = 1).value = test
    r += 1
rb.save('didthiswork.xlsx')
</code>```

答:
Here is one version with no extra installs on top of anaconda.
It is not keeping styling, but that you can fix with a copy/'paste values' back to original xlsx.

Most excel manipulators have issues with keeping the original file intact. There are ways around that as well, but if you want it to be waterproof, you basically end up with a specific solution for you, or more or less recode all libraries out there, so it's not worth the effort.

Pandas can be a bit tricky to get right when extending existing dataframes, but there are always several alternative ways to do it. Here it's done with assign, so then one only needs to make sure that the dataframe's rowcount is long enough for what one wants to add.

```<code>import pandas as pd

# read the excel
df = pd.read_excel('Geen titel 1.xlsx') # there are options to choose sheet
print('original df')
print(df)
# your data is not valid python syntax so let's assume it's strings
col_test = ['1L', '2L', '3L', '4L', '5L']
new_idx = range(max(len(col_test), len(df.index)))
df = df.reindex(new_idx) # now it will accommodate different lengths
print('reindexed df')
print(df)
df = df.assign(new_col=col_test) # new column added at right side
print('modified df')
print(df)
df.to_excel('the_new.xlsx')
</code>```

The printouts:

```<code>original df
   a  b
0  1  c
1  2  d
2  3  e
reindexed df
     a    b
0  1.0    c
1  2.0    d
2  3.0    e
3  NaN  NaN
4  NaN  NaN
modified df
     a    b new_col
0  1.0    c      1L
1  2.0    d      2L
2  3.0    e      3L
3  NaN  NaN      4L
4  NaN  NaN      5L
</code>```

Body:
I am having some trouble finding the best way to write a list to a loaded excel sheet and then saving the result as an xlsx. What I want my code to do is to take the lists that I have created and put them in specific columns of the loaded workbook. I think there is probably an easier way to do this using dataframes, but I do not know how. Ideally, I would like to save the formatting of the loaded workbook.

col_test = [1L, 2L, 3L, 4L, 5L]

My code is this

import xlrt
from xlrd import open_workbook
rb = open_workbook("Excel FDT Master_01_update.xlsx")
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(row = r, column = 1).value = test
    r += 1
rb.save('didthiswork.xlsx')

Body:
Here is one version with no extra installs on top of anaconda.
It is not keeping styling, but that you can fix with a copy/'paste values' back to original xlsx.

Most excel manipulators have issues with keeping the original file intact. There are ways around that as well, but if you want it to be waterproof, you basically end up with a specific solution for you, or more or less recode all libraries out there, so it's not worth the effort.

Pandas can be a bit tricky to get right when extending existing dataframes, but there are always several alternative ways to do it. Here it's done with assign, so then one only needs to make sure that the dataframe's rowcount is long enough for what one wants to add.

import pandas as pd

# read the excel
df = pd.read_excel('Geen titel 1.xlsx') # there are options to choose sheet
print('original df')
print(df)
# your data is not valid python syntax so let's assume it's strings
col_test = ['1L', '2L', '3L', '4L', '5L']
new_idx = range(max(len(col_test), len(df.index)))
df = df.reindex(new_idx) # now it will accommodate different lengths
print('reindexed df')
print(df)
df = df.assign(new_col=col_test) # new column added at right side
print('modified df')
print(df)
df.to_excel('the_new.xlsx')

The printouts:

original df
   a  b
0  1  c
1  2  d
2  3  e
reindexed df
     a    b
0  1.0    c
1  2.0    d
2  3.0    e
3  NaN  NaN
4  NaN  NaN
modified df
     a    b new_col
0  1.0    c      1L
1  2.0    d      2L
2  3.0    e      3L
3  NaN  NaN      4L
4  NaN  NaN      5L


问:
How to extract critical (above the fold) CSS from each entry?
I have a simple multi-page app with three pages, my webpack.config.js entry looks like:

```<code>{
  entry: {
    a: 'pages/a.js',
    b: 'pages/b.js',
    c: 'pages/c.js',
  }
}
</code>```

Each page consists of several React components, some of which are visible above-the-fold on first render, and some of which are out of view.

I'd like to declaratively define which components are 'critical' (above-the-fold) for each page/entry, and have that CSS extracted into a separate file. Something like:

```<code>{
  a: ['compononents/button/style.css', ...],
  b: ['compononents/title/style.css', ...],
  c: ['compononents/header/style.css', ...]
}
</code>```

outputting something like:

```<code>- dist/a.critical.css
- dist/b.critical.css
- dist/c.critical.css
</code>```

I've been playing around with the extract-text-webpack-plugin, but can't seem to find a way to tell it to only extract specific CSS in the context of a specific entry.

How can I extract specific CSS file content when in the context of a specific entry/page?

答:
I'm in the same situation, our project is big enough and we need more than 20 different critical css files. I found a way to make generating critical CSS more painless.
I'm using https://github.com/zgreen/postcss-critical-css which allow creating different critical css files.

```<code>@critical crit.css {
    .head {
        background: red;
    }

    .head .logo {
        display: block
    }
}

@critical v2.css {
    .head.v2 {
        background: green;
    }
}

.main {
    color: #333;
}

.footer {
   background: black;
}
</code>```

Postcss-critical-css will generate 3 files - my css file (with or without critical styles) and 2 critical css files - v2.css and crit.css

Hope this will help you!

Body:
I have a simple multi-page app with three pages, my webpack.config.js entry looks like:

{
  entry: {
    a: 'pages/a.js',
    b: 'pages/b.js',
    c: 'pages/c.js',
  }
}

Each page consists of several React components, some of which are visible above-the-fold on first render, and some of which are out of view.

I'd like to declaratively define which components are 'critical' (above-the-fold) for each page/entry, and have that CSS extracted into a separate file. Something like:

{
  a: ['compononents/button/style.css', ...],
  b: ['compononents/title/style.css', ...],
  c: ['compononents/header/style.css', ...]
}

outputting something like:

- dist/a.critical.css
- dist/b.critical.css
- dist/c.critical.css

I've been playing around with the extract-text-webpack-plugin, but can't seem to find a way to tell it to only extract specific CSS in the context of a specific entry.

How can I extract specific CSS file content when in the context of a specific entry/page?

Body:
I'm in the same situation, our project is big enough and we need more than 20 different critical css files. I found a way to make generating critical CSS more painless.
I'm using https://github.com/zgreen/postcss-critical-css which allow creating different critical css files.

@critical crit.css {
    .head {
        background: red;
    }

    .head .logo {
        display: block
    }
}

@critical v2.css {
    .head.v2 {
        background: green;
    }
}

.main {
    color: #333;
}

.footer {
   background: black;
}

Postcss-critical-css will generate 3 files - my css file (with or without critical styles) and 2 critical css files - v2.css and crit.css

Hope this will help you!


问:
Perl: Parentheses vs Brackets for array definition, why is one considered a scalar?
I was following this tutorial on the HTML::Template module for Perl. Here's the template:

```<code><!--template2.tmpl-->
<html>
<body>
<table>
  <tr>
    <th>Language</th>
    <th>Description</th>
  </tr>
  <tmpl_loop name="language">
  <tr>
    <td><tmpl_var name="language_name"></td>
    <td><tmpl_var name="description"></td>
  </tr>
  </tmpl_loop>
</table>
</body>
</html>
</code>```

And here's the CGI test program:

```<code>#!"C:\Strawberry\perl\bin\perl.exe" -wT
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my @rows = (
  {
    language_name => 'C#',
    description   => 'Created by Microsoft'
  },
  {
    language_name => 'PHP',
    description   => 'Hypertext Preprocessor'
  },
  {
    language_name => 'Haskell',
    description   => 'Functional language'
  },
);

print header;
my $template=HTML::Template->new(filename=>'template2.tmpl');
$template->param(language => @rows);
print $template->output();
</code>```

This fails with the following error: HTML::Template::param() : attempt to set parameter 'language' with a scalar - parameter is not a TMPL_VAR!

However, when I change the definition of @rows from using parenthesis to using square brackets(from my @rows=(...) to my @rows = [...]) the code works fine; it displays a table with the data.

As I understood from reading this article, the first form is an array defined from a list and the second one is a reference to an anonymous array. It's still not clear to me why the first form doesn't work. I'd appreciate you clarifying this for me.

答:
The tutorial you're following contains an error.  The line

```<code>$template->param( language => @languages );
</code>```

should be

```<code>$template->param( language => \@languages );
</code>```

Why?  Short answer: the right-hand side of the loop name you pass to param must be a reference to an array, not an array.

Long answer: When you pass arguments to a function or method, all of the arguments get expanded into one long list.  This is a common source of mistakes for beginners.  So in your code (and in the tutorial's code), you're not passing two parameters to the param method, you're passing four (one for the string 'language', and three for the elements of @languages.

Here's an example of this argument-list unraveling.  If you have three variables as follows:

```<code>my $scalar = 'bear';
my @array  = ('rat', 'moose', 'owl');
my %hash   = (mass => 500, units => 'kg');
</code>```

and you pass them to a function like so:

```<code>some_function($scalar, @array, %hash);
</code>```

then the function will see eight arguments: 'bear', 'rat', 'moose', 'owl', 'mass', 500, 'units', and 'kg'!  Perhaps even more surprising, the two sets of values from the hash might be passed in a different order, because hashes are not stored or retrieved in a determinate order.

Your solution of changing the parentheses to square brackets works, but not for a very good reason.  Parentheses delimit lists (which can be stored in arrays or hashes); square brackets delimit references to arrays.  So your square-bracket code creates a reference to an anonymous array, which is then stored as the first (and only) element of your named array @rows.  Instead, you should either store the array reference (delimited with square brackets) in a scalar variable (say, $rows), or you should use parentheses, store the list in the array @rows, and pass a reference to that array to the param method (by using a backslash, as I did above with \@languages).

Body:
I was following this tutorial on the HTML::Template module for Perl. Here's the template:

    Language
    Description

  <tmpl_loop name="language">

    <tmpl_var name="language_name">
    <tmpl_var name="description">

  </tmpl_loop>

And here's the CGI test program:

#!"C:\Strawberry\perl\bin\perl.exe" -wT
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use HTML::Template;

my @rows = (
  {
    language_name => 'C#',
    description   => 'Created by Microsoft'
  },
  {
    language_name => 'PHP',
    description   => 'Hypertext Preprocessor'
  },
  {
    language_name => 'Haskell',
    description   => 'Functional language'
  },
);

print header;
my $template=HTML::Template->new(filename=>'template2.tmpl');
$template->param(language => @rows);
print $template->output();

This fails with the following error: HTML::Template::param() : attempt to set parameter 'language' with a scalar - parameter is not a TMPL_VAR!

However, when I change the definition of @rows from using parenthesis to using square brackets(from my @rows=(...) to my @rows = [...]) the code works fine; it displays a table with the data.

As I understood from reading this article, the first form is an array defined from a list and the second one is a reference to an anonymous array. It's still not clear to me why the first form doesn't work. I'd appreciate you clarifying this for me.

Body:
The tutorial you're following contains an error.  The line

$template->param( language => @languages );

should be

$template->param( language => \@languages );

Why?  Short answer: the right-hand side of the loop name you pass to param must be a reference to an array, not an array.

Long answer: When you pass arguments to a function or method, all of the arguments get expanded into one long list.  This is a common source of mistakes for beginners.  So in your code (and in the tutorial's code), you're not passing two parameters to the param method, you're passing four (one for the string 'language', and three for the elements of @languages.

Here's an example of this argument-list unraveling.  If you have three variables as follows:

my $scalar = 'bear';
my @array  = ('rat', 'moose', 'owl');
my %hash   = (mass => 500, units => 'kg');

and you pass them to a function like so:

some_function($scalar, @array, %hash);

then the function will see eight arguments: 'bear', 'rat', 'moose', 'owl', 'mass', 500, 'units', and 'kg'!  Perhaps even more surprising, the two sets of values from the hash might be passed in a different order, because hashes are not stored or retrieved in a determinate order.

Your solution of changing the parentheses to square brackets works, but not for a very good reason.  Parentheses delimit lists (which can be stored in arrays or hashes); square brackets delimit references to arrays.  So your square-bracket code creates a reference to an anonymous array, which is then stored as the first (and only) element of your named array @rows.  Instead, you should either store the array reference (delimited with square brackets) in a scalar variable (say, $rows), or you should use parentheses, store the list in the array @rows, and pass a reference to that array to the param method (by using a backslash, as I did above with \@languages).


问:
Add View to ScrollView and then scroll to bottom: Which callback is needed?
In a Dialog I have a ScrollView which contains a (vertical) LinearLayout; the bottommost View in the LinearLayout is a TextView that starts out with android:visibility="gone".

At some point during the program I want to setVisiblity(View.VISIBLE) on the TextView and display an error message. And because the ScrollView could be in any position at this point, I want to scroll to the bottom, when the error message appears.

I tried all of:

```<code>scrollView.fullScroll(View.FOCUS_DOWN);

scrollView.scrollTo(0, tvLoginError.getTop());

scrollView.scrollTo(0, tvLoginError.getBottom());
</code>```

and each of those in each of these:

```<code>scrollView.post(...)

tvLoginError.post(...)

scrollView.getViewTreeObserver.addOnGlobalLayoutListener(...)

tvLoginError.getViewTreeObserver.addOnGlobalLayoutListener(...)

scrollView.getViewTreeObserver.addOnPreDrawListener(...)

tvLoginError.getViewTreeObserver.addOnPreDrawListener(...)
</code>```

None of these works properly. The scolling always stops when the newly visible TextView is just outside the ScrollView or when it is halfway visible - but never truly at the bottom. (The ones with ViewTreeObserver would work in principle but only if I don't remove the callback after the first update. But if I keep it around longer, I have no way of knowing when to remove it instead (...?)

Please tell me what callback I need to use to scroll to the bottom after the TextView is completely visible.

答:
Since I found this question when looking for the answer, I figure I'll save the next person some time.

The underlying problem is that you are calling your scroll command too early. If you add something to the view, the layout changes don't really happen until the view is redrawn. If you write content_view.getHeight to the log where you are doing the scroll call, you will find that the value is unchanged by adding to the content.

The solution is to do something like the following:

```<code>scroll_view.post(new Runnable() {
    @Override
    public void run() {
        // Get content_view
        scroll_view.smoothScrollTo(content_view.getWidth(), content_view.getHeight());
    }
});
</code>```

This resolves the problem because you are posting to the main event loop and it will run after the events already queued up -- which includes rendering the layout.

NOTE: I just found that in at least one case this didn't work as expected because it still ran the post runnable too early. That is quickly solved by using a short delayed post, but I'd love to understand why the above solution doesn't always work. Here is an example (Java 8 lambda version) using postDelayed:

```<code>view_port.postDelayed(()->{
        LinearLayout content = scroll_view.findViewById(R.id.content);
        scroll_view.smoothScrollTo(0, content.getHeight());
    }, 200);
</code>```

Body:
In a Dialog I have a ScrollView which contains a (vertical) LinearLayout; the bottommost View in the LinearLayout is a TextView that starts out with android:visibility="gone".

At some point during the program I want to setVisiblity(View.VISIBLE) on the TextView and display an error message. And because the ScrollView could be in any position at this point, I want to scroll to the bottom, when the error message appears.

I tried all of:

scrollView.fullScroll(View.FOCUS_DOWN);

scrollView.scrollTo(0, tvLoginError.getTop());

scrollView.scrollTo(0, tvLoginError.getBottom());

and each of those in each of these:

scrollView.post(...)

tvLoginError.post(...)

scrollView.getViewTreeObserver.addOnGlobalLayoutListener(...)

tvLoginError.getViewTreeObserver.addOnGlobalLayoutListener(...)

scrollView.getViewTreeObserver.addOnPreDrawListener(...)

tvLoginError.getViewTreeObserver.addOnPreDrawListener(...)

None of these works properly. The scolling always stops when the newly visible TextView is just outside the ScrollView or when it is halfway visible - but never truly at the bottom. (The ones with ViewTreeObserver would work in principle but only if I don't remove the callback after the first update. But if I keep it around longer, I have no way of knowing when to remove it instead (...?)

Please tell me what callback I need to use to scroll to the bottom after the TextView is completely visible.

Body:
Since I found this question when looking for the answer, I figure I'll save the next person some time.

The underlying problem is that you are calling your scroll command too early. If you add something to the view, the layout changes don't really happen until the view is redrawn. If you write content_view.getHeight to the log where you are doing the scroll call, you will find that the value is unchanged by adding to the content.

The solution is to do something like the following:

scroll_view.post(new Runnable() {
    @Override
    public void run() {
        // Get content_view
        scroll_view.smoothScrollTo(content_view.getWidth(), content_view.getHeight());
    }
});

This resolves the problem because you are posting to the main event loop and it will run after the events already queued up -- which includes rendering the layout.

NOTE: I just found that in at least one case this didn't work as expected because it still ran the post runnable too early. That is quickly solved by using a short delayed post, but I'd love to understand why the above solution doesn't always work. Here is an example (Java 8 lambda version) using postDelayed:

view_port.postDelayed(()->{
        LinearLayout content = scroll_view.findViewById(R.id.content);
        scroll_view.smoothScrollTo(0, content.getHeight());
    }, 200);


问:
covariance matrix by group
I have been able to calculate covariance for my large data set with:

cov(MyMatrix, use="pairwise.complete.obs",method="pearson")

This provided the covariance table I was looking for, as well as dealing with the NA issues that are throughout my data. For a deeper analysis, however, I want to create covariance matrices that deal separately with the 800+ groups I have in my data set (some have 40+ observations, others only 1). I tried (from http://www.mail-archive.com/r-help@r-project.org/msg86328.html):

lapply(list(cov), by, data = MyMatrix[8:13], INDICES = MyMatrix["Group"])

Which gave me the following error:

Error in tapply(seq_len(6L), list(MyMatrix["Group"] = NA_real_), function (x)  :
    arguments must have same length

This made me think the issue with the code involved the missing NA data, so I tried incorporating the "use="pairwise.complete.obs",method="pearson"" phrase into the lapply code and can't get it to work. I'm not sure the best place for it, so I tried sticking it everywhere:

lapply(list(cov), use="pairwise.complete.obs",method="pearson"),by,data=MyMatrix[8:13], INDICES = MyMatrix["Group"])

lapply(list(cov),by,data=PhenoMtrix[8:13], INDICES = PhenoMtrix["Group"], use="pairwise.complete.obs",method="pearson")

This is obviously sloppy and doesn't work, so I'm a little stuck. Thanks in advance for your help!

My data is formatted as such:

Group      HML       RML        FML       TML       FHD     BIB

```<code> 1      323.50    248.75     434.50    355.75    46.84    NA

 2        NA      238.50     441.50    353.00    45.83    277.0

 2      309.50    227.75     419.00    332.25    46.39    284.0
</code>```

答:
you can also try:</p>

```<code>  by(MyMatrix[-1],MyMatrix$group,cov,use="na.or.complete")
</code>```

Title: covariance matrix by group

Body:
I have been able to calculate covariance for my large data set with:

cov(MyMatrix, use="pairwise.complete.obs",method="pearson")

This provided the covariance table I was looking for, as well as dealing with the NA issues that are throughout my data. For a deeper analysis, however, I want to create covariance matrices that deal separately with the 800+ groups I have in my data set (some have 40+ observations, others only 1). I tried (from http://www.mail-archive.com/r-help@r-project.org/msg86328.html):

lapply(list(cov), by, data = MyMatrix[8:13], INDICES = MyMatrix["Group"])

Which gave me the following error:

Error in tapply(seq_len(6L), list(MyMatrix["Group"] = NA_real_), function (x)  :
    arguments must have same length

This made me think the issue with the code involved the missing NA data, so I tried incorporating the "use="pairwise.complete.obs",method="pearson"" phrase into the lapply code and can't get it to work. I'm not sure the best place for it, so I tried sticking it everywhere:

lapply(list(cov), use="pairwise.complete.obs",method="pearson"),by,data=MyMatrix[8:13], INDICES = MyMatrix["Group"])

lapply(list(cov),by,data=PhenoMtrix[8:13], INDICES = PhenoMtrix["Group"], use="pairwise.complete.obs",method="pearson")

This is obviously sloppy and doesn't work, so I'm a little stuck. Thanks in advance for your help!

My data is formatted as such:

Group      HML       RML        FML       TML       FHD     BIB

 1      323.50    248.75     434.50    355.75    46.84    NA

 2        NA      238.50     441.50    353.00    45.83    277.0

 2      309.50    227.75     419.00    332.25    46.39    284.0

Body:
you can also try:

  by(MyMatrix[-1],MyMatrix$group,cov,use="na.or.complete")


问:
C++ code gets strangely skipped with no optimizations. Any ideas why?
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

```<code>...
short id;
...
</code>```

file.cc

```<code>id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}
</code>```

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.

答: short is 16 bits long and its range is -32768 to 32767. So it can never be 40000 or 45000 and compiler eliminated dead code (as it will never be reached).</p>

Body:
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

...
short id;
...

file.cc

id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.


问:
Read txt file into array and assign to variables
So essentially what I need to do is make this while loop run through the txt file and store it in an array to be stored inside the instance variables

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * <insert class description here>
 *
 * @author Chris Crosby
 *
 */
public class TrackInput
{
    private Scanner keyboard = new Scanner(System.in);

    public int readTrackData(Railroad[] Reservations) {
        final String FILE_NAME = "TrackData.txt";
        int size =0;
        Scanner input = null;
        try {
            input= new Scanner(new File(FILE_NAME));
        }
        catch(FileNotFoundException e) {
            System.out.println("Unable to open file " + FILE_NAME + ".");
        }
        String passengerName="";
        String routeNumber="";
        String departureDate="";
        String departureTrack="";
        String arrivalTrack="";
        String departureTime="";
        String arrivalTime="";
        String seat="";
        String returnRouteNumber="";
        String ReturnDate="";

        while (input.hasNext()&& size<Reservations.length) {

        }
        return size;
    }
}
</code>```

here's the txt file that the loop is reading through

```<code>Carl Foreman
1234
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23A
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8A
Jennifer Foreman
1235
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23B
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8B
Jane Anderson
4577
UA317
08/04/2014
ORD
SFO
8:10 AM
10:45 AM
11C
UA728
08/14/2014
SFO
ORD
12:52 PM
7:03 PM
10D
Jason Anderson
4578
</code>```

TrackData.txt format

passenger name – include first and last name in one variable

reservation number

departure route number

departure date

departure track

arrival track

departure time

arrival time

seat

return route number

return date

departure track

arrival track

departure time

arrival time

seat

here's a similar method I had to write for a previous assignment

```<code>public int readInventory(Automobile[] inventory)
    {
        final String FILENAME = "inventory.csv";
        int size = 0;

        Scanner input = null;
        try
        {
            input = new Scanner(new File(FILENAME));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Unable to open file " + FILENAME + ".");
        }

        // read header line and discard first line
        String line = input.nextLine();

        // create vars
        int year = 0;
        String make = "";
        String model = "";
        double price = 0.0;
        String condition = "";
        int rating = 0;
        String status = "";
        String vin = "";

        // Customer vars
        String firstName = "";
        String lastName = "";
        String streetAddress = "";
        String city = "";
        String state = "";
        String zip = "";
        String email = "";
        String phone = "";

        while (input.hasNext() && size < inventory.length)
        {
            line = input.nextLine();
            String[] record = line.split(",");

            year = Integer.parseInt(record[0]);
            make = record[1];
            model = record[2];

            // If use this version, comment out the following if statements

            if (!(record[3].equals("")))
            {
                price = Double.parseDouble(record[3]);
            }
            else
            {
                price = 0;
            }

            condition = record[4];

            if (!(record[5].equals("")))
            {
                rating = Integer.parseInt(record[5]);
            }
            else
            {
                rating = 0;
            }

            status = record[6];
            vin = record[7];

            // this is where the records differ
            // they either don't have buyer information or some do

            if (record.length > 8)
            {
                if (!(record[8].equals("")))
                    firstName = record[8];
                else
                    firstName = "";

                if (!(record[9].equals("")))
                    lastName = record[9];
                else
                    lastName = "";

                if (!(record[10].equals("")))
                    streetAddress = record[10];
                else
                    streetAddress = "";

                if (!(record[11].equals("")))
                    city = record[11];
                else
                    city = "";

                if (!(record[12].equals("")))
                    state = record[12];
                else
                    state = "";

                if (!(record[13].equals("")))
                    zip = record[13];
                else
                    zip = "";

                if (!(record[14].equals("")))
                    email = record[14];
                else
                    email = "";

                if (!(record[15].equals("")))
                    phone = record[15];
                else
                    phone = "";

            }

            // changes to integrate Customer class go below

            Customer tempCustomer = new Customer(firstName,lastName, city, state, email, phone,zip,streetAddress);
            Automobile tempAutomobile = new Automobile( year, make, model, price,
                    condition, rating, status, vin, tempCustomer);

            inventory[size] = tempAutomobile;
            size++;

        } // end of while loop

        input.close();

        return size;
    }
</code>```

not sure how to make it work for this program since this is multilined and the previous was a single line separated by commas hence the line.split

答:
```<code>package edu.ilstu;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * <insert class description here>
 *
 * @author Chris Crosby
 *
 */
public class TrackInput
{
    public final String TRANSACTION_FILE = "Transactions.txt";
    public final String DATA_FILE = "RailroadData.txt";

    public TrackInput() {

    }
    Scanner transaction = null;
    public Scanner readTransactions() {
        try {
            transaction= new Scanner(new File(TRANSACTION_FILE));
        }
        catch(FileNotFoundException e){
            System.out.println("Unable to open file" + TRANSACTION_FILE);
            System.exit(1);
        }
        return transaction;
    }
    public char readTransactionCode() {
        char choice = transaction.nextLine().charAt(0);
        return choice;
    }
    public int readRailroadData(Reservation [] reservations) {
        Scanner data;
        int count = 0;
        try {
            data = new Scanner(new File(DATA_FILE));
            while(data.hasNext()) {
                Reservation reservation = readReservationData(data);
                reservations [count] = reservation;
                count++;
            }
        }
        catch(FileNotFoundException e){
            System.out.println("Unable to open file" + DATA_FILE);
            System.exit(1);
        }
        return count;
    }
    public Reservation readReservationData(Scanner input) {
        String name = input.nextLine();
        String departureReservationNumber=input.nextLine();
        String departureRouteNumber = input.nextLine();
        String departureRouteDate = input.nextLine();
        String departureTrack = input.nextLine();
        String departureArrivalTrack = input.nextLine();
        String departureTime = input.nextLine();
        String departureArrivalTime = input.nextLine();
        String departureSeatAssignment = input.nextLine();

        String returnRoute = input.nextLine();
        String returnDate = input.nextLine();
        String returnDepartureTrack = input.nextLine();
        String returnArrivalTrack = input.nextLine();
        String returnDepartureTime = input.nextLine();
        String returnArrivalTime = input.nextLine();
        String returnSeatAssignment = input.nextLine();
        Route departureRoute = new Route(departureRouteNumber, departureRouteDate, departureTrack, departureArrivalTrack,departureTime, departureArrivalTime, departureSeatAssignment);
        Route arrivalRoute= new Route(returnRoute, returnDate, returnDepartureTrack, returnArrivalTrack,returnDepartureTime,returnArrivalTime,returnSeatAssignment);
        Reservation reservation = new Reservation(name,departureReservationNumber, departureRoute, arrivalRoute);
        return reservation;
    }
    public int addReservationToList(Reservation[] reservationList,Reservation reservation, int size) {
        reservationList[size] = reservation;
        size++;
        return size;
    }

}
</code>```

Body:
So essentially what I need to do is make this while loop run through the txt file and store it in an array to be stored inside the instance variables

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * <insert class description here>
 *
 * @author Chris Crosby
 *
 */
public class TrackInput
{
    private Scanner keyboard = new Scanner(System.in);

    public int readTrackData(Railroad[] Reservations) {
        final String FILE_NAME = "TrackData.txt";
        int size =0;
        Scanner input = null;
        try {
            input= new Scanner(new File(FILE_NAME));
        }
        catch(FileNotFoundException e) {
            System.out.println("Unable to open file " + FILE_NAME + ".");
        }
        String passengerName="";
        String routeNumber="";
        String departureDate="";
        String departureTrack="";
        String arrivalTrack="";
        String departureTime="";
        String arrivalTime="";
        String seat="";
        String returnRouteNumber="";
        String ReturnDate="";

        while (input.hasNext()&& size<Reservations.length) {

        }
        return size;
    }
}

here's the txt file that the loop is reading through

Carl Foreman
1234
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23A
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8A
Jennifer Foreman
1235
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23B
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8B
Jane Anderson
4577
UA317
08/04/2014
ORD
SFO
8:10 AM
10:45 AM
11C
UA728
08/14/2014
SFO
ORD
12:52 PM
7:03 PM
10D
Jason Anderson
4578

TrackData.txt format

passenger name – include first and last name in one variable

reservation number

departure route number

departure date

departure track

arrival track

departure time

arrival time

seat

return route number

return date

departure track

arrival track

departure time

arrival time

seat

here's a similar method I had to write for a previous assignment

public int readInventory(Automobile[] inventory)
    {
        final String FILENAME = "inventory.csv";
        int size = 0;

        Scanner input = null;
        try
        {
            input = new Scanner(new File(FILENAME));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Unable to open file " + FILENAME + ".");
        }

        // read header line and discard first line
        String line = input.nextLine();

        // create vars
        int year = 0;
        String make = "";
        String model = "";
        double price = 0.0;
        String condition = "";
        int rating = 0;
        String status = "";
        String vin = "";

        // Customer vars
        String firstName = "";
        String lastName = "";
        String streetAddress = "";
        String city = "";
        String state = "";
        String zip = "";
        String email = "";
        String phone = "";

        while (input.hasNext() && size < inventory.length)
        {
            line = input.nextLine();
            String[] record = line.split(",");

            year = Integer.parseInt(record[0]);
            make = record[1];
            model = record[2];

            // If use this version, comment out the following if statements

            if (!(record[3].equals("")))
            {
                price = Double.parseDouble(record[3]);
            }
            else
            {
                price = 0;
            }

            condition = record[4];

            if (!(record[5].equals("")))
            {
                rating = Integer.parseInt(record[5]);
            }
            else
            {
                rating = 0;
            }

            status = record[6];
            vin = record[7];

            // this is where the records differ
            // they either don't have buyer information or some do

            if (record.length > 8)
            {
                if (!(record[8].equals("")))
                    firstName = record[8];
                else
                    firstName = "";

                if (!(record[9].equals("")))
                    lastName = record[9];
                else
                    lastName = "";

                if (!(record[10].equals("")))
                    streetAddress = record[10];
                else
                    streetAddress = "";

                if (!(record[11].equals("")))
                    city = record[11];
                else
                    city = "";

                if (!(record[12].equals("")))
                    state = record[12];
                else
                    state = "";

                if (!(record[13].equals("")))
                    zip = record[13];
                else
                    zip = "";

                if (!(record[14].equals("")))
                    email = record[14];
                else
                    email = "";

                if (!(record[15].equals("")))
                    phone = record[15];
                else
                    phone = "";

            }

            // changes to integrate Customer class go below

            Customer tempCustomer = new Customer(firstName,lastName, city, state, email, phone,zip,streetAddress);
            Automobile tempAutomobile = new Automobile( year, make, model, price,
                    condition, rating, status, vin, tempCustomer);

            inventory[size] = tempAutomobile;
            size++;

        } // end of while loop

        input.close();

        return size;
    }

not sure how to make it work for this program since this is multilined and the previous was a single line separated by commas hence the line.split


问:
curl: (60) SSL certificate problem: unable to get local issuer certificate
```<code>root@sclrdev:/home/sclr/certs/FreshCerts# curl --ftp-ssl --verbose ftp://{abc}/ -u trup:trup --cacert /etc/ssl/certs/ca-certificates.crt
* About to connect() to {abc} port 21 (#0)
*   Trying {abc}...
* Connected to {abc} ({abc}) port 21 (#0)
< 220-Cerberus FTP Server - Home Edition
< 220-This is the UNLICENSED Home Edition and may be used for home, personal use only
< 220-Welcome to Cerberus FTP Server
< 220 Created by Cerberus, LLC
> AUTH SSL
< 234 Authentication method accepted
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS alert, Server hello (2):
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
</code>```

答:
On windows - if you want to run from cmd

```<code>> curl -X GET "https://some.place"
</code>```

Download cacert.pem from
https://curl.haxx.se/docs/caextract.html

Set permanently the environment variable:

```<code>CURL_CA_BUNDLE = C:\somefolder\cacert.pem
</code>```

And reload the environment by reopening any cmd window in which you want to
use curl; if Chocolatey is installed you can use:

```<code>refreshenv
</code>```

Now try again

Reason for the trouble:
https://laracasts.com/discuss/channels/general-discussion/curl-error-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate/replies/95548

ContentLicense: CC BY-SA 4.0

Body:
On windows - if you want to run from cmd

> curl -X GET "https://some.place"

Download cacert.pem from
https://curl.haxx.se/docs/caextract.html

Set permanently the environment variable:

CURL_CA_BUNDLE = C:\somefolder\cacert.pem

And reload the environment by reopening any cmd window in which you want to
use curl; if Chocolatey is installed you can use:

refreshenv

Now try again

Reason for the trouble:
https://laracasts.com/discuss/channels/general-discussion/curl-error-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate/replies/95548


问:
Ajax.ActionLink alternative with mvc core
In MVC5 there is @Ajax.ActionLink that is useful to update just a partial view instead of reloading the whole View. Apparently in MVC6 is not supported anymore.

I have tried using @Html.ActionLink like the following but it doesn't update the form, it return just the partial view:

View:

```<code>@Html.ActionLink("Update", "GetEnvironment", "Environments", new { id = Model.Id }, new
       {
           data_ajax = "true",
           data_ajax_method = "GET",
           data_ajax_mode = "replace",
           data_ajax_update = "environment-container",
           @class = "btn btn-danger"
       })
</code>```

control:

```<code>public async Task<ActionResult> GetEnvironment(int? id)
{

        var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
        return PartialView("_Environment",environments);
}
</code>```

Partial view:

```<code>@model PowerPhysics.Models.Environments
this is a partial view
</code>```

Then I tried using ViewComponents. When the page loads the component works correctly but I don't understand how to refresh just the component afterward (for example with a button):

View:

```<code>@Component.InvokeAsync("Environments", new { id = Model.Id }).Result
</code>```

component:

```<code>public class EnvironmentsViewComponent : ViewComponent
{
    public EnvironmentsViewComponent(PowerPhysics_DataContext context)
    {
        _context = context;
    }

    public async Task<IViewComponentResult> InvokeAsync(int? id)
    {
        var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);

        return View(environments);
    }
}
</code>```

How can I update just a part of a view by using PartialViews in MVC6?

答:
Use tag helpers instead and make sure to include _ViewImport  in your views folder.

Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.

Example - Razor Page

```<code><script type="text/javascript" language="javascript">
    $(function () {
        var myEl = document.getElementsByName('theName');
        $(myEl).click(function (e) {

            e.preventDefault();
            var _this = $(this);
            $.get(_this.attr("href"), function (res) {
                $('#' + _this.data("target")).html(res);
            });
        });
    });
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>

<div id="divReplacable">
    Some Default Content
</div>
</code>```

Body:
In MVC5 there is @Ajax.ActionLink that is useful to update just a partial view instead of reloading the whole View. Apparently in MVC6 is not supported anymore.

I have tried using @Html.ActionLink like the following but it doesn't update the form, it return just the partial view:

View:

@Html.ActionLink("Update", "GetEnvironment", "Environments", new { id = Model.Id }, new
       {
           data_ajax = "true",
           data_ajax_method = "GET",
           data_ajax_mode = "replace",
           data_ajax_update = "environment-container",
           @class = "btn btn-danger"
       })

control:

public async Task<ActionResult> GetEnvironment(int? id)
{

        var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
        return PartialView("_Environment",environments);
}

Partial view:

@model PowerPhysics.Models.Environments
this is a partial view

Then I tried using ViewComponents. When the page loads the component works correctly but I don't understand how to refresh just the component afterward (for example with a button):

View:

@Component.InvokeAsync("Environments", new { id = Model.Id }).Result

component:

public class EnvironmentsViewComponent : ViewComponent
{
    public EnvironmentsViewComponent(PowerPhysics_DataContext context)
    {
        _context = context;
    }

    public async Task<IViewComponentResult> InvokeAsync(int? id)
    {
        var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);

        return View(environments);
    }
}

How can I update just a part of a view by using PartialViews in MVC6?

Body:
Use tag helpers instead and make sure to include _ViewImport  in your views folder.

Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.

Example - Razor Page

<script type="text/javascript" language="javascript">
    $(function () {
        var myEl = document.getElementsByName('theName');
        $(myEl).click(function (e) {

            e.preventDefault();
            var _this = $(this);
            $.get(_this.attr("href"), function (res) {
                $('#' + _this.data("target")).html(res);
            });
        });
    });
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>

<div id="divReplacable">
    Some Default Content
</div>


问:
Build the OpenCV 2.0 libraries from source using Visual Studio 2010 Beta and CMake
OpenCV 2.0a does not include pre-compiled OpenCV libraries for Visual Studio users. I am trying to build the libraries from source using Visual Studio 2010 Beta and CMake, but I am getting lot of errors.

I even tried generating the libs from dlls using dumpbin but the linker errors are still persisting. Please guide me to generate the static libs for VS2010.

答: It's kind of late, but I created a video tutorial for compiling and configuring OpenCV 2.1 with Visual Studio 2010.</p>


问:
Python OOP: how to use a flag parameter to access methods?
It's unclear to me how one accomplishes this in Python, though I am confused about the fundamentals of OOP:

Let's say I create a Shape class, and use this as an example.

```<code>class Shape:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def scaleSize(self,scale):
        self.x = self.x * scale
        self.y = self.y * scale
</code>```

In my case, I must create a Class which inputs a file whereby there are only two types, file_typeA and file_typeB. For the user, it would be exceptionally cumbersome to use a Class for Type A and a Class for Type B.

```<code>## use case for an a "read in file name" class `filename`
foo = filename(path = "path/to/file.txt", file_type = "TypeA")
</code>```

My question is, how do I restrict the "Type A" methods for a file initialized with flag file_type="TypeA", and restrict the methods for a file initialized with flag file_type = "TypeB"?

Let's try the Shape class again, whereby the two types are Square and Triangle. The wrong way to code this is something like this:

```<code>class Shape:
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = type

    if type == "Square":

        def area(self):
            return self.x * self.y

        def perimeter(self):
            return 2 * self.x + 2 * self.y

        def scaleSize(self,scale):
            self.x = self.x * scale
            self.y = self.y * scale

    elif type == "Triangle":

        def hooray(self):
            print("HOORAY! It's hip to be a triangle!")

    else:
        print("'type' must be either Circle or Triangle")

 ## example Class instantiation
 bar = Shape(2, 3, type="Square")
</code>```

For such a class, how do I create it such that the method area cannot be used for a Shape of type=="TypeB"?

答:
I think you need to define a mother class:

```<code>class Shape:
   pass
</code>```

then sub-classes

```<code>class Triangle(Shape):
   # whatever methods there are
</code>```

What you're describing is a factory function which creates the proper object according to some parameter:

```<code>def create(type):
   if type=="Triangle":
       return Triangle()
   elif type=="Square":
       return Square()
</code>```

but it's not very useful since the caller has to pass the name of the class instead:

```<code>c = create("Triangle")
</code>```

instead of just doing:

```<code>c = Triangle()
</code>```

Well, it may have its interest when saving/restoring a program state from a text file containing the type(s) of the objects in the program memory when saved (if you don't want to use pickle).

Body:
It's unclear to me how one accomplishes this in Python, though I am confused about the fundamentals of OOP:

Let's say I create a Shape class, and use this as an example.

class Shape:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def scaleSize(self,scale):
        self.x = self.x * scale
        self.y = self.y * scale

In my case, I must create a Class which inputs a file whereby there are only two types, file_typeA and file_typeB. For the user, it would be exceptionally cumbersome to use a Class for Type A and a Class for Type B.

## use case for an a "read in file name" class `filename`
foo = filename(path = "path/to/file.txt", file_type = "TypeA")

My question is, how do I restrict the "Type A" methods for a file initialized with flag file_type="TypeA", and restrict the methods for a file initialized with flag file_type = "TypeB"?

Let's try the Shape class again, whereby the two types are Square and Triangle. The wrong way to code this is something like this:

class Shape:
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = type

    if type == "Square":

        def area(self):
            return self.x * self.y

        def perimeter(self):
            return 2 * self.x + 2 * self.y

        def scaleSize(self,scale):
            self.x = self.x * scale
            self.y = self.y * scale

    elif type == "Triangle":

        def hooray(self):
            print("HOORAY! It's hip to be a triangle!")

    else:
        print("'type' must be either Circle or Triangle")

 ## example Class instantiation
 bar = Shape(2, 3, type="Square")

For such a class, how do I create it such that the method area cannot be used for a Shape of type=="TypeB"?

Body:
I think you need to define a mother class:

class Shape:
   pass

then sub-classes

class Triangle(Shape):
   # whatever methods there are

What you're describing is a factory function which creates the proper object according to some parameter:

def create(type):
   if type=="Triangle":
       return Triangle()
   elif type=="Square":
       return Square()

but it's not very useful since the caller has to pass the name of the class instead:

c = create("Triangle")

instead of just doing:

c = Triangle()

Well, it may have its interest when saving/restoring a program state from a text file containing the type(s) of the objects in the program memory when saved (if you don't want to use pickle).


问:
Why am I getting this (apparently) unusual AttributeError: 'bytes' object has no attribute '_all_strings'? Is there a way to get around it?
I've been searching for a solution to this AttributeError I keep getting, and no solution I've been able to find deals with '_all_strings'.

I want to code a web-crawler, but there's a lot of nonsense at the top and bottom of the page, so I'm trying to clean up the HTML code as a precursor to excluding the unwanted noise at the top and bottom of the webpage.

When I run the code below, specifically, the last line of it, I get an AttributeError:

```<code>from __future__ import division
from urllib.request import urlopen
from bs4 import BeautifulSoup

textSource = 'http://celt.ucc.ie/irlpage.html'
html = urlopen(textSource).read()
raw = BeautifulSoup.get_text(html)
</code>```

This is the full Traceback I get:

```<code>Traceback (most recent call last):
  File "...Crawler_Celt_Namelink_Test.py", line 7, in <module>
    raw = BeautifulSoup.get_text(html)
  File "...Python\Python35\lib\site-packages\bs4\element.py", line 950, in get_text
    return separator.join([s for s in self._all_strings(
AttributeError: 'bytes' object has no attribute '_all_strings'
</code>```

Has anybody encountered this error before? Or can anyone suggest how I can overcome it, please?

答:
When you look at the BeautifulSoup docs it is used like this:</p>

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
textSource = 'http://celt.ucc.ie/irlpage.html'
html = urlopen(textSource).read()

soup = BeautifulSoup(html, 'html.parser')

raw = BeautifulSoup.get_text(soup)
</code>```

Body:
I've been searching for a solution to this AttributeError I keep getting, and no solution I've been able to find deals with '_all_strings'.

I want to code a web-crawler, but there's a lot of nonsense at the top and bottom of the page, so I'm trying to clean up the HTML code as a precursor to excluding the unwanted noise at the top and bottom of the webpage.

When I run the code below, specifically, the last line of it, I get an AttributeError:

from __future__ import division
from urllib.request import urlopen
from bs4 import BeautifulSoup

textSource = 'http://celt.ucc.ie/irlpage.html'
html = urlopen(textSource).read()
raw = BeautifulSoup.get_text(html)

This is the full Traceback I get:

Traceback (most recent call last):
  File "...Crawler_Celt_Namelink_Test.py", line 7, in <module>
    raw = BeautifulSoup.get_text(html)
  File "...Python\Python35\lib\site-packages\bs4\element.py", line 950, in get_text
    return separator.join([s for s in self._all_strings(
AttributeError: 'bytes' object has no attribute '_all_strings'

Has anybody encountered this error before? Or can anyone suggest how I can overcome it, please?

Body:
When you look at the BeautifulSoup docs it is used like this:

from urllib.request import urlopen
from bs4 import BeautifulSoup
textSource = 'http://celt.ucc.ie/irlpage.html'
html = urlopen(textSource).read()

soup = BeautifulSoup(html, 'html.parser')

raw = BeautifulSoup.get_text(soup)


问:
When using igraph in R, edge curves not smooth at all
This may sound like a very minor detail of a question, however I am trying to make this graph look at clean as possible, and any feedback is appreciated. I am working on creating network graphs in R for basketball. I made this post a few days ago - Draw beautiful network graphs in R - with shows the type of graph I am trying to mimic.

Using the igraph package, I have been able to recreate the graph for the most part. Example below, with the dataframe I am using too:

```<code>library(igraph)
nba.nodes <- data.frame(id = c('s01', 's02', 's03', 's04', 's05'),
                        color = c('darkred', 'darkblue', 'darkgreen', 'darkorange',  'darkmagenta'),
                        names = c('Jarrett\nJack', 'Tim\nHardaway', 'Courtney\nLee', 'Kristaps\nPorzingis', 'Enes\nKanter'))

nba.edges <- data.frame(from = c('s01', 's01', 's01', 's01',
                                 's02', 's02', 's02', 's02',
                                 's03', 's03', 's03', 's03',
                                 's04', 's04', 's04', 's04',
                                 's05', 's05', 's05', 's05'),
                        to = c('s02', 's03', 's04', 's05',
                               's01', 's03', 's04', 's05',
                               's01', 's02', 's04', 's05',
                               's01', 's02', 's03', 's05',
                               's01', 's02', 's03', 's04'),
                        width = sample(1:12, 20, replace = TRUE))

nba.net <- graph_from_data_frame(d = nba.edges, vertices = nba.nodes, directed = T)

# ignore the layout = l, i have this commented out, was just testing it
# l <- layout_in_circle(nba.net)
plot(nba.net, # layout = l,
     vertex.size = 20,
     edge.curved = 0.3,
     vertex.label = V(nba.net)$names,
     vertex.label.dist = 4,
     vertex.label.font = 2)
</code>```

As you can see, the plot is nice but I am very unhappy with how the edge.curved parameters works. Rather than plotting a smooth, curved edge line similar to those in the graph in the link I shared, the edges are these bent lines... the larger i set the parameter edge.curved, the more bent the line... not the curve i was hoping for.

As you can tell, the edges in the graph in the link i shared appear to be perfect curves (perfect in the sense that they have the curvature of a circle). Is there any way I could do this using igraph? any help is appreciated with this, thanks!

答:
If you are trying to get a better picture on the screen, I have no help. But if you are trying to save the picture (say for inclusion in a paper or PowerPoint) you can get a picture without the aliasing by using a different graphics device.   Try:

```<code>png('Graph.png', 500, 500, type='cairo')
plot(nba.net, # layout = l,
     vertex.size = 20,
     edge.curved = 0.3,
     vertex.label = V(nba.net)$names,
     vertex.label.dist = 4,
     vertex.label.font = 2)
dev.off()
</code>```

And look for the output in the current directory (use getwd())

Body:
This may sound like a very minor detail of a question, however I am trying to make this graph look at clean as possible, and any feedback is appreciated. I am working on creating network graphs in R for basketball. I made this post a few days ago - Draw beautiful network graphs in R - with shows the type of graph I am trying to mimic.

Using the igraph package, I have been able to recreate the graph for the most part. Example below, with the dataframe I am using too:

library(igraph)
nba.nodes <- data.frame(id = c('s01', 's02', 's03', 's04', 's05'),
                        color = c('darkred', 'darkblue', 'darkgreen', 'darkorange',  'darkmagenta'),
                        names = c('Jarrett\nJack', 'Tim\nHardaway', 'Courtney\nLee', 'Kristaps\nPorzingis', 'Enes\nKanter'))

nba.edges <- data.frame(from = c('s01', 's01', 's01', 's01',
                                 's02', 's02', 's02', 's02',
                                 's03', 's03', 's03', 's03',
                                 's04', 's04', 's04', 's04',
                                 's05', 's05', 's05', 's05'),
                        to = c('s02', 's03', 's04', 's05',
                               's01', 's03', 's04', 's05',
                               's01', 's02', 's04', 's05',
                               's01', 's02', 's03', 's05',
                               's01', 's02', 's03', 's04'),
                        width = sample(1:12, 20, replace = TRUE))

nba.net <- graph_from_data_frame(d = nba.edges, vertices = nba.nodes, directed = T)

# ignore the layout = l, i have this commented out, was just testing it
# l <- layout_in_circle(nba.net)
plot(nba.net, # layout = l,
     vertex.size = 20,
     edge.curved = 0.3,
     vertex.label = V(nba.net)$names,
     vertex.label.dist = 4,
     vertex.label.font = 2)

As you can see, the plot is nice but I am very unhappy with how the edge.curved parameters works. Rather than plotting a smooth, curved edge line similar to those in the graph in the link I shared, the edges are these bent lines... the larger i set the parameter edge.curved, the more bent the line... not the curve i was hoping for.

As you can tell, the edges in the graph in the link i shared appear to be perfect curves (perfect in the sense that they have the curvature of a circle). Is there any way I could do this using igraph? any help is appreciated with this, thanks!

Body:
If you are trying to get a better picture on the screen, I have no help. But if you are trying to save the picture (say for inclusion in a paper or PowerPoint) you can get a picture without the aliasing by using a different graphics device.   Try:

png('Graph.png', 500, 500, type='cairo')
plot(nba.net, # layout = l,
     vertex.size = 20,
     edge.curved = 0.3,
     vertex.label = V(nba.net)$names,
     vertex.label.dist = 4,
     vertex.label.font = 2)
dev.off()

And look for the output in the current directory (use getwd())


问:
Return all records from parent table if id = 0
Let's say I have a table that assigns Users as managers for division(s) such as:

UserManagerTable:

```<code>ID      UserId    DivisionId
1       23        1
2       45        0
</code>```

When DivisionId = 0 it is meant to represent that the user is assigned as a manager to All Divisions in the Divisions table.

I would like to know the best possible way to query this table to return DivisionId's and if DivisionId = 0 then return all DivisionIds from the Divisions table.

```<code>SELECT DivisionId FROM UserManagerTable...?

DivisionId
1
1
2
3
...
...
30
</code>```

Initially I thought I could do something like:

```<code>SELECT
CASE
    WHEN DivisionId  = 0 THEN (Select DivisionId FROM Division)
    ELSE DivisionId
END AS DivisionID
FROM PoAppApprovedRequestor
</code>```

But that did not get me what I wanted.

答:
Do you mean something like this?</p>

```<code>select d.*
from divisions d
where exists (select 1
              from usermanager um
              where um.id = @id and
                    (um.divisionid = 0 or um.divisionid = d.divisionid)
             );
</code>```

Body:
Let's say I have a table that assigns Users as managers for division(s) such as:

UserManagerTable:

ID      UserId    DivisionId
1       23        1
2       45        0

When DivisionId = 0 it is meant to represent that the user is assigned as a manager to All Divisions in the Divisions table.

I would like to know the best possible way to query this table to return DivisionId's and if DivisionId = 0 then return all DivisionIds from the Divisions table.

SELECT DivisionId FROM UserManagerTable...?

DivisionId
1
1
2
3
...
...
30

Initially I thought I could do something like:

SELECT
CASE
    WHEN DivisionId  = 0 THEN (Select DivisionId FROM Division)
    ELSE DivisionId
END AS DivisionID
FROM PoAppApprovedRequestor

But that did not get me what I wanted.

Body:
Do you mean something like this?

select d.*
from divisions d
where exists (select 1
              from usermanager um
              where um.id = @id and
                    (um.divisionid = 0 or um.divisionid = d.divisionid)
             );