问:
Column Sorting with PROC Transpose in SAS
I am using below mentioned code to get the columns sorted dynamically after proc transpose. I have gone a lot of solutions for this solution. But now I am getting an error if I run

```<code>data work.AB ;
input name $ class $ dt $ gpa $;
datalines;
JOHN 1 201607 C-
JOHN 1 201608 C+
JOHN 1 201702 B-
JOHN 2 201608 A
NICK 1 201608 A
NICK 1 201707 A
MIKE 2 201608 B
MIKE 2 201607 B
MIKE 2 201707 B+
MIKE 2 201702 B
BOB 3 201702 D
BOB 3 201607 C
BOB 3 201707 C
;
proc sort data=work.AB;
by NAME ClASS dt;
run;

PROC TRANSPOSE DATA = AB OUT = ABC(drop=_name_) ;
BY nAME cLASS;
VAR GPA;
ID dt;
RUN ;

proc sql ;
create table test as
select name into : list separated by ' '
from dictionary.columns
where libname='WORK' and memname='ABC'
order by input(substr(name,anydigit(name)),best32.)
;
quit;

%put &list;

data want;
retain &list;
set ABC;
run;
</code>```

Error that I get is

```<code>22 GOPTIONS ACCESSIBLE;
WARNING: Apparent symbolic reference LIST not resolved.
23 %put &list;
&list

24 data want;
25 retain &list;
_
22
200
WARNING: Apparent symbolic reference LIST not resolved.

ERROR 22-322: Syntax error, expecting one of the following: a name, ;, _ALL_, _CHARACTER_, _CHAR_, _NUMERIC_.
ERROR 200-322: The symbol is not recognized and will be ignored.

26 set ABC;
27 run;
</code>```

Kindly suggest.

答:
You cannot put the values from the same SELECT statement into both a dataset and macro variables. Remove the create table test as from your SQL code.

You also might want to suppress some of the warnings by changing the query to:

```<code>proc sql noprint ;
select case when (not anydigit(name)) then -1
            else input(substr(name,anydigit(name)),?32.)
       end as order
     , name
  into :list
     , :list separated by ' '
from dictionary.columns
where libname='WORK' and memname='ABC'
order by 1
;
quit;

%put &list;
</code>```

Body:
I am using below mentioned code to get the columns sorted dynamically after proc transpose. I have gone a lot of solutions for this solution. But now I am getting an error if I run

data work.AB ;
input name $ class $ dt $ gpa $;
datalines;
JOHN 1 201607 C-
JOHN 1 201608 C+
JOHN 1 201702 B-
JOHN 2 201608 A
NICK 1 201608 A
NICK 1 201707 A
MIKE 2 201608 B
MIKE 2 201607 B
MIKE 2 201707 B+
MIKE 2 201702 B
BOB 3 201702 D
BOB 3 201607 C
BOB 3 201707 C
;
proc sort data=work.AB;
by NAME ClASS dt;
run;

PROC TRANSPOSE DATA = AB OUT = ABC(drop=_name_) ;
BY nAME cLASS;
VAR GPA;
ID dt;
RUN ;

proc sql ;
create table test as
select name into : list separated by ' '
from dictionary.columns
where libname='WORK' and memname='ABC'
order by input(substr(name,anydigit(name)),best32.)
;
quit;

%put &list;

data want;
retain &list;
set ABC;
run;

Error that I get is

22 GOPTIONS ACCESSIBLE;
WARNING: Apparent symbolic reference LIST not resolved.
23 %put &list;
&list

24 data want;
25 retain &list;
_
22
200
WARNING: Apparent symbolic reference LIST not resolved.

ERROR 22-322: Syntax error, expecting one of the following: a name, ;, _ALL_, _CHARACTER_, _CHAR_, _NUMERIC_.
ERROR 200-322: The symbol is not recognized and will be ignored.

26 set ABC;
27 run;

Kindly suggest.

Body:
You cannot put the values from the same SELECT statement into both a dataset and macro variables. Remove the create table test as from your SQL code.

You also might want to suppress some of the warnings by changing the query to:

proc sql noprint ;
select case when (not anydigit(name)) then -1
            else input(substr(name,anydigit(name)),?32.)
       end as order
     , name
  into :list
     , :list separated by ' '
from dictionary.columns
where libname='WORK' and memname='ABC'
order by 1
;
quit;

%put &list;


来源: stackexchange

问:
Is there a difference between int(floatvar) and (int)floatvar?

Possible Duplicate:

  C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

```<code>int(floatvar)

(int)floatvar
</code>```

Is there any difference between the two? Are there any preferences about when to use which?

答:
The notation is a general one for any type, and the fact you can do it with int means it will work in templates.

```<code>template < typename T, typename U >
T makeTFromU( U u )
{
   return T( u );
}
</code>```

Ok, that is a very simple case to show a point, but it works even when T is int and U is a type that can be converted to int.

An example in the standard library would be vector. If you use this constructor it constructs one element from the parameter and the others by copy-constructor from the first.

```<code>std::vector< int > v( 20, x );
</code>```

thus it will probably internally call int(x) to create the first one to then copy into the 20 elements.

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

int(floatvar)

(int)floatvar

Is there any difference between the two? Are there any preferences about when to use which?

Body:
The notation is a general one for any type, and the fact you can do it with int means it will work in templates.

template < typename T, typename U >
T makeTFromU( U u )
{
   return T( u );
}

Ok, that is a very simple case to show a point, but it works even when T is int and U is a type that can be converted to int.

An example in the standard library would be vector. If you use this constructor it constructs one element from the parameter and the others by copy-constructor from the first.

std::vector< int > v( 20, x );

thus it will probably internally call int(x) to create the first one to then copy into the 20 elements.


问:
In array or object add data with key dynamically
I want to add a object with key a data. but data is any string.

Example PHP

```<code>// PHP
$object;

// Knowing Key
$object["knowingKey"] = "knowingData";

// Dynamic Key
$dynamicKey = "key1";
$dynamicValue = "value";
$object[$dynamicKey] = $dynamicValue
</code>```

But. How can i do this with JS.

```<code> var obj = {};
 // Normally;
 obj.knowingData = 'Any Text';

 // How can i add dynamically data?
</code>```

答:
Creating data with obj[data]

var x = 'anyText';

var obj = {};

obj[x] = 'any Value';

console.log(obj[x])```

ContentLicense: CC BY-SA 4.0

Body:
I want to add a object with key a data. but data is any string.

Example PHP

// PHP
$object;

// Knowing Key
$object["knowingKey"] = "knowingData";

// Dynamic Key
$dynamicKey = "key1";
$dynamicValue = "value";
$object[$dynamicKey] = $dynamicValue

But. How can i do this with JS.

 var obj = {};
 // Normally;
 obj.knowingData = 'Any Text';

 // How can i add dynamically data?


问:
angular2- Observable getting data from list out of order
```<code>    for (let i = 0; i < this.data.VirtualHosts.length; i++) {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
            }
</code>```

Here, I loop through a list of ID's of VirtualHosts and do a get call (findVH) on every single one of them. However, the get call seems to be calling each index out of order. How would I make it so that the get call returns a list of data in the order that it was given in the this.data.VirtualHosts list?

答: The return values are in an incorrect order mainly due to the fact that Observables will create a separate thread per call therefore the loop completes before the result arrives; this is why unordered list. What I done in this kind of situation is to put that in a method, store the unordered list and then filter the result to another variable by running a something like find or filter method to use common value from this.data.virtualHosts and the unordered result to put them back to order.

ContentLicense: CC BY-SA 3.0

Body:
    for (let i = 0; i < this.data.VirtualHosts.length; i++) {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
            }

Here, I loop through a list of ID's of VirtualHosts and do a get call (findVH) on every single one of them. However, the get call seems to be calling each index out of order. How would I make it so that the get call returns a list of data in the order that it was given in the this.data.VirtualHosts list?


问:
Check if user has scrolled to the bottom in Angular 2
What is the best practice to check if user has scrolled to the bottom of the page in Angular2 without jQuery?  Do I have access to the window in my app component?  If not should i check for scrolling to the bottom of the footer component, and how would I do that?  A directive on the footer component?  Has anyone accomplished this?</p>

答:
For me the bottom of my chatbox wasn't at the bottom of the page, so I couldn't use window.innerHeight to see if the user scrolled to the bottom of the chatbox. (My goal was to always scroll to the bottom of the chat unless the user is trying to scroll up)

I used the following instead which worked perfectly:

```<code>let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
</code>```

some context:

```<code>@ViewChild('scrollMe') private myScrollContainer: ElementRef;
disableScrollDown = false

 ngAfterViewChecked() {
    this.scrollToBottom();
}

private onScroll() {
    let element = this.myScrollContainer.nativeElement
    let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
    if (this.disableScrollDown && atBottom) {
        this.disableScrollDown = false
    } else {
        this.disableScrollDown = true
    }
}

private scrollToBottom(): void {
    if (this.disableScrollDown) {
        return
    }
    try {
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    } catch(err) { }
}
</code>```

and

```<code><div class="messages-box" #scrollMe (scroll)="onScroll()">
    <app-message [message]="message" *ngFor="let message of messages.slice().reverse()"></app-message>
 </div>
</code>```

Body:
For me the bottom of my chatbox wasn't at the bottom of the page, so I couldn't use window.innerHeight to see if the user scrolled to the bottom of the chatbox. (My goal was to always scroll to the bottom of the chat unless the user is trying to scroll up)

I used the following instead which worked perfectly:

let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight

some context:

@ViewChild('scrollMe') private myScrollContainer: ElementRef;
disableScrollDown = false

 ngAfterViewChecked() {
    this.scrollToBottom();
}

private onScroll() {
    let element = this.myScrollContainer.nativeElement
    let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
    if (this.disableScrollDown && atBottom) {
        this.disableScrollDown = false
    } else {
        this.disableScrollDown = true
    }
}

private scrollToBottom(): void {
    if (this.disableScrollDown) {
        return
    }
    try {
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    } catch(err) { }
}

and

<div class="messages-box" #scrollMe (scroll)="onScroll()">
    <app-message [message]="message" *ngFor="let message of messages.slice().reverse()"></app-message>
 </div>


问:
Showing column numbers in Dreamweaver?
I wasn't quite sure if this would go on SU or here, but I figured people here were more likely to have an answer.

Everyone knows the 80 character column rule, right? I'd like to be able to follow this, but I use Dreamweaver, and until this point I have not been able to find a way to turn on a display for the current column in the text I am on.

Does anyone know where this might be found?

EDIT: An alternative answer to this question would be an alternative program that has as nice of an explorer module of Dreamweaver. (I don't like Eclipse or Notepad++'s explorer windows.)

答:
In 2017, I found myself looking for this answer too. I located line column in lower right corner of Dreamweaver, next to the "Real-time Preview" icon--between the "OVR"/"INS" text (whichever you have activated) and the "Real-time Preview" icon. As you move your cursor in the work screen, row / col will change.

Hope that helps someone.

Title: Showing column numbers in Dreamweaver?


问:
CSS side by side div's auto equal widths
```<code><div id="wrapper" style="width:90%;height:100px;background-color:Gray;">
    <div id="one" style="height:100px;background-color:Green;float:left;"></div>
    <div id="two" style="height:100px;background-color:blue;float:left;"></div>
    <div id="three" style="height:100px;background-color:Red;float:left;"></div>
</div>
</code>```

I have a parent div which will contain 2 or 3 child divs. I want child divs to take equal widths automatically.

Thank You

答:
For the sake of older browser compatibility, here's a solution that works.

html:

```<code><div class="parent">
    <div></div>
    <div></div>
    <div></div>
</div>
</code>```

css:

```<code>.parent{
    height: 200px;
    background: #f00;
}
.parent > div{
    width: calc(100%/3);
    height: 100%;
    float: left;
    background: #fff;
}
</code>```

However, to make it dynamic, since you'd know if it'd be 2 or 3 columns, you can put the count in a variable and do internal / inline css:

//$count = 2 or 3

Internal CSS (recommended)

```<code>...
<style>
    .parent > div{
        width: calc(100%/<?=$count;?>);
    }
</style>
<body>
...
</code>```

Inline CSS:

```<code><div class="parent">
    <div style="calc(100%/<?=$count;?>)"></div>
    <div style="calc(100%/<?=$count;?>)"></div>
    <div style="calc(100%/<?=$count;?>)"></div>
</div>
</code>```

Body:
For the sake of older browser compatibility, here's a solution that works.

html:

<div class="parent">
    <div></div>
    <div></div>
    <div></div>
</div>

css:

.parent{
    height: 200px;
    background: #f00;
}
.parent > div{
    width: calc(100%/3);
    height: 100%;
    float: left;
    background: #fff;
}

However, to make it dynamic, since you'd know if it'd be 2 or 3 columns, you can put the count in a variable and do internal / inline css:

//$count = 2 or 3

Internal CSS (recommended)

...
<style>
    .parent > div{
        width: calc(100%/<?=$count;?>);
    }
</style>
<body>
...

Inline CSS:

<div class="parent">
    <div style="calc(100%/<?=$count;?>)"></div>
    <div style="calc(100%/<?=$count;?>)"></div>
    <div style="calc(100%/<?=$count;?>)"></div>
</div>


问:
Qt Qml, embedding a map (OSM Mapbox Mapboxgl) into a QQuickWidget C++ object, on iOS
I am developing a cross-platform mobile application which must display a geographical map. then we're using Qt framework (Qt 5.9), and the main part of the implementation is in C++.

Qt has ready-to-use Map objects available in QML. Then, the best way I found to integrate the map view is to load QML code into a QQuickWidget.

The following piece of code works fine on MacOS Desktop but I am still getting a blank view when deploying on iOS.

map.qml

```<code>import QtQuick 2.0
import QtQuick.Controls 1.4
import QtLocation 5.9
import QtPositioning 5.5

Map {
    id: map
    plugin: Plugin {
        name: "mapboxgl"
        PluginParameter { name: "mapboxgl.access_token"; value: "***" }
    }

    center: QtPositioning.coordinate(60.170448, 24.942046) // Helsinki
    zoomLevel: 8

    width: 500  // no effects since it will be resized
    height: 500 // no effects since it will be resized
    gesture.enabled: true

    Component.onCompleted: {
        console.log("Dimensions: ", width, height) // print 500 500 whether or not the map is displayed
    }
}
</code>```

viewport.cpp

```<code>Viewport::Viewport(QWidget *parent) : QWidget(parent),
    _engine(new QQmlEngine(this)),
    _mapview(new QQuickWidget(_engine,this)),
    _toolbar(new Toolbar(this)) // subclass of QWidget
{
    _mapview->setSource(QUrl("qrc:/map.qml"));
    _mapview->setResizeMode(QQuickWidget::SizeRootObjectToView);
}
</code>```

Note :

map.qml is properly declared at the root of a qt resource file, so that mobile device can access it. I know mapboxgl plugin is very new on Qt 5.9 No matter what plugin I use for the map (osm, mapbox, mapboxgl) I'm always getting a blank view on iOS, with no error message.

When running a simple sample project, the warning message for mapboxgl plugin is something like ssl handshake failed. Even though Qt says the mapboxgl QML plugin, for instance, supports iOS.

The Viewport class inherits from QWidget and is not associated to any ui file, both of the _mapview and the _toolbar geometries are managed by hand. For the moment there is no overlapping widgets and all of them are fully opaque. Nevertheless I tried to set/unset several OpenGL attributes (Qt::AA_UseOpenGLES, Qt::AA_ShareOpenGLContexts etc...) but still don't do the thing ...

Last note : replacing the map of the above code, with a simple red Rectangle with a Text on it works well.

My question what am I doing wrong ? Did I miss something in the documentation ? Nothing says iOS cannot support these map qml objects.

答:
It looks as though this is due to a bug in Qt 5.9.0's SSL socket handling for iOS - https://bugreports.qt.io/browse/QTBUG-61053

I was seeing in the debug output "SSL handshake failed" when attempting either with osm highdpi tiles, or with mapboxgl.

I opened the online installer, added Qt 5.9.1 iOS, waited a bit while it downloaded, then reconfigured the project for 5.9.1 iOS and it worked.

Body:
I am developing a cross-platform mobile application which must display a geographical map. then we're using Qt framework (Qt 5.9), and the main part of the implementation is in C++.

Qt has ready-to-use Map objects available in QML. Then, the best way I found to integrate the map view is to load QML code into a QQuickWidget.

The following piece of code works fine on MacOS Desktop but I am still getting a blank view when deploying on iOS.

map.qml

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtLocation 5.9
import QtPositioning 5.5

Map {
    id: map
    plugin: Plugin {
        name: "mapboxgl"
        PluginParameter { name: "mapboxgl.access_token"; value: "***" }
    }

    center: QtPositioning.coordinate(60.170448, 24.942046) // Helsinki
    zoomLevel: 8

    width: 500  // no effects since it will be resized
    height: 500 // no effects since it will be resized
    gesture.enabled: true

    Component.onCompleted: {
        console.log("Dimensions: ", width, height) // print 500 500 whether or not the map is displayed
    }
}

viewport.cpp

Viewport::Viewport(QWidget *parent) : QWidget(parent),
    _engine(new QQmlEngine(this)),
    _mapview(new QQuickWidget(_engine,this)),
    _toolbar(new Toolbar(this)) // subclass of QWidget
{
    _mapview->setSource(QUrl("qrc:/map.qml"));
    _mapview->setResizeMode(QQuickWidget::SizeRootObjectToView);
}

Note :

map.qml is properly declared at the root of a qt resource file, so that mobile device can access it. I know mapboxgl plugin is very new on Qt 5.9 No matter what plugin I use for the map (osm, mapbox, mapboxgl) I'm always getting a blank view on iOS, with no error message.

When running a simple sample project, the warning message for mapboxgl plugin is something like ssl handshake failed. Even though Qt says the mapboxgl QML plugin, for instance, supports iOS.

The Viewport class inherits from QWidget and is not associated to any ui file, both of the _mapview and the _toolbar geometries are managed by hand. For the moment there is no overlapping widgets and all of them are fully opaque. Nevertheless I tried to set/unset several OpenGL attributes (Qt::AA_UseOpenGLES, Qt::AA_ShareOpenGLContexts etc...) but still don't do the thing ...

Last note : replacing the map of the above code, with a simple red Rectangle with a Text on it works well.

My question what am I doing wrong ? Did I miss something in the documentation ? Nothing says iOS cannot support these map qml objects.


问:
Python-requests library still showing default headers after setting custom headers
Today I was playing with some post data in python, however when trying to set custom headers using the python-requests library and setting the custom headers, it still sends it's default headers, not my custom ones.

```<code>headers={'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip',
'User-Agent': 'okhttp/3.5.0',
}
response = requests.post(url,headers,postdata)
</code>```

What appears while inspecting the data with fiddler:

答:
You seem to have an error in your call to the requests.post function. The correct call could look like this:

```<code>requests.post(url,headers=headers,data=postdata)
</code>```

Changing this in the code you provided should result in requests sending your custom headers.

Body:
Today I was playing with some post data in python, however when trying to set custom headers using the python-requests library and setting the custom headers, it still sends it's default headers, not my custom ones.

headers={'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip',
'User-Agent': 'okhttp/3.5.0',
}
response = requests.post(url,headers,postdata)

What appears while inspecting the data with fiddler:

Body:
You seem to have an error in your call to the requests.post function. The correct call could look like this:

requests.post(url,headers=headers,data=postdata)

Changing this in the code you provided should result in requests sending your custom headers.


问:
Tensorflow version ''1.1.0' SKCompat AttributeError
I am attempting to implement VGGnet using TF 1.1.0, using the MNIST CNN tutorial provided here. The error message I am receiving is:

```<code>AttributeError: 'SKCompat' object has no attribute 'evaluate'
</code>```

This part of my code throws up the AttributeError:

```<code>#create estimator
vggnet_classifier = learn.SKCompat(learn.Estimator(model_fn=vggnet_model, model_dir= "/tmp/vgg_net"))

# Set up logging for predictions
tensors_to_log = {"probabilities": "softmax_tensor"}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=100)

#train model
vggnet_classifier.fit(
    x=X_train,
    y=y_train,
    batch_size=100,
    steps=2,
    monitors=[logging_hook])

# Configure the accuracy metric for evaluation
metrics = {
    "accuracy":
        learn.MetricSpec(metric_fn=tf.metrics.accuracy, prediction_key="classes"),}

# Evaluate the model and print results
eval_results = vggnet_classifier.evaluate(x=X_val, y=y_val, metrics=metrics)
print(eval_results)
</code>```

I originally added the SKCompat() wrapper around learn.Estimator due to a deprecation warning, but I can't seem to find any information on how to use the wrapped estimator to evaluate the model.

答: I wonder if there is any elegant solution now. Just as the OP points out, using the SKCompat() wrapper avoids the warnings, and it seems to be the thing to do in the future; but on the other hand the evaluate() function breaks that way.</p>

Body:
I am attempting to implement VGGnet using TF 1.1.0, using the MNIST CNN tutorial provided here. The error message I am receiving is:

AttributeError: 'SKCompat' object has no attribute 'evaluate'

This part of my code throws up the AttributeError:

#create estimator
vggnet_classifier = learn.SKCompat(learn.Estimator(model_fn=vggnet_model, model_dir= "/tmp/vgg_net"))

# Set up logging for predictions
tensors_to_log = {"probabilities": "softmax_tensor"}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=100)

#train model
vggnet_classifier.fit(
    x=X_train,
    y=y_train,
    batch_size=100,
    steps=2,
    monitors=[logging_hook])

# Configure the accuracy metric for evaluation
metrics = {
    "accuracy":
        learn.MetricSpec(metric_fn=tf.metrics.accuracy, prediction_key="classes"),}

# Evaluate the model and print results
eval_results = vggnet_classifier.evaluate(x=X_val, y=y_val, metrics=metrics)
print(eval_results)

I originally added the SKCompat() wrapper around learn.Estimator due to a deprecation warning, but I can't seem to find any information on how to use the wrapped estimator to evaluate the model.


问:
Output of command to array not working
I'm attempting to store the output of a series of beeline HQL queries into an array, so that I can parse it to pull out the interesting bits.  Here's the relevant code:

```<code>    #!/usr/bin/env ksh
    ext_output=()
    while IFS= read -r line; do
      ext_output+=( "$line" )
    done < <( bee  --hiveconf hive.auto.convert.join=false  -f temp.hql)
</code>```

bee is just an alias to the full beeline command with the JDBC url, etc.  Temp.hql is multiple hql queries.

And here's a snippet of what the output of each query looks like:

```<code>    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    | tableName:myTable                                                                                |
    | owner:foo                                                                                |
    | location:hdfs://<server>/<path>...
<big snip>
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    15 rows selected (0.187 seconds)
</code>```

The problem is, my array is only getting the last line from each result (15 rows selected (0.187 seconds).

Am I doing something wrong here?  The exact same approach is working in other instances, so I really don't understand.

答:
Hmmmm, I'm not having any problems with the code you've posted.

I can reproduce what I think you may be seeing (ie, array contains a single value consisting of the last line of output) if I make the following change in your code:

```<code># current/correct code - from your post
ext_output+=( "$line" )

# modified/wrong code
ext_output=+( "$line" )
</code>```

Notice the placement of the plus sign (+):

when on the left side of the equal sign (+=) each $line is appended to the end of the array (see sample run - below)

when on the right side of the equal sign (=+) each $line is assigned to the first slot in the array (index=0); the plus sign (+) and parens (()) are treated as part of the data to be stored in the array (see sample run - at bottom of this post)

Could there be a typo between what you're running (with 'wrong' results) vs what you've posted here in this thread (and what you've mentioned generates the correct results in other instances)?

Here's what I get when I run your posted code (plus sign on the left of the equal sign : +=) ...

NOTE: I've replaced the bee/HCL call with an output file containing your sample lines plus a couple (bogus) data lines; also cut down the longer lines for readability:

```<code>$ cat temp.out
    -----------------------------------------+--+
    | tableName:myTable
    | owner:foo
    | location:hdfs://<server>/<path>...

abc def ghi
123 456 789

    -----------------------------------------+--+
    15 rows selected (0.187 seconds)
</code>```

Then I ran your code against temp.out:

```<code>ext_output=()

while IFS= read -r line
do
    ext_output+=( "$line" )
done < temp.out
</code>```

Some stats on the array:

```<code>$ echo "array size : ${#ext_output[*]}"
array size : 10

$ echo "array indx : ${!ext_output[*]}"
array indx : 0 1 2 3 4 5 6 7 8 9

$ echo "array vals : ${ext_output[*]}"
array vals :     -----------------------------------------+--+     | tableName:myTable                              | owner:foo                                      | location:hdfs://<server>/<path>...  abc def ghi 123 456 789      -----------------------------------------+--+     15 rows selected (0.187 seconds)
</code>```

And a dump of the array's contents:

```<code>$ for i in ${!ext_output[*]}
> do
> echo "${i} : ${ext_output[$i]}"
> done
0 :     -----------------------------------------+--+
1 :     | tableName:myTable
2 :     | owner:foo
3 :     | location:hdfs://<server>/<path>...
4 :
5 : abc def ghi
6 : 123 456 789
7 :
8 :     -----------------------------------------+--+
9 :     15 rows selected (0.187 seconds)
</code>```

If I modify your code to place the plus sign on the right side of the equal sign (=+) ...

```<code>ext_output=()

while IFS= read -r line
do
    ext_output=+( "$line" )
done < temp.out
</code>```

... the array stats:

```<code>$ echo "array size : ${#ext_output[*]}"
array size : 1

$ echo "array indx : ${!ext_output[*]}"
array indx : 0

$ echo "array vals : ${ext_output[*]}"
array vals : +(     15 rows selected (0.187 seconds) )
</code>```

... and the contents of the array:

```<code>$ for i in ${!ext_output[*]}
> do
> echo "${i} : ${ext_output[$i]}"
> done
0 : +(     15 rows selected (0.187 seconds) )
</code>```

!! Notice that the plus sign and parens are part of the string stored in ext_output[0]

Title: Output of command to array not working

Body:
I'm attempting to store the output of a series of beeline HQL queries into an array, so that I can parse it to pull out the interesting bits.  Here's the relevant code:

    #!/usr/bin/env ksh
    ext_output=()
    while IFS= read -r line; do
      ext_output+=( "$line" )
    done < <( bee  --hiveconf hive.auto.convert.join=false  -f temp.hql)

bee is just an alias to the full beeline command with the JDBC url, etc.  Temp.hql is multiple hql queries.

And here's a snippet of what the output of each query looks like:

    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    | tableName:myTable                                                                                |
    | owner:foo                                                                                |
    | location:hdfs://<server>/<path>...
<big snip>
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    15 rows selected (0.187 seconds)

The problem is, my array is only getting the last line from each result (15 rows selected (0.187 seconds).

Am I doing something wrong here?  The exact same approach is working in other instances, so I really don't understand.

Body:
Hmmmm, I'm not having any problems with the code you've posted.

I can reproduce what I think you may be seeing (ie, array contains a single value consisting of the last line of output) if I make the following change in your code:

# current/correct code - from your post
ext_output+=( "$line" )

# modified/wrong code
ext_output=+( "$line" )

Notice the placement of the plus sign (+):

when on the left side of the equal sign (+=) each $line is appended to the end of the array (see sample run - below)

when on the right side of the equal sign (=+) each $line is assigned to the first slot in the array (index=0); the plus sign (+) and parens (()) are treated as part of the data to be stored in the array (see sample run - at bottom of this post)

Could there be a typo between what you're running (with 'wrong' results) vs what you've posted here in this thread (and what you've mentioned generates the correct results in other instances)?

Here's what I get when I run your posted code (plus sign on the left of the equal sign : +=) ...

NOTE: I've replaced the bee/HCL call with an output file containing your sample lines plus a couple (bogus) data lines; also cut down the longer lines for readability:

$ cat temp.out
    -----------------------------------------+--+
    | tableName:myTable
    | owner:foo
    | location:hdfs://<server>/<path>...

abc def ghi
123 456 789

    -----------------------------------------+--+
    15 rows selected (0.187 seconds)

Then I ran your code against temp.out:

ext_output=()

while IFS= read -r line
do
    ext_output+=( "$line" )
done < temp.out

Some stats on the array:

$ echo "array size : ${#ext_output[*]}"
array size : 10

$ echo "array indx : ${!ext_output[*]}"
array indx : 0 1 2 3 4 5 6 7 8 9

$ echo "array vals : ${ext_output[*]}"
array vals :     -----------------------------------------+--+     | tableName:myTable                              | owner:foo                                      | location:hdfs://<server>/<path>...  abc def ghi 123 456 789      -----------------------------------------+--+     15 rows selected (0.187 seconds)

And a dump of the array's contents:

$ for i in ${!ext_output[*]}
> do
> echo "${i} : ${ext_output[$i]}"
> done
0 :     -----------------------------------------+--+
1 :     | tableName:myTable
2 :     | owner:foo
3 :     | location:hdfs://<server>/<path>...
4 :
5 : abc def ghi
6 : 123 456 789
7 :
8 :     -----------------------------------------+--+
9 :     15 rows selected (0.187 seconds)

If I modify your code to place the plus sign on the right side of the equal sign (=+) ...

ext_output=()

while IFS= read -r line
do
    ext_output=+( "$line" )
done < temp.out

... the array stats:

$ echo "array size : ${#ext_output[*]}"
array size : 1

$ echo "array indx : ${!ext_output[*]}"
array indx : 0

$ echo "array vals : ${ext_output[*]}"
array vals : +(     15 rows selected (0.187 seconds) )

... and the contents of the array:

$ for i in ${!ext_output[*]}
> do
> echo "${i} : ${ext_output[$i]}"
> done
0 : +(     15 rows selected (0.187 seconds) )

!! Notice that the plus sign and parens are part of the string stored in ext_output[0]


问:
Using ActiveRecord and Rails to insert Data into postgresql database get this error: RuntimeError: ERROR C22003 Minteger o
I am using Ruby 1.8.6 and rails 2.1.1 (I have tested rails 2.2.2 as well).  I have been using Sqlite3 and I recently migrated to Postgresql 8.2.6 for production use.  Now this error shows up.  The interesting thing is that when I copy the insert statment and use psql to directly insert it into postgres it works fine.  I guess the problem is somewhere on the rails level.  But, I have no idea what it is.  So if anybody knows what the problem is or how to fix it please let me know.</p>

```<code>RuntimeError: ERROR C22003  Minteger out of range   Fint8.c L1008   Rint84: INSERT INTO     "resource_usages" ("measurement_type", "updated_at", "time", "max", "min", "average", "tst_data_id", "created_at") VALUES(E'jmxMemHeapMax', '2009-01-16 12:54:56.600105', 1, 5726666752, 5726666752, 5726666752, 2, '2009-01-16 12:54:56.600105') RETURNING "id"
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract_adapter.rb:147:in `log'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:484:in `execute'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:929:in `select_raw'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:916:in `select'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/query_cache.rb:61:in `select_all'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract    /database_statements.rb:13:in `select_one'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract  /database_statements.rb:19:in `select_value'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters  /postgresql_adapter.rb:433:in `insert'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:2517:in `create_without_callbacks'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/callbacks.rb:220:in `create_without_timestamps'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/timestamp.rb:29:in `create'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:2483:in `create_or_update_without_callbacks'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/callbacks.rb:207:in `create_or_update'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:2211:in `save_without_validation'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/validations.rb:911:in `save_without_dirty'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/dirty.rb:75:in `save_without_transactions'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:106:in `save'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:66:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:79:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:98:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:106:in `save'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:118:in `rollback_active_record_state!'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:106:in `save'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/has_many_association.rb:62:in `insert_record'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:102:in `<<'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:339:in `add_record_to_target_with_callbacks'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:101:in `<<'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:99:in `each'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:99:in `<<'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract  /database_statements.rb:66:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:79:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:98:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:98:in `<<'
/srv/www/vhosts/performanceTesting/app/models/tst_data.rb:80:in `add_resource_usage_data'
/srv/www/vhosts/performanceTesting/app/models/tst_data.rb:68:in `each'
/srv/www/vhosts/performanceTesting/app/models/tst_data.rb:68:in `add_resource_usage_data'
/srv/www/vhosts/performanceTesting/app/models/tst_definition.rb:196:in `run'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_proxy.rb:173:in `send'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_proxy.rb:173:in `method_missing'
/srv/www/vhosts/performanceTesting/app/models/job.rb:54:in `send'
/srv/www/vhosts/performanceTesting/app/models/job.rb:54:in `start'
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:34
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:29:in `initialize'
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:29:in `new'
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:29
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:503:in `load'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:503:in `load'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:503:in `load'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:176:in `start_load'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:257:in `start'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/controller.rb:69:in `run'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:139:in `run'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `call'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `catch_exceptions'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:138:in `run'
./lib/daemons/queue_runner_ctl:26
</code>```

答: The error is at the PostgreSQL level. Error 22003 is the "NUMERIC VALUE OUT OF RANGE" error for PostgreSQL as seen here. A quick glance at your insert statement shows integers that are greater than 32 bits, those might be the culprits.</p>

OwnerDisplayName: Josh Moore

Body:
I am using Ruby 1.8.6 and rails 2.1.1 (I have tested rails 2.2.2 as well).  I have been using Sqlite3 and I recently migrated to Postgresql 8.2.6 for production use.  Now this error shows up.  The interesting thing is that when I copy the insert statment and use psql to directly insert it into postgres it works fine.  I guess the problem is somewhere on the rails level.  But, I have no idea what it is.  So if anybody knows what the problem is or how to fix it please let me know.

RuntimeError: ERROR C22003  Minteger out of range   Fint8.c L1008   Rint84: INSERT INTO     "resource_usages" ("measurement_type", "updated_at", "time", "max", "min", "average", "tst_data_id", "created_at") VALUES(E'jmxMemHeapMax', '2009-01-16 12:54:56.600105', 1, 5726666752, 5726666752, 5726666752, 2, '2009-01-16 12:54:56.600105') RETURNING "id"
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract_adapter.rb:147:in `log'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:484:in `execute'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:929:in `select_raw'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:916:in `select'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/query_cache.rb:61:in `select_all'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract    /database_statements.rb:13:in `select_one'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract  /database_statements.rb:19:in `select_value'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters  /postgresql_adapter.rb:433:in `insert'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:2517:in `create_without_callbacks'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/callbacks.rb:220:in `create_without_timestamps'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/timestamp.rb:29:in `create'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:2483:in `create_or_update_without_callbacks'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/callbacks.rb:207:in `create_or_update'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:2211:in `save_without_validation'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/validations.rb:911:in `save_without_dirty'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/dirty.rb:75:in `save_without_transactions'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:106:in `save'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:66:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:79:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:98:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:106:in `save'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:118:in `rollback_active_record_state!'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:106:in `save'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/has_many_association.rb:62:in `insert_record'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:102:in `<<'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:339:in `add_record_to_target_with_callbacks'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:101:in `<<'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:99:in `each'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:99:in `<<'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract  /database_statements.rb:66:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:79:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/transactions.rb:98:in `transaction'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_collection.rb:98:in `<<'
/srv/www/vhosts/performanceTesting/app/models/tst_data.rb:80:in `add_resource_usage_data'
/srv/www/vhosts/performanceTesting/app/models/tst_data.rb:68:in `each'
/srv/www/vhosts/performanceTesting/app/models/tst_data.rb:68:in `add_resource_usage_data'
/srv/www/vhosts/performanceTesting/app/models/tst_definition.rb:196:in `run'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_proxy.rb:173:in `send'
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/associations/association_proxy.rb:173:in `method_missing'
/srv/www/vhosts/performanceTesting/app/models/job.rb:54:in `send'
/srv/www/vhosts/performanceTesting/app/models/job.rb:54:in `start'
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:34
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:29:in `initialize'
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:29:in `new'
/srv/www/vhosts/performanceTesting/lib/daemons/queue_runner.rb:29
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:503:in `load'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:503:in `load'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:503:in `load'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:176:in `start_load'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/application.rb:257:in `start'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/controller.rb:69:in `run'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:139:in `run'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `call'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons/cmdline.rb:105:in `catch_exceptions'
/usr/lib64/ruby/gems/1.8/gems/daemons-1.0.10/lib/daemons.rb:138:in `run'
./lib/daemons/queue_runner_ctl:26

LastEditorDisplayName: Josh Moore


问:
Factory Pattern implementation in C#
I'm implementing a factory pattern that looks as follows.

```<code>public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}
</code>```

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

答:
Just as a side note -- as a factory is intended to wrap creation, it's a curious choice that you're creating objects and registering them with the factory. Is this more an object repository than a factory, or is there more to the class than I'm seeing?

If it is an object repository, then you might also find some extra inspiration in other questions, like this one.

Title: Factory Pattern implementation in C#

Body:
I'm implementing a factory pattern that looks as follows.

public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?


问:
bash diff fails to found existing files when providing a path variable containing tilde (~)
I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

```<code>#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar
</code>```

So my question is:

Why ? :-)

答:
Tilde expansion only applies to unquoted tildes. The tilde must be expanded at the time you perform the assignment to folder, because tilde expansion is not applied to parameter expansions, only word splitting and pathname expansion.

```<code>folder=~  # ~ is expanded, and the result is assigned to folder
</code>```

Body:
I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar

So my question is:

Why ? :-)

Body:
Tilde expansion only applies to unquoted tildes. The tilde must be expanded at the time you perform the assignment to folder, because tilde expansion is not applied to parameter expansions, only word splitting and pathname expansion.

folder=~  # ~ is expanded, and the result is assigned to folder


问:
Directive binding to functions end up in $digest loop -- Error: $rootScope:infdig
I want a directive that works with a list of object but I also need to accept either an 2-way bind or a function bind.

```<code>app.directive('myDir', function() {
    return {
        scope: {
            list: "=?",
            list_func: "&?listFunc"
        },

        controller: ['$scope', function($scope) {
            $scope.get_list = function() {
                if($scope.list !== undefined)
                    return $scope.list();

                if($scope.list_func !== undefined)
                    return $scope.list_func()();
            };
        }]
    };
});
</code>```

However when I use the listFunc attribute with a function that returns a list, I get this error:

VM607 angular.js:68 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
      Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":19,"oldVal":17},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":9,"oldVal":8},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":21,"oldVal":19},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":10,"oldVal":9},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":23,"oldVal":21},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":11,"oldVal":10},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":25,"oldVal":23},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":12,"oldVal":11},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":27,"oldVal":25},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":13,"oldVal":12},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}]]
      http://errors.angularjs.org/1.6.2/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…2fn%3A%20regularInterceptedExpression%22%2C%22newVal%22%3A%221%22%7D%5D%5D
          at VM607 angular.js:68
          at Scope.$digest (VM607 angular.js:17893)
          at Scope.$apply (VM607 angular.js:18125)
          at done (VM607 angular.js:12233)
          at completeRequest (VM607 angular.js:12459)
          at XMLHttpRequest.requestLoaded (VM607 angular.js:12387)

I created this plunker example (with an open a javascript console you can see these errors) demonstrating what I need. In this example I get these errors but the view still gets updated. On the app I'm developing (which is much bigger) I get so many $digest errors that the site slows down and the view doens't get updated.

What is the best way of binding a function without ending in an endless loop?

答:
Angular registers an implicit $watchCollection on the get_list() expression. This expression will get called at least twice because angular wants to check if the model has stabilized.

```<code><ul>
  <li ng-repeat="obj in get_list()">
    name: {{ obj.name }}<br />
    age: {{ obj.age }}
  </li>
</ul>
</code>```

Your code returns a different array of objects everytime get_list() is called so angular continues digesting until it reaches the max digest cycles limit.

```<code>  $scope.get_list = function(val) {
    return function() {
      return [ { name: "val", age: val } ];
    }
  }
</code>```

Even though the content is the same, the function creates new objects each time it is called.

Avoid using function calls in templates. Instead put values on scope and have the directive react to changes in those values.

From the Docs:

Error: $rootScope:infdig

This error occurs when the application's model becomes unstable and each $digest cycle triggers a state change and subsequent $digest cycle. AngularJS detects this situation and prevents an infinite loop from causing the browser to become unresponsive.

One common mistake is binding to a function which generates a new array every time it is called. For example:

```<code><div ng-repeat="user in getUsers()">{{ user.name }}</div>
</code>```

```<code>$scope.getUsers = function() {
    return [ { name: 'Hank' }, { name: 'Francisco' } ];
};
</code>```

Since getUsers() returns a new array, AngularJS determines that the model is different on each $digest cycle, resulting in the error. The solution is to return the same array object if the elements have not changed:

```<code>var users = [ { name: 'Hank' }, { name: 'Francisco' } ];

$scope.getUsers = function() {
    return users;
};
</code>```

— AngularJS Error Reference - Error: $rootScope:infdig

Should I give up with this kind of functions and use a filter instead?

TL;DR Yes.

Components should just act as "skins". They should only display the data given to them and communicate user events to the parent controller. The Model should be the Single Source of Truth. Directive should not need to fetch data from a parent controller.

Expression & binding should only used to communicate user events to the parent controller. The parent controller should then change the Model appropriately. This Separation of Concerns makes for an app that is more easily understood, debug, tested, and maintained.

One more question: this also applies for functions returning functions, right?

The "functions returning functions" pattern should be avoided. It makes for a confusing template. Instead invoke functions with locals:

```<code><my-component on-event="gotEvent($event)">
</my-compnent>
</code>```

```<code>scope: { onEvent: "&" },
template: `<input ng-model=myModel ng-change="myChange()" />`,
link: function(scope, elem, attrs) {
    scope.myChange = function() {
        scope.onEvent({$event: myModel});
    };
}
</code>```

I recommend prefixing local variable with $ to differentiate them from parent scope variable. Some people recommend using $event to conform to the conventions of Angular 2+.

From the Docs:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <my-component my-attr="count = count + $value"> and the isolate scope definition scope: { localFn:'&myAttr' }, the isolate scope property localFn will point to a function wrapper for the count = count + $value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope. This can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment($amount) then we can specify the amount value by calling the localFn as localFn({$amount: 22}).

— AngularJS Comprehensive Directive API Reference ($scope)

Body:
I want a directive that works with a list of object but I also need to accept either an 2-way bind or a function bind.

app.directive('myDir', function() {
    return {
        scope: {
            list: "=?",
            list_func: "&?listFunc"
        },

        controller: ['$scope', function($scope) {
            $scope.get_list = function() {
                if($scope.list !== undefined)
                    return $scope.list();

                if($scope.list_func !== undefined)
                    return $scope.list_func()();
            };
        }]
    };
});

However when I use the listFunc attribute with a function that returns a list, I get this error:

VM607 angular.js:68 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
      Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":19,"oldVal":17},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":9,"oldVal":8},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":21,"oldVal":19},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":10,"oldVal":9},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":23,"oldVal":21},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":11,"oldVal":10},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":25,"oldVal":23},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":12,"oldVal":11},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}],[{"msg":"fn: regularInterceptedExpression","newVal":27,"oldVal":25},{"msg":"fn: regularInterceptedExpression","newVal":"Harry"},{"msg":"fn: regularInterceptedExpression","newVal":"65"},{"msg":"fn: regularInterceptedExpression","newVal":"Sally"},{"msg":"fn: regularInterceptedExpression","newVal":"66"},{"msg":"fn: regularInterceptedExpression","newVal":13,"oldVal":12},{"msg":"fn: regularInterceptedExpression","newVal":"val"},{"msg":"fn: regularInterceptedExpression","newVal":"1"}]]
      http://errors.angularjs.org/1.6.2/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…2fn%3A%20regularInterceptedExpression%22%2C%22newVal%22%3A%221%22%7D%5D%5D
          at VM607 angular.js:68
          at Scope.$digest (VM607 angular.js:17893)
          at Scope.$apply (VM607 angular.js:18125)
          at done (VM607 angular.js:12233)
          at completeRequest (VM607 angular.js:12459)
          at XMLHttpRequest.requestLoaded (VM607 angular.js:12387)

I created this plunker example (with an open a javascript console you can see these errors) demonstrating what I need. In this example I get these errors but the view still gets updated. On the app I'm developing (which is much bigger) I get so many $digest errors that the site slows down and the view doens't get updated.

What is the best way of binding a function without ending in an endless loop?

Body:
Angular registers an implicit $watchCollection on the get_list() expression. This expression will get called at least twice because angular wants to check if the model has stabilized.

<ul>
  <li ng-repeat="obj in get_list()">
    name: {{ obj.name }}<br />
    age: {{ obj.age }}
  </li>
</ul>

Your code returns a different array of objects everytime get_list() is called so angular continues digesting until it reaches the max digest cycles limit.

  $scope.get_list = function(val) {
    return function() {
      return [ { name: "val", age: val } ];
    }
  }

Even though the content is the same, the function creates new objects each time it is called.

Avoid using function calls in templates. Instead put values on scope and have the directive react to changes in those values.

From the Docs:

Error: $rootScope:infdig

This error occurs when the application's model becomes unstable and each $digest cycle triggers a state change and subsequent $digest cycle. AngularJS detects this situation and prevents an infinite loop from causing the browser to become unresponsive.

One common mistake is binding to a function which generates a new array every time it is called. For example:

<div ng-repeat="user in getUsers()">{{ user.name }}</div>

$scope.getUsers = function() {
    return [ { name: 'Hank' }, { name: 'Francisco' } ];
};

Since getUsers() returns a new array, AngularJS determines that the model is different on each $digest cycle, resulting in the error. The solution is to return the same array object if the elements have not changed:

var users = [ { name: 'Hank' }, { name: 'Francisco' } ];

$scope.getUsers = function() {
    return users;
};

— AngularJS Error Reference - Error: $rootScope:infdig

Should I give up with this kind of functions and use a filter instead?

TL;DR Yes.

Components should just act as "skins". They should only display the data given to them and communicate user events to the parent controller. The Model should be the Single Source of Truth. Directive should not need to fetch data from a parent controller.

Expression & binding should only used to communicate user events to the parent controller. The parent controller should then change the Model appropriately. This Separation of Concerns makes for an app that is more easily understood, debug, tested, and maintained.

One more question: this also applies for functions returning functions, right?

The "functions returning functions" pattern should be avoided. It makes for a confusing template. Instead invoke functions with locals:

<my-component on-event="gotEvent($event)">
</my-compnent>

scope: { onEvent: "&" },
template: `<input ng-model=myModel ng-change="myChange()" />`,
link: function(scope, elem, attrs) {
    scope.myChange = function() {
        scope.onEvent({$event: myModel});
    };
}

I recommend prefixing local variable with $ to differentiate them from parent scope variable. Some people recommend using $event to conform to the conventions of Angular 2+.

From the Docs:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <my-component my-attr="count = count + $value"> and the isolate scope definition scope: { localFn:'&myAttr' }, the isolate scope property localFn will point to a function wrapper for the count = count + $value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope. This can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment($amount) then we can specify the amount value by calling the localFn as localFn({$amount: 22}).

— AngularJS Comprehensive Directive API Reference ($scope)


问:
Square GridPane of square cells
My goal is to create a GridView that is resizable, always square and contains an equal number of rows and columns, making their cells also square, similar to a Reversi or Chess board.

Here's a small illustration, the grid is centered horizontally on the content pane.

I've tried a multitude of different binding variants and layouts, but I can't quite get it right. Here's my controller (so far):

```<code>public class Controller {

    public HBox contentPane;

    public void initialize() {
        final int sideLength = 10;

        final GridPane gridPane = new GridPane();

        gridPane.setStyle("-fx-border-color: red; -fx-border-insets: 2");

        HBox.setHgrow(gridPane, Priority.ALWAYS);

        for (int i = 0; i < sideLength; i++) {
            final ColumnConstraints columnConstraints = new ColumnConstraints(Control.USE_PREF_SIZE, 10, Double.MAX_VALUE);
            columnConstraints.setHgrow(Priority.ALWAYS);
            gridPane.getColumnConstraints()
                    .add(columnConstraints);

            final RowConstraints rowConstraints = new RowConstraints(Control.USE_PREF_SIZE, 10, Double.MAX_VALUE);
            rowConstraints.setVgrow(Priority.ALWAYS);

            gridPane.getRowConstraints()
                    .add(rowConstraints);
        }

        contentPane.getChildren().add(gridPane);

        for (int i = 0; i < sideLength; i++) {
            for (int j = 0; j < sideLength; j++) {
                final GameCell child = new GameCell();
                GridPane.setRowIndex(child, i);
                GridPane.setColumnIndex(child, j);
                gridPane.getChildren().add(child);
            }
        }
    }
}
</code>```

And the cells, which are supposed to contain Shapes lates, but I've but Circles for now just to test it:

```<code>public class GameCell extends VBox {

    private final Circle circle;

    public GameCell() {
        circle = new Circle();

        setMinSize(0, 0);
        setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE);
        getChildren().add(circle);

        final ChangeListener<Number> listener = (observable, oldValue, newValue) ->
                circle.setRadius((int) (Math.min(this.getWidth(), this.getHeight()) / 2));

        widthProperty().addListener(listener);
        heightProperty().addListener(listener);
    }
}
</code>```

This is how it looks currently:

答:
Solved it with a lot of tinkering, here's my solution for future reference:

GameCell:

```<code>public class GameCell extends Pane {
    public GameCell() {
        final Circle circle = new Circle(10);
        circle.radiusProperty().bind(Bindings.divide(widthProperty(), 4));

        circle.centerXProperty().bind(widthProperty().divide(2));
        circle.centerYProperty().bind(widthProperty().divide(2));

        getChildren().add(circle);
    }
}
</code>```

GamePane:

```<code>public class GamePane extends HBox {
    public GamePane() {
        final VBox vBox = new VBox();

        vBox.alignmentProperty().set(Pos.CENTER);
        alignmentProperty().set(Pos.CENTER);

        final GridPane gridPane = new GridPane();

        final NumberBinding binding = Bindings.min(widthProperty(), heightProperty());

        gridPane.setMinSize(200, 200);
        vBox.prefWidthProperty().bind(binding);
        vBox.prefHeightProperty().bind(binding);
        vBox.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);

        vBox.setFillWidth(true);
        VBox.setVgrow(gridPane, Priority.ALWAYS);

        final int sideLength = 8;
        for (int i = 0; i < sideLength; i++) {
            final ColumnConstraints columnConstraints = new ColumnConstraints(Control.USE_PREF_SIZE, Control.USE_COMPUTED_SIZE, Double.MAX_VALUE);
            columnConstraints.setHgrow(Priority.SOMETIMES);
            gridPane.getColumnConstraints().add(columnConstraints);

            final RowConstraints rowConstraints = new RowConstraints(Control.USE_PREF_SIZE, Control.USE_COMPUTED_SIZE, Double.MAX_VALUE);
            rowConstraints.setVgrow(Priority.SOMETIMES);
            gridPane.getRowConstraints().add(rowConstraints);
        }

        vBox.getChildren().add(gridPane);

        getChildren().add(vBox);

        HBox.setHgrow(this, Priority.ALWAYS);

        for (int i = 0; i < sideLength; i++) {
            for (int j = 0; j < sideLength; j++) {
                final Pane child = new GameCell();

                GridPane.setRowIndex(child, i);
                GridPane.setColumnIndex(child, j);
                gridPane.getChildren().add(child);
            }
        }
    }
}
</code>```

Title: Square GridPane of square cells

Body:
My goal is to create a GridView that is resizable, always square and contains an equal number of rows and columns, making their cells also square, similar to a Reversi or Chess board.

Here's a small illustration, the grid is centered horizontally on the content pane.

I've tried a multitude of different binding variants and layouts, but I can't quite get it right. Here's my controller (so far):

public class Controller {

    public HBox contentPane;

    public void initialize() {
        final int sideLength = 10;

        final GridPane gridPane = new GridPane();

        gridPane.setStyle("-fx-border-color: red; -fx-border-insets: 2");

        HBox.setHgrow(gridPane, Priority.ALWAYS);

        for (int i = 0; i < sideLength; i++) {
            final ColumnConstraints columnConstraints = new ColumnConstraints(Control.USE_PREF_SIZE, 10, Double.MAX_VALUE);
            columnConstraints.setHgrow(Priority.ALWAYS);
            gridPane.getColumnConstraints()
                    .add(columnConstraints);

            final RowConstraints rowConstraints = new RowConstraints(Control.USE_PREF_SIZE, 10, Double.MAX_VALUE);
            rowConstraints.setVgrow(Priority.ALWAYS);

            gridPane.getRowConstraints()
                    .add(rowConstraints);
        }

        contentPane.getChildren().add(gridPane);

        for (int i = 0; i < sideLength; i++) {
            for (int j = 0; j < sideLength; j++) {
                final GameCell child = new GameCell();
                GridPane.setRowIndex(child, i);
                GridPane.setColumnIndex(child, j);
                gridPane.getChildren().add(child);
            }
        }
    }
}

And the cells, which are supposed to contain Shapes lates, but I've but Circles for now just to test it:

public class GameCell extends VBox {

    private final Circle circle;

    public GameCell() {
        circle = new Circle();

        setMinSize(0, 0);
        setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE);
        getChildren().add(circle);

        final ChangeListener<Number> listener = (observable, oldValue, newValue) ->
                circle.setRadius((int) (Math.min(this.getWidth(), this.getHeight()) / 2));

        widthProperty().addListener(listener);
        heightProperty().addListener(listener);
    }
}

This is how it looks currently:

Body:
Solved it with a lot of tinkering, here's my solution for future reference:

GameCell:

public class GameCell extends Pane {
    public GameCell() {
        final Circle circle = new Circle(10);
        circle.radiusProperty().bind(Bindings.divide(widthProperty(), 4));

        circle.centerXProperty().bind(widthProperty().divide(2));
        circle.centerYProperty().bind(widthProperty().divide(2));

        getChildren().add(circle);
    }
}

GamePane:

public class GamePane extends HBox {
    public GamePane() {
        final VBox vBox = new VBox();

        vBox.alignmentProperty().set(Pos.CENTER);
        alignmentProperty().set(Pos.CENTER);

        final GridPane gridPane = new GridPane();

        final NumberBinding binding = Bindings.min(widthProperty(), heightProperty());

        gridPane.setMinSize(200, 200);
        vBox.prefWidthProperty().bind(binding);
        vBox.prefHeightProperty().bind(binding);
        vBox.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);

        vBox.setFillWidth(true);
        VBox.setVgrow(gridPane, Priority.ALWAYS);

        final int sideLength = 8;
        for (int i = 0; i < sideLength; i++) {
            final ColumnConstraints columnConstraints = new ColumnConstraints(Control.USE_PREF_SIZE, Control.USE_COMPUTED_SIZE, Double.MAX_VALUE);
            columnConstraints.setHgrow(Priority.SOMETIMES);
            gridPane.getColumnConstraints().add(columnConstraints);

            final RowConstraints rowConstraints = new RowConstraints(Control.USE_PREF_SIZE, Control.USE_COMPUTED_SIZE, Double.MAX_VALUE);
            rowConstraints.setVgrow(Priority.SOMETIMES);
            gridPane.getRowConstraints().add(rowConstraints);
        }

        vBox.getChildren().add(gridPane);

        getChildren().add(vBox);

        HBox.setHgrow(this, Priority.ALWAYS);

        for (int i = 0; i < sideLength; i++) {
            for (int j = 0; j < sideLength; j++) {
                final Pane child = new GameCell();

                GridPane.setRowIndex(child, i);
                GridPane.setColumnIndex(child, j);
                gridPane.getChildren().add(child);
            }
        }
    }
}


问:
I don't understand how to use document.getElementById(‘id’).onclick
I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.

I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.

If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.

Here is my code

```<code><nav>
      <button class="nav-button" id="nav">
        <div class="menu-button"></div>
        <div class="menu-button"></div>
        <div class="menu-button"></div>
      </button>
      <div class="dropdown-menu" id="dropdown">
        <a href="#">Hello</a>
        <a href="#">Hello</a>
        <a href="#">Hello</a>
      </div>
    </nav>

.nav-button {
  background: none;
  border: none;
  margin-left: 1em;
  padding-top: 12px;
  cursor: pointer;
}

.menu-button {
  background-color: #fff;
  width: 30px;
  height: 4px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.dropdown-menu {
  margin-top: 7px;
  width: 100px;
  background-color: #fff;
  display: none;
}

.showDropDown {
  display: block;
}

function showDropDown() {
  document.getElementById('dropdown').classList.toggle("showDropDown");
}

document.getElementById("nav").onclick = function showDropDown()
</code>```

Here is a codepen

Thanks for your help!

答:
It will be much easier to work with jquery than plain javascript.
Here how you are calling showDropDown function  is wrong

change function showDropDown to
  showDropDown

Better you can make the closure at the button click event like

```<code>let btn = document.getElementById("nav");
let toggleIt = document.getElementById('dropdown');
btn.onclick = function(){
toggleIt.classList.toggle("showDropDown");
};
</code>```

Body:
I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.

I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.

If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.

Here is my code

      <button class="nav-button" id="nav">

      </button>

        Hello
        Hello
        Hello

.nav-button {
  background: none;
  border: none;
  margin-left: 1em;
  padding-top: 12px;
  cursor: pointer;
}

.menu-button {
  background-color: #fff;
  width: 30px;
  height: 4px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.dropdown-menu {
  margin-top: 7px;
  width: 100px;
  background-color: #fff;
  display: none;
}

.showDropDown {
  display: block;
}

function showDropDown() {
  document.getElementById('dropdown').classList.toggle("showDropDown");
}

document.getElementById("nav").onclick = function showDropDown()

Here is a codepen

Thanks for your help!

Body:
It will be much easier to work with jquery than plain javascript.
Here how you are calling showDropDown function  is wrong

change function showDropDown to
  showDropDown

Better you can make the closure at the button click event like

let btn = document.getElementById("nav");
let toggleIt = document.getElementById('dropdown');
btn.onclick = function(){
toggleIt.classList.toggle("showDropDown");
};


问:
Export JAR with Netbeans
How to export java project to JAR with Netbeans ? I cannot find options like in Eclipse.</p>

答:
Do you mean compile it to JAR? NetBeans does that automatically, just do "clean and build" and look in the "dist" subdirectory of your project. There will be the JAR with "lib" folder containing the required libraries. These JAR + lib are enough to run the application.

If you disable "Compile on save" in the project properties, then it is no longer necessary to do "clean and build", simply "build" will suffice in most cases. This will save time if you want to change just a bit of the code and rebuild the JAR. However, note that NetBeans sometimes fails to handle dependencies and binary compatibility properly, which will lead to a faulty JAR throwing "no such method" or other obscure exceptions. Therefore, if you made a lot of changes since the last full rebuild and even remotely unsure that it will still work even if some classes aren't recompiled, then you must still do a full "clean and build" in order to get a perfectly working JAR.

Title: Export JAR with Netbeans


问:
How to display Decimal and Date Arrays from MySQL database using php
I am having difficulty getting Price and Date to display on the webpage.

Below is a section of the current code that I have. The MYSQLI_ASSOC part displays the correct data but the MYSQLI_NUM section of the code does not display at all. I am having trouble finding information on how to make it work.

```<code> <?php
    $query = "SELECT ItemID, Name, Category, Price, Duration, Photo FROM
    item ORDER by ItemID LIMIT 3";
    $result = $mysqli->query($query);

  if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_array(MYSQLI_ASSOC)) {
         echo "<br> Row: ". $row["ItemID"]. " - Name: ". $row["Name"]. "<br> " . $row["Category"] .  "<br>" ;
   }
    } else {
      echo "0 results";
  }

    if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_array(MYSQLI_NUM)) {
       echo "<br> Price: ". $row["Price"]. " - Finish Time: ". $row["Duration"]. "<br> ";
   }
    } else {
      echo "0 results";
  }
?>
</code>```

答:
MYSQLI_NUM is the 'ordinal position' of a column, starting with 0 to the first column in the query results, 1 for the next column, 2 for the next, and so on. For example, if the 'Price' column appears first in the query results, it will be $row[0], but in your query, it is currently at $row[3]. Otherwise, use the number that corresponds to the correct position of the query for the column.

See this for an example:  http://php.net/manual/en/mysqli-result.fetch-row.php

Also, know that because your first loop cycles the recordset before your 2nd loop, you'll need to reset the list to avoid having to query twice.

```<code>if ($result->num_rows > 0) {
 // output data of each row
 $result->data_seek(0); // set the recordset back to the first row.

 while($row = $result->fetch_array(MYSQLI_NUM)) {
</code>```

MYSQLI_BOTH, which is the default, returns an array so that you can use the row results by column name OR by column number.

======

Know that many don't like using the column order numbers except for very small queries, like ones that return a single row, typically having only one column, such a count query. The reason is that if a larger query ever changes the column ordering, then the code has be 'scoured' to ensure that the column position numbers align/match to the updated query changes.

Body:
I am having difficulty getting Price and Date to display on the webpage.

Below is a section of the current code that I have. The MYSQLI_ASSOC part displays the correct data but the MYSQLI_NUM section of the code does not display at all. I am having trouble finding information on how to make it work.

 <?php
    $query = "SELECT ItemID, Name, Category, Price, Duration, Photo FROM
    item ORDER by ItemID LIMIT 3";
    $result = $mysqli->query($query);

  if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_array(MYSQLI_ASSOC)) {
         echo "
 Row: ". $row["ItemID"]. " - Name: ". $row["Name"]. "
 " . $row["Category"] .  "
" ;
   }
    } else {
      echo "0 results";
  }

    if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_array(MYSQLI_NUM)) {
       echo "
 Price: ". $row["Price"]. " - Finish Time: ". $row["Duration"]. "
 ";
   }
    } else {
      echo "0 results";
  }
?>

Body:
MYSQLI_NUM is the 'ordinal position' of a column, starting with 0 to the first column in the query results, 1 for the next column, 2 for the next, and so on. For example, if the 'Price' column appears first in the query results, it will be $row[0], but in your query, it is currently at $row[3]. Otherwise, use the number that corresponds to the correct position of the query for the column.

See this for an example:  http://php.net/manual/en/mysqli-result.fetch-row.php

Also, know that because your first loop cycles the recordset before your 2nd loop, you'll need to reset the list to avoid having to query twice.

if ($result->num_rows > 0) {
 // output data of each row
 $result->data_seek(0); // set the recordset back to the first row.

 while($row = $result->fetch_array(MYSQLI_NUM)) {

MYSQLI_BOTH, which is the default, returns an array so that you can use the row results by column name OR by column number.

======

Know that many don't like using the column order numbers except for very small queries, like ones that return a single row, typically having only one column, such a count query. The reason is that if a larger query ever changes the column ordering, then the code has be 'scoured' to ensure that the column position numbers align/match to the updated query changes.


问:
IBM WL.Client.getUserInfo - Discontinued in v8.0 - What's the replacement?
I am using IBM MFP in my code and my current assignment involves migrating a project from MFP version v6.3 (Called as WorkLight) to Mobile First Platform v8.0.

During the migration process, the following Client API methods are considered as discontinued in v8.0. When I looked at IBM support site, it is told "No replacement". There is no more detail given on this. The methods are,

WL.Client.getUserInfo

WL.Client.updateUserInfo

WL.Client.isUserAuthenticated

Does any one know what exactly this term "No replacement" mean? Does it mean the equivalent code has to be manually written by the developer who previously used WL.Client.getUserInfo?

This is the same case for other client API methods WL.Client.updateUserInfo & WL.Client.isUserAuthenticated?

Please help. I have gone through the IBM support knowledge centre, I don't see any page that gives a detailed explanation of "No replacement".

https://www.ibm.com/support/knowledgecenter/en/SSHS8R_8.0.0/com.ibm.worklight.upgrade.doc/devref/c_sdk_changes4migration.html

答:
The following API's are discontinued in MFP Version 8.0 and there is no replacement/equivalent API's for these.

WL.Client.getUserInfo

WL.Client.updateUserInfo

WL.Client.isUserAuthenticated

The following are the workarounds where you can achieve same behavior of these API's.

WL.Client.getUserInfo - User information can be obtained in onSuccess callback of SecurityCheck Challenge Handler soon after authentication process else in response callback of Login API for UserAuthentication Security Check. You can write logic to store it locally in application and use it whenever it is required.

WL.Client.updateUserInfo - Do Logout from UserAuthentication security check and Re-login with new user information.

WL.Client.isUserAuthenticated - Implement the timer functionality in onSuccess callback of SecurityCheck Challenge Handler for UserAuthentication Security Check, which should start at onSuccess callback & Set the time of timer equal to the expiration time of access token. In application if you want to check whether user is authenticated or not, You can check the timer object, if it is expired - This means access token is expired else user is still authenticated.

and also you can request these API's support for MobileFirst Platform version 8.0 here.


问:
Chart JS not rendering on iOS devices
Im currently creating an app using cordova and ChartJS - I'm rendering a doughnut chart and it works perfectly fine in the emulator, but when I come to test the app on a ipad/ipod/iphone the chart does not render.

```<code>function renderMainClock(hourId) {

        var clockData = gVMainClockData[hourId - 1];
        var ctx = document.getElementById("main-clock").getContext("2d");
        window.mainClock = new Chart(ctx).Doughnut(clockData, {responsive:true});

        alert(ctx);

    }
</code>```

The alert gets called within the emulator, but is never called when its ran on a iOS device.

Does anyone know what the problem is?

Here is my index.html too:

```<code><!DOCTYPE html>

<html>

    <head>

        <link rel="stylesheet" type="text/css" href="css/materialize.min.css" media="screen,projection"/>
        <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/index.css"/>

        <title>NUH Nursing Activity</title>

    </head>

    <body>

        <!-- Top Bar -->
        <div id="top-bar"></div>

        <!-- Navigation -->
        <div class="">
            <nav>
                <div class="nav-wrapper blue darken-4">
                    <a href="#" class="brand-logo">NUH Nursing Activity</a>
                    <ul class="right">
                        <li><a href="#"><i class="mdi-action-info"></i></a></li>
                    </ul>
                </div>
            </nav>
        </div>

        <div class="container-custom">

            <div class="center small-circle-padding">
                <div id="small-circles"></div>
            </div>

            <div id="canvas-holder" class="center">
                <canvas id="main-clock"></canvas>
            </div>

            <div class="card red darken-1">
                <div class="card-content white-text">
                    <p>Current Shift Hour: 1</p>
                </div>
            </div>

            <div class="row">
                <div class="col s5">
                    <a class="btn blue darken-2">Add</a>
                </div>
                <div class="col s7 right">
                    <a class="btn blue darken-4 right disabled">Finish</a>
                </div>
            </div>

        </div>

        <!-- Include Relevant JavaScript -->
        <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
        <script type="text/javascript" src="cordova.js"></script>

        <script type="text/javascript" src="js/globalVariables.js"></script>
        <script tyoe="text/javascript" src="js/materialize.min.js"></script>

        <script type="text/javascript" src="js/chart.min.js"></script>

        <script type="text/javascript" src="js/appStart.js"></script>
        <script type="text/javascript" src="js/mainClock.js"></script>

    </body>

</html>
</code>```

答: It's so silly, but removing the []'s from my backgroundColor and borderColor options fixed the rending issue I was having.</p>

Title: Chart JS not rendering on iOS devices

Body:
Im currently creating an app using cordova and ChartJS - I'm rendering a doughnut chart and it works perfectly fine in the emulator, but when I come to test the app on a ipad/ipod/iphone the chart does not render.

function renderMainClock(hourId) {

        var clockData = gVMainClockData[hourId - 1];
        var ctx = document.getElementById("main-clock").getContext("2d");
        window.mainClock = new Chart(ctx).Doughnut(clockData, {responsive:true});

        alert(ctx);

    }

The alert gets called within the emulator, but is never called when its ran on a iOS device.

Does anyone know what the problem is?

Here is my index.html too:

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="css/materialize.min.css" media="screen,projection"/>
        <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/index.css"/>

        <title>NUH Nursing Activity</title>

                    NUH Nursing Activity

                <canvas id="main-clock"></canvas>

Current Shift Hour: 1

                    Add

                    Finish


问:
Calling a controller function from onchange event in html view
I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this:  "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

```<code>@Html.DropDownList("selectList", Model.ReverseMonthsLists())
</code>```

View Model Code

```<code>public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}
</code>```

Controller function

```<code>    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }
</code>```

答:
The normal way to get a value to a controller is for the user to post the page back to the server, e.g. via a submit button. When this happens, the controller's action method can receive the selected item as an argument and then do what it needs to do. So if you just want the user to submit the form, and allow the web site to render the next page based on the selected value (and a list that you compute based on that value), that is all you need to do.

On the other hand, perhaps you don't want the user to submit the page; you want a series of dates to be displayed within the page, or for the dates to be processed by code running in the browser. If that is the case, I would suggest you perform the computations in Javascript within the browser itself, thereby avoiding the need for a round trip. Nothing in your GetDates() method requires any server side data, so it's just a question of converting your c# code to Javascript code.

In some rare cases, you will want a UX element on the page to get updated immediately based on a server computation, without the page being posted. If that is what you want, you'll have to use the AJAX solutions the other posters have provided. It's much more complicated and much more work. If you don't need that, use one of the solutions I provided above.

Body:
I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this:  "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

@Html.DropDownList("selectList", Model.ReverseMonthsLists())

View Model Code

public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}

Controller function

    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }