问:
Swift 3: Stretchy UITableView footer
Can anybody tell me how to implement a stretchy UITableView footer.

I want my image inside my footer to stretch/increase size when the user 'overscrolls'. (If the user are scrolling down when the UITableView is already at the bottom)

Current code:

```<code>private let tableFooterHeight: CGFloat = 300
private var footerCustomView = UIImageView()

    func setupFooterView(){
         // Footer view
         self.footerCustomView = UIImageView(frame: CGRect.zero)
         self.footerCustomView.backgroundColor = UIColor.brown
         self.footerCustomView.image = UIImage(named: "image")

         self.view.addSubview(self.footerCustomView)
//        self.view.bringSubview(toFront: self.tableView)

         self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self.tableFooterHeight, right: 0)

         self.footerCustomView.translatesAutoresizingMaskIntoConstraints = false

         let leadingConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                               attribute: .leading,
                                               relatedBy: .equal,
                                               toItem: self.tableView,
                                               attribute: .leading,
                                               multiplier: 1,
                                               constant: 0)

         let trailingConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                           attribute: .trailing,
                                           relatedBy: .equal,
                                           toItem: self.tableView,
                                           attribute: .trailing,
                                           multiplier: 1,
                                           constant: 0)

        let bottomConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                           attribute: .bottom,
                                           relatedBy: .equal,
                                           toItem: self.tableView,
                                           attribute: .bottom,
                                           multiplier: 1,
                                           constant: 0)

        let heightConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                              attribute: .height,
                                              relatedBy: .equal,
                                              toItem: nil,
                                              attribute: .height,
                                              multiplier: 1,
                                              constant: self.tableFooterHeight)

        self.view.addConstraints([bottomConstraint, trailingConstraint, heightConstraint, leadingConstraint])
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    self.updateFooterView()
}

func updateFooterView() {
    if self.tableView.bounds.origin.y > 1559 { // 1559 is end of tableView
        let diff = self.tableView.contentOffset.y - 1559
        self.footerCustomView.frame.size.height = self.tableFooterHeight + diff
    }
}
</code>```

Thank you!

Normal:

Stretch mode:

答:
A UITableView already has a property tableFooterView

We can subclass UIView with a UIImageView, a UIScrollView, and another UIView to serve as a container for the UIImageView. Let's call it StretchyFooterView.

I like to use a library called PureLayout for adding constraints.

```<code>class YourView: UIView, UITableViewDelegate {

fileprivate let tableView = UITableView(frame: .zero, style: .plain)

fileprivate let image = UIImage(named: "yourImage")!

// ----------------------------------------------------------------------------
// MARK: Init
// ----------------------------------------------------------------------------

override init(frame: CGRect) {
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

// ----------------------------------------------------------------------------
// MARK: UIView
// ----------------------------------------------------------------------------

override func updateConstraints() {
    tableView.autoPinEdgesToSuperviewEdges()

    super.updateConstraints()
}

override func layoutSubviews() {
    super.layoutSubviews()

    // do this after the view lays out so we know the frame width and height
    let imageAspect = image.size.width / image.size.height
    let footerWidth = frame.size.width
    let footerHeight = footerWidth / imageAspect
    let footerSize = CGSize(width: footerWidth, height: footerHeight)
    let footerFrame = CGRect(origin: .zero, size: footerSize)

    tableView.tableFooterView = StretchyFooterView(frame: footerFrame, image: image)
}

// ----------------------------------------------------------------------------
// MARK: Internal
// ----------------------------------------------------------------------------

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let verticalScrollDistance = scrollView.contentOffset.y
    let bottomOfView = frame.height

    if let stretchyFooterView = tableView.tableFooterView as? StretchyFooterView {
        stretchyFooterView.stretchBy(verticalScrollDistance, bottomBound: bottomOfView)
    }
}

// ----------------------------------------------------------------------------
// MARK: Private
// ----------------------------------------------------------------------------

fileprivate func setupViews() {
    tableView.delegate = self

    addSubview(tableView)
}
}

class StretchyFooterView: UIView {

fileprivate let containerView = UIView()
fileprivate let scrollView = UIScrollView()
fileprivate let imageView = UIImageView()

fileprivate let image: UIImage

// ----------------------------------------------------------------------------
// MARK: Init
// ----------------------------------------------------------------------------

init(frame: CGRect, image: UIImage) {
    self.image = image

    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

// ----------------------------------------------------------------------------
// MARK: UIView
// ----------------------------------------------------------------------------

override func updateConstraints() {
    containerView.autoCenterInSuperview()
    containerView.autoMatch(.height, to: .height, of: scrollView)

    imageView.autoPinEdgesToSuperviewEdges()
    imageView.autoMatch(.width, to: .height, of: scrollView, withMultiplier: image.aspect)

    super.updateConstraints()
}

// ----------------------------------------------------------------------------
// MARK: Internal
// ----------------------------------------------------------------------------

func stretchBy(_ distanceScrolled: CGFloat, bottomBound: CGFloat) {
    let distanceFromTop = bottomBound + distanceScrolled // the footer could be offscreen, so we need to add the distance scrolled to the bottom of the view
    let distanceFromBottom = frame.maxY - distanceFromTop // this is how much we need to scroll

    if distanceFromBottom < 0 { // once we hit zero and below, we need to stretch the height
        let origin = CGPoint.zero // since we are scrolling, the origin needs to stay at zero
        let newSize = CGSize(width: frame.width, height: frame.height - distanceFromBottom) // subtract distanceFromBottom because it's negative

        scrollView.frame = CGRect(origin: origin, size: newSize)
    }
}

// ----------------------------------------------------------------------------
// MARK: Private
// ----------------------------------------------------------------------------

fileprivate func setupViews() {
    imageView.image = image

    containerView.addSubview(imageView)

    scrollView.frame = bounds
    scrollView.addSubview(containerView)

    addSubview(scrollView)
}
}
</code>```

Title: Swift 3: Stretchy UITableView footer

Body:
Can anybody tell me how to implement a stretchy UITableView footer.

I want my image inside my footer to stretch/increase size when the user 'overscrolls'. (If the user are scrolling down when the UITableView is already at the bottom)

Current code:

private let tableFooterHeight: CGFloat = 300
private var footerCustomView = UIImageView()

    func setupFooterView(){
         // Footer view
         self.footerCustomView = UIImageView(frame: CGRect.zero)
         self.footerCustomView.backgroundColor = UIColor.brown
         self.footerCustomView.image = UIImage(named: "image")

         self.view.addSubview(self.footerCustomView)
//        self.view.bringSubview(toFront: self.tableView)

         self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self.tableFooterHeight, right: 0)

         self.footerCustomView.translatesAutoresizingMaskIntoConstraints = false

         let leadingConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                               attribute: .leading,
                                               relatedBy: .equal,
                                               toItem: self.tableView,
                                               attribute: .leading,
                                               multiplier: 1,
                                               constant: 0)

         let trailingConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                           attribute: .trailing,
                                           relatedBy: .equal,
                                           toItem: self.tableView,
                                           attribute: .trailing,
                                           multiplier: 1,
                                           constant: 0)

        let bottomConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                           attribute: .bottom,
                                           relatedBy: .equal,
                                           toItem: self.tableView,
                                           attribute: .bottom,
                                           multiplier: 1,
                                           constant: 0)

        let heightConstraint = NSLayoutConstraint(item: self.footerCustomView,
                                              attribute: .height,
                                              relatedBy: .equal,
                                              toItem: nil,
                                              attribute: .height,
                                              multiplier: 1,
                                              constant: self.tableFooterHeight)

        self.view.addConstraints([bottomConstraint, trailingConstraint, heightConstraint, leadingConstraint])
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    self.updateFooterView()
}

func updateFooterView() {
    if self.tableView.bounds.origin.y > 1559 { // 1559 is end of tableView
        let diff = self.tableView.contentOffset.y - 1559
        self.footerCustomView.frame.size.height = self.tableFooterHeight + diff
    }
}

Thank you!

Normal:

Stretch mode:

Body:
A UITableView already has a property tableFooterView

We can subclass UIView with a UIImageView, a UIScrollView, and another UIView to serve as a container for the UIImageView. Let's call it StretchyFooterView.

I like to use a library called PureLayout for adding constraints.

class YourView: UIView, UITableViewDelegate {

fileprivate let tableView = UITableView(frame: .zero, style: .plain)

fileprivate let image = UIImage(named: "yourImage")!

// ----------------------------------------------------------------------------
// MARK: Init
// ----------------------------------------------------------------------------

override init(frame: CGRect) {
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

// ----------------------------------------------------------------------------
// MARK: UIView
// ----------------------------------------------------------------------------

override func updateConstraints() {
    tableView.autoPinEdgesToSuperviewEdges()

    super.updateConstraints()
}

override func layoutSubviews() {
    super.layoutSubviews()

    // do this after the view lays out so we know the frame width and height
    let imageAspect = image.size.width / image.size.height
    let footerWidth = frame.size.width
    let footerHeight = footerWidth / imageAspect
    let footerSize = CGSize(width: footerWidth, height: footerHeight)
    let footerFrame = CGRect(origin: .zero, size: footerSize)

    tableView.tableFooterView = StretchyFooterView(frame: footerFrame, image: image)
}

// ----------------------------------------------------------------------------
// MARK: Internal
// ----------------------------------------------------------------------------

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let verticalScrollDistance = scrollView.contentOffset.y
    let bottomOfView = frame.height

    if let stretchyFooterView = tableView.tableFooterView as? StretchyFooterView {
        stretchyFooterView.stretchBy(verticalScrollDistance, bottomBound: bottomOfView)
    }
}

// ----------------------------------------------------------------------------
// MARK: Private
// ----------------------------------------------------------------------------

fileprivate func setupViews() {
    tableView.delegate = self

    addSubview(tableView)
}
}

class StretchyFooterView: UIView {

fileprivate let containerView = UIView()
fileprivate let scrollView = UIScrollView()
fileprivate let imageView = UIImageView()

fileprivate let image: UIImage

// ----------------------------------------------------------------------------
// MARK: Init
// ----------------------------------------------------------------------------

init(frame: CGRect, image: UIImage) {
    self.image = image

    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

// ----------------------------------------------------------------------------
// MARK: UIView
// ----------------------------------------------------------------------------

override func updateConstraints() {
    containerView.autoCenterInSuperview()
    containerView.autoMatch(.height, to: .height, of: scrollView)

    imageView.autoPinEdgesToSuperviewEdges()
    imageView.autoMatch(.width, to: .height, of: scrollView, withMultiplier: image.aspect)

    super.updateConstraints()
}

// ----------------------------------------------------------------------------
// MARK: Internal
// ----------------------------------------------------------------------------

func stretchBy(_ distanceScrolled: CGFloat, bottomBound: CGFloat) {
    let distanceFromTop = bottomBound + distanceScrolled // the footer could be offscreen, so we need to add the distance scrolled to the bottom of the view
    let distanceFromBottom = frame.maxY - distanceFromTop // this is how much we need to scroll

    if distanceFromBottom < 0 { // once we hit zero and below, we need to stretch the height
        let origin = CGPoint.zero // since we are scrolling, the origin needs to stay at zero
        let newSize = CGSize(width: frame.width, height: frame.height - distanceFromBottom) // subtract distanceFromBottom because it's negative

        scrollView.frame = CGRect(origin: origin, size: newSize)
    }
}

// ----------------------------------------------------------------------------
// MARK: Private
// ----------------------------------------------------------------------------

fileprivate func setupViews() {
    imageView.image = image

    containerView.addSubview(imageView)

    scrollView.frame = bounds
    scrollView.addSubview(containerView)

    addSubview(scrollView)
}
}


来源: stackexchange

问:
Regular expression in Scala
I want to extract a word from a string and then use that word in my regex.

My string looks like this:

```<code> val s = "null_eci_count"
</code>```

I want to derive the below string from the above string:

```<code>sum(cast((eci is null or eci in ('', '0', 'null', 'NULL')) as int))
</code>```

I used replaceAll and had derived a part of the above expression:

```<code>scala> s.replaceAll("null_", "sum(cast((").replaceAll("_count"," is null) as int))")
res69: String = sum(cast((eci is null) as int))
</code>```

Please suggest a way to derive the whole expression.

答:
I used ArrayBuffer to do this:</p>

```<code>import scala.collection.mutable.ArrayBuffer
val tgt=spark.sql("select * from ctx_monitor.xpo_click_counts")
val a = tgt.columns.slice(4,tgt.columns.length)
for (e <- a) {
if (e contains "null"){ val c=e.replaceFirst("null_","");
col += "sum(cast((" + c + " is null or " + c + " in('','0','null','NULL')) as int))"}}

val cols=col.mkString(",")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regular expression in Scala

Body:
I want to extract a word from a string and then use that word in my regex.

My string looks like this:

 val s = "null_eci_count"

I want to derive the below string from the above string:

sum(cast((eci is null or eci in ('', '0', 'null', 'NULL')) as int))

I used replaceAll and had derived a part of the above expression:

scala> s.replaceAll("null_", "sum(cast((").replaceAll("_count"," is null) as int))")
res69: String = sum(cast((eci is null) as int))

Please suggest a way to derive the whole expression.

Body:
I used ArrayBuffer to do this:

import scala.collection.mutable.ArrayBuffer
val tgt=spark.sql("select * from ctx_monitor.xpo_click_counts")
val a = tgt.columns.slice(4,tgt.columns.length)
for (e <- a) {
if (e contains "null"){ val c=e.replaceFirst("null_","");
col += "sum(cast((" + c + " is null or " + c + " in('','0','null','NULL')) as int))"}}

val cols=col.mkString(",")


问:
Counting Rows Based on Exist Condition
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

```<code>CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)
</code>```

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

```<code>| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |
</code>```

So here is what I have so far:

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

答:
I think this solves the problem.
You'll be counting others as not you and anyone not in the ProjectTaskOwner table for this task.</p>

```<code>DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo,
    COUNT(CASE WHEN pte.AssignedUserId != @userId AND pte.AssignedUserId != pto.UserId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
LEFT JOIN ProjectTaskOwner pto
    on pto.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId
</code>```

Title: Counting Rows Based on Exist Condition

Body:
I have researched many Stackoverflow questions that demonstrate how to add conditions to the COUNT statement using a CASE statement but I can't find an example of how to do what I need to.  Let's assume I have the following tables:

CREATE TABLE [Project](
    [ProjectId] [int] NOT NULL,
    [ProjectName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTask](
    [ProjectTaskId] [int] NOT NULL,
    [ProjectId] [int] NOT NULL,
    [TaskName] [nvarchar](100) NOT NULL
)
GO

CREATE TABLE [ProjectTaskOwner](
    [ProjectTaskId] [int] NOT NULL,
    [UserId] [int] NOT NULL
 )
GO

CREATE TABLE [ProjectTaskEntity](
    [ProjectTaskId] [int] NOT NULL,
    [EntityId] [int] NOT NULL,
    [AssignedUserId] [int]
 )
GO

INSERT Project (ProjectId, ProjectName) VALUES (1, 'Test Project')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(1, 1, 'Task1')
INSERT ProjectTask (ProjectTaskId, ProjectId, TaskName) VALUES(2, 1, 'Task2')
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 1)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 2)
INSERT ProjectTaskOwner (ProjectTaskId, UserId) VALUES (1, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 1, 1)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 2, 2)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 3, 3)
INSERT ProjectTaskEntity (ProjectTaskId, EntityId, AssignedUserId) VALUES (1, 4, 256)

What I want to do is get for each Project Task the count of entities that are assigned to me and assigned to other task owners.  So for the test data above, given a user id of 1 and a project id of 1 I expect:

| TaskId | AssignedToMe | AssignedToOthers |
|   1    |      1       |       2          |
|   2    |      0       |       0          |

So here is what I have so far:

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId

Assigned to me was easy.  The problem is I'm not sure how to do others because others isn't just anyone not me.  It is anyone not in the ProjectTaskOwner table for this task.  Anyone have any idea how to achieve this?

Body:
I think this solves the problem.
You'll be counting others as not you and anyone not in the ProjectTaskOwner table for this task.

DECLARE @userId INT = 1
SELECT
    pt.ProjectId,
    pt.ProjectTaskId,
    COUNT(CASE WHEN pte.AssignedUserId = @userId THEN 1 ELSE NULL END) AS AssignedTo,
    COUNT(CASE WHEN pte.AssignedUserId != @userId AND pte.AssignedUserId != pto.UserId THEN 1 ELSE NULL END) AS AssignedTo
FROM ProjectTask pt
INNER JOIN Project p
    ON p.ProjectId = pt.ProjectId
LEFT JOIN ProjectTaskEntity pte
    ON pte.ProjectTaskId = pt.ProjectTaskId
LEFT JOIN ProjectTaskOwner pto
    on pto.ProjectTaskId = pt.ProjectTaskId
WHERE p.ProjectId = 1
GROUP BY pt.ProjectId,  pt.ProjectTaskId


问:
How to develop "shippable" components for ASP.NET MVC?
In ASP.NET webforms we have server components, that can be encapsulated into an external assembly and shipped as product. In ASP.NET MVC we don't have server components, so what's the best option for external components?

Looking around it seems like the only possible option is making an Html helper method that returns a bunch of html + js that manipulates things. And if the component needs some logic, a http module that add some new routes and a controller defined in the same external assembly to handle the ajax calls.

Otherwise RenderPartial only returns a view... but a view is a real file, so difficult to encapsulate in an external assembly unless it's added as resource file and then retrieved using a path provider that looks into the resource file instead of a real location on the disk.

Or are there any other options I'm not considering?

Thx
Simo

答:
Try PortableArea from MVCContrib. It seems to be what you are looking for. Even if it is not, the source code might help you achieve the goal.

Demonstration video: http://www.viddler.com/explore/c4mvc/videos/11/

OwnerDisplayName: CodeClimber

ContentLicense: CC BY-SA 2.5


问:
How to split a constant 2D array initialization on several lines?
I need to create a 2D array which is not intended to be updated, only read.
Reading this question, I found this possibility using evaluate:

```<code>Dim varData As Variant
varData = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]
</code>```

In my case, the number of values requires to split the assignment on several lines, e.g.

```<code>varData = [{value1, value2; _
            ...; _
            valueM, valueN}]
</code>```

However when using _ to split this assignment, VBA complains at the first line with:

Compile Error:

Missing end bracket

I've tried to find the explanation, but all examples seems to use only a single line. What is wrong?

Note: I'm trying to populate an array, not cells in a sheet.

答:
I was thinking of this.</p>

```<code>Dim A as Variant
A = Array(Array(1, 2), _
          Array(3, 4), _
          Array(5, 6))
</code>```

Body:
I need to create a 2D array which is not intended to be updated, only read.
Reading this question, I found this possibility using evaluate:

Dim varData As Variant
varData = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]

In my case, the number of values requires to split the assignment on several lines, e.g.

varData = [{value1, value2; _
            ...; _
            valueM, valueN}]

However when using _ to split this assignment, VBA complains at the first line with:

Compile Error:

Missing end bracket

I've tried to find the explanation, but all examples seems to use only a single line. What is wrong?

Note: I'm trying to populate an array, not cells in a sheet.

Body:
I was thinking of this.

Dim A as Variant
A = Array(Array(1, 2), _
          Array(3, 4), _
          Array(5, 6))


问:
ERR_TOO_MANY_REDIRECTS from htacces
I change the .htaccess file and I added this:

```<code>RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

but when I try to access the page, it gives me this error:

```<code>ERR_TOO_MANY_REDIRECTS
</code>```

I cleared all my cache and cookies, I tried it with another browser, and it didn't work.

Please help me

答:
Add RewriteEngine On to your first line, vai parecer assim:

```<code> RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
</code>```

Last line you could change to something like:

```<code> RewriteRule ^(.*)$ https://www.example.com/$1
</code>```

Where https://www.website.com add your own domain.

That should send you on the right way

Title: ERR_TOO_MANY_REDIRECTS from htacces

Body:
I change the .htaccess file and I added this:

RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

but when I try to access the page, it gives me this error:

ERR_TOO_MANY_REDIRECTS

I cleared all my cache and cookies, I tried it with another browser, and it didn't work.

Please help me

Body:
Add RewriteEngine On to your first line, vai parecer assim:

 RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Last line you could change to something like:

 RewriteRule ^(.*)$ https://www.example.com/$1

Where https://www.website.com add your own domain.

That should send you on the right way


问:
H2OGeneralizedLinearEstimator() - Prediction Error
I am trying to predict test times in a Kaggle comp using the H2OGeneralizedLinearEstimator function. The model trains normally in line 3 and the metrics are all reasonable. However when I come to the predict step I get an error despite the test data frame matching the train data frame.

Has anyone seen this error before?

```<code> h2o_glm = H2OGeneralizedLinearEstimator()

 h2o_glm.train(training_frame=train_h2o,y='y')

 h2o_glm_predictions = h2o_glm.predict(test_data=test_h2o).as_data_frame()

 test_pred = pd.read_csv('test.csv')[['ID']]
 test_pred['y'] = h2o_glm_predictions
 test_pred.to_csv('h2o_glm_predictions.csv',index=False)
</code>```

glm Model Build progress: |███████████████████████████████████████████████| 100%

```<code>glm prediction progress: | (failed)

OSError Traceback (most recent call last) in () 3 h2o_glm.train(training_frame=train_h2o,y='y') 4 ----> 5 h2o_glm_predictions = h2o_glm.predict(test_data=test_h2o).as_data_frame() 6 7 test_pred = pd.read_csv('test.csv')[['ID']]

/Applications/anaconda/lib/python3.6/site-packages/h2o/model/model_base.py in predict(self, test_data) 130 j = H2OJob(h2o.api("POST /4/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id)), 131 self._model_json["algo"] + " prediction") --> 132 j.poll() 133 return h2o.get_frame(j.dest_key) 134

/Applications/anaconda/lib/python3.6/site-packages/h2o/job.py in poll(self) 71 if (isinstance(self.job, dict)) and ("stacktrace" in list(self.job)): 72 raise EnvironmentError("Job with key {} failed with an exception: {}\nstacktrace: " ---> 73 "\n{}".format(self.job_key, self.exception, self.job["stacktrace"])) 74 else: 75 raise EnvironmentError("Job with key %s failed with an exception: %s" % (self.job_key, self.exception))
</code>```

OSError: Job with key
  $03017f00000132d4ffffffff$_868312f4c32f683871930a1145c1476a failed
  with an exception: DistributedException from /127.0.0.1:54321: 'null',
  caused by java.lang.ArrayIndexOutOfBoundsException stacktrace:
  DistributedException from /127.0.0.1:54321: 'null', caused by
  java.lang.ArrayIndexOutOfBoundsException at
  water.MRTask.getResult(MRTask.java:478) at
  water.MRTask.getResult(MRTask.java:486) at
  water.MRTask.doAll(MRTask.java:390) at
  water.MRTask.doAll(MRTask.java:396) at
  hex.glm.GLMModel.predictScoreImpl(GLMModel.java:1215) at
  hex.Model.score(Model.java:1077) at
  water.api.ModelMetricsHandler$1.compute2(ModelMetricsHandler.java:351)
  at water.H2O$H2OCountedCompleter.compute(H2O.java:1349) at
  jsr166y.CountedCompleter.exec(CountedCompleter.java:468) at
  jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:263) at
  jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:974) at
  jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1477) at
  jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104) Caused
  by: java.lang.ArrayIndexOutOfBoundsException

答: To summarize the comments above, the current solution is to add a response column (with fake data if it doesn't exist) to the test_data frame.  However, this is a bug that should be fixed.  The JIRA is here.

Body:
I am trying to predict test times in a Kaggle comp using the H2OGeneralizedLinearEstimator function. The model trains normally in line 3 and the metrics are all reasonable. However when I come to the predict step I get an error despite the test data frame matching the train data frame.

Has anyone seen this error before?

 h2o_glm = H2OGeneralizedLinearEstimator()

 h2o_glm.train(training_frame=train_h2o,y='y')

 h2o_glm_predictions = h2o_glm.predict(test_data=test_h2o).as_data_frame()

 test_pred = pd.read_csv('test.csv')[['ID']]
 test_pred['y'] = h2o_glm_predictions
 test_pred.to_csv('h2o_glm_predictions.csv',index=False)

glm Model Build progress: |███████████████████████████████████████████████| 100%

glm prediction progress: | (failed)

OSError Traceback (most recent call last) in () 3 h2o_glm.train(training_frame=train_h2o,y='y') 4 ----> 5 h2o_glm_predictions = h2o_glm.predict(test_data=test_h2o).as_data_frame() 6 7 test_pred = pd.read_csv('test.csv')[['ID']]

/Applications/anaconda/lib/python3.6/site-packages/h2o/model/model_base.py in predict(self, test_data) 130 j = H2OJob(h2o.api("POST /4/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id)), 131 self._model_json["algo"] + " prediction") --> 132 j.poll() 133 return h2o.get_frame(j.dest_key) 134

/Applications/anaconda/lib/python3.6/site-packages/h2o/job.py in poll(self) 71 if (isinstance(self.job, dict)) and ("stacktrace" in list(self.job)): 72 raise EnvironmentError("Job with key {} failed with an exception: {}\nstacktrace: " ---> 73 "\n{}".format(self.job_key, self.exception, self.job["stacktrace"])) 74 else: 75 raise EnvironmentError("Job with key %s failed with an exception: %s" % (self.job_key, self.exception))

OSError: Job with key
  $03017f00000132d4ffffffff$_868312f4c32f683871930a1145c1476a failed
  with an exception: DistributedException from /127.0.0.1:54321: 'null',
  caused by java.lang.ArrayIndexOutOfBoundsException stacktrace:
  DistributedException from /127.0.0.1:54321: 'null', caused by
  java.lang.ArrayIndexOutOfBoundsException at
  water.MRTask.getResult(MRTask.java:478) at
  water.MRTask.getResult(MRTask.java:486) at
  water.MRTask.doAll(MRTask.java:390) at
  water.MRTask.doAll(MRTask.java:396) at
  hex.glm.GLMModel.predictScoreImpl(GLMModel.java:1215) at
  hex.Model.score(Model.java:1077) at
  water.api.ModelMetricsHandler$1.compute2(ModelMetricsHandler.java:351)
  at water.H2O$H2OCountedCompleter.compute(H2O.java:1349) at
  jsr166y.CountedCompleter.exec(CountedCompleter.java:468) at
  jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:263) at
  jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:974) at
  jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1477) at
  jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104) Caused
  by: java.lang.ArrayIndexOutOfBoundsException


问:
Python: Statistics T-test
I am using python 3.6 to run some statistics test on a data-set. What I am trying to accomplish is
 to run a t-test between the data-set and the trend line to determine the statistical significance. I and using scipy to do this however I am not sure what variables I should include in the test to get the outcome I need.

Here is my code so far:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

p = np.load('data.npy')

#0=1901
start=0
end=100

plt.figure()
plt.plot(a,annualmean,  '-')
slope, intercept, r_value, p_value, std_err = stats.linregress(a,annualmean)
plt.plot(a,intercept+slope*a, 'r')

annualmean=[]
for n in range(start,end):
    annualmean.append(np.nanmean(p[n]))

#Trendline Plots
a=range(start,end)
year1 = 1901

print(stats.ttest_ind(annualmean,a))
</code>```

Right now the code is working, no error messages, however I am getting an incredibly small p-value that I don't think is correct. If anyone knows knows what variables I should write into the t-test that would be very helpful.
Thanks!

答:
So turns out I was confused about how to test the statistical significance. I already had figured out a p-value for the data in the line:

```<code>slope, intercept, r_value, p_value, std_err = stats.linregress(a,annualmean)
</code>```

All I needed to do was:
print(p_value)

Title: Python: Statistics T-test

Body:
I am using python 3.6 to run some statistics test on a data-set. What I am trying to accomplish is
 to run a t-test between the data-set and the trend line to determine the statistical significance. I and using scipy to do this however I am not sure what variables I should include in the test to get the outcome I need.

Here is my code so far:

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

p = np.load('data.npy')

#0=1901
start=0
end=100

plt.figure()
plt.plot(a,annualmean,  '-')
slope, intercept, r_value, p_value, std_err = stats.linregress(a,annualmean)
plt.plot(a,intercept+slope*a, 'r')

annualmean=[]
for n in range(start,end):
    annualmean.append(np.nanmean(p[n]))

#Trendline Plots
a=range(start,end)
year1 = 1901

print(stats.ttest_ind(annualmean,a))

Right now the code is working, no error messages, however I am getting an incredibly small p-value that I don't think is correct. If anyone knows knows what variables I should write into the t-test that would be very helpful.
Thanks!

Body:
So turns out I was confused about how to test the statistical significance. I already had figured out a p-value for the data in the line:

slope, intercept, r_value, p_value, std_err = stats.linregress(a,annualmean)

All I needed to do was:
print(p_value)


问:
Connect to MS SQL Server on Arch Linux
I installed on my arch machine mssql-server and mssql-tools via yaourt. I started the server from /opt/mssql/bin/sqlservr and tried to connect with my credentials, but with no luck. I found this article which says to connect with the command sqlcmd -S localhost -U SA -P 'YourPasswordHere', but it didn't work either. The error message says:

2017-07-06 21:57:28.25 Logon       Error: 18456, Severity: 14, State:
  7.

2017-07-06 21:57:28.25 Logon       Login failed for user 'SA'. Reason:
  An error occurred while evaluating the password. [CLIENT: 127.0.0.1]

I tried with blank password, with Password123 and with my user's password but the message was the same.

Has anyone managed to connect and if yes what was the default password?

Please let me know if you need any further information.

Thanks.

答: I found it. I had to run this command sudo /opt/mssql/bin/mssql-conf setup in order to set the password for the SA user. Now I can connect.

Title: Connect to MS SQL Server on Arch Linux


问:
Replace Text/Image URL with CSS
I am trying to make a custom style for the stylish plugin to use for the Eve Online forums.  I am attempting to resize the avatar image because it was too small for my liking. However it's using a low-quality image and it looks too grainy when resized, so I am trying to figure out how to use the larger image by replacing part of the text, or replacing the url (whatever is easier).  In the image, the only difference a piece of text that shows the size.

See:

meta.eveonline.com/erika_mizune/45/2168_1.png
meta.eveonline.com/erika_mizune/90/2168_1.png

So essentially the 45 (original) needs to be replaced with the 90 in order to look less grainy.

URL to Post: https://meta.eveonline.com/t/avatar-size-category-adjustment/9032

Stylish Plugin: https://userstyles.org/styles/144974/avatar-category-adjustment

My code to resize the image is this:

 .topic-avatar img.avatar
  {
    height: 75px;
    width: 75px;
    border-radius: 0;
  }

  .topic-avatar
  {
    width: 75px !important;
  }```
</div>
</div>
</p>

<p>I tried to search before posting but I'm not finding anything that will work for what I need. </p>

<p>Thanks!</p>

<hr>

<p>Edit 1: I attempted to switch to tampermonkey to use JS as suggested but is not working.  Below is the origional code:</p>

```

```

<p>And the script I have in tampermonkey:</p>

```    var imagelist = document.getElementsByClassName("avatar");
    imagelist.foreach(function(element) {
        element.src = element.src.replace("/45/", "/90/");
    });
```

<hr>

<p>Edit 2: After trying to use debugging in the console I got the error that .foreach is not a function and attempted to try the following as well:</p>

<p>Try 1:</p>

```var imagelist = document.getElementsByTagName("img");
        imagelist.foreach(function(element) {
            element.src = element.src.replace("/45/", "/90/");
        });
```

<p>Try 2:</p>

```var imagelist = Array.from(document.getElementsByClassName('avatar'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});
```

<p>Try 3:</p>

```   var imagelist = Array.from(document.getElementsByTagName('img'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});
```

All of these attempts have returned the same error in console that .foreach is not a function.

答:
I think the javascript solution is the right way to go.

It's really hard to say what's wrong with just a few lines of js from tampermonkey. Is it possible to show the complete files? Or post an example on jsfiddle or something?

It's easy to debug this kind of issue yourself in Chrome Inspector, by typing "debugger" in your code and opening the Source tab in Chrome Inspector (F12 button in Chrome). The inspector will stop at that line and you can see the values of different variables. For example:

First, open Chrome Inspector in Chrome browser. Then load the page with the debugger line:

```<code>var imagelist = document.getElementsByClassName("forum_image_class");
debugger;
imagelist.foreach(function(element){
    element.src = element.src.replace("/45/", "/90/");
}
</code>```

The browser will stop on the debugger line. Type 'imagelist' into the console and hit enter to see its current value. It might be empty, in which case the getElementsByClassName isnt retrieving anything. Which might be happening for a few different reasons. Or the imagelist array might get populated but the replace() isnt working as expected. Is it possible for you to figure out which is happenng and report it here?

ALSO: be careful with .replace(). You have to escape certain characters with a backslash and you should know what those special characters are. In this case you may or may not need to escape the forward slashes.

Title: Replace Text/Image URL with CSS

Body:
I am trying to make a custom style for the stylish plugin to use for the Eve Online forums.  I am attempting to resize the avatar image because it was too small for my liking. However it's using a low-quality image and it looks too grainy when resized, so I am trying to figure out how to use the larger image by replacing part of the text, or replacing the url (whatever is easier).  In the image, the only difference a piece of text that shows the size.

See:

meta.eveonline.com/erika_mizune/45/2168_1.png
meta.eveonline.com/erika_mizune/90/2168_1.png

So essentially the 45 (original) needs to be replaced with the 90 in order to look less grainy.

URL to Post: https://meta.eveonline.com/t/avatar-size-category-adjustment/9032

Stylish Plugin: https://userstyles.org/styles/144974/avatar-category-adjustment

My code to resize the image is this:

 .topic-avatar img.avatar
  {
    height: 75px;
    width: 75px;
    border-radius: 0;
  }

  .topic-avatar
  {
    width: 75px !important;
  }

I tried to search before posting but I'm not finding anything that will work for what I need.

Thanks!

Edit 1: I attempted to switch to tampermonkey to use JS as suggested but is not working.  Below is the origional code:

And the script I have in tampermonkey:

    var imagelist = document.getElementsByClassName("avatar");
    imagelist.foreach(function(element) {
        element.src = element.src.replace("/45/", "/90/");
    });

Edit 2: After trying to use debugging in the console I got the error that .foreach is not a function and attempted to try the following as well:

Try 1:

var imagelist = document.getElementsByTagName("img");
        imagelist.foreach(function(element) {
            element.src = element.src.replace("/45/", "/90/");
        });

Try 2:

var imagelist = Array.from(document.getElementsByClassName('avatar'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});

Try 3:

   var imagelist = Array.from(document.getElementsByTagName('img'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});

All of these attempts have returned the same error in console that .foreach is not a function.

Body:
I think the javascript solution is the right way to go.

It's really hard to say what's wrong with just a few lines of js from tampermonkey. Is it possible to show the complete files? Or post an example on jsfiddle or something?

It's easy to debug this kind of issue yourself in Chrome Inspector, by typing "debugger" in your code and opening the Source tab in Chrome Inspector (F12 button in Chrome). The inspector will stop at that line and you can see the values of different variables. For example:

First, open Chrome Inspector in Chrome browser. Then load the page with the debugger line:

var imagelist = document.getElementsByClassName("forum_image_class");
debugger;
imagelist.foreach(function(element){
    element.src = element.src.replace("/45/", "/90/");
}

The browser will stop on the debugger line. Type 'imagelist' into the console and hit enter to see its current value. It might be empty, in which case the getElementsByClassName isnt retrieving anything. Which might be happening for a few different reasons. Or the imagelist array might get populated but the replace() isnt working as expected. Is it possible for you to figure out which is happenng and report it here?

ALSO: be careful with .replace(). You have to escape certain characters with a backslash and you should know what those special characters are. In this case you may or may not need to escape the forward slashes.


问:
WPF - Why doesn't Microsoft supply a decent set of most-used controls ?
I've been playing with WPF for some months now, and I quite like it.
But one of the things I don't get is why MS doesn't put a little more effort in helping developers by supplying basic controls, and I need to get this off my chest :)

For example, I figure most applications somewhere will need to let you edit some properties - for configuration or whatever.
What would be the most used types in a proprety-grid editor ?

text

numbers (byte, float/double, int, etc)

colors

....etc.

So why isn't there even something as simple as a control to edit numbers ? Like a generic NumericUpDown control that allows you to type in numbers (no text, no pasting invalid input) or spin them up/down according to some given rules (decimal, floating point, min/maxvalue) ?
Why isn't there a generic colorpicker, so people get the same user-experience in every application ?
Why isn't there a standard implementation of a SearchTextBox, a BreadCrumb-control, or all these other standard control types users have gotten accustomed to the last 10 years ?

(..but at least they DID have the time to implement a generic splashscreen - because everyone knows that greatly increases user-productivity....)

The well-known ideal is always to give people the same user-experience over different applications. So even if some of those controls would be easy to make - it would be preferred to have one version over different applications.

I see people all over the internet trying to do the same stuff over and over again.
Okay, so MS started a WPF Toolkit project on Codeplex that tries to implement some controls, but only did so half-heartedly and is completely dead by now (last update of the roadmap dates back to Mar 21 2009).

The result of this is that a lot of people starting a WPF-project end up spending a lot of time on trying to figure out how to create some generic controls and get really frustrated.

Wasn't the mantra "Developers, developers, developers!" ..?

/Rant

答:
That's exactly what i thought at the beginning with WPF..

But afterall, a NumericUpDown is easily created with a cutom usercontrol, same for all the controls you will ever need, you can create it by yourself in (almost) no time, or grab some implementation googling around, and then you can still customize

I think they provided the very basic implementations for the UI elements and leaved all the custom stuff to developers and who need custom stuff, if they would have done a generic color picker, maybe it wouldn't have had all the functionalities that anyone would ever need


问:
How can I compile and load the pure CSS in ReactJS with webpack?
I am using a simple CSS based template for a ReactJS application with webpack module and not able to connect the CSS after compilation.

My webpack configuration looks like this...

var rucksack = require('rucksack-css')
var webpack = require('webpack')
var path = require('path')

module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    css : './public/assets/css/main.css',
    jsx: './index.js',
    html: './public/index.html',
    vendor: [
      'react',
      'react-dom',
      'react-redux',
      'react-router',
      'react-router-redux',
      'redux'
    ]
  },
  output: {
    path: path.join(__dirname, './static'),
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]'
      },
      {
        test: /\.css$/,
        include: /src/,
        loaders: [
          'style-loader',
          'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
          'postcss-loader'
        ]
      },
      {
        test: /\.css$/,
        exclude: /src/,
        loader: 'style!css'
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'react-hot',
          'babel-loader'
        ]
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  postcss: [
    rucksack({
      autoprefixer: true
    })
  ],
  plugins: [

    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
    })
  ],
  devServer: {
    contentBase: './src',
    hot: true
  }
}```

and relative path for my css file is 'src/public/assets/css/main.css'.
Is there any way to use pure traditional CSS without changing it to the react based CSS-in-JS ?

答: I keep the CSS as a seprate thing, i use gulp or grunt to make things easyer then include the files as your base html</p>

Body:
I am using a simple CSS based template for a ReactJS application with webpack module and not able to connect the CSS after compilation.

My webpack configuration looks like this...

var rucksack = require('rucksack-css')
var webpack = require('webpack')
var path = require('path')

module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    css : './public/assets/css/main.css',
    jsx: './index.js',
    html: './public/index.html',
    vendor: [
      'react',
      'react-dom',
      'react-redux',
      'react-router',
      'react-router-redux',
      'redux'
    ]
  },
  output: {
    path: path.join(__dirname, './static'),
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]'
      },
      {
        test: /\.css$/,
        include: /src/,
        loaders: [
          'style-loader',
          'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
          'postcss-loader'
        ]
      },
      {
        test: /\.css$/,
        exclude: /src/,
        loader: 'style!css'
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'react-hot',
          'babel-loader'
        ]
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  postcss: [
    rucksack({
      autoprefixer: true
    })
  ],
  plugins: [

    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
    })
  ],
  devServer: {
    contentBase: './src',
    hot: true
  }
}

and relative path for my css file is 'src/public/assets/css/main.css'.
Is there any way to use pure traditional CSS without changing it to the react based CSS-in-JS ?


问:
How to read a specific column from csv?
I'm relatively new to python.
I want to read a specific column from a csv file using the column name as my search data. Is there a way to do that ?</p>

答:
```<code>import csv
import sys

print "What column are you searching for? "
userinput = sys.stdin.readline().rstrip();

with open("my.csv", "rb") as f:
    reader = csv.reader(f)
    header = reader.next()
    try:
        pos = header.index(userinput)
        print "Values in column " + userinput + ": "
        for row in reader:
            print row[pos]
    except:
        print "column not found."
</code>```

Title: How to read a specific column from csv?


问:
Java inheritance - Two classes that use the same methods
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

```<code>public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}
</code>```

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

答:
One final solution would be to create a proxy abstract class AbstractMasterObject that implements MyInterface this would allow ObjectA and ObjectB to have full functionality of both MasterObject and MyInterface if they extend AbstractMasterObject

This can be done like so:

```<code>public abstract class AbstractMasterObject extends MasterObject implements MyInterface{

}
</code>```

Then you could declare your Objects like so:

```<code>AbstractMasterObject a = new ObjectA();
AbstractMasterObject b = new ObjectB();
</code>```

Body:
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

Body:
One final solution would be to create a proxy abstract class AbstractMasterObject that implements MyInterface this would allow ObjectA and ObjectB to have full functionality of both MasterObject and MyInterface if they extend AbstractMasterObject

This can be done like so:

public abstract class AbstractMasterObject extends MasterObject implements MyInterface{

}

Then you could declare your Objects like so:

AbstractMasterObject a = new ObjectA();
AbstractMasterObject b = new ObjectB();


问:
When @Builder and @NoArgsConstructor are set, variables do not get initialized
Let's say there is a class A:

```<code>@Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor
public class A extends X implements Y, Z {

    private B b = new B();

    private List<C> cList = new ArrayList<>();

}
</code>```

When I create an object by calling A a = new A();, no variables get initialized, so b and cList are null.

If @Builder annotation is removed, it works.

I didn't find any solution in project lombok documentation.

What should I do to get them initialized?

答:
As per https://github.com/rzwitserloot/lombok/pull/1429

"For now, the workaround is to type a no-args constructor and initialize the fields with the same expression in the constructor."

```<code>@Getter @Setter @Builder @AllArgsConstructor
public class A extends X implements Y, Z {

    private B b = new B();

    private List<C> cList = new ArrayList<>();

    public A() {
        b = new B();
        cList = new ArrayList<>();
    }

}
</code>```

Body:
Let's say there is a class A:

@Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor
public class A extends X implements Y, Z {

    private B b = new B();

    private List<C> cList = new ArrayList<>();

}

When I create an object by calling A a = new A();, no variables get initialized, so b and cList are null.

If @Builder annotation is removed, it works.

I didn't find any solution in project lombok documentation.

What should I do to get them initialized?

Body:
As per https://github.com/rzwitserloot/lombok/pull/1429

"For now, the workaround is to type a no-args constructor and initialize the fields with the same expression in the constructor."

@Getter @Setter @Builder @AllArgsConstructor
public class A extends X implements Y, Z {

    private B b = new B();

    private List<C> cList = new ArrayList<>();

    public A() {
        b = new B();
        cList = new ArrayList<>();
    }

}


问:
Rotate a string in C
I am trying to shift a string both left and right given the number of positions to shift the string by.

This is what I wrote so far but it does not work.

```<code>void Shift(char* string, shift)
{
    int length = strlen(string)-1;
    int i;
    char *buff;
    buff = malloc((sizeof(char) *shift) + 1);
    strncpy(buff, string, shift);
    buff[shift] = '/0';
    while (string[i + shift] != '/0')
        string[i++] = string[i + shift];
    strcat(string, buff);
}
</code>```

How can I fix this?
This should be the example:
shift = 1

HELLO ->
OHELL

答:
My solution rotates the string in place using O(1) storage:

```<code>#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void rotleftmem(void *p, size_t len, size_t lshift)
{
    unsigned char *d;
    size_t start;
    size_t dx, sx;
    size_t todo;
    unsigned char x;

    if (!len)
        return;
    lshift %= len;
    if (!lshift)
        return;

    d = p;
    todo = len;
    for (start = 0; todo; start++) {
        x = d[start];
        dx = start;
        while (1) {
            todo--;
            sx = dx + lshift;
            if (sx >= len || sx < dx /*overflow*/)
                sx -= len;
            if (sx == start) {
                d[dx] = x;
                break;
            }
            d[dx] = d[sx];
            dx = sx;
        }
    }
}

void *rotatemem(void *p, size_t len, ssize_t rshift)
{
    if (len) {
        size_t lshift = rshift < 0 ? -rshift : len - rshift % len;

        rotleftmem(p, len, lshift);
    }
    return p;
}

char *rotatestr(char *s, ssize_t rshift)
{
    return rotatemem(s, strlen(s), rshift);
}

int main(int argc, char *argv[])
{
    ssize_t rshift;
    char *s;

    if (argc != 3) {
        fprintf(stderr,
                "usage: %s N STR\n"
                "Rotate STR right by N or left by -N\n",
                argv[0]);
        return 2;
    }

    rshift = strtol(argv[1], NULL, 10);
    s = argv[2];
    printf("%s\n", rotatestr(s, rshift));
    return 0;
}
</code>```

The guts of the code is in function rotleftmem, which rotates a block of memory of specified length left by a specified, unsigned "left-shift" value. rotatemem is a wrapper around rotleftmem that rotates in either direction; a negative shift value rotates left and a positive shift value rotates right; the signed shift value is converted to a positive "left-shift" value. rotatestr is a wrapper around rotatemem that takes a pointer to a null-terminated string instead of a pointer to void plus a length. Both rotatestr and rotatemem return the original pointer.

For rotleftmem, if the block length (len) is non-zero, the "left-shift" value (lshift) is reduced modulo len. If either of len or the  (reduced) lshift value is 0, the function does nothing. Otherwise, the outer loop will iterate GCD(len, lshift) times (where GCD(a, b) is the greatest common divisor of a and b). For each iteration of the outer loop, the inner loop will iterate len / GCD(len, lshift) times, so the total number of iterations of the inner loop is len. The time complexity is O(n), where n is the length of the block.

Title: Rotate a string in C

Body:
I am trying to shift a string both left and right given the number of positions to shift the string by.

This is what I wrote so far but it does not work.

void Shift(char* string, shift)
{
    int length = strlen(string)-1;
    int i;
    char *buff;
    buff = malloc((sizeof(char) *shift) + 1);
    strncpy(buff, string, shift);
    buff[shift] = '/0';
    while (string[i + shift] != '/0')
        string[i++] = string[i + shift];
    strcat(string, buff);
}

How can I fix this?
This should be the example:
shift = 1

HELLO ->
OHELL

Body:
My solution rotates the string in place using O(1) storage:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void rotleftmem(void *p, size_t len, size_t lshift)
{
    unsigned char *d;
    size_t start;
    size_t dx, sx;
    size_t todo;
    unsigned char x;

    if (!len)
        return;
    lshift %= len;
    if (!lshift)
        return;

    d = p;
    todo = len;
    for (start = 0; todo; start++) {
        x = d[start];
        dx = start;
        while (1) {
            todo--;
            sx = dx + lshift;
            if (sx >= len || sx < dx /*overflow*/)
                sx -= len;
            if (sx == start) {
                d[dx] = x;
                break;
            }
            d[dx] = d[sx];
            dx = sx;
        }
    }
}

void *rotatemem(void *p, size_t len, ssize_t rshift)
{
    if (len) {
        size_t lshift = rshift < 0 ? -rshift : len - rshift % len;

        rotleftmem(p, len, lshift);
    }
    return p;
}

char *rotatestr(char *s, ssize_t rshift)
{
    return rotatemem(s, strlen(s), rshift);
}

int main(int argc, char *argv[])
{
    ssize_t rshift;
    char *s;

    if (argc != 3) {
        fprintf(stderr,
                "usage: %s N STR\n"
                "Rotate STR right by N or left by -N\n",
                argv[0]);
        return 2;
    }

    rshift = strtol(argv[1], NULL, 10);
    s = argv[2];
    printf("%s\n", rotatestr(s, rshift));
    return 0;
}

The guts of the code is in function rotleftmem, which rotates a block of memory of specified length left by a specified, unsigned "left-shift" value. rotatemem is a wrapper around rotleftmem that rotates in either direction; a negative shift value rotates left and a positive shift value rotates right; the signed shift value is converted to a positive "left-shift" value. rotatestr is a wrapper around rotatemem that takes a pointer to a null-terminated string instead of a pointer to void plus a length. Both rotatestr and rotatemem return the original pointer.

For rotleftmem, if the block length (len) is non-zero, the "left-shift" value (lshift) is reduced modulo len. If either of len or the  (reduced) lshift value is 0, the function does nothing. Otherwise, the outer loop will iterate GCD(len, lshift) times (where GCD(a, b) is the greatest common divisor of a and b). For each iteration of the outer loop, the inner loop will iterate len / GCD(len, lshift) times, so the total number of iterations of the inner loop is len. The time complexity is O(n), where n is the length of the block.


问:
Spark Job estimated overhead on smaller datasets
Are there any rules of thumb - for when the data size is sufficient to offset the overhead that spark processing requires?

I'm working on between 1 and 10 million records. Each record carries 5 Long ids; and a small (less than 5000 characters) amount of text.

The work load is to create reports - so filter; group and aggregate. In most cases; the top level aggregation will be over all the records; so at some point in the report generation - I don't have a good partition key to work with.

Aware the question is low on specifics; but does this jump off the page that I'm doing lots of silly things in Spark? Or would spark job orchestration be likely to add that kind of overhead; and I would be better off looking to only use Spark on larger datasets?

Thanks

答:
The most informative piece of docs I came across was

Spark can efficiently support tasks as short as 200 ms

https://spark.apache.org/docs/2.1.0/tuning.html


问:
Renaming files in a folder to sequential numbers
I want to rename the files in a directory to sequential numbers. Based on creation date of the files.

For Example sadf.jpg to 0001.jpg, wrjr3.jpg to 0002.jpg and so on, the number of leading zeroes depending on the total amount of files (no need for extra zeroes if not needed).

答:
On OSX, install the rename script from Homebrew:

```<code>brew install rename
</code>```

Then you can do it really ridiculously easily:

```<code>rename -e 's/.*/$N.jpg/' *.jpg
</code>```

Or to add a nice prefix:

```<code>rename -e 's/.*/photo-$N.jpg/' *.jpg
</code>```

Body:
On OSX, install the rename script from Homebrew:

brew install rename

Then you can do it really ridiculously easily:

rename -e 's/.*/$N.jpg/' *.jpg

Or to add a nice prefix:

rename -e 's/.*/photo-$N.jpg/' *.jpg


问:
Oracle SQL - Combine values in the same column in one column in the result set from multiple table
I would liek to know how to concatnate several records from the same column from two different table in one. for instance below are my tables:

NOTE TABLE:

```<code>INVOICE NOTES
1000    REPLACE PUMP
1000    REPLACE OIL
1000    REPLACE FILTER
1111    WO# 123
1111    REPLACE GASKET
1234    REPLACE OIL
</code>```

INVOICE TABLE:

```<code>INVOICE AMOUNT
1000    100
1111    50
1234    20
</code>```

I can run this query and the result:

```<code>SELECT INV.INVOICE, INV.AMOUNT FROM INVOICE INV
INNER JOIN NOTES ON INV.INVOICE = NOTES.INVOICE
</code>```

but I would like to combine the Notes for each invoice in one column in my result set. For examples my result should look like this

```<code>INVOICE  AMOUNT     NOTES
1000     100        REPLACE PUMP, REPLACE OIL, REPLACE FILTER
1111     50         WO# 123,REPLACE GASKET
1234     20         REPLACE OIL
</code>```

答:
documentation - listagg

query

```<code>with inv_notes as
(select 1000 as INVOICE, 'REPLACE PUMP' as notes from dual union all
select 1000, 'REPLACE PUMP' from dual union all
select 1000, 'REPLACE OIL' from dual union all
select 1000, 'REPLACE FILTER' from dual union all
select 1111, 'WO# 123' from dual union all
select 1111, 'REPLACE GASKET' from dual union all
select 1234, 'REPLACE OIL' from dual
)
,
inv_amount as (
select 1000 as INVOICE, 100 AMOUNT from dual union all
select 1111, 50 from dual union all
select 1234, 20 from dual)
select a.invoice, a.amount, listagg(n.notes, ',') WITHIN GROUP (ORDER BY a.invoice, a.amount) notes
from inv_notes n
 inner join inv_amount a on n.invoice = a.invoice
group by a.invoice, a.amount
</code>```

result

```<code>1   1000    100 REPLACE FILTER,REPLACE OIL,REPLACE PUMP,REPLACE PUMP
2   1111    50  REPLACE GASKET,WO# 123
3   1234    20  REPLACE OIL
</code>```

Body:
I would liek to know how to concatnate several records from the same column from two different table in one. for instance below are my tables:

NOTE TABLE:

INVOICE NOTES
1000    REPLACE PUMP
1000    REPLACE OIL
1000    REPLACE FILTER
1111    WO# 123
1111    REPLACE GASKET
1234    REPLACE OIL

INVOICE TABLE:

INVOICE AMOUNT
1000    100
1111    50
1234    20

I can run this query and the result:

SELECT INV.INVOICE, INV.AMOUNT FROM INVOICE INV
INNER JOIN NOTES ON INV.INVOICE = NOTES.INVOICE

but I would like to combine the Notes for each invoice in one column in my result set. For examples my result should look like this

INVOICE  AMOUNT     NOTES
1000     100        REPLACE PUMP, REPLACE OIL, REPLACE FILTER
1111     50         WO# 123,REPLACE GASKET
1234     20         REPLACE OIL

Body:
documentation - listagg

query

with inv_notes as
(select 1000 as INVOICE, 'REPLACE PUMP' as notes from dual union all
select 1000, 'REPLACE PUMP' from dual union all
select 1000, 'REPLACE OIL' from dual union all
select 1000, 'REPLACE FILTER' from dual union all
select 1111, 'WO# 123' from dual union all
select 1111, 'REPLACE GASKET' from dual union all
select 1234, 'REPLACE OIL' from dual
)
,
inv_amount as (
select 1000 as INVOICE, 100 AMOUNT from dual union all
select 1111, 50 from dual union all
select 1234, 20 from dual)
select a.invoice, a.amount, listagg(n.notes, ',') WITHIN GROUP (ORDER BY a.invoice, a.amount) notes
from inv_notes n
 inner join inv_amount a on n.invoice = a.invoice
group by a.invoice, a.amount

result

1   1000    100 REPLACE FILTER,REPLACE OIL,REPLACE PUMP,REPLACE PUMP
2   1111    50  REPLACE GASKET,WO# 123
3   1234    20  REPLACE OIL


问:
Array of filepath strings to file tree JSON (compatible with react-sortable-tree)
How do I build a JSON object thats is compatible with react-sortable-tree (every nested object has title, children) to render the file tree.

For example, I have this array of filepaths.

```<code>var filePaths = [
   "Diagnoses/Endocrine disorders/Thyroid disorders/Congenital hypothyroidism",
   "Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism",
   "Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism/Postsurgical hypothyroidism"
];
</code>```

I would like a JSON Object like this.

```<code>var treeData = [
  {
    title: 'Diagnoses',
    children: [{
      title: 'Endocrine disorders',
      children: [{
        title: 'Thyroid disorders',
        children: [
        {
          title: 'Congential hypothyroidism'
        },
        {
          title: 'Acquired hypothyroidism',
          children: [{
            title: 'Postsurgical hypothyroidism'
          }]
        }
        ]
      }]
    }]
  }
];
</code>```

Edit: I tried this but after the first iteration, I'm overwriting the children property of the whole tree. I tried a couple of checks to stop that but they didn't quite pan out.

```<code>var hierarchy = filePaths.reduce(function(hier,path){
    var x = hier;
    path.split('/').forEach(function(item, index, array){
        if(x[0].title != item){
            x[0].title = item;
        }
        // console.log(index, array.length)
        if (index != array.length - 1 && !x[0].children){
          x[0].children = [{
            title: ''
          }];
        }
        x = x[0].children;
    });

    return hier;
}, [{title: ''}]);
</code>```

答:
I think the main issue with your code is that you're not walking down the tree to insert nodes at the right place.

I took a two-step approach, since I didn't like the idea of iterating through a list of children each time when a dictionary lookup would be faster.

See the comments in the code for an explanation of what's going on:

var filePaths = [
  "Diagnoses/Endocrine disorders/Thyroid disorders/Congenital hypothyroidism",
  "Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism",
  "Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism/Postsurgical hypothyroidism"
];

// Step 1:
// Convert the flat list of paths to nested dictionaries.
// (This representation is more efficient for the initial construction.)
// Basic algorithm:
// 1. Split each path into segments.
// 2. Walk down the tree using the segments as keys.
// 3. Create new nodes as necessary.

var tree = {};
filePaths.forEach(function (path) {
  var currentNode = tree;
  path.split('/').forEach(function (segment) {
    if (currentNode[segment] === undefined) {
      currentNode[segment] = {};
    }
    currentNode = currentNode[segment];
  });
});

// Now we have a tree represented as nested dictionaries.
console.log(JSON.stringify(tree, null, 2));

// {
//   "Diagnoses": {
//     "Endocrine disorders": {
//       "Thyroid disorders": {
//         "Congenital hypothyroidism": {},
//         "Acquired hypothyroidism": {
//           "Postsurgical hypothyroidism": {}
//         }
//       }
//     }
//   }
// }

// Step 2:
// Convert the nested dictionaries into lists of children.
// This is the format required for react-sortable-tree.
// Basic algorithm:
// 1. Each dictionary becomes an array of children.
// 2. Each element of the array has a title and a list of children.
// 3. We recurse for the list of children (if we have children).
function toTreeData(tree) {
  return Object.keys(tree).map(function (title) {
    var o = { title: title };
    if (Object.keys(tree[title]).length > 0) {
      o.children = toTreeData(tree[title]);
    }

    return o;
  });
}

console.log(JSON.stringify(toTreeData(tree), null, 2));

// [
//   {
//     "title": "Diagnoses",
//     "children": [
//       {
//         "title": "Endocrine disorders",
//         "children": [
//           {
//             "title": "Thyroid disorders",
//             "children": [
//               {
//                 "title": "Congenital hypothyroidism"
//               },
//               {
//                 "title": "Acquired hypothyroidism",
//                 "children": [
//                   {
//                     "title": "Postsurgical hypothyroidism"
//                   }
//                 ]
//               }
//             ]
//           }
//         ]
//       }
//     ]
//   }
// ]```

Body:
How do I build a JSON object thats is compatible with react-sortable-tree (every nested object has title, children) to render the file tree.

For example, I have this array of filepaths.

var filePaths = [
   "Diagnoses/Endocrine disorders/Thyroid disorders/Congenital hypothyroidism",
   "Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism",
   "Diagnoses/Endocrine disorders/Thyroid disorders/Acquired hypothyroidism/Postsurgical hypothyroidism"
];

I would like a JSON Object like this.

var treeData = [
  {
    title: 'Diagnoses',
    children: [{
      title: 'Endocrine disorders',
      children: [{
        title: 'Thyroid disorders',
        children: [
        {
          title: 'Congential hypothyroidism'
        },
        {
          title: 'Acquired hypothyroidism',
          children: [{
            title: 'Postsurgical hypothyroidism'
          }]
        }
        ]
      }]
    }]
  }
];

Edit: I tried this but after the first iteration, I'm overwriting the children property of the whole tree. I tried a couple of checks to stop that but they didn't quite pan out.

var hierarchy = filePaths.reduce(function(hier,path){
    var x = hier;
    path.split('/').forEach(function(item, index, array){
        if(x[0].title != item){
            x[0].title = item;
        }
        // console.log(index, array.length)
        if (index != array.length - 1 && !x[0].children){
          x[0].children = [{
            title: ''
          }];
        }
        x = x[0].children;
    });

    return hier;
}, [{title: ''}]);


问:
I'm getting Haskell "parse error (possibly incorrect indentation or mismatched brackets)" and I cannot see what's wrong
Here is the code where I'm actually having the problem:

```<code>-----Function to test the postcondition----------------------------------
testPost :: Name -> Int -> [a] -> [b] -> IO ()
testPost _ _ [] [] = putStrLn "Test finished correctly"
testPost f_name n (t:ts) (o:os) = if (not aux_bool) then
                                         do putStr ("Failed on function " ++ (nameBase f_name) ++ " with inputs ")
                                            print ts
                                            putStr " and output "
                                            print os
                                            putStrLn ""
                                  else do
                                  do testPost f_name n ts os
                                      where aux_bool = post f_name n t o
</code>```

The compiler just complains about the first line:

```<code>C:\Users\pegartillo\Desktop\TFG\CaseGenerator\src\UUTReader.hs:205:1:
    parse error (possibly incorrect indentation or mismatched brackets)
</code>```

I am using the template haskell library, that's why it appears Name data type.

答:
To get it to compile, at least:

```<code>import Control.Monad (when)

newtype Name = Name { nameBase::String}

post _ _ _ _ = True

-----Function to test the postcondition----------------------------------
testPost :: (Show a,Show b) => Name -> Int -> [a] -> [b] -> IO ()
testPost _ _ [] [] = putStrLn "Test finished correctly"
testPost f_name n (t:ts) (o:os) = do
  when (not aux_bool) $ do
    putStr ("Failed on function " ++ (nameBase f_name) ++ " with inputs ")
    print ts
    putStr " and output "
    print os
    putStrLn ""
  testPost f_name n ts os
  where
    aux_bool = post f_name n t o
</code>```

The layout with if-then-else and do can get tricky. Personally, I try to avoid mixing them if I can. Something that could have helped is pulling out the bodies of each block into their own expressions to simplify things when trying to debug.

Body:
Here is the code where I'm actually having the problem:

-----Function to test the postcondition----------------------------------
testPost :: Name -> Int -> [a] -> [b] -> IO ()
testPost _ _ [] [] = putStrLn "Test finished correctly"
testPost f_name n (t:ts) (o:os) = if (not aux_bool) then
                                         do putStr ("Failed on function " ++ (nameBase f_name) ++ " with inputs ")
                                            print ts
                                            putStr " and output "
                                            print os
                                            putStrLn ""
                                  else do
                                  do testPost f_name n ts os
                                      where aux_bool = post f_name n t o

The compiler just complains about the first line:

C:\Users\pegartillo\Desktop\TFG\CaseGenerator\src\UUTReader.hs:205:1:
    parse error (possibly incorrect indentation or mismatched brackets)

I am using the template haskell library, that's why it appears Name data type.

Body:
To get it to compile, at least:

import Control.Monad (when)

newtype Name = Name { nameBase::String}

post _ _ _ _ = True

-----Function to test the postcondition----------------------------------
testPost :: (Show a,Show b) => Name -> Int -> [a] -> [b] -> IO ()
testPost _ _ [] [] = putStrLn "Test finished correctly"
testPost f_name n (t:ts) (o:os) = do
  when (not aux_bool) $ do
    putStr ("Failed on function " ++ (nameBase f_name) ++ " with inputs ")
    print ts
    putStr " and output "
    print os
    putStrLn ""
  testPost f_name n ts os
  where
    aux_bool = post f_name n t o

The layout with if-then-else and do can get tricky. Personally, I try to avoid mixing them if I can. Something that could have helped is pulling out the bodies of each block into their own expressions to simplify things when trying to debug.


问:
Vertically position material icon besides paragraph text
I have a p element, besides which I am placing a material icon via font method.

Both are inline-block to display side by side, but I am having trouble moving the icon vertically without breaking neighboring layout.

I have tried wrapping the icon in a div, span, and playing with making its container positioned relatively/absolutely but cannot seem to make it behave.

Simplified example for my project:

html

```<code><div class="card-heading">
  <p>
    my title
  </p>
  <div class="icon-holder">
    <i class="material-icons">camera</i>
  </div>
</div>
</code>```

scss

```<code>.card-heading {
  p {
    display: inline-block;
  }

  .icon-holder {
    display: inline-block;

    i {
      padding-top: 6px;
    }
  }
}
</code>```

Example codepen illustrating issue https://codepen.io/joshuaohana/pen/dRqgye

In this example, I am trying to move the icon down by 6px, but instead of moves both the p and the icon

答:
Use vertical-align to center the icon.

.card-heading p {
  display: inline-block;
}

.card-heading .icon-holder {
  display: inline-block;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

<div class="card-heading">
  <p>
    my title
  </p>
  <div class="icon-holder">
    <i class="material-icons">camera</i>
  </div>
</div></code>```

Body:
I have a p element, besides which I am placing a material icon via font method.

Both are inline-block to display side by side, but I am having trouble moving the icon vertically without breaking neighboring layout.

I have tried wrapping the icon in a div, span, and playing with making its container positioned relatively/absolutely but cannot seem to make it behave.

Simplified example for my project:

html

    my title

    camera

scss

.card-heading {
  p {
    display: inline-block;
  }

  .icon-holder {
    display: inline-block;

    i {
      padding-top: 6px;
    }
  }
}

Example codepen illustrating issue https://codepen.io/joshuaohana/pen/dRqgye

In this example, I am trying to move the icon down by 6px, but instead of moves both the p and the icon

Body:
Use vertical-align to center the icon.

.card-heading p {
  display: inline-block;
}

.card-heading .icon-holder {
  display: inline-block;
  vertical-align: middle;
}

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

<div class="card-heading">
  <p>
    my title
  </p>
  <div class="icon-holder">
    <i class="material-icons">camera</i>
  </div>
</div>


问:
How to Implement auto round off to even number in a input field with Angular 4
I've an input field in which any even number should be converted to nearest lower odd number. Plus, there should be 2 buttons to increment and decrement the value by 2.

Ex. If I enter 5, then number should be converted to 4 and should be replaced in the input field. I don't have any code so please don't down rank the question.

Any help would be appreciated. Thanks!

答:
You must be looking for something like this:

In your xyz.component.html

```<code><div class="col-lg-12">
    <button class="btn" (click)="quantity = quantity - 2"[disabled]="quantity == 0">minus</button>
    <input type="number" [value]="quantity" #quantitySelect (keyup)="roundOffQuantity(quantitySelect.value)" min="0" />
    <button class="btn" (click)="quantity = quantity + 2">plus</button>
</div>
</code>```

In the xyz.component.ts

```<code>roundOffQuantity(value: number) {
    if (value % 2 != 0) {
        this.quantity = (2 * (Math.round(value / 2 - 0.01)));
    }
}
</code>```

Body:
You must be looking for something like this:

In your xyz.component.html

<div class="col-lg-12">
    <button class="btn" (click)="quantity = quantity - 2"[disabled]="quantity == 0">minus</button>
    <input type="number" [value]="quantity" #quantitySelect (keyup)="roundOffQuantity(quantitySelect.value)" min="0" />
    <button class="btn" (click)="quantity = quantity + 2">plus</button>
</div>

In the xyz.component.ts

roundOffQuantity(value: number) {
    if (value % 2 != 0) {
        this.quantity = (2 * (Math.round(value / 2 - 0.01)));
    }
}


问:
I need help figuring out the correct syntax for the watson-developer-cloud Node.js function to insert a document into Watson's Discovery service
I'm trying to insert JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK.  This is the relevant code:

```<code>var DiscoveryV1=require('watson-developer-cloud/discovery/v1');
var discovery=new DiscoveryV1(credentials);

let doc=aSmallValidJsonObject;
let parms={
  environment_id: envID,
  collection_id: collID,
  configuration_id: confID,
  file: {
        value: new Buffer(JSON.stringify(doc)),
        options:{
          contentType:'application/json',
          "Content-Type":'application/json' //just to be sure
        }
     }
  };
discovery.addDocument(parms,
  function(err,results)
    {
    if (err) {...
</code>```

The error being returned from this call is

```<code>"Error: Request must specify either a "metadata" or "file" part"
</code>```

I have also tried making parms this way:

```<code>let parms={
  environment_id: envID,
  collection_id: collID,
  configuration_id: confID,
  metadata:{"Content-Type":"application/json"},
  file:new Buffer(JSON.stringify(doc))
  };
</code>```

The error I get in this case is

```<code>[TypeError: source.on is not a function]
</code>```

(I traced this error down to line 33 in the library delayed_stream.js)

If I make the metadata field a string (i.e., enclose the value in single quotes) in the above parms, I get this error:

```<code>Error: The Media Type [application/octet-stream] of the input document is not supported. Auto correction was attempted, but the auto detected media type [text/plain] is also not supported. Supported Media Types are: application/json, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/pdf, text/html, application/xhtml+xml
</code>```

Can someone tell me what the correct syntax is for this function?

答:
Require the FileSystem (fs) library to send the document correctly, if you want to send one doc inside your Computer HD.
The error seems like the header inside your options isn't recognize. Try the official example or my example:

The Official API Reference show one example to addDocument like:

```<code>var DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
var fs = require('fs');

var discovery = new DiscoveryV1({
  username: '{username}',
  password: '{password}',
  version_date: '2017-06-25'
});

var file = fs.readFileSync('{/path/to/file}');

discovery.addDocument(('{environment_id}', '{collection_id}', file),
function(error, data) {
  console.log(JSON.stringify(data, null, 2));
});
</code>```

With your example:

```<code>discovery.addDocument({
    environment_id: yourEnvId,
    collection_id: yourCollId,
    metadata:'{"Content-Type":"application/json"}',
    file: Buffer.from(doc)
}, function(err, data) {
    if (err) {
        return next(err);
    } else {
        return res.json(data)
      }
});
</code>```

Body:
I'm trying to insert JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK.  This is the relevant code:

var DiscoveryV1=require('watson-developer-cloud/discovery/v1');
var discovery=new DiscoveryV1(credentials);

let doc=aSmallValidJsonObject;
let parms={
  environment_id: envID,
  collection_id: collID,
  configuration_id: confID,
  file: {
        value: new Buffer(JSON.stringify(doc)),
        options:{
          contentType:'application/json',
          "Content-Type":'application/json' //just to be sure
        }
     }
  };
discovery.addDocument(parms,
  function(err,results)
    {
    if (err) {...

The error being returned from this call is

"Error: Request must specify either a "metadata" or "file" part"

I have also tried making parms this way:

let parms={
  environment_id: envID,
  collection_id: collID,
  configuration_id: confID,
  metadata:{"Content-Type":"application/json"},
  file:new Buffer(JSON.stringify(doc))
  };

The error I get in this case is

[TypeError: source.on is not a function]

(I traced this error down to line 33 in the library delayed_stream.js)

If I make the metadata field a string (i.e., enclose the value in single quotes) in the above parms, I get this error:

Error: The Media Type [application/octet-stream] of the input document is not supported. Auto correction was attempted, but the auto detected media type [text/plain] is also not supported. Supported Media Types are: application/json, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/pdf, text/html, application/xhtml+xml

Can someone tell me what the correct syntax is for this function?

Body:
Require the FileSystem (fs) library to send the document correctly, if you want to send one doc inside your Computer HD.
The error seems like the header inside your options isn't recognize. Try the official example or my example:

The Official API Reference show one example to addDocument like:

var DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
var fs = require('fs');

var discovery = new DiscoveryV1({
  username: '{username}',
  password: '{password}',
  version_date: '2017-06-25'
});

var file = fs.readFileSync('{/path/to/file}');

discovery.addDocument(('{environment_id}', '{collection_id}', file),
function(error, data) {
  console.log(JSON.stringify(data, null, 2));
});

With your example:

discovery.addDocument({
    environment_id: yourEnvId,
    collection_id: yourCollId,
    metadata:'{"Content-Type":"application/json"}',
    file: Buffer.from(doc)
}, function(err, data) {
    if (err) {
        return next(err);
    } else {
        return res.json(data)
      }
});


问:
How to find a bug in my date arithmetic shell script?
I wrote below piece of code to calculate the date after a given date:

```<code>date=$DATE_FINAL
declare -a  max_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
eval $(echo $date|sed 's!\(....\)\(..\)\(..\)!year=\1;month=\2;day=\3!')
(( year4=year%4 ))
(( year100=year%100 ))
(( year400=year%400 ))
if [ \( $year4 -eq 0 -a \
        $year100 -ne 0 \) -o \
     $year400 -eq 0 ]
then
declare -a  max_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
fi
day=$((day+1))
if [ $day -gt ${max_month[$month]} ] >| /wload/baot/home/baoted9/logs_bde27_conversion_1/ataa_display.logs 2>&1
then
  day=1
  month=$((month+1))
  if [ $month -gt 12 ]
  then
    year=$((year+1))
    month=1
  fi
fi
if [ $month -eq "08" ] ||  [ $month -eq "09" ]
then
future_date_final=$(echo $year"$month"$day)
else
future_date_final=$(printf "%4.4d%2.2d%2.2d" $year $month $day)
fi
echo "this is your final business date $future_date_final"
</code>```

It calculates the date correctly however throws an error at the end of the code as below -

```<code>line 79: 08: value too great for base (error token is "08")
</code>```

It just looks too ugly, not sure how to remove it as otherwise code is working fine, tried redirecting it to a log file still appearing.
Also, I am facing issue with below code for a plain cd command with code highlighted in red -

```<code>echo "pset  date $Param_date_1"
cd /wload/baot/home/baotasa0/sandboxes_finance/ext_ukba_bde/pset >| /wload/baot/home/baoted9/logs_bde27_conversion_1/at_display.logs 2>&1
sh UKBA_publish.sh UKBA $Param_date_1 3 >| /wload/baot/home/baoted9/logs_bde27_conversion_1/ate_display.logs 2>&1
</code>```

Error is -

```<code>./auto2.sh: line 190: syntax error: unexpected end of file
</code>```

答:
The problem is, that if you're using $((val+1)) where $val is beginning with a 0, then bash isn't operating on decimal base but on octal base. Since 08 isn't a valid number in octal base, it complains.

You can force decimal representation by writing

```<code>$((10#$val+1))
</code>```

Please note, that by doing so, any preceding zeros are removed. If you need to have a representation with preceding zero, just use

```<code>val=$(printf '%02d' $((10#$val+1)))
</code>```

For reference, see the bash manual:

Constants with a leading 0 are interpreted as octal numbers. A leading ‘0x’ or ‘0X’ denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, ‘@’, and ‘_’, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.

P.S.: This is a very good article about falsehoods programmers believe about time I had to read myself. If possible, try to use date -d instead of doing manual date arithmetic. You can use for instance date -d "+5 days" +%d.%m.%Y to get the date in five days.

Body:
I wrote below piece of code to calculate the date after a given date:

date=$DATE_FINAL
declare -a  max_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
eval $(echo $date|sed 's!\(....\)\(..\)\(..\)!year=\1;month=\2;day=\3!')
(( year4=year%4 ))
(( year100=year%100 ))
(( year400=year%400 ))
if [ \( $year4 -eq 0 -a \
        $year100 -ne 0 \) -o \
     $year400 -eq 0 ]
then
declare -a  max_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
fi
day=$((day+1))
if [ $day -gt ${max_month[$month]} ] >| /wload/baot/home/baoted9/logs_bde27_conversion_1/ataa_display.logs 2>&1
then
  day=1
  month=$((month+1))
  if [ $month -gt 12 ]
  then
    year=$((year+1))
    month=1
  fi
fi
if [ $month -eq "08" ] ||  [ $month -eq "09" ]
then
future_date_final=$(echo $year"$month"$day)
else
future_date_final=$(printf "%4.4d%2.2d%2.2d" $year $month $day)
fi
echo "this is your final business date $future_date_final"

It calculates the date correctly however throws an error at the end of the code as below -

line 79: 08: value too great for base (error token is "08")

It just looks too ugly, not sure how to remove it as otherwise code is working fine, tried redirecting it to a log file still appearing.
Also, I am facing issue with below code for a plain cd command with code highlighted in red -

echo "pset  date $Param_date_1"
cd /wload/baot/home/baotasa0/sandboxes_finance/ext_ukba_bde/pset >| /wload/baot/home/baoted9/logs_bde27_conversion_1/at_display.logs 2>&1
sh UKBA_publish.sh UKBA $Param_date_1 3 >| /wload/baot/home/baoted9/logs_bde27_conversion_1/ate_display.logs 2>&1

Error is -

./auto2.sh: line 190: syntax error: unexpected end of file

Body:
The problem is, that if you're using $((val+1)) where $val is beginning with a 0, then bash isn't operating on decimal base but on octal base. Since 08 isn't a valid number in octal base, it complains.

You can force decimal representation by writing

$((10#$val+1))

Please note, that by doing so, any preceding zeros are removed. If you need to have a representation with preceding zero, just use

val=$(printf '%02d' $((10#$val+1)))

For reference, see the bash manual:

Constants with a leading 0 are interpreted as octal numbers. A leading ‘0x’ or ‘0X’ denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, ‘@’, and ‘_’, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.

P.S.: This is a very good article about falsehoods programmers believe about time I had to read myself. If possible, try to use date -d instead of doing manual date arithmetic. You can use for instance date -d "+5 days" +%d.%m.%Y to get the date in five days.